Skip to content

Computer use CLI for AI agents

fix: harden native accessibility targeting and delivery (#210)

Lahfir882c4c4695c0
diff --git a/Cargo.lock b/Cargo.lock
index fa2b7b850..be02cd896 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -21,6 +21,7 @@ dependencies = [
"agent-desktop-windows",
"base64",
"clap",
+ "libc",
"serde",
"serde_json",
"thiserror",
diff --git a/crates/core/src/actionability_live_tests.rs b/crates/core/src/actionability_live_tests.rs
index 2dc0d0bca..08e581ab4 100644
--- a/crates/core/src/actionability_live_tests.rs
+++ b/crates/core/src/actionability_live_tests.rs
@@ -227,6 +227,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("OK".into()),
value: None,
diff --git a/crates/core/src/actionability_tests.rs b/crates/core/src/actionability_tests.rs
index 58db4b807..c82b70d6a 100644
--- a/crates/core/src/actionability_tests.rs
+++ b/crates/core/src/actionability_tests.rs
@@ -17,6 +17,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("OK".into()),
value: None,
diff --git a/crates/core/src/adapter/observation_tests.rs b/crates/core/src/adapter/observation_tests.rs
index a5f0d9743..2c8f65e82 100644
--- a/crates/core/src/adapter/observation_tests.rs
+++ b/crates/core/src/adapter/observation_tests.rs
@@ -58,6 +58,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: None,
value: None,
diff --git a/crates/core/src/commands/drag_tests.rs b/crates/core/src/commands/drag_tests.rs
index 40934059a..5cfc8f234 100644
--- a/crates/core/src/commands/drag_tests.rs
+++ b/crates/core/src/commands/drag_tests.rs
@@ -255,6 +255,7 @@ fn ref_entry(pid: u32) -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Item".into()),
value: None,
diff --git a/crates/core/src/commands/drag_wait_scope_tests.rs b/crates/core/src/commands/drag_wait_scope_tests.rs
index a20ee609d..a8d1c9976 100644
--- a/crates/core/src/commands/drag_wait_scope_tests.rs
+++ b/crates/core/src/commands/drag_wait_scope_tests.rs
@@ -62,6 +62,7 @@ impl CrossAppWaitAdapter {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Dropped".into()),
..Default::default()
},
@@ -81,6 +82,7 @@ impl CrossAppWaitAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some(window.title.clone()),
..Default::default()
},
diff --git a/crates/core/src/commands/execute_by_ref_tests.rs b/crates/core/src/commands/execute_by_ref_tests.rs
index d12d05070..ac9d5ccc1 100644
--- a/crates/core/src/commands/execute_by_ref_tests.rs
+++ b/crates/core/src/commands/execute_by_ref_tests.rs
@@ -26,6 +26,7 @@ fn snapshot_with_ref(role: &str, available_actions: &[&str]) -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: role.into(),
name: Some("Target".into()),
value: None,
diff --git a/crates/core/src/commands/find.rs b/crates/core/src/commands/find.rs
index 32adbcc65..b58d0db86 100644
--- a/crates/core/src/commands/find.rs
+++ b/crates/core/src/commands/find.rs
@@ -176,23 +176,18 @@ fn collect_snapshot_matches(
}
if query::node_matches(node, query) {
let interactive = node.ref_id.is_some();
- let display_name = node
- .identity
- .name
- .as_deref()
- .or(node.identity.value.as_deref())
- .or(node.identity.description.as_deref())
- .map(String::from)
- .unwrap_or_else(|| format!("(unnamed {})", node.role));
- matches.push(json!({
- "ref_id": node.ref_id,
- "role": node.role,
- "name": display_name,
- "value": node.identity.value,
- "states": node.presentation.states,
- "interactive": interactive,
- "path": path.clone()
- }));
+ matches.push(
+ serde_json::to_value(crate::live_locator::LocatorMatchData {
+ ref_id: node.ref_id.clone(),
+ role: node.role.clone(),
+ name: node.identity.name.clone().unwrap_or_default(),
+ value: node.identity.value.clone(),
+ states: node.presentation.states.clone(),
+ interactive,
+ path: path.clone(),
+ })
+ .unwrap(),
+ );
if max_matches.is_some_and(|limit| matches.len() >= limit) {
return true;
}
diff --git a/crates/core/src/commands/find_tests.rs b/crates/core/src/commands/find_tests.rs
index bda1b4322..3a158b9ed 100644
--- a/crates/core/src/commands/find_tests.rs
+++ b/crates/core/src/commands/find_tests.rs
@@ -8,6 +8,7 @@ fn node(name: Option<&str>, value: Option<&str>, description: Option<&str>) -> A
ref_id: Some("@e1".into()),
role: "textfield".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: name.map(String::from),
value: value.map(String::from),
description: description.map(String::from),
@@ -57,14 +58,15 @@ fn no_selection() -> FindSelectionArgs {
}
#[test]
-fn display_name_prefers_value_before_description() {
+fn unnamed_match_keeps_value_separate_from_name() {
let root = node(None, Some("current value"), Some("help text"));
let query = LocatorQuery::default();
let mut matches = Vec::new();
search_tree(&root, &query, &mut Vec::new(), &mut matches, None);
- assert_eq!(matches[0]["name"], "current value");
+ assert!(matches[0].get("name").is_none());
+ assert_eq!(matches[0]["value"], "current value");
}
#[test]
diff --git a/crates/core/src/commands/get.rs b/crates/core/src/commands/get.rs
index 62ceb6aa1..a20e42296 100644
--- a/crates/core/src/commands/get.rs
+++ b/crates/core/src/commands/get.rs
@@ -33,16 +33,26 @@ pub fn execute(
let (prop_name, value) = match args.property {
GetProperty::Role => ("role", json!(entry.identity.role)),
GetProperty::Title => ("title", json!(entry.identity.name)),
- GetProperty::Text => {
- let live = optional_live_read(adapter.get_live_value(&handle, deadline))?;
- ("text", json!(live.or(entry.identity.value)))
+ GetProperty::Text | GetProperty::Value => {
+ let property = if matches!(args.property, GetProperty::Text) {
+ "text"
+ } else {
+ "value"
+ };
+ let live = optional_live_read(adapter.get_live_value(&handle, deadline).map(Some))?;
+ (property, json!(live.unwrap_or(entry.identity.value)))
}
- GetProperty::Value => {
- let live = optional_live_read(adapter.get_live_value(&handle, deadline))?;
- ("value", json!(live.or(entry.identity.value)))
+ GetProperty::Bounds => {
+ let live = optional_live_read(adapter.get_element_bounds(&handle, deadline).map(Some))?;
+ ("bounds", json!(live.unwrap_or(entry.geometry.bounds)))
+ }
+ GetProperty::States => {
+ let live = optional_live_read(adapter.get_live_state(&handle, deadline))?;
+ (
+ "states",
+ json!(live.map_or(entry.capabilities.states, |state| state.states)),
+ )
}
- GetProperty::Bounds => ("bounds", json!(entry.geometry.bounds)),
- GetProperty::States => ("states", json!(entry.capabilities.states)),
};
Ok(json!({ "property": prop_name, "ref": args.ref_id, "value": value }))
diff --git a/crates/core/src/commands/get_consistency_tests.rs b/crates/core/src/commands/get_consistency_tests.rs
new file mode 100644
index 000000000..1334042ad
--- /dev/null
+++ b/crates/core/src/commands/get_consistency_tests.rs
@@ -0,0 +1,191 @@
+use super::*;
+use crate::commands::get::{self, GetArgs, GetProperty};
+
+fn get_property(
+ snapshot: &str,
+ adapter: &dyn PlatformAdapter,
+ property: GetProperty,
+) -> Result<Value, AppError> {
+ get::execute(
+ GetArgs {
+ ref_id: "@e1".into(),
+ snapshot_id: Some(snapshot.into()),
+ property,
+ },
+ adapter,
+ &CommandContext::default(),
+ )
+}
+
+#[test]
+fn get_states_and_is_checked_agree_after_both_live_transitions() {
+ let _guard = HomeGuard::new();
+ for (saved, live, expected) in [
+ (vec![], vec![state::CHECKED.into()], true),
+ (vec![state::CHECKED.into()], vec![], false),
+ ] {
+ let snapshot = save_entry(entry(saved, None, vec![]));
+ let adapter = LiveStateAdapter::with_live(visible_bounds(), live.clone());
+ let observed = get_property(&snapshot, &adapter, GetProperty::States).unwrap();
+ let checked = execute(
+ IsArgs {
+ ref_id: "@e1".into(),
+ snapshot_id: Some(snapshot),
+ property: IsProperty::Checked,
+ },
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ assert_eq!(observed["value"], json!(live));
+ assert_eq!(checked["result"], expected);
+ }
+}
+
+#[test]
+fn get_bounds_reads_the_resolved_elements_current_geometry() {
+ let _guard = HomeGuard::new();
+ let mut saved = entry(vec![], None, vec![]);
+ saved.geometry.bounds = Some(Rect {
+ x: 90.0,
+ ..visible_bounds()
+ });
+ saved.geometry.bounds_hash = saved
+ .geometry
+ .bounds
+ .and_then(|bounds| bounds.bounds_hash());
+ let snapshot = save_entry(saved);
+ let adapter = LiveStateAdapter::with_live(visible_bounds(), vec![]);
+ let observed = get_property(&snapshot, &adapter, GetProperty::Bounds).unwrap();
+ assert_eq!(observed["value"], json!(visible_bounds()));
+}
+
+#[test]
+fn absent_live_bounds_never_resurrect_snapshot_coordinates() {
+ let _guard = HomeGuard::new();
+ let mut saved = entry(vec![], None, vec![]);
+ saved.geometry.bounds = Some(visible_bounds());
+ saved.geometry.bounds_hash = visible_bounds().bounds_hash();
+ let snapshot = save_entry(saved);
+ let adapter = LiveStateAdapter::with_live(visible_bounds(), vec![]);
+ *adapter.bounds.lock().unwrap() = None;
+
+ assert_eq!(
+ get_property(&snapshot, &adapter, GetProperty::Bounds).unwrap()["value"],
+ Value::Null
+ );
+ assert_eq!(
+ get_property(
+ &snapshot,
+ &LiveStateAdapter::without_live_support(),
+ GetProperty::Bounds
+ )
+ .unwrap()["value"],
+ json!(visible_bounds())
+ );
+}
+
+#[test]
+fn unsupported_live_reads_preserve_existing_is_fallback_contract() {
+ let _guard = HomeGuard::new();
+ let snapshot = save_entry(entry(vec![state::CHECKED.into()], None, vec![]));
+ let adapter = LiveStateAdapter::without_live_support();
+ let observed = get_property(&snapshot, &adapter, GetProperty::States).unwrap();
+ assert_eq!(observed["value"], json!([state::CHECKED]));
+ assert_eq!(
+ get_property(&snapshot, &adapter, GetProperty::Bounds).unwrap()["value"],
+ Value::Null
+ );
+}
+
+struct FailedLiveRead;
+
+impl ObservationOps for FailedLiveRead {
+ fn get_live_value(
+ &self,
+ _handle: &NativeHandle,
+ _deadline: crate::Deadline,
+ ) -> Result<Option<String>, AdapterError> {
+ Err(AdapterError::timeout("live read failed"))
+ }
+
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ fn get_live_state(
+ &self,
+ _handle: &NativeHandle,
+ _deadline: crate::Deadline,
+ ) -> Result<Option<ElementState>, AdapterError> {
+ Err(AdapterError::timeout("live read failed"))
+ }
+
+ fn get_element_bounds(
+ &self,
+ _handle: &NativeHandle,
+ _deadline: crate::Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ Err(AdapterError::timeout("live read failed"))
+ }
+}
+
+impl ActionOps for FailedLiveRead {}
+impl InputOps for FailedLiveRead {}
+impl SystemOps for FailedLiveRead {}
+
+#[test]
+fn failed_live_reads_never_become_successful_cached_answers() {
+ let _guard = HomeGuard::new();
+ let snapshot = save_entry(entry(vec![state::CHECKED.into()], None, vec![]));
+ for property in [
+ GetProperty::States,
+ GetProperty::Bounds,
+ GetProperty::Text,
+ GetProperty::Value,
+ ] {
+ let error = get_property(&snapshot, &FailedLiveRead, property).unwrap_err();
+ assert!(
+ matches!(error, AppError::Adapter(error) if error.code == crate::ErrorCode::Timeout)
+ );
+ }
+}
+
+#[test]
+fn is_enabled_and_wait_enabled_agree_on_live_evidence() {
+ let _guard = HomeGuard::new();
+ let saved = entry(vec![], None, vec![]);
+ let snapshot = save_entry(saved.clone());
+ for enabled in [Some(false), None, Some(true)] {
+ let adapter = LiveStateAdapter::with_live(visible_bounds(), vec![]);
+ adapter.state.lock().unwrap().as_mut().unwrap().enabled = enabled;
+ let result = execute(
+ IsArgs {
+ ref_id: "@e1".into(),
+ snapshot_id: Some(snapshot.clone()),
+ property: IsProperty::Enabled,
+ },
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ let wait = crate::commands::wait_predicate::observe(
+ &saved,
+ &NativeHandle::null(),
+ &crate::commands::wait_predicate::ElementPredicate::Enabled,
+ &adapter,
+ crate::Deadline::standard().unwrap(),
+ crate::actionability::StabilityExpectation::strict_hash(None),
+ )
+ .unwrap();
+ assert_eq!(result["applicable"], wait["applicable"]);
+ assert_eq!(result["result"], wait["enabled"] == true);
+ }
+}
+
+#[path = "get_live_value_tests.rs"]
+mod live_value_tests;
diff --git a/crates/core/src/commands/get_live_value_tests.rs b/crates/core/src/commands/get_live_value_tests.rs
new file mode 100644
index 000000000..d6a15886b
--- /dev/null
+++ b/crates/core/src/commands/get_live_value_tests.rs
@@ -0,0 +1,49 @@
+use super::*;
+
+struct LiveValue(Option<String>);
+
+impl ObservationOps for LiveValue {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ fn get_live_value(
+ &self,
+ _handle: &NativeHandle,
+ _deadline: crate::Deadline,
+ ) -> Result<Option<String>, AdapterError> {
+ Ok(self.0.clone())
+ }
+}
+
+impl ActionOps for LiveValue {}
+impl InputOps for LiveValue {}
+impl SystemOps for LiveValue {}
+
+#[test]
+fn get_value_does_not_resurrect_snapshot_text_when_live_value_is_absent() {
+ let _guard = HomeGuard::new();
+ let snapshot = save_entry(entry(vec![], Some("old text"), vec![]));
+ for live in [None, Some(String::new()), Some("new text".into())] {
+ let adapter = LiveValue(live.clone());
+ for property in [GetProperty::Value, GetProperty::Text] {
+ assert_eq!(
+ get_property(&snapshot, &adapter, property).unwrap()["value"],
+ json!(live)
+ );
+ }
+ }
+ assert_eq!(
+ get_property(
+ &snapshot,
+ &LiveStateAdapter::without_live_support(),
+ GetProperty::Value
+ )
+ .unwrap()["value"],
+ "old text"
+ );
+}
diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs
index a4b65ebe5..8f286fd76 100644
--- a/crates/core/src/commands/helpers.rs
+++ b/crates/core/src/commands/helpers.rs
@@ -5,10 +5,8 @@ use crate::{
commands::{wait_selector, wait_selector::WaitSelectorInput},
context::CommandContext,
ref_action_wait_context::RefActionWaitContext,
- ref_resolve_deadline::resolve_within_deadline,
refs::RefEntry,
refs_store::RefStore,
- resolve_attempt_outcome::ResolveAttemptOutcome,
window_lookup,
};
use serde_json::{Value, json};
@@ -51,12 +49,7 @@ pub(crate) fn resolve_ref_with_context(
)
}
-/// Resolves a ref to a live element handle, capping the strict resolve to
-/// `deadline` when supplied (the `hover`/`drag` wait path) or resolving
-/// uncapped otherwise (`get`/`is`). Delegates entry loading and its
-/// `ref.resolve.start/entry/error` tracing to [`load_ref_entry`], then adds
-/// handle resolution and the `ref.resolve.ok` event, so budgeted and
-/// single-shot resolution trace identically.
+/// Resolves a saved ref under the caller deadline and records resolution traces.
fn resolve_ref_within_deadline(
ref_id: &str,
snapshot_id: Option<&str>,
@@ -81,21 +74,16 @@ fn resolve_ref_within_deadline(
Ok((entry, handle))
}
-/// Performs the strict resolve for [`resolve_ref_within_deadline`], capping the
-/// attempt to `deadline` when one is supplied and surfacing an exhausted budget
-/// as a `TIMEOUT`, or resolving uncapped when it is not.
+/// Gives one-shot resolution its full caller budget; polling paths own their slices.
pub(crate) fn resolve_handle_within_deadline(
adapter: &dyn PlatformAdapter,
entry: &RefEntry,
deadline: crate::Deadline,
) -> Result<crate::adapter::NativeHandle, crate::AdapterError> {
- match resolve_within_deadline(adapter, entry, deadline) {
- ResolveAttemptOutcome::Resolved(handle) => Ok(handle),
- ResolveAttemptOutcome::Failed(err) => Err(err),
- ResolveAttemptOutcome::DeadlinePassed => Err(crate::AdapterError::timeout(
- "Target did not resolve within the wait budget",
- )),
+ if deadline.is_expired() {
+ return Err(deadline.timeout_error());
}
+ adapter.resolve_element_strict(entry, deadline)
}
pub(crate) fn execute_ref_action_with_context(
diff --git a/crates/core/src/commands/helpers_ref_action_wait_tests.rs b/crates/core/src/commands/helpers_ref_action_wait_tests.rs
index 417179f8e..af4b6087b 100644
--- a/crates/core/src/commands/helpers_ref_action_wait_tests.rs
+++ b/crates/core/src/commands/helpers_ref_action_wait_tests.rs
@@ -56,6 +56,7 @@ impl ObservationOps for ScopedWaitAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Saved!".into()),
..Default::default()
},
@@ -105,6 +106,7 @@ impl ObservationOps for ScopedWaitAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Saved!".into()),
..Default::default()
},
@@ -199,6 +201,7 @@ impl ObservationOps for MultiWindowAdapter {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Saved!".into()),
..Default::default()
},
@@ -215,6 +218,7 @@ impl ObservationOps for MultiWindowAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some(window.title.clone()),
..Default::default()
},
@@ -278,6 +282,7 @@ impl ObservationOps for MultiWindowAdapter {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Saved!".into()),
..Default::default()
},
@@ -293,6 +298,7 @@ impl ObservationOps for MultiWindowAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some(win.title.clone()),
..Default::default()
},
diff --git a/crates/core/src/commands/helpers_resolution_budget_tests.rs b/crates/core/src/commands/helpers_resolution_budget_tests.rs
new file mode 100644
index 000000000..40bdf8fda
--- /dev/null
+++ b/crates/core/src/commands/helpers_resolution_budget_tests.rs
@@ -0,0 +1,56 @@
+use super::*;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct BudgetAdapter {
+ received: Mutex<Vec<(u64, bool)>>,
+}
+
+impl ObservationOps for BudgetAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ self.received
+ .lock()
+ .unwrap()
+ .push((deadline.timeout_ms(), deadline.was_capped()));
+ Ok(NativeHandle::null())
+ }
+}
+impl ActionOps for BudgetAdapter {}
+impl InputOps for BudgetAdapter {}
+impl SystemOps for BudgetAdapter {}
+
+#[test]
+fn single_attempt_resolution_receives_the_callers_budget_without_poll_slicing() {
+ let adapter = BudgetAdapter::default();
+ for timeout in [5_000, 100] {
+ resolve_handle_within_deadline(
+ &adapter,
+ &entry(),
+ crate::Deadline::detached_after(timeout).unwrap(),
+ )
+ .unwrap();
+ }
+ assert_eq!(
+ *adapter.received.lock().unwrap(),
+ [(5_000, false), (100, false)]
+ );
+}
+
+#[test]
+fn expired_single_attempt_budget_never_calls_the_adapter() {
+ let adapter = BudgetAdapter::default();
+ let deadline = crate::Deadline::at(
+ std::time::Instant::now() - std::time::Duration::from_secs(1),
+ 1,
+ )
+ .unwrap();
+ let Err(error) = resolve_handle_within_deadline(&adapter, &entry(), deadline) else {
+ panic!("expired resolution must fail");
+ };
+ assert_eq!(error.code, ErrorCode::Timeout);
+ assert!(adapter.received.lock().unwrap().is_empty());
+}
diff --git a/crates/core/src/commands/helpers_test_support.rs b/crates/core/src/commands/helpers_test_support.rs
index d8c4ba12a..41ee0679f 100644
--- a/crates/core/src/commands/helpers_test_support.rs
+++ b/crates/core/src/commands/helpers_test_support.rs
@@ -13,6 +13,7 @@ pub(super) fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("OK".into()),
value: None,
diff --git a/crates/core/src/commands/helpers_tests.rs b/crates/core/src/commands/helpers_tests.rs
index dc13b1036..29a1fb332 100644
--- a/crates/core/src/commands/helpers_tests.rs
+++ b/crates/core/src/commands/helpers_tests.rs
@@ -385,3 +385,6 @@ fn ref_action_pipeline_resolves_under_lease_before_dispatch() {
assert_eq!(adapter.executes.load(Ordering::SeqCst), 1);
assert_eq!(adapter.drops.load(Ordering::SeqCst), 1);
}
+
+#[path = "helpers_resolution_budget_tests.rs"]
+mod resolution_budget_tests;
diff --git a/crates/core/src/commands/hover_tests.rs b/crates/core/src/commands/hover_tests.rs
index 9c124ae89..402ec743e 100644
--- a/crates/core/src/commands/hover_tests.rs
+++ b/crates/core/src/commands/hover_tests.rs
@@ -116,6 +116,7 @@ fn ref_snapshot(pid: u32) -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Target".into()),
value: None,
diff --git a/crates/core/src/commands/is_check.rs b/crates/core/src/commands/is_check.rs
index edf2705a6..c391353b6 100644
--- a/crates/core/src/commands/is_check.rs
+++ b/crates/core/src/commands/is_check.rs
@@ -5,7 +5,7 @@ use crate::{
context::CommandContext,
element_state::ElementState,
refs::RefEntry,
- state::{self, CHECKED, DISABLED, EXPANDED, FOCUSED, SELECTED, VisibilityEvidence},
+ state::{self, CHECKED, EXPANDED, FOCUSED, SELECTED, VisibilityEvidence},
};
use serde_json::{Value, json};
@@ -59,7 +59,10 @@ pub fn execute(
};
(visibility.applicable(), visibility.result())
}
- IsProperty::Enabled => (true, !state::has_state(&state.states, DISABLED)),
+ IsProperty::Enabled => {
+ let enabled = state.enabled;
+ (enabled.is_some(), enabled == Some(true))
+ }
IsProperty::Focused => (true, state::has_state(&state.states, FOCUSED)),
IsProperty::Checked => (
crate::roles::is_toggleable_role(&entry.identity.role)
diff --git a/crates/core/src/commands/is_check_applicability_tests.rs b/crates/core/src/commands/is_check_applicability_tests.rs
index 5b08afbb1..9e0506217 100644
--- a/crates/core/src/commands/is_check_applicability_tests.rs
+++ b/crates/core/src/commands/is_check_applicability_tests.rs
@@ -9,6 +9,7 @@ fn action_availability_makes_toggle_and_expand_applicable() {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "cell".into(),
name: Some("Disclosure".into()),
value: None,
diff --git a/crates/core/src/commands/is_check_tests.rs b/crates/core/src/commands/is_check_tests.rs
index 4a56854f8..19e155ed4 100644
--- a/crates/core/src/commands/is_check_tests.rs
+++ b/crates/core/src/commands/is_check_tests.rs
@@ -91,6 +91,7 @@ fn entry(states: Vec<String>, value: Option<&str>, actions: Vec<&str>) -> RefEnt
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "checkbox".into(),
name: Some("Target".into()),
value: value.map(str::to_string),
@@ -363,3 +364,6 @@ mod applicability_tests;
#[path = "is_check_vocabulary_tests.rs"]
mod vocabulary_tests;
+
+#[path = "get_consistency_tests.rs"]
+mod get_consistency_tests;
diff --git a/crates/core/src/commands/point_resolve_tests.rs b/crates/core/src/commands/point_resolve_tests.rs
index 2f367e265..2bb380b62 100644
--- a/crates/core/src/commands/point_resolve_tests.rs
+++ b/crates/core/src/commands/point_resolve_tests.rs
@@ -85,6 +85,7 @@ fn ref_snapshot(pid: u32) -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Target".into()),
value: None,
@@ -247,6 +248,7 @@ fn focus_ref_entry() -> RefEntry {
process_instance: Some("instance-42".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Target".into()),
value: None,
diff --git a/crates/core/src/commands/pointer_action_tests.rs b/crates/core/src/commands/pointer_action_tests.rs
index a4d38cf2e..41501f79f 100644
--- a/crates/core/src/commands/pointer_action_tests.rs
+++ b/crates/core/src/commands/pointer_action_tests.rs
@@ -49,6 +49,7 @@ fn point_ref_snapshot() -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Target".into()),
value: None,
diff --git a/crates/core/src/commands/pointer_single_shot_tests.rs b/crates/core/src/commands/pointer_single_shot_tests.rs
index 5928a9260..040f57f9e 100644
--- a/crates/core/src/commands/pointer_single_shot_tests.rs
+++ b/crates/core/src/commands/pointer_single_shot_tests.rs
@@ -137,6 +137,7 @@ fn ref_entry(pid: u32) -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some(format!("Target {pid}")),
value: None,
diff --git a/crates/core/src/commands/press_tests.rs b/crates/core/src/commands/press_tests.rs
index 1fe8c5f56..a9f2f0448 100644
--- a/crates/core/src/commands/press_tests.rs
+++ b/crates/core/src/commands/press_tests.rs
@@ -241,6 +241,7 @@ fn saved_tree() -> crate::AccessibilityNode {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Saved!".into()),
..Default::default()
},
diff --git a/crates/core/src/commands/query_tests.rs b/crates/core/src/commands/query_tests.rs
index 13681376d..7bab907bf 100644
--- a/crates/core/src/commands/query_tests.rs
+++ b/crates/core/src/commands/query_tests.rs
@@ -6,6 +6,7 @@ fn node(role: &str, name: Option<&str>, value: Option<&str>) -> AccessibilityNod
ref_id: None,
role: role.into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: name.map(String::from),
value: value.map(String::from),
..Default::default()
diff --git a/crates/core/src/commands/ref_policy_tests.rs b/crates/core/src/commands/ref_policy_tests.rs
index 1e01d1893..20901f4bf 100644
--- a/crates/core/src/commands/ref_policy_tests.rs
+++ b/crates/core/src/commands/ref_policy_tests.rs
@@ -130,6 +130,7 @@ fn snapshot_id() -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "textfield".into(),
name: Some("Target".into()),
value: None,
diff --git a/crates/core/src/commands/right_click_tests.rs b/crates/core/src/commands/right_click_tests.rs
index 937cc8058..bb72cde2c 100644
--- a/crates/core/src/commands/right_click_tests.rs
+++ b/crates/core/src/commands/right_click_tests.rs
@@ -109,6 +109,7 @@ fn save_refmap(source_app: Option<String>) -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Open".into()),
value: None,
diff --git a/crates/core/src/commands/snapshot_tests.rs b/crates/core/src/commands/snapshot_tests.rs
index 6a3d30b52..987b7f7cd 100644
--- a/crates/core/src/commands/snapshot_tests.rs
+++ b/crates/core/src/commands/snapshot_tests.rs
@@ -39,6 +39,7 @@ impl ObservationOps for WaitSnapshotAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Doc".into()),
..Default::default()
},
@@ -50,6 +51,7 @@ impl ObservationOps for WaitSnapshotAdapter {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Submit".into()),
..Default::default()
},
@@ -62,6 +64,7 @@ impl ObservationOps for WaitSnapshotAdapter {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("zero-bounds-button".into()),
..Default::default()
},
@@ -112,6 +115,7 @@ impl ObservationOps for WaitSnapshotAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Doc".into()),
..Default::default()
},
@@ -122,6 +126,7 @@ impl ObservationOps for WaitSnapshotAdapter {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Submit".into()),
..Default::default()
},
diff --git a/crates/core/src/commands/wait_element.rs b/crates/core/src/commands/wait_element.rs
index c4d1d6373..747cbb2f8 100644
--- a/crates/core/src/commands/wait_element.rs
+++ b/crates/core/src/commands/wait_element.rs
@@ -1,10 +1,9 @@
use crate::{
AppError,
adapter::PlatformAdapter,
- commands::{wait_predicate, wait_timeout},
+ commands::{helpers::load_ref_entry, wait_predicate, wait_timeout},
context::CommandContext,
ref_resolve_deadline::{POLL_INTERVAL, resolve_within_deadline},
- refs_store::RefStore,
resolve_attempt_outcome::ResolveAttemptOutcome,
};
use serde_json::{Value, json};
@@ -30,16 +29,7 @@ pub(crate) fn wait_for_element(
} = input;
let start = Instant::now();
let deadline = crate::Deadline::at(start, timeout_ms)?;
- let (resolved_snapshot_id, local_ref) =
- crate::ref_token::resolve_ref_target(&ref_id, snapshot_id.as_deref())?;
- let store = RefStore::for_session(context.session_id())?;
- let refmap = store.load_snapshot(&resolved_snapshot_id)?;
- let entry = refmap.get(&local_ref).cloned().ok_or_else(|| {
- AppError::invalid_input_with_suggestion(
- format!("Ref {ref_id} is not present in the requested snapshot"),
- "Use a snapshot-qualified ref returned by that snapshot, or pair a legacy @eN ref with its snapshot_id.",
- )
- })?;
+ let entry = load_ref_entry(&ref_id, snapshot_id.as_deref(), context)?;
let mut last_observed = json!(null);
let mut expected_bounds_hash = None;
@@ -59,6 +49,14 @@ pub(crate) fn wait_for_element(
) {
Ok(observed) => {
last_observed = observed;
+ if deadline.is_expired() {
+ return wait_timeout::element(
+ ref_id,
+ predicate,
+ timeout_ms,
+ last_observed,
+ );
+ }
if let Some(observed) = last_observed
.get("observed_bounds_hash")
.and_then(Value::as_u64)
diff --git a/crates/core/src/commands/wait_element_tests.rs b/crates/core/src/commands/wait_element_tests.rs
index c42dbe5bf..97e0adb18 100644
--- a/crates/core/src/commands/wait_element_tests.rs
+++ b/crates/core/src/commands/wait_element_tests.rs
@@ -59,13 +59,13 @@ impl InputOps for LiveErrorPredicateAdapter {}
impl SystemOps for LiveErrorPredicateAdapter {}
#[test]
-fn snapshot_pinned_missing_ref_is_invalid_args() {
+fn snapshot_pinned_missing_ref_matches_get_recovery() {
let _guard = HomeGuard::new();
let snapshot_id = snapshot_with_one_ref();
let err = wait_for_element_test(
"@e2".into(),
- Some(snapshot_id),
+ Some(snapshot_id.clone()),
wait_predicate::ElementPredicate::Exists,
1,
&NoopAdapter,
@@ -73,10 +73,88 @@ fn snapshot_pinned_missing_ref_is_invalid_args() {
)
.unwrap_err();
- assert_eq!(err.code(), "INVALID_ARGS");
+ let get_error = crate::commands::get::execute(
+ crate::commands::get::GetArgs {
+ ref_id: "@e2".into(),
+ snapshot_id: Some(snapshot_id),
+ property: crate::commands::get::GetProperty::Value,
+ },
+ &NoopAdapter,
+ &crate::context::CommandContext::default(),
+ )
+ .unwrap_err();
+ assert_eq!(err.code(), get_error.code());
+ assert_eq!(err.code(), "STALE_REF");
assert!(err.suggestion().is_some());
}
+struct LateObservationAdapter {
+ delay_resolution: bool,
+ reads: AtomicU32,
+}
+
+impl ObservationOps for LateObservationAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ if self.delay_resolution {
+ while !deadline.is_expired() {
+ std::thread::sleep(deadline.remaining());
+ }
+ }
+ Ok(NativeHandle::null())
+ }
+
+ fn get_live_value(
+ &self,
+ _handle: &NativeHandle,
+ deadline: crate::Deadline,
+ ) -> Result<Option<String>, AdapterError> {
+ self.reads.fetch_add(1, Ordering::SeqCst);
+ while !deadline.is_expired() {
+ std::thread::sleep(deadline.remaining());
+ }
+ Ok(Some("ready".into()))
+ }
+}
+
+impl ActionOps for LateObservationAdapter {}
+impl InputOps for LateObservationAdapter {}
+impl SystemOps for LateObservationAdapter {}
+
+#[test]
+fn element_wait_rejects_late_resolution_and_late_matching_value() {
+ let _guard = HomeGuard::new();
+ let snapshot_id = snapshot_with_one_ref();
+ for delay_resolution in [true, false] {
+ let adapter = LateObservationAdapter {
+ delay_resolution,
+ reads: AtomicU32::new(0),
+ };
+ let predicate = if delay_resolution {
+ wait_predicate::ElementPredicate::Exists
+ } else {
+ wait_predicate::ElementPredicate::Value("ready".into())
+ };
+ let error = wait_for_element_test(
+ "@e1".into(),
+ Some(snapshot_id.clone()),
+ predicate,
+ 500,
+ &adapter,
+ &crate::context::CommandContext::default(),
+ )
+ .expect_err("late observations cannot satisfy a bounded wait");
+ assert_eq!(error.code(), "TIMEOUT");
+ assert_eq!(
+ adapter.reads.load(Ordering::SeqCst),
+ u32::from(!delay_resolution)
+ );
+ }
+}
+
#[test]
fn element_wait_explicit_session_snapshot_with_matching_session_context() {
let _guard = HomeGuard::new();
diff --git a/crates/core/src/commands/wait_resolution_tests.rs b/crates/core/src/commands/wait_resolution_tests.rs
index 30e228646..f8d5cd2c1 100644
--- a/crates/core/src/commands/wait_resolution_tests.rs
+++ b/crates/core/src/commands/wait_resolution_tests.rs
@@ -124,6 +124,7 @@ fn snapshot_with_one_ref() -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/commands/wait_scenario_count_tests.rs b/crates/core/src/commands/wait_scenario_count_tests.rs
index 921f07808..503467917 100644
--- a/crates/core/src/commands/wait_scenario_count_tests.rs
+++ b/crates/core/src/commands/wait_scenario_count_tests.rs
@@ -7,6 +7,7 @@ fn ready_button(name: &str) -> crate::AccessibilityNode {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some(name.into()),
..Default::default()
},
@@ -22,6 +23,7 @@ fn truncated_container(child_count: u32) -> crate::AccessibilityNode {
ref_id: None,
role: "group".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("list".into()),
..Default::default()
},
@@ -37,6 +39,7 @@ fn doc_window(children: Vec<crate::AccessibilityNode>) -> crate::AccessibilityNo
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Doc".into()),
..Default::default()
},
diff --git a/crates/core/src/commands/wait_scenario_tests.rs b/crates/core/src/commands/wait_scenario_tests.rs
index 34feef56a..5759d91b6 100644
--- a/crates/core/src/commands/wait_scenario_tests.rs
+++ b/crates/core/src/commands/wait_scenario_tests.rs
@@ -17,6 +17,7 @@ impl ObservationOps for TextlessTreeAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Doc".into()),
..Default::default()
},
@@ -57,6 +58,7 @@ impl ObservationOps for TextlessTreeAdapter {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Doc".into()),
..Default::default()
},
diff --git a/crates/core/src/commands/wait_selector_tests.rs b/crates/core/src/commands/wait_selector_tests.rs
index 90b4333eb..4e9533d20 100644
--- a/crates/core/src/commands/wait_selector_tests.rs
+++ b/crates/core/src/commands/wait_selector_tests.rs
@@ -11,6 +11,7 @@ fn window_node(children: Vec<AccessibilityNode>) -> AccessibilityNode {
ref_id: None,
role: "window".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some("Doc".into()),
..Default::default()
},
@@ -26,6 +27,7 @@ fn button_node(label: &str) -> AccessibilityNode {
ref_id: None,
role: "button".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some(label.into()),
..Default::default()
},
diff --git a/crates/core/src/commands/wait_test_support.rs b/crates/core/src/commands/wait_test_support.rs
index be3886ff0..06483af58 100644
--- a/crates/core/src/commands/wait_test_support.rs
+++ b/crates/core/src/commands/wait_test_support.rs
@@ -166,6 +166,7 @@ fn save_ref_in_store(store: RefStore, states: Vec<String>) -> String {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/commands/wait_text_match.rs b/crates/core/src/commands/wait_text_match.rs
index dfd272fcd..d05e9ea15 100644
--- a/crates/core/src/commands/wait_text_match.rs
+++ b/crates/core/src/commands/wait_text_match.rs
@@ -49,6 +49,7 @@ mod tests {
ref_id: None,
role: "group".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: Some(name.into()),
..Default::default()
},
diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs
index 5b9dad27a..a4714685a 100644
--- a/crates/core/src/context.rs
+++ b/crates/core/src/context.rs
@@ -20,6 +20,7 @@ pub use wait_selector::WaitSelector;
#[derive(Debug, Clone, Default)]
pub struct CommandContext {
session: Option<SessionScope>,
+ pinned_session_namespace: bool,
inherited_deadline: Option<crate::Deadline>,
trace: TraceConfig,
artifacts_full: bool,
@@ -96,6 +97,7 @@ impl CommandContext {
session::cursor_overlay_for_session(session.as_ref().map(|scope| scope.id.as_str()))?;
Ok(Self {
session,
+ pinned_session_namespace: false,
inherited_deadline: None,
trace: TraceConfig::build(trace_path, segment_dir, trace_strict)?,
artifacts_full,
@@ -156,6 +158,15 @@ impl CommandContext {
self
}
+ pub fn with_pinned_session_namespace(mut self) -> Self {
+ self.pinned_session_namespace = true;
+ self
+ }
+
+ pub fn session_namespace_is_pinned(&self) -> bool {
+ self.pinned_session_namespace
+ }
+
pub fn is_headed(&self) -> bool {
self.options.interaction_policy.is_headed()
}
@@ -228,6 +239,11 @@ impl CommandContext {
pub fn for_batch_item(&self, session_id: Option<String>) -> Result<Self, AppError> {
let session_id = session_id.or_else(|| self.session_id().map(str::to_owned));
+ if self.pinned_session_namespace && session_id.as_deref() != self.session_id() {
+ return Err(AppError::invalid_input(
+ "A command host cannot switch snapshot namespaces",
+ ));
+ }
if let Some(id) = session_id.as_deref() {
validate_session_id(id)?;
}
@@ -258,6 +274,7 @@ impl CommandContext {
};
Ok(Self {
session,
+ pinned_session_namespace: self.pinned_session_namespace,
inherited_deadline: self.inherited_deadline,
trace,
artifacts_full,
diff --git a/crates/core/src/hit_test_tests.rs b/crates/core/src/hit_test_tests.rs
index 6c7fe7ce7..66d11ec73 100644
--- a/crates/core/src/hit_test_tests.rs
+++ b/crates/core/src/hit_test_tests.rs
@@ -124,6 +124,7 @@ fn clickable_entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Save".into()),
value: None,
diff --git a/crates/core/src/live_locator/hydrate.rs b/crates/core/src/live_locator/hydrate.rs
index 885718485..50dc58beb 100644
--- a/crates/core/src/live_locator/hydrate.rs
+++ b/crates/core/src/live_locator/hydrate.rs
@@ -1,7 +1,4 @@
-use super::{
- LocatorField, LocatorResolution, ObservationRequest, ObservationRoot, ObservedNode,
- ObservedTree,
-};
+use super::{LocatorResolution, ObservationRequest, ObservationRoot, ObservedNode, ObservedTree};
use crate::{
AdapterError, AppError, ErrorCode, IdentityMatch, adapter::PlatformAdapter,
locator::LocatorQuery, refs::RefEntry, refs::RefMap,
@@ -81,7 +78,7 @@ pub(super) fn selected_matches(
}
let mut entry = super::materialize::ref_entry(node, &hydrated.source, query);
preserve_verified_identity(&preliminary, node, &mut entry);
- let name = display_name(node, &entry.identity.role);
+ let name = node.evidence.name.meaningful_string().unwrap_or_default();
let value = node.evidence.value.meaningful_string();
(entry, name, value, node.document_order)
};
@@ -166,6 +163,7 @@ fn anchor_matches(preliminary: &RefEntry, node: &ObservedNode) -> bool {
) {
IdentityMatch::Match => true,
IdentityMatch::NoMatch => false,
+ IdentityMatch::Unknown if preliminary.identity.retained_object.is_some() => false,
IdentityMatch::Unknown => preliminary
.geometry
.bounds_hash
@@ -199,19 +197,6 @@ fn preserve_verified_identity(preliminary: &RefEntry, node: &ObservedNode, entry
}
}
-fn display_name(node: &ObservedNode, role: &str) -> String {
- match &node.evidence.name {
- LocatorField::Unknown => "(name unavailable)".into(),
- LocatorField::Known(name) if !name.is_empty() => name.clone(),
- LocatorField::Known(_) | LocatorField::Absent => node
- .evidence
- .value
- .meaningful_string()
- .or_else(|| node.evidence.description.meaningful_string())
- .unwrap_or_else(|| format!("(unnamed {role})")),
- }
-}
-
fn anchor_missing(entry: &RefEntry) -> AdapterError {
AdapterError::new(
ErrorCode::StaleRef,
@@ -290,3 +275,26 @@ fn evidence_incomplete(
}))
.with_disposition(crate::DeliverySemantics::not_delivered())
}
+
+#[cfg(test)]
+mod retained_tests {
+ use super::*;
+ use crate::live_locator::test_support::{evidence, node, tree};
+
+ #[test]
+ fn missing_retained_identity_cannot_pass_hydration_through_geometry() {
+ let mut observed = evidence("textfield", None);
+ observed.identifiers = observed.identifiers.with_retained_object("host:1".into());
+ let observed = node(0, observed, vec![], &[]);
+ let tree = tree(vec![observed.clone()], vec![0], true);
+ let entry =
+ super::super::materialize::ref_entry(&observed, &tree.source, &LocatorQuery::default());
+ assert!(anchor_matches(&entry, &observed));
+ let mut replacement = observed;
+ replacement.evidence.identifiers = crate::IdentifierEvidence::absent();
+ assert!(!anchor_matches(&entry, &replacement));
+ replacement.evidence.identifiers =
+ crate::IdentifierEvidence::absent().with_retained_object("host:2".into());
+ assert!(!anchor_matches(&entry, &replacement));
+ }
+}
diff --git a/crates/core/src/live_locator/identifier_evidence.rs b/crates/core/src/live_locator/identifier_evidence.rs
index 84262be38..99c3a244e 100644
--- a/crates/core/src/live_locator/identifier_evidence.rs
+++ b/crates/core/src/live_locator/identifier_evidence.rs
@@ -3,6 +3,7 @@ pub struct IdentifierEvidence {
identifiers: Vec<crate::ElementIdentifier>,
preferred: Option<usize>,
complete: bool,
+ retained_object: Option<String>,
}
impl IdentifierEvidence {
@@ -46,9 +47,19 @@ impl IdentifierEvidence {
identifiers: normalized,
preferred: normalized_preferred,
complete,
+ retained_object: None,
}
}
+ pub fn with_retained_object(mut self, token: String) -> Self {
+ self.retained_object = Some(token);
+ self
+ }
+
+ pub fn retained_object(&self) -> Option<&str> {
+ self.retained_object.as_deref()
+ }
+
pub fn absent() -> Self {
Self::new([], None, true)
}
diff --git a/crates/core/src/live_locator/locator_match_data.rs b/crates/core/src/live_locator/locator_match_data.rs
index 31f172403..ac740e322 100644
--- a/crates/core/src/live_locator/locator_match_data.rs
+++ b/crates/core/src/live_locator/locator_match_data.rs
@@ -4,6 +4,7 @@ use serde::Serialize;
pub struct LocatorMatchData {
pub ref_id: Option<String>,
pub role: String,
+ #[serde(skip_serializing_if = "String::is_empty")]
pub name: String,
pub value: Option<String>,
pub states: Vec<String>,
diff --git a/crates/core/src/live_locator/materialize.rs b/crates/core/src/live_locator/materialize.rs
index f2f833bb7..1a0c76883 100644
--- a/crates/core/src/live_locator/materialize.rs
+++ b/crates/core/src/live_locator/materialize.rs
@@ -64,6 +64,11 @@ pub(crate) fn ref_entry(
process_instance: None,
},
identity: crate::RefEntryIdentity {
+ retained_object: node
+ .evidence
+ .identifiers
+ .retained_object()
+ .map(str::to_owned),
role: role.clone(),
name: node.evidence.name.meaningful_string(),
value: node.evidence.value.meaningful_string(),
diff --git a/crates/core/src/live_locator/materialize_tests.rs b/crates/core/src/live_locator/materialize_tests.rs
index c77afc4f4..5f0f37cf5 100644
--- a/crates/core/src/live_locator/materialize_tests.rs
+++ b/crates/core/src/live_locator/materialize_tests.rs
@@ -239,6 +239,7 @@ fn source_entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "group".into(),
name: Some("Scope".into()),
value: None,
diff --git a/crates/core/src/live_locator/mod.rs b/crates/core/src/live_locator/mod.rs
index 2300ba6e1..9b1293b4c 100644
--- a/crates/core/src/live_locator/mod.rs
+++ b/crates/core/src/live_locator/mod.rs
@@ -100,6 +100,8 @@ mod resolve_query_tests;
#[cfg(test)]
mod resolve_tests;
#[cfg(test)]
+mod retained_identity_tests;
+#[cfg(test)]
mod scrollarea_name_tests;
#[cfg(test)]
mod selected_hydration_churn_tests;
diff --git a/crates/core/src/live_locator/observed_tree.rs b/crates/core/src/live_locator/observed_tree.rs
index d31756a49..5d4c56c6e 100644
--- a/crates/core/src/live_locator/observed_tree.rs
+++ b/crates/core/src/live_locator/observed_tree.rs
@@ -149,6 +149,11 @@ impl ObservedTree {
ref_id: node.ref_id.take(),
role,
identity: crate::NodeIdentity {
+ retained_object: node
+ .evidence
+ .identifiers
+ .retained_object()
+ .map(str::to_owned),
name: node
.evidence
.name
diff --git a/crates/core/src/live_locator/resolve.rs b/crates/core/src/live_locator/resolve.rs
index 9033c9f65..7054b1409 100644
--- a/crates/core/src/live_locator/resolve.rs
+++ b/crates/core/src/live_locator/resolve.rs
@@ -169,7 +169,8 @@ fn resolve_query_attempt(
aggregate: &mut LocatorStats,
) -> Result<LocatorResolution, AppError> {
let observation_request =
- ObservationRequest::locator_for_root(query, request, root, request.deadline).validate()?;
+ ObservationRequest::locator_for_root(query, request, root, observation_deadline(request))
+ .validate()?;
let tree = crate::renderer_accessibility::observe_tree(adapter, root, &observation_request)?;
let mut tree = tree;
tree.stats.reads.counts.observation_attempts =
@@ -192,3 +193,37 @@ fn resolve_query_attempt(
}
Ok(resolution)
}
+
+fn observation_deadline(request: &LocatorResolveRequest) -> crate::Deadline {
+ if request.materialization != super::LocatorMaterialization::SelectedMatches {
+ return request.deadline;
+ }
+ let remaining = request.deadline.remaining();
+ let reserve = (remaining / 2).min(Duration::from_secs(1));
+ request.deadline.capped(remaining.saturating_sub(reserve))
+}
+
+#[cfg(test)]
+mod budget_tests {
+ use super::*;
+
+ #[test]
+ fn selected_ref_hydration_has_budget_without_extending_the_operation() {
+ let request = LocatorResolveRequest {
+ selection: super::super::LocatorSelection::First,
+ deadline: crate::Deadline::after(60_000).unwrap(),
+ max_raw_depth: 50,
+ surface: None,
+ materialization: super::super::LocatorMaterialization::SelectedMatches,
+ };
+ let observation = observation_deadline(&request);
+ assert!(observation.was_capped());
+ assert!(!request.deadline.was_capped());
+ assert_eq!(observation.timeout_ms(), request.deadline.timeout_ms());
+ let count_request = LocatorResolveRequest {
+ materialization: super::super::LocatorMaterialization::None,
+ ..request
+ };
+ assert_eq!(observation_deadline(&count_request), request.deadline);
+ }
+}
diff --git a/crates/core/src/live_locator/retained_identity_tests.rs b/crates/core/src/live_locator/retained_identity_tests.rs
new file mode 100644
index 000000000..86ec41e16
--- /dev/null
+++ b/crates/core/src/live_locator/retained_identity_tests.rs
@@ -0,0 +1,94 @@
+use super::test_support::{evidence, node, tree};
+use super::{IdentifierEvidence, LocatorField};
+use crate::{IdentityMatch, RefEntry, locator::LocatorQuery};
+
+fn identifiers(token: Option<&str>) -> IdentifierEvidence {
+ let identifiers = IdentifierEvidence::typed(
+ [crate::ElementIdentifier {
+ kind: crate::IdentifierKind::AxIdentifier,
+ value: "shared-title".into(),
+ }],
+ Some(0),
+ true,
+ );
+ match token {
+ Some(token) => identifiers.with_retained_object(token.into()),
+ None => identifiers,
+ }
+}
+
+fn observed() -> super::ObservedTree {
+ let mut field = evidence("textfield", None);
+ field.value = LocatorField::Known("Alpha".into());
+ field.identifiers = identifiers(Some("host-generation:object-1"));
+ tree(vec![node(0, field, vec![], &[])], vec![0], true)
+}
+
+fn saved() -> RefEntry {
+ let tree = observed();
+ super::materialize::ref_entry(&tree.nodes[0], &tree.source, &LocatorQuery::default())
+}
+
+fn matches(entry: &RefEntry, token: Option<&str>, value: &str) -> IdentityMatch {
+ crate::ref_identity::identity_match(
+ entry,
+ &LocatorField::Absent,
+ &LocatorField::Known(value.into()),
+ &LocatorField::Absent,
+ &identifiers(token),
+ )
+}
+
+#[test]
+fn retained_identity_rejects_replacements_without_freezing_control_values() {
+ let entry = saved();
+ assert_eq!(
+ matches(&entry, Some("host-generation:object-1"), "Edited"),
+ IdentityMatch::Match
+ );
+ assert_eq!(
+ matches(&entry, Some("host-generation:object-2"), "Alpha"),
+ IdentityMatch::NoMatch
+ );
+ assert_eq!(
+ matches(&entry, Some("other-host:object-1"), "Alpha"),
+ IdentityMatch::NoMatch
+ );
+ assert_eq!(matches(&entry, None, "Alpha"), IdentityMatch::Unknown);
+ assert!(crate::ref_identity::has_meaningful_identity(&entry));
+}
+
+#[test]
+fn snapshot_and_find_preserve_identical_private_identity_evidence() {
+ let from_find = saved();
+ let projected = observed().into_accessibility_tree().unwrap();
+ let from_snapshot = crate::ref_alloc::ref_entry_from_node(
+ &projected,
+ &crate::ref_alloc_source::RefAllocSource {
+ pid: crate::ProcessId::new(42),
+ app: Some("FixtureApp"),
+ window_id: Some("w-1"),
+ window_title: Some("Fixture"),
+ window_bounds_hash: None,
+ process_instance: Some("test-instance"),
+ surface: crate::SnapshotSurface::Window,
+ },
+ None,
+ &[],
+ );
+ assert_eq!(from_find.identity, from_snapshot.identity);
+ let serialized = serde_json::to_string(&from_snapshot).unwrap();
+ let restored: RefEntry = serde_json::from_str(&serialized).unwrap();
+ assert_eq!(restored.identity, from_find.identity);
+ let public = serde_json::to_value(projected).unwrap();
+ assert!(public.get("retained_object").is_none());
+ assert_eq!(public["native_id"]["value"], "shared-title");
+}
+
+#[test]
+fn empty_retained_token_cannot_downgrade_to_native_id_matching() {
+ let mut entry = saved();
+ entry.identity.retained_object = Some(String::new());
+ assert_eq!(matches(&entry, Some(""), "Alpha"), IdentityMatch::Unknown);
+ assert_eq!(matches(&entry, None, "Alpha"), IdentityMatch::Unknown);
+}
diff --git a/crates/core/src/live_locator/select.rs b/crates/core/src/live_locator/select.rs
index cea7040f8..697b542eb 100644
--- a/crates/core/src/live_locator/select.rs
+++ b/crates/core/src/live_locator/select.rs
@@ -35,13 +35,7 @@ pub(crate) fn match_data(
.known()
.cloned()
.unwrap_or_else(|| "unknown".into());
- let name = node
- .evidence
- .name
- .meaningful_string()
- .or_else(|| node.evidence.value.meaningful_string())
- .or_else(|| node.evidence.description.meaningful_string())
- .unwrap_or_else(|| format!("(unnamed {role})"));
+ let name = node.evidence.name.meaningful_string().unwrap_or_default();
let mut ancestor_indices = Vec::new();
let mut parent = parents.get(index).copied().flatten();
while let Some(parent_index) = parent {
@@ -86,3 +80,37 @@ fn node_label(node: &super::ObservedNode) -> String {
.map(|label| format!("{role}:{label}"))
.unwrap_or_else(|| role.to_string())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::live_locator::{LocatorField, test_support};
+
+ #[test]
+ fn match_names_never_substitute_values_descriptions_or_placeholders() {
+ for name in [
+ LocatorField::Absent,
+ LocatorField::Unknown,
+ LocatorField::Known(String::new()),
+ LocatorField::Known("Editor".into()),
+ ] {
+ let expected = name.meaningful_string();
+ let mut evidence = test_support::evidence("textfield", None);
+ evidence.name = name;
+ evidence.value = LocatorField::Known("seed-target".into());
+ evidence.description = LocatorField::Known("Help text".into());
+ let tree = test_support::tree(
+ vec![test_support::node(0, evidence, Vec::new(), &[])],
+ vec![0],
+ true,
+ );
+ let data = match_data(&tree, 0, &[None]).unwrap();
+ let result = serde_json::to_value(data).unwrap();
+ assert_eq!(
+ result.get("name").and_then(|name| name.as_str()),
+ expected.as_deref()
+ );
+ assert_eq!(result["value"], "seed-target");
+ }
+ }
+}
diff --git a/crates/core/src/live_locator/selected_hydration_contract_tests.rs b/crates/core/src/live_locator/selected_hydration_contract_tests.rs
index 30d73deca..1c2581f91 100644
--- a/crates/core/src/live_locator/selected_hydration_contract_tests.rs
+++ b/crates/core/src/live_locator/selected_hydration_contract_tests.rs
@@ -80,7 +80,13 @@ fn role_only_geometry_anchor_accepts_unknown_optional_identity_once() {
assert_eq!(adapter.window_observations.load(Ordering::SeqCst), 1);
assert_eq!(adapter.strict_resolutions.load(Ordering::SeqCst), 1);
assert_eq!(adapter.hydration_observations.load(Ordering::SeqCst), 1);
- assert_eq!(resolution.matches[0].data.name, "(name unavailable)");
+ assert!(resolution.matches[0].data.name.is_empty());
+ assert!(
+ serde_json::to_value(&resolution.matches[0].data)
+ .unwrap()
+ .get("name")
+ .is_none()
+ );
let entry = resolution.refmap.unwrap().get("@e1").unwrap().clone();
assert_eq!(entry.identity.name, None);
assert_eq!(entry.geometry.bounds, Some(bounds()));
diff --git a/crates/core/src/live_locator/validation_tests.rs b/crates/core/src/live_locator/validation_tests.rs
index fdfd790c3..04a5af9ea 100644
--- a/crates/core/src/live_locator/validation_tests.rs
+++ b/crates/core/src/live_locator/validation_tests.rs
@@ -108,6 +108,7 @@ fn element_root_derives_surface_with_relative_depth_budgets() {
process_instance: Some("instance-1".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "group".into(),
name: Some("Menu root".into()),
value: None,
diff --git a/crates/core/src/locator_tests.rs b/crates/core/src/locator_tests.rs
index 35ddf8788..bfc5fd0c6 100644
--- a/crates/core/src/locator_tests.rs
+++ b/crates/core/src/locator_tests.rs
@@ -11,6 +11,7 @@ fn node(
ref_id: None,
role: role.into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: name.map(String::from),
value: value.map(String::from),
..Default::default()
diff --git a/crates/core/src/node_identity.rs b/crates/core/src/node_identity.rs
index 88877a905..ff41d9708 100644
--- a/crates/core/src/node_identity.rs
+++ b/crates/core/src/node_identity.rs
@@ -2,6 +2,8 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NodeIdentity {
+ #[serde(skip)]
+ pub retained_object: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
diff --git a/crates/core/src/ref_action_cursor_overlay_tests.rs b/crates/core/src/ref_action_cursor_overlay_tests.rs
index b15599e09..e0f68f5b4 100644
--- a/crates/core/src/ref_action_cursor_overlay_tests.rs
+++ b/crates/core/src/ref_action_cursor_overlay_tests.rs
@@ -108,6 +108,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "textfield".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/ref_action_exactly_once_tests.rs b/crates/core/src/ref_action_exactly_once_tests.rs
index 703658c13..7df465926 100644
--- a/crates/core/src/ref_action_exactly_once_tests.rs
+++ b/crates/core/src/ref_action_exactly_once_tests.rs
@@ -189,6 +189,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/ref_action_poll.rs b/crates/core/src/ref_action_poll.rs
index b6e5efeac..eae13e102 100644
--- a/crates/core/src/ref_action_poll.rs
+++ b/crates/core/src/ref_action_poll.rs
@@ -68,7 +68,7 @@ fn handle_actionability_failure(
error: AdapterError,
deadline: Deadline,
) -> Result<(), AdapterError> {
- if is_permanent_actionability_error(&error.code) {
+ if is_permanent_actionability_error(&error.code) || !error.permits_retry_by_default() {
return Err(error);
}
let stability_changed = failed_check(&error, "stable");
@@ -205,6 +205,25 @@ pub(crate) fn timeout_with_last_report(last_report: serde_json::Value) -> Adapte
mod tests {
use super::*;
+ #[test]
+ fn preflight_preserves_explicit_non_retryable_failures() {
+ for code in [
+ ErrorCode::ActionFailed,
+ ErrorCode::AppUnresponsive,
+ ErrorCode::Timeout,
+ ] {
+ let mut state = RefActionPollState::default();
+ let error = AdapterError::new(code.clone(), "terminal native read")
+ .with_details(json!({ "retryable": false, "native_error": -25202 }));
+ let result =
+ handle_actionability_failure(&mut state, error, Deadline::after(5_000).unwrap());
+ let error = result.expect_err("an explicit stop must not become another poll");
+ assert_eq!(error.code, code);
+ assert_eq!(error.details.unwrap()["native_error"], -25202);
+ assert!(state.last_report.is_none());
+ }
+ }
+
#[test]
fn preflight_identity_failures_are_terminal() {
assert!(is_permanent_actionability_error(&ErrorCode::StaleRef));
diff --git a/crates/core/src/ref_action_tests.rs b/crates/core/src/ref_action_tests.rs
index 42b94594a..8b81b93c6 100644
--- a/crates/core/src/ref_action_tests.rs
+++ b/crates/core/src/ref_action_tests.rs
@@ -194,6 +194,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/ref_action_wait_app_not_found_tests.rs b/crates/core/src/ref_action_wait_app_not_found_tests.rs
index 8333e42ff..0523cbe6e 100644
--- a/crates/core/src/ref_action_wait_app_not_found_tests.rs
+++ b/crates/core/src/ref_action_wait_app_not_found_tests.rs
@@ -17,6 +17,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/ref_action_wait_process_state_tests.rs b/crates/core/src/ref_action_wait_process_state_tests.rs
index 4ddaf8ec8..8b9fd1346 100644
--- a/crates/core/src/ref_action_wait_process_state_tests.rs
+++ b/crates/core/src/ref_action_wait_process_state_tests.rs
@@ -20,6 +20,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/ref_action_wait_success_tests.rs b/crates/core/src/ref_action_wait_success_tests.rs
index 9d2c04aee..3453aedfe 100644
--- a/crates/core/src/ref_action_wait_success_tests.rs
+++ b/crates/core/src/ref_action_wait_success_tests.rs
@@ -24,6 +24,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/ref_action_wait_tests.rs b/crates/core/src/ref_action_wait_tests.rs
index f8b8d8b81..4eed8ca63 100644
--- a/crates/core/src/ref_action_wait_tests.rs
+++ b/crates/core/src/ref_action_wait_tests.rs
@@ -130,6 +130,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/core/src/ref_alloc.rs b/crates/core/src/ref_alloc.rs
index eaa1c4d0d..a0804ea44 100644
--- a/crates/core/src/ref_alloc.rs
+++ b/crates/core/src/ref_alloc.rs
@@ -22,6 +22,7 @@ pub(crate) fn ref_entry_from_node(
process_instance: source.process_instance.map(str::to_string),
},
identity: crate::RefEntryIdentity {
+ retained_object: node.identity.retained_object.clone(),
role: node.role.clone(),
name: meaningful_string(node.identity.name.clone()),
value: meaningful_string(node.identity.value.clone()),
diff --git a/crates/core/src/ref_alloc_tests.rs b/crates/core/src/ref_alloc_tests.rs
index c67fb549a..803a36164 100644
--- a/crates/core/src/ref_alloc_tests.rs
+++ b/crates/core/src/ref_alloc_tests.rs
@@ -6,6 +6,7 @@ fn node(role: &str, name: Option<&str>) -> AccessibilityNode {
ref_id: None,
role: role.into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: name.map(str::to_string),
..Default::default()
},
diff --git a/crates/core/src/ref_entry_identity.rs b/crates/core/src/ref_entry_identity.rs
index 8e3c29c09..9c6054cc4 100644
--- a/crates/core/src/ref_entry_identity.rs
+++ b/crates/core/src/ref_entry_identity.rs
@@ -2,6 +2,8 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RefEntryIdentity {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub retained_object: Option<String>,
pub role: String,
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
diff --git a/crates/core/src/ref_identity.rs b/crates/core/src/ref_identity.rs
index 320619d28..f37c5b39d 100644
--- a/crates/core/src/ref_identity.rs
+++ b/crates/core/src/ref_identity.rs
@@ -6,6 +6,9 @@ use crate::{
};
pub fn has_meaningful_identity(entry: &RefEntry) -> bool {
+ if entry.identity.retained_object.is_some() {
+ return true;
+ }
entry
.identity
.native_id
@@ -36,6 +39,15 @@ pub fn identity_match(
actual_description: &LocatorField<String>,
actual_identifiers: &IdentifierEvidence,
) -> IdentityMatch {
+ if let Some(expected) = entry.identity.retained_object.as_deref() {
+ return match (
+ meaningful_text(Some(expected)),
+ actual_identifiers.retained_object(),
+ ) {
+ (Some(expected), Some(actual)) => equality_match(expected, actual),
+ _ => IdentityMatch::Unknown,
+ };
+ }
if let Some(expected) = entry.identity.native_id.as_ref() {
let Some(expected_value) = meaningful_text(Some(&expected.value)) else {
return IdentityMatch::Unknown;
diff --git a/crates/core/src/ref_identity_scroll_tests.rs b/crates/core/src/ref_identity_scroll_tests.rs
new file mode 100644
index 000000000..d7b0b4d14
--- /dev/null
+++ b/crates/core/src/ref_identity_scroll_tests.rs
@@ -0,0 +1,57 @@
+use super::*;
+
+#[test]
+fn scroll_positions_neither_prove_nor_reject_element_identity() {
+ for role in ["scrollbar", "handle"] {
+ for promoted_name in [false, true] {
+ let mut saved = entry();
+ saved.identity.role = role.into();
+ saved.identity.value = Some("0".into());
+ saved.identity.name = promoted_name.then(|| "0".into());
+ assert!(!has_meaningful_identity(&saved), "{role}");
+ for live_value in ["0", "0.10000000149011612"] {
+ let name = if promoted_name {
+ LocatorField::Known(live_value.into())
+ } else {
+ LocatorField::Absent
+ };
+ assert_eq!(
+ identity_match(
+ &saved,
+ &name,
+ &LocatorField::Known(live_value.into()),
+ &LocatorField::Absent,
+ &IdentifierEvidence::typed([], None, true),
+ ),
+ IdentityMatch::Unknown,
+ "{role} must require geometry or native identity, not scroll position",
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn named_scroll_controls_still_require_the_same_label() {
+ for role in ["scrollbar", "handle"] {
+ let mut saved = entry();
+ saved.identity.role = role.into();
+ saved.identity.name = Some("Document scroll position".into());
+ saved.identity.value = Some("0".into());
+ assert!(has_meaningful_identity(&saved));
+ assert!(identity_matches(
+ &saved,
+ Some("Document scroll position"),
+ Some("0.1"),
+ None,
+ None,
+ ));
+ assert!(!identity_matches(
+ &saved,
+ Some("Sidebar scroll position"),
+ Some("0.1"),
+ None,
+ None,
+ ));
+ }
+}
diff --git a/crates/core/src/ref_identity_tests.rs b/crates/core/src/ref_identity_tests.rs
index 02e7f1b5d..68ab08ae8 100644
--- a/crates/core/src/ref_identity_tests.rs
+++ b/crates/core/src/ref_identity_tests.rs
@@ -18,6 +18,7 @@ fn entry() -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: None,
value: None,
@@ -389,3 +390,5 @@ fn unknown_stable_text_field_does_not_collapse_to_absence() {
IdentityMatch::Unknown
);
}
+#[path = "ref_identity_scroll_tests.rs"]
+mod scroll_tests;
diff --git a/crates/core/src/ref_resolve_deadline.rs b/crates/core/src/ref_resolve_deadline.rs
index 90693708d..89b05c035 100644
--- a/crates/core/src/ref_resolve_deadline.rs
+++ b/crates/core/src/ref_resolve_deadline.rs
@@ -19,6 +19,7 @@ pub(crate) fn resolve_within_deadline(
return ResolveAttemptOutcome::DeadlinePassed;
}
match adapter.resolve_element_strict(entry, deadline.capped(RESOLVE_ATTEMPT)) {
+ Ok(_) if deadline.is_expired() => ResolveAttemptOutcome::DeadlinePassed,
Ok(handle) => ResolveAttemptOutcome::Resolved(handle),
Err(error) => classify_error(error, deadline),
}
diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rs
index c46b8842f..4d284f277 100644
--- a/crates/core/src/refs.rs
+++ b/crates/core/src/refs.rs
@@ -84,6 +84,12 @@ impl RefMap {
self.inner.is_empty()
}
+ pub(crate) fn retained_object_tokens(&self) -> impl Iterator<Item = &str> {
+ self.inner
+ .values()
+ .filter_map(|entry| entry.identity.retained_object.as_deref())
+ }
+
pub fn remove_by_root_ref(&mut self, root: &str) {
let root_entry = self.inner.get(root).cloned();
self.inner.retain(|ref_id, entry| {
diff --git a/crates/core/src/refs_serde_tests.rs b/crates/core/src/refs_serde_tests.rs
index e535062e4..bd4a763d1 100644
--- a/crates/core/src/refs_serde_tests.rs
+++ b/crates/core/src/refs_serde_tests.rs
@@ -8,6 +8,7 @@ fn minimal_entry(role: &str) -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: role.into(),
name: None,
value: None,
@@ -170,6 +171,7 @@ fn ref_entry_full_roundtrip_preserves_all_fields() {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "textfield".into(),
name: Some("Email".into()),
value: Some("[email protected]".into()),
diff --git a/crates/core/src/refs_store.rs b/crates/core/src/refs_store.rs
index 1fef67fd6..6d7fb7ef5 100644
--- a/crates/core/src/refs_store.rs
+++ b/crates/core/src/refs_store.rs
@@ -164,6 +164,34 @@ impl RefStore {
self.read_latest_snapshot_id()
}
+ pub fn retained_object_tokens(&self) -> Result<std::collections::HashSet<String>, AppError> {
+ self.with_write_lock(|| {
+ let entries = match std::fs::read_dir(self.snapshots_dir()) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Default::default()),
+ Err(error) => return Err(error.into()),
+ };
+ let mut tokens = std::collections::HashSet::new();
+ let mut candidates = 0_usize;
+ for entry in entries {
+ let entry = entry?;
+ let id = entry.file_name().to_string_lossy().into_owned();
+ if validate_snapshot_id(&id).is_err() {
+ continue;
+ }
+ candidates += 1;
+ if candidates > MAX_SAVED_SNAPSHOTS {
+ return Err(AppError::invalid_input(
+ "Snapshot inventory exceeds retention limit",
+ ));
+ }
+ let map = self.load_snapshot(&id)?;
+ tokens.extend(map.retained_object_tokens().map(str::to_owned));
+ }
+ Ok(tokens)
+ })
+ }
+
fn save_snapshot_unlocked(&self, snapshot_id: &str, refmap: &RefMap) -> Result<(), AppError> {
validate_snapshot_id(snapshot_id)?;
let json = refmap.serialize_with_size_check()?;
@@ -282,3 +310,7 @@ mod trace_tests;
#[cfg(test)]
#[path = "refs_store_transaction_tests.rs"]
mod transaction_tests;
+
+#[cfg(test)]
+#[path = "refs_store_retained_tests.rs"]
+mod retained_tests;
diff --git a/crates/core/src/refs_store_retained_tests.rs b/crates/core/src/refs_store_retained_tests.rs
new file mode 100644
index 000000000..da1c65b3c
--- /dev/null
+++ b/crates/core/src/refs_store_retained_tests.rs
@@ -0,0 +1,67 @@
+use super::*;
+use crate::refs_test_support::HomeGuard;
+use std::collections::HashSet;
+
+fn map(token: &str) -> RefMap {
+ let node = serde_json::from_str(r#"{"role":"button","name":"Target"}"#).unwrap();
+ let source = crate::ref_alloc_source::RefAllocSource {
+ pid: crate::ProcessId::new(42),
+ app: Some("App"),
+ window_id: Some("w-42"),
+ window_title: None,
+ window_bounds_hash: None,
+ process_instance: Some("instance"),
+ surface: crate::SnapshotSurface::Window,
+ };
+ let mut entry = crate::ref_alloc::ref_entry_from_node(&node, &source, None, &[0]);
+ entry.identity.retained_object = Some(token.into());
+ let mut map = RefMap::new();
+ map.allocate(entry);
+ map
+}
+
+#[test]
+fn retained_tokens_follow_all_saved_snapshots_and_the_selected_namespace() {
+ let _home = HomeGuard::new();
+ let store = RefStore::for_session(Some("owner")).unwrap();
+ assert!(store.retained_object_tokens().unwrap().is_empty());
+ let first = store.save_new_snapshot(&map("host:1")).unwrap();
+ store.save_new_snapshot(&map("host:2")).unwrap();
+ RefStore::for_session(Some("other"))
+ .unwrap()
+ .save_new_snapshot(&map("other:1"))
+ .unwrap();
+ assert_eq!(
+ store.retained_object_tokens().unwrap(),
+ HashSet::from(["host:1".into(), "host:2".into(),])
+ );
+ store.save_snapshot(&first, &RefMap::new()).unwrap();
+ assert_eq!(
+ store.retained_object_tokens().unwrap(),
+ HashSet::from(["host:2".into()])
+ );
+}
+
+#[test]
+fn stray_directory_entries_do_not_count_toward_the_inventory_limit() {
+ let _home = HomeGuard::new();
+ let store = RefStore::new().unwrap();
+ store.save_new_snapshot(&map("host:1")).unwrap();
+ let snapshots = store.base_dir().join("snapshots");
+ for index in 0..MAX_SAVED_SNAPSHOTS {
+ std::fs::create_dir_all(snapshots.join(format!("stray file {index}.json"))).unwrap();
+ }
+ assert_eq!(
+ store.retained_object_tokens().unwrap(),
+ HashSet::from(["host:1".into()])
+ );
+}
+
+#[test]
+fn an_unreadable_snapshot_prevents_a_partial_prune() {
+ let _home = HomeGuard::new();
+ let store = RefStore::new().unwrap();
+ let id = store.save_new_snapshot(&map("host:1")).unwrap();
+ write_private_file(&store.snapshot_path(&id), b"invalid json").unwrap();
+ assert!(store.retained_object_tokens().is_err());
+}
diff --git a/crates/core/src/refs_store_tests.rs b/crates/core/src/refs_store_tests.rs
index c7421e8d3..db2b482f3 100644
--- a/crates/core/src/refs_store_tests.rs
+++ b/crates/core/src/refs_store_tests.rs
@@ -5,7 +5,6 @@ use crate::{
refs::{RefEntry, RefMap},
refs_test_support::HomeGuard,
};
-
fn entry(name: &str) -> RefEntry {
let bounds = crate::Rect {
x: 1.0,
@@ -19,6 +18,7 @@ fn entry(name: &str) -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some(name.into()),
value: None,
diff --git a/crates/core/src/refs_store_transaction_tests.rs b/crates/core/src/refs_store_transaction_tests.rs
index dfb33d7e7..954532895 100644
--- a/crates/core/src/refs_store_transaction_tests.rs
+++ b/crates/core/src/refs_store_transaction_tests.rs
@@ -8,6 +8,7 @@ fn entry(name: &str, root_ref: Option<&str>) -> crate::RefEntry {
process_instance: Some("instance-1".into()),
},
identity: RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some(name.into()),
value: None,
diff --git a/crates/core/src/refs_tests.rs b/crates/core/src/refs_tests.rs
index 36aeb8256..bccf7d974 100644
--- a/crates/core/src/refs_tests.rs
+++ b/crates/core/src/refs_tests.rs
@@ -1,6 +1,5 @@
use super::*;
use crate::refs_test_support::HomeGuard;
-
fn entry(role: &str, name: Option<&str>) -> RefEntry {
RefEntry {
process: crate::RefProcess {
@@ -8,6 +7,7 @@ fn entry(role: &str, name: Option<&str>) -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: role.into(),
name: name.map(String::from),
value: None,
@@ -62,6 +62,7 @@ fn test_get_existing() {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "textfield".into(),
name: None,
value: None,
@@ -255,6 +256,7 @@ fn test_save_load_roundtrip_with_home_override() {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Send".into()),
value: None,
@@ -367,7 +369,6 @@ fn test_write_private_file_ignores_stale_predictable_tmp_symlink() {
std::os::unix::fs::symlink(&target, &stale).unwrap();
write_private_file(&path, b"new").unwrap();
-
assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert_eq!(std::fs::read(&target).unwrap(), b"existing");
let _ = std::fs::remove_dir_all(dir);
@@ -393,7 +394,6 @@ fn test_write_private_file_cleans_tmp_when_rename_fails() {
std::fs::create_dir_all(path.join("child")).unwrap();
let result = write_private_file(&path, b"new");
-
assert!(result.is_err());
assert!(!dir.join("blocked.tmp").exists());
let _ = std::fs::remove_dir_all(dir);
diff --git a/crates/core/src/roles.rs b/crates/core/src/roles.rs
index 2748a06a6..a3f1ca7b8 100644
--- a/crates/core/src/roles.rs
+++ b/crates/core/src/roles.rs
@@ -90,9 +90,11 @@ pub fn is_mutable_value_role(role: &str) -> bool {
crate::Role::from_token(role),
crate::Role::ComboBox
| crate::Role::Checkbox
+ | crate::Role::Handle
| crate::Role::Incrementor
| crate::Role::ListBox
| crate::Role::RadioButton
+ | crate::Role::ScrollBar
| crate::Role::Slider
| crate::Role::Switch
| crate::Role::TextField
diff --git a/crates/core/src/search_text_tests.rs b/crates/core/src/search_text_tests.rs
index 840b1719e..bead62574 100644
--- a/crates/core/src/search_text_tests.rs
+++ b/crates/core/src/search_text_tests.rs
@@ -6,6 +6,7 @@ fn node(name: Option<&str>, value: Option<&str>, description: Option<&str>) -> A
ref_id: None,
role: "textfield".into(),
identity: crate::NodeIdentity {
+ retained_object: None,
name: name.map(String::from),
value: value.map(String::from),
description: description.map(String::from),
diff --git a/crates/core/src/snapshot_ref.rs b/crates/core/src/snapshot_ref.rs
index 11bfed6f5..9522760e1 100644
--- a/crates/core/src/snapshot_ref.rs
+++ b/crates/core/src/snapshot_ref.rs
@@ -141,7 +141,7 @@ fn resolve_result_window(
.list_windows(
&WindowFilter {
focused_only: false,
- app: None,
+ app: entry.source.source_app.clone(),
},
deadline,
)?
diff --git a/crates/core/src/snapshot_ref_tests.rs b/crates/core/src/snapshot_ref_tests.rs
index 0e43f28a1..9170e17b1 100644
--- a/crates/core/src/snapshot_ref_tests.rs
+++ b/crates/core/src/snapshot_ref_tests.rs
@@ -55,6 +55,7 @@ struct StubAdapter {
resolve_calls: AtomicU32,
drops: Arc<AtomicU32>,
windows: Vec<crate::WindowInfo>,
+ expected_app: Option<String>,
}
impl StubAdapter {
@@ -65,6 +66,7 @@ impl StubAdapter {
resolve_calls: AtomicU32::new(0),
drops: Arc::new(AtomicU32::new(0)),
windows: vec![window_info("w-42", true)],
+ expected_app: None,
}
}
@@ -75,6 +77,7 @@ impl StubAdapter {
resolve_calls: AtomicU32::new(0),
drops: Arc::new(AtomicU32::new(0)),
windows,
+ expected_app: None,
}
}
@@ -85,6 +88,7 @@ impl StubAdapter {
resolve_calls: AtomicU32::new(0),
drops: Arc::new(AtomicU32::new(0)),
windows: vec![window_info("w-42", true)],
+ expected_app: None,
}
}
}
@@ -118,9 +122,12 @@ impl ObservationOps for StubAdapter {
fn list_windows(
&self,
- _filter: &crate::adapter::WindowFilter,
+ filter: &crate::adapter::WindowFilter,
_deadline: crate::Deadline,
) -> Result<Vec<crate::WindowInfo>, AdapterError> {
+ if let Some(expected) = &self.expected_app {
+ assert_eq!(filter.app.as_ref(), Some(expected));
+ }
Ok(self.windows.clone())
}
diff --git a/crates/core/src/snapshot_ref_window_tests.rs b/crates/core/src/snapshot_ref_window_tests.rs
index 7f2480f9a..e8fcc96ca 100644
--- a/crates/core/src/snapshot_ref_window_tests.rs
+++ b/crates/core/src/snapshot_ref_window_tests.rs
@@ -19,10 +19,11 @@ fn test_run_from_ref_resolves_source_window_among_same_process_windows() {
let snapshot_id = save_latest(seed_skeleton_refmap_on_window(Some("w-467")));
let subtree = named("button", "Save");
- let adapter = StubAdapter::with_windows(
+ let mut adapter = StubAdapter::with_windows(
subtree,
vec![window_info("w-467", false), window_info("w-475", false)],
);
+ adapter.expected_app = Some("TestApp".into());
let result = run_from_ref(&adapter, &drill_opts(), "@e1", Some(&snapshot_id))
.expect("drill must resolve its own source window, not the process");
diff --git a/crates/core/src/trace_artifacts_tests.rs b/crates/core/src/trace_artifacts_tests.rs
index a844e2a09..9f809a41c 100644
--- a/crates/core/src/trace_artifacts_tests.rs
+++ b/crates/core/src/trace_artifacts_tests.rs
@@ -38,6 +38,7 @@ pub(super) fn entry(pid: u32) -> RefEntry {
process_instance: Some("test-instance".into()),
},
identity: crate::RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Run".into()),
value: None,
diff --git a/crates/ffi/src/actions/resolve.rs b/crates/ffi/src/actions/resolve.rs
index 6b51f1b8e..49aff2842 100644
--- a/crates/ffi/src/actions/resolve.rs
+++ b/crates/ffi/src/actions/resolve.rs
@@ -11,7 +11,6 @@ use agent_desktop_core::{
const MAX_REF_FIELD_BYTES: usize = 65_536;
const MAX_REF_TOKEN_BYTES: usize = 256;
-
/// # Safety
///
/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
@@ -275,6 +274,7 @@ unsafe fn decode_core_ref_entry(
process_instance: Some(process_instance),
},
identity: RefEntryIdentity {
+ retained_object: None,
role,
name,
value,
diff --git a/crates/macos/src/actions/activate_descendant.rs b/crates/macos/src/actions/activate_descendant.rs
index ad8574527..c2d3a41be 100644
--- a/crates/macos/src/actions/activate_descendant.rs
+++ b/crates/macos/src/actions/activate_descendant.rs
@@ -1,3 +1,24 @@
+#[cfg(any(target_os = "macos", test))]
+use crate::actions::chain_delivery::DeliveryOutcome;
+#[cfg(any(target_os = "macos", test))]
+use agent_desktop_core::AdapterError;
+
+#[cfg(any(target_os = "macos", test))]
+fn activate_candidates<T>(
+ children: &[T],
+ mut perform: impl FnMut(&T, &str) -> Result<DeliveryOutcome, AdapterError>,
+) -> Result<DeliveryOutcome, AdapterError> {
+ for child in children {
+ for action in crate::tree::action_list::PRIMARY_ACTIVATION_ACTIONS {
+ let outcome = perform(child, action)?;
+ if outcome.terminates_chain() {
+ return Ok(outcome);
+ }
+ }
+ }
+ Ok(DeliveryOutcome::NotDelivered)
+}
+
#[cfg(target_os = "macos")]
mod imp {
use agent_desktop_core::{AdapterError, Deadline};
@@ -13,10 +34,8 @@ mod imp {
/// which the row accepts and reports back while the application never
/// navigates.
///
- /// Descending is a guess about which child owns the row's behaviour, so
- /// only an observed effect ends the chain here. A child that merely claims
- /// success — Xcode's rows answer that to `AXConfirm` and do nothing — must
- /// not consume the selection step that actually works for them.
+ /// 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(
element: &AXElement,
deadline: Deadline,
@@ -32,16 +51,9 @@ mod imp {
.flatten()
.unwrap_or_default();
- for child in children {
- for action in crate::tree::action_list::PRIMARY_ACTIVATION_ACTIONS {
- let outcome =
- crate::actions::ax_helpers::perform_observed_action(&child, action, deadline)?;
- if outcome.was_verified() {
- return Ok(outcome);
- }
- }
- }
- Ok(DeliveryOutcome::NotDelivered)
+ super::activate_candidates(&children, |child, action| {
+ crate::actions::ax_helpers::perform_observed_action(child, action, deadline)
+ })
}
}
@@ -61,3 +73,40 @@ mod imp {
}
pub(crate) use imp::activate_descendant;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn unverified_descendant_delivery_stops_before_another_action_or_sibling() {
+ let mut attempts = Vec::new();
+ let outcome = activate_candidates(&[1, 2], |child, action| {
+ attempts.push((*child, action.to_owned()));
+ Ok(if attempts.len() == 1 {
+ DeliveryOutcome::NotDelivered
+ } else {
+ DeliveryOutcome::DeliveredUnverified
+ })
+ })
+ .unwrap();
+ assert_eq!(outcome, DeliveryOutcome::DeliveredUnverified);
+ assert_eq!(attempts, [(1, "AXPress".into()), (1, "AXOpen".into())]);
+ }
+
+ #[test]
+ fn unsupported_descendant_actions_can_reach_a_verified_sibling() {
+ let mut attempts = 0;
+ let outcome = activate_candidates(&[1, 2, 3], |child, _| {
+ attempts += 1;
+ Ok(if *child == 2 {
+ DeliveryOutcome::DeliveredVerified
+ } else {
+ DeliveryOutcome::NotDelivered
+ })
+ })
+ .unwrap();
+ assert_eq!(outcome, DeliveryOutcome::DeliveredVerified);
+ assert_eq!(attempts, 4);
+ }
+}
diff --git a/crates/macos/src/actions/activation_effect.rs b/crates/macos/src/actions/activation_effect.rs
index c513fa217..a9f6c5af5 100644
--- a/crates/macos/src/actions/activation_effect.rs
+++ b/crates/macos/src/actions/activation_effect.rs
@@ -18,6 +18,7 @@ mod imp {
pub(crate) struct FocusState {
focused_element: Option<AXElement>,
selected: Option<bool>,
+ menu_open: Option<bool>,
}
/// Accessibility hands back a fresh reference for the same element on every
@@ -57,9 +58,53 @@ mod imp {
)
.ok()
.flatten(),
+ menu_open: owned_menu_open(element, deadline),
})
}
+ fn owned_menu_open(element: &AXElement, deadline: Deadline) -> Option<bool> {
+ use crate::tree::surface_read;
+ let end = crate::tree::locator_deadline::from_operation(deadline).ok()?;
+ let role = surface_read::string(element, "AXRole", end).ok()??;
+ if !matches!(
+ role.as_str(),
+ "AXMenuButton" | "AXPopUpButton" | "AXMenuBarItem" | "AXMenuItem"
+ ) {
+ return None;
+ }
+ let mut complete = true;
+ for child in surface_read::elements(element, "AXChildren", end).ok()? {
+ if surface_read::string(&child, "AXRole", end).ok()?? != "AXMenu" {
+ continue;
+ }
+ let visible = surface_read::boolean(&child, "AXVisible", end).ok()?;
+ let hidden = surface_read::boolean(&child, "AXHidden", end).ok()?;
+ let bounds =
+ crate::tree::element_bounds::read_bounds_with_deadline(&child, end).ok()?;
+ match menu_visibility(visible, hidden, bounds) {
+ Some(true) => return Some(true),
+ Some(false) => {}
+ None => complete = false,
+ }
+ }
+ complete.then_some(false)
+ }
+
+ fn menu_visibility(
+ visible: Option<bool>,
+ hidden: Option<bool>,
+ bounds: Option<agent_desktop_core::Rect>,
+ ) -> Option<bool> {
+ if visible == Some(false) || hidden == Some(true) {
+ return Some(false);
+ }
+ let bounds = bounds?;
+ if bounds.width <= 0.0 || bounds.height <= 0.0 {
+ return Some(false);
+ }
+ (visible == Some(true) || hidden == Some(false)).then_some(true)
+ }
+
pub(crate) fn changed_now(
before: &Option<FocusState>,
element: &AXElement,
@@ -128,7 +173,15 @@ mod imp {
) -> 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)
+ focus_moved_to_target
+ || selection_turned_on(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))
+ )
}
/// An element that was not selected and now is has been acted on, whatever
@@ -152,6 +205,7 @@ mod imp {
Some(FocusState {
focused_element: Some(crate::tree::element_for_pid(pid)),
selected: None,
+ menu_open: None,
})
}
@@ -159,6 +213,7 @@ mod imp {
Some(FocusState {
focused_element: None,
selected: value,
+ menu_open: None,
})
}
@@ -208,6 +263,57 @@ mod imp {
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),
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn menu_verification_requires_visible_nonempty_geometry() {
+ let bounds = agent_desktop_core::Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 100.0,
+ height: 100.0,
+ };
+ assert_eq!(menu_visibility(None, Some(false), Some(bounds)), Some(true));
+ assert_eq!(menu_visibility(Some(true), None, Some(bounds)), Some(true));
+ assert_eq!(menu_visibility(None, None, Some(bounds)), None);
+ assert_eq!(menu_visibility(Some(true), None, None), None);
+ assert_eq!(
+ menu_visibility(Some(false), Some(false), Some(bounds)),
+ Some(false)
+ );
+ assert_eq!(
+ menu_visibility(Some(true), Some(true), Some(bounds)),
+ Some(false)
+ );
+ assert_eq!(
+ menu_visibility(
+ Some(true),
+ Some(false),
+ Some(agent_desktop_core::Rect {
+ width: 0.0,
+ ..bounds
+ })
+ ),
+ Some(false)
+ );
+ }
}
}
diff --git a/crates/macos/src/actions/ax_helpers.rs b/crates/macos/src/actions/ax_helpers.rs
index 433ef20d2..037bd7f0d 100644
--- a/crates/macos/src/actions/ax_helpers.rs
+++ b/crates/macos/src/actions/ax_helpers.rs
@@ -274,8 +274,11 @@ mod imp {
) -> Result<Option<String>, AdapterError> {
use accessibility_sys::kAXRoleAttribute;
prepare(el, deadline)?;
- let role = crate::tree::attributes::copy_string_attr_result(el, kAXRoleAttribute, deadline)
- .map_err(|error| read_failure(kAXRoleAttribute, error))?;
+ let read_deadline = crate::tree::ax_ipc::AxDeadline::absolute(deadline)?;
+ let role = crate::tree::read_recovery::read(read_deadline, || {
+ crate::tree::attributes::copy_string_attr_result(el, kAXRoleAttribute, read_deadline)
+ })
+ .map_err(|error| read_failure(kAXRoleAttribute, error))?;
ensure_read_finished(deadline)?;
Ok(role.map(|role| crate::tree::roles::ax_role_to_str(&role).to_string()))
}
diff --git a/crates/macos/src/actions/chain_disclosure_steps.rs b/crates/macos/src/actions/chain_disclosure_steps.rs
index 7828daa38..30e461cb9 100644
--- a/crates/macos/src/actions/chain_disclosure_steps.rs
+++ b/crates/macos/src/actions/chain_disclosure_steps.rs
@@ -125,7 +125,21 @@ mod imp {
if let Some(value) = crate::tree::surface_read::boolean(element, "AXExpanded", instant)? {
return Ok(Some(value));
}
- crate::tree::surface_read::boolean(element, "AXDisclosing", instant)
+ if let Some(value) = crate::tree::surface_read::boolean(element, "AXDisclosing", instant)? {
+ return Ok(Some(value));
+ }
+ let role = crate::tree::surface_read::string(element, "AXRole", instant)?;
+ if role.as_deref() != Some("AXDisclosureTriangle") {
+ return Ok(None);
+ }
+ let value = crate::tree::attributes::copy_value_typed_result(element, deadline).map_err(
+ |error| crate::tree::query::read_error::semantic_read(error, "disclosure.value"),
+ )?;
+ Ok(crate::tree::state_reader::expanded_state(
+ role.as_deref(),
+ None,
+ value.as_deref(),
+ ))
}
fn prepare(element: &AXElement, deadline: Deadline) -> Result<(), AdapterError> {
diff --git a/crates/macos/src/actions/container_select.rs b/crates/macos/src/actions/container_select.rs
index db7ddeef1..628ca559c 100644
--- a/crates/macos/src/actions/container_select.rs
+++ b/crates/macos/src/actions/container_select.rs
@@ -8,6 +8,25 @@ pub(crate) fn role_activates_by_selection(role: &str) -> bool {
)
}
+#[cfg(any(target_os = "macos", test))]
+fn verify_selection(
+ delivered: bool,
+ verify: impl FnOnce() -> bool,
+) -> Result<bool, agent_desktop_core::AdapterError> {
+ if !delivered {
+ return Ok(false);
+ }
+ if verify() {
+ return Ok(true);
+ }
+ Err(agent_desktop_core::AdapterError::new(
+ agent_desktop_core::ErrorCode::ActionFailed,
+ "Selection was delivered but its effect could not be verified",
+ )
+ .with_disposition(agent_desktop_core::DeliverySemantics::delivered_unverified())
+ .with_suggestion("Inspect the selection before deciding whether to act again."))
+}
+
#[cfg(target_os = "macos")]
mod imp {
use agent_desktop_core::{AdapterError, Deadline};
@@ -110,8 +129,11 @@ mod imp {
if !crate::actions::ax_helpers::is_attr_settable(member, SELECTED, deadline)? {
return Ok(false);
}
- crate::actions::ax_helpers::set_ax_bool_or_err(member, SELECTED, true, deadline)?;
- Ok(crate::tree::attributes::copy_bool_attr(member, SELECTED, deadline) == Some(true))
+ let delivered =
+ crate::actions::ax_helpers::set_ax_bool_or_err(member, SELECTED, true, deadline)?;
+ super::verify_selection(delivered, || {
+ crate::tree::attributes::copy_bool_attr(member, SELECTED, deadline) == Some(true)
+ })
}
fn select_member_in_container(
@@ -131,9 +153,15 @@ mod imp {
members.as_CFTypeRef(),
deadline,
)?;
- if error == accessibility_sys::kAXErrorSuccess
- && holds_selection(container, member, attribute, deadline)
- {
+ let delivered = crate::actions::ax_mutation::classify_result(
+ container,
+ attribute,
+ "AXUIElementSetAttributeValue",
+ error,
+ )?;
+ if super::verify_selection(delivered, || {
+ holds_selection(container, member, attribute, deadline)
+ })? {
return Ok(true);
}
}
@@ -250,4 +278,34 @@ mod tests {
assert!(!role_activates_by_selection(role));
}
}
+
+ #[test]
+ fn accepted_selection_with_failed_readback_never_authorizes_another_write() {
+ let mut attempts = 0;
+ let result: Result<bool, agent_desktop_core::AdapterError> = (|| {
+ for verified in [false, true] {
+ attempts += 1;
+ if super::verify_selection(true, || verified)? {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+ })();
+ let error = result.unwrap_err();
+ assert_eq!(attempts, 1);
+ assert_eq!(
+ error.disposition,
+ agent_desktop_core::DeliverySemantics::delivered_unverified()
+ );
+ assert_eq!(
+ error.disposition.retry(),
+ agent_desktop_core::RetryDisposition::Unsafe
+ );
+ }
+
+ #[test]
+ fn unsupported_selection_skips_readback_and_verified_selection_succeeds() {
+ assert!(!super::verify_selection(false, || panic!("not delivered")).unwrap());
+ assert!(super::verify_selection(true, || true).unwrap());
+ }
}
diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs
index ac7182dd1..1d15db73e 100644
--- a/crates/macos/src/actions/mod.rs
+++ b/crates/macos/src/actions/mod.rs
@@ -29,6 +29,8 @@ pub(crate) mod scroll;
pub(crate) mod scroll_into_view;
mod scroll_read;
pub(crate) mod select_menu;
+mod select_name;
+mod select_search;
pub(crate) mod toggle_state;
pub(crate) mod type_text;
diff --git a/crates/macos/src/actions/post_state.rs b/crates/macos/src/actions/post_state.rs
index aa9903016..349fad1b6 100644
--- a/crates/macos/src/actions/post_state.rs
+++ b/crates/macos/src/actions/post_state.rs
@@ -2,9 +2,8 @@ use agent_desktop_core::{
AdapterError, Deadline, ElementState, ErrorCode, EvidenceRequirements, LiveElement,
LiveIdentity, LocatorField, Rect,
};
-use std::time::Instant;
-use crate::tree::AXElement;
+use crate::tree::{AXElement, element_bounds::ancestor_viewport};
pub(crate) fn read_element_state(
element: &AXElement,
@@ -13,12 +12,7 @@ pub(crate) fn read_element_state(
let read = read_live_observation(element, deadline)?;
let attrs = read.attrs;
let role = known_role(&read.evidence.role)?;
- element_state_from_attrs(
- element,
- attrs,
- role,
- owning_window_bounds(element, deadline)?,
- )
+ element_state_from_attrs(element, attrs, role, ancestor_viewport(element, deadline)?)
}
pub(crate) fn read_live_element(
@@ -35,13 +29,8 @@ pub(crate) fn read_live_element(
let available_actions = known_actions(read.evidence.ref_evidence.available_actions)?;
let attrs = read.attrs;
let bounds = attrs.bounds;
- let expanded_observed = attrs
- .states
- .control
- .expanded
- .or(attrs.states.control.disclosing)
- .is_some();
- let window_bounds = owning_window_bounds(element, deadline)?;
+ let expanded_observed = crate::tree::state_reader::expanded_from_attrs(&attrs).is_some();
+ let window_bounds = ancestor_viewport(element, deadline)?;
let state = element_state_from_attrs(element, attrs, role, window_bounds)?;
Ok(LiveElement {
identity,
@@ -62,6 +51,50 @@ pub(crate) fn read_live_actions(
fn read_live_observation(
element: &AXElement,
deadline: Deadline,
+) -> Result<crate::tree::query::node_read::NodeRead, AdapterError> {
+ read_observation_with_recovery(deadline, || read_live_observation_once(element, deadline))
+}
+
+fn read_observation_with_recovery<T>(
+ deadline: Deadline,
+ mut read: impl FnMut() -> Result<T, AdapterError>,
+) -> Result<T, AdapterError> {
+ for attempt in 0..3 {
+ if deadline.is_expired() {
+ return Err(deadline.timeout_error());
+ }
+ match read() {
+ Err(error) if attempt < 2 && transient_observation_failure(&error) => {
+ if deadline.is_expired() {
+ return Err(error);
+ }
+ std::thread::sleep(
+ deadline
+ .remaining()
+ .min(std::time::Duration::from_millis(1)),
+ );
+ }
+ result => return result,
+ }
+ }
+ Err(deadline.timeout_error())
+}
+
+fn transient_observation_failure(error: &AdapterError) -> bool {
+ error.code == ErrorCode::AppUnresponsive
+ && error.permits_retry_by_default()
+ && error.details.as_ref().is_some_and(|details| {
+ details["kind"] == "live_element_evidence"
+ && details
+ .pointer("/query_stats/reads/cannot_complete")
+ .and_then(serde_json::Value::as_u64)
+ .is_some_and(|failures| failures > 0)
+ })
+}
+
+fn read_live_observation_once(
+ element: &AXElement,
+ deadline: Deadline,
) -> Result<crate::tree::query::node_read::NodeRead, AdapterError> {
let mut usage = new_usage();
if !usage.claim_node() {
@@ -70,14 +103,14 @@ fn read_live_observation(
let mut stats = agent_desktop_core::LocatorStats::default();
let child_plan =
crate::tree::query::child_read_plan::ChildReadPlan::load(usage.child_capacity());
- let read = crate::tree::query::node_read::read_node(
+ let mut read = crate::tree::query::node_read::read_node(
element,
crate::tree::query::node_read_context::NodeReadContext {
tree: &crate::tree::TreeBuildContext::empty(false),
stats: &mut stats,
usage: &mut usage,
requirements: EvidenceRequirements::snapshot(),
- deadline: deadline_instant(deadline)?,
+ deadline: crate::tree::locator_deadline::from_operation(deadline)?,
child_plan,
},
)?;
@@ -98,6 +131,8 @@ fn read_live_observation(
"query_stats": stats,
})));
}
+ read.attrs.states.semantic.hidden =
+ hidden_state(read.attrs.states.semantic.hidden, &read.evidence.states);
Ok(read)
}
@@ -113,34 +148,6 @@ fn new_usage() -> crate::tree::observation_usage::ObservationUsage {
crate::tree::observation_usage::ObservationUsage::with_defaults()
}
-fn owning_window_bounds(
- element: &AXElement,
- deadline: Deadline,
-) -> Result<Option<Rect>, AdapterError> {
- crate::tree::attributes::set_messaging_timeout(element, deadline)?;
- let window = first_owning_container(|attribute| {
- crate::tree::attributes::copy_element_attr_result(element, attribute, deadline)
- })
- .map_err(|(attribute, error)| read_error(attribute, error))?;
- if deadline.is_expired() {
- return Err(deadline.timeout_error());
- }
- let Some(window) = window else {
- return Ok(None);
- };
- crate::tree::element_bounds::read_bounds_with_deadline(&window, deadline_instant(deadline)?)
-}
-
-/// The viewport an element is clipped by. `AXTopLevelUIElement` is not a
-/// substitute: for menu content it resolves to the menu bar, a 29-point strip
-/// that reports every open menu item as offscreen. An element with no window is
-/// drawn on its own surface, so its clipping viewport is simply unknown.
-fn first_owning_container(
- mut read: impl FnMut(&'static str) -> Result<Option<AXElement>, i32>,
-) -> Result<Option<AXElement>, (&'static str, i32)> {
- read("AXWindow").map_err(|error| ("AXWindow", error))
-}
-
fn known_role(role: &LocatorField<String>) -> Result<String, AdapterError> {
role.known().cloned().ok_or_else(incomplete_live_evidence)
}
@@ -195,7 +202,7 @@ fn element_state_from_attrs(
};
let states = crate::tree::state_reader::states_from_element(element, &attrs, &role, &context);
let enabled = Some(attrs.states.enabled);
- let hidden = hidden_state(attrs.states.semantic.hidden);
+ let hidden = attrs.states.semantic.hidden;
let offscreen = crate::tree::state_reader::offscreen(attrs.bounds, window_bounds);
Ok(ElementState {
role,
@@ -207,8 +214,14 @@ fn element_state_from_attrs(
})
}
-fn hidden_state(reported: Option<bool>) -> Option<bool> {
- reported
+fn hidden_state(reported: Option<bool>, canonical: &LocatorField<Vec<String>>) -> Option<bool> {
+ reported.or_else(|| match canonical {
+ LocatorField::Known(states) => Some(agent_desktop_core::state::has_state(
+ states,
+ agent_desktop_core::state::HIDDEN,
+ )),
+ _ => None,
+ })
}
#[cfg(test)]
@@ -219,32 +232,6 @@ fn normalized_role(ax_role: Option<&str>, ax_subrole: Option<&str>) -> String {
.to_string()
}
-fn deadline_instant(deadline: Deadline) -> Result<Instant, AdapterError> {
- let remaining = deadline.remaining();
- if remaining.is_zero() {
- return Err(deadline.timeout_error());
- }
- Instant::now()
- .checked_add(remaining)
- .ok_or_else(|| AdapterError::new(ErrorCode::InvalidArgs, "Deadline is out of range"))
-}
-
-fn read_error(attribute: &str, error: i32) -> AdapterError {
- AdapterError::new(
- if error == accessibility_sys::kAXErrorCannotComplete {
- ErrorCode::Timeout
- } else if error == accessibility_sys::kAXErrorAPIDisabled {
- ErrorCode::PermDenied
- } else if error == accessibility_sys::kAXErrorInvalidUIElement {
- ErrorCode::StaleRef
- } else {
- ErrorCode::ActionFailed
- },
- format!("Could not read {attribute} for live state"),
- )
- .with_details(serde_json::json!({ "attribute": attribute, "ax_error": error }))
-}
-
#[cfg(test)]
#[path = "post_state_tests.rs"]
mod tests;
diff --git a/crates/macos/src/actions/post_state_tests.rs b/crates/macos/src/actions/post_state_tests.rs
index 0bf93d72e..109910a93 100644
--- a/crates/macos/src/actions/post_state_tests.rs
+++ b/crates/macos/src/actions/post_state_tests.rs
@@ -1,6 +1,65 @@
use super::*;
use crate::tree::{node_attr_states::NodeAttrStates, node_attrs::NodeAttrs};
+fn transient_observation_error() -> AdapterError {
+ incomplete_live_evidence().with_details(serde_json::json!({
+ "kind": "live_element_evidence",
+ "retryable": true,
+ "query_stats": { "reads": { "cannot_complete": 1 } }
+ }))
+}
+
+#[test]
+fn live_observation_recovers_transient_native_reads_without_mutation() {
+ let mut reads = 0;
+ let result = read_observation_with_recovery(Deadline::after(5_000).unwrap(), || {
+ reads += 1;
+ if reads < 3 {
+ Err(transient_observation_error())
+ } else {
+ Ok("observed")
+ }
+ })
+ .unwrap();
+ assert_eq!(result, "observed");
+ assert_eq!(reads, 3);
+}
+
+#[test]
+fn live_observation_recovery_is_bounded_and_preserves_terminal_errors() {
+ for (error, expected_reads) in [
+ (transient_observation_error(), 3),
+ (AdapterError::permission_denied(), 1),
+ (AdapterError::stale_ref("replaced"), 1),
+ (incomplete_live_evidence(), 1),
+ (
+ transient_observation_error().with_details(serde_json::json!({
+ "kind": "live_element_evidence",
+ "retryable": false,
+ "query_stats": { "reads": { "cannot_complete": 1 } }
+ })),
+ 1,
+ ),
+ ] {
+ let mut reads = 0;
+ let result = read_observation_with_recovery::<()>(Deadline::after(5_000).unwrap(), || {
+ reads += 1;
+ Err(error.clone())
+ })
+ .unwrap_err();
+ assert_eq!(reads, expected_reads);
+ assert_eq!(result.code, error.code);
+ assert_eq!(result.details, error.details);
+ }
+}
+
+#[test]
+fn expired_live_observation_budget_never_calls_native_reader() {
+ let deadline = Deadline::after(0).unwrap();
+ let result = read_observation_with_recovery::<()>(deadline, || panic!("expired read"));
+ assert_eq!(result.unwrap_err().code, ErrorCode::Timeout);
+}
+
fn attrs_with_bounds(bounds: Rect) -> NodeAttrs {
NodeAttrs {
role: Some("AXButton".into()),
@@ -88,45 +147,36 @@ fn secure_subrole_never_exposes_its_value() {
#[test]
fn element_visibility_preserves_live_hidden_evidence_for_every_role() {
- assert_eq!(hidden_state(None), None);
- assert_eq!(hidden_state(Some(false)), Some(false));
- assert_eq!(hidden_state(Some(true)), Some(true));
-}
-
-/// A menu item's `AXTopLevelUIElement` is the menu bar, whose 29-point height
-/// clips every open menu item. A window-less element therefore reports no
-/// clipping viewport rather than a wrong one.
-#[test]
-fn a_window_less_element_reports_no_clipping_viewport() {
- let mut attributes = Vec::new();
- let container = first_owning_container(|attribute| {
- attributes.push(attribute);
- Ok(None)
- })
- .unwrap();
-
- assert!(container.is_none());
- assert_eq!(attributes, ["AXWindow"]);
+ for canonical in [LocatorField::Unknown, LocatorField::Absent] {
+ assert_eq!(hidden_state(None, &canonical), None);
+ assert_eq!(hidden_state(Some(false), &canonical), Some(false));
+ assert_eq!(hidden_state(Some(true), &canonical), Some(true));
+ }
}
#[test]
-fn incomplete_window_read_never_falls_through_to_a_weaker_container() {
- for error in [
- accessibility_sys::kAXErrorCannotComplete,
- accessibility_sys::kAXErrorInvalidUIElement,
- ] {
- let calls = std::cell::Cell::new(0);
- let result = first_owning_container(|_| {
- calls.set(calls.get() + 1);
- Err(error)
+fn complete_visibility_evidence_does_not_require_an_expanded_attribute() {
+ let el = crate::tree::AXElement(std::ptr::null_mut());
+ let bounds = Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 28.0,
+ height: 28.0,
+ };
+ for hidden in [false, true] {
+ let mut attrs = attrs_with_bounds(bounds);
+ attrs.role = Some("AXMenuButton".into());
+ let canonical = LocatorField::Known(if hidden {
+ vec![agent_desktop_core::state::HIDDEN.into()]
+ } else {
+ Vec::new()
});
-
- let failure = match result {
- Err(failure) => failure,
- Ok(_) => panic!("incomplete AXWindow read must fail"),
- };
- assert_eq!(failure, ("AXWindow", error));
- assert_eq!(calls.get(), 1);
+ attrs.states.semantic.hidden = hidden_state(None, &canonical);
+ let state =
+ element_state_from_attrs(&el, attrs, "menubutton".into(), Some(bounds)).unwrap();
+ assert_eq!(state.hidden, Some(hidden));
+ assert_eq!(state.offscreen, Some(false));
+ assert!(!states_are_complete(&state, false));
}
}
diff --git a/crates/macos/src/actions/scroll.rs b/crates/macos/src/actions/scroll.rs
index efee995b6..5b75eec9b 100644
--- a/crates/macos/src/actions/scroll.rs
+++ b/crates/macos/src/actions/scroll.rs
@@ -232,7 +232,7 @@ fn try_sub_elements(
Ok(false)
}
-fn find_scroll_area(
+pub(crate) fn find_scroll_area(
element: &AXElement,
deadline: Deadline,
) -> Result<Option<AXElement>, AdapterError> {
diff --git a/crates/macos/src/actions/scroll_into_view.rs b/crates/macos/src/actions/scroll_into_view.rs
index 85be29787..34ad88709 100644
--- a/crates/macos/src/actions/scroll_into_view.rs
+++ b/crates/macos/src/actions/scroll_into_view.rs
@@ -36,9 +36,17 @@ mod imp {
) -> Result<DeliveryOutcome, AdapterError> {
let mut delivery = crate::actions::DeliveryTracker::default();
for attempt in 0..MAX_ANCESTOR_SCROLLS {
- let Some(direction) =
- direction_to_window(element, deadline).map_err(|error| delivery.annotate(error))?
+ let Some(direction) = direction_to_viewport(element, deadline)
+ .map_err(|error| delivery.annotate(error))?
else {
+ if !visible_through_ancestors(element, deadline)
+ .map_err(|error| delivery.annotate(error))?
+ {
+ return Err(delivery.annotate(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "Target remains clipped or its visible bounds are unknown",
+ )));
+ }
return Ok(if attempt == 0 {
DeliveryOutcome::SatisfiedNoDelivery
} else {
@@ -70,21 +78,25 @@ mod imp {
.with_disposition(DeliverySemantics::delivered_unverified()))
}
- fn direction_to_window(
+ fn direction_to_viewport(
element: &AXElement,
deadline: Deadline,
) -> Result<Option<Direction>, AdapterError> {
let instant = crate::tree::locator_deadline::from_operation(deadline)?;
let bounds = crate::tree::element_bounds::read_bounds_with_deadline(element, instant)?
.ok_or_else(|| AdapterError::new(ErrorCode::ActionFailed, "Target has no bounds"))?;
- let window = require_window(crate::tree::surface_read::element(
- element, "AXWindow", instant,
- )?)?;
- let window_bounds = crate::tree::element_bounds::read_bounds_with_deadline(
- &window, instant,
- )?
- .ok_or_else(|| AdapterError::new(ErrorCode::ActionFailed, "Target window has no bounds"))?;
- Ok(direction_for_visibility(bounds, window_bounds))
+ let viewport = match crate::actions::scroll::find_scroll_area(element, deadline)? {
+ Some(viewport) => viewport,
+ None => require_window(crate::tree::surface_read::element(
+ element, "AXWindow", instant,
+ )?)?,
+ };
+ let viewport_bounds =
+ crate::tree::element_bounds::read_bounds_with_deadline(&viewport, instant)?
+ .ok_or_else(|| {
+ AdapterError::new(ErrorCode::ActionFailed, "Target viewport has no bounds")
+ })?;
+ Ok(direction_for_visibility(bounds, viewport_bounds))
}
pub(super) fn require_window(window: Option<AXElement>) -> Result<AXElement, AdapterError> {
@@ -125,7 +137,7 @@ mod imp {
}
let local_end = Instant::now() + Duration::from_millis(800);
loop {
- if visible_in_window(element, deadline).map_err(after_delivery)? {
+ if visible_through_ancestors(element, deadline).map_err(after_delivery)? {
return Ok(DeliveryOutcome::DeliveredVerified);
}
if deadline.is_expired() {
@@ -182,22 +194,17 @@ mod imp {
.with_suggestion("Inspect target visibility before deciding whether to scroll again.")
}
- fn visible_in_window(element: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {
- let instant = crate::tree::locator_deadline::from_operation(deadline)?;
- let Some(bounds) =
- crate::tree::element_bounds::read_bounds_with_deadline(element, instant)?
- else {
- return Ok(false);
- };
- let Some(window) = crate::tree::surface_read::element(element, "AXWindow", instant)? else {
- return Ok(false);
- };
- let Some(window_bounds) =
- crate::tree::element_bounds::read_bounds_with_deadline(&window, instant)?
- else {
+ fn visible_through_ancestors(
+ element: &AXElement,
+ deadline: Deadline,
+ ) -> Result<bool, AdapterError> {
+ if crate::actions::scroll_read::element(element, "AXWindow", deadline)?.is_none() {
return Ok(false);
- };
- Ok(rect_has_area(bounds) && intersects(bounds, window_bounds))
+ }
+ Ok(
+ crate::tree::hit_test::visible_bounds_ax_element(element, deadline)?
+ .is_some_and(rect_has_area),
+ )
}
pub(crate) fn rect_has_area(rect: Rect) -> bool {
@@ -209,13 +216,6 @@ mod imp {
&& rect.height > 0.0
}
- pub(crate) fn intersects(left: Rect, right: Rect) -> bool {
- left.x < right.x + right.width
- && left.x + left.width > right.x
- && left.y < right.y + right.height
- && left.y + left.height > right.y
- }
-
fn prepare(element: &AXElement, deadline: Deadline) -> Result<(), AdapterError> {
crate::tree::attributes::set_messaging_timeout(element, deadline)
}
@@ -244,7 +244,7 @@ pub(crate) use imp::scroll_into_view_impl;
pub(crate) use imp::scroll_into_view_outcome;
#[cfg(all(test, target_os = "macos"))]
-pub(crate) use imp::{direction_for_visibility, intersects, rect_has_area, scroll_effect_observed};
+pub(crate) use imp::{direction_for_visibility, rect_has_area, scroll_effect_observed};
#[cfg(all(test, target_os = "macos"))]
#[path = "scroll_into_view_tests.rs"]
diff --git a/crates/macos/src/actions/scroll_into_view_tests.rs b/crates/macos/src/actions/scroll_into_view_tests.rs
index 9c8510c32..6c4bb6da4 100644
--- a/crates/macos/src/actions/scroll_into_view_tests.rs
+++ b/crates/macos/src/actions/scroll_into_view_tests.rs
@@ -1,6 +1,6 @@
use agent_desktop_core::{Direction, Rect};
-use super::{direction_for_visibility, intersects, rect_has_area, scroll_effect_observed};
+use super::{direction_for_visibility, rect_has_area, scroll_effect_observed};
fn rect(x: f64, y: f64, width: f64, height: f64) -> Rect {
Rect {
@@ -20,17 +20,6 @@ fn area_requires_finite_positive_dimensions_and_coordinates() {
assert!(!rect_has_area(rect(0.0, 0.0, f64::INFINITY, 10.0)));
}
-#[test]
-fn intersection_requires_positive_overlapping_area() {
- let window = rect(0.0, 0.0, 100.0, 100.0);
-
- assert!(intersects(rect(10.0, 10.0, 20.0, 20.0), window));
- assert!(intersects(rect(90.0, 90.0, 20.0, 20.0), window));
- assert!(intersects(rect(80.0, 10.0, 20.0, 20.0), window));
- assert!(!intersects(rect(101.0, 10.0, 20.0, 20.0), window));
- assert!(!intersects(rect(100.0, 10.0, 20.0, 20.0), window));
-}
-
#[test]
fn offscreen_direction_uses_global_viewport_edges() {
let viewport = rect(1496.0, 87.0, 1496.0, 937.0);
@@ -46,6 +35,19 @@ fn offscreen_direction_uses_global_viewport_edges() {
assert!(direction_for_visibility(rect(1500.0, 100.0, 73.0, 24.0), viewport).is_none());
}
+#[test]
+fn nested_viewport_requires_scrolling_even_inside_window() {
+ let target = rect(370.0, 466.0, 202.0, 32.0);
+ let window = rect(300.0, 135.0, 500.0, 632.0);
+ let viewport = rect(350.0, 617.0, 300.0, 100.0);
+
+ assert!(direction_for_visibility(target, window).is_none());
+ assert!(matches!(
+ direction_for_visibility(target, viewport),
+ Some(Direction::Up)
+ ));
+}
+
#[test]
fn final_scroll_read_timeout_does_not_claim_safe_non_delivery() {
let error = agent_desktop_core::AdapterError::timeout("final bounds read")
diff --git a/crates/macos/src/actions/select_menu.rs b/crates/macos/src/actions/select_menu.rs
index 35e99b2de..e574b8fb1 100644
--- a/crates/macos/src/actions/select_menu.rs
+++ b/crates/macos/src/actions/select_menu.rs
@@ -1,5 +1,6 @@
use agent_desktop_core::{AdapterError, Deadline, DeliverySemantics, ErrorCode};
+use super::select_search::SelectSearch;
use crate::tree::AXElement;
const MAX_SELECT_NODES: usize = 2_048;
@@ -81,7 +82,9 @@ pub(crate) fn select_collection_item(
value: &str,
deadline: Deadline,
) -> Result<bool, AdapterError> {
- let Some(candidate) = find_named_descendant(element, value, deadline)? else {
+ let Some(candidate) =
+ find_named_descendant(element, value, deadline, SelectSearch::Collection)?
+ else {
return Err(AdapterError::new(
ErrorCode::ElementNotFound,
format!(
@@ -89,7 +92,8 @@ pub(crate) fn select_collection_item(
value.chars().count()
),
)
- .with_suggestion("Use find to inspect the collection's available items."));
+ .with_suggestion("Use find to inspect the collection's available items.")
+ .with_disposition(DeliverySemantics::not_delivered()));
};
select_collection_candidate(&candidate, deadline)
}
@@ -117,7 +121,8 @@ fn select_open_menu_item(
));
}
if let Some(menu) = menu_root(pid, deadline)?
- && let Some(candidate) = find_named_descendant(&menu, value, deadline)?
+ && let Some(candidate) =
+ find_named_descendant(&menu, value, deadline, SelectSearch::MenuItem)?
{
let verified = activate_menu_item(&candidate, deadline)?;
return if verified {
@@ -142,9 +147,11 @@ fn find_named_descendant(
root: &AXElement,
value: &str,
deadline: Deadline,
+ search: SelectSearch,
) -> Result<Option<AXElement>, AdapterError> {
let mut stack = vec![(root.clone(), 0_u8)];
let mut visited = 0_usize;
+ let mut selected: Option<AXElement> = None;
while let Some((candidate, depth)) = stack.pop() {
visited = visited.saturating_add(1);
if visited > MAX_SELECT_NODES {
@@ -159,37 +166,60 @@ fn find_named_descendant(
})));
}
let instant = crate::tree::locator_deadline::from_operation(deadline)?;
- if candidate_matches(&candidate, value, instant)? {
- return Ok(Some(candidate));
+ match search {
+ SelectSearch::Collection => {
+ if let Some(target) =
+ super::select_name::collection_target(&candidate, root, value, instant)?
+ {
+ if selected.as_ref().is_some_and(|previous| {
+ !crate::tree::capabilities::same_element(previous, &target)
+ }) {
+ return Err(AdapterError::ambiguous_target(
+ "More than one collection item matched the requested value",
+ )
+ .with_disposition(DeliverySemantics::not_delivered()));
+ }
+ selected = Some(target);
+ }
+ }
+ SelectSearch::MenuItem => {
+ if super::select_name::matches(&candidate, value, instant)? {
+ return Ok(Some(candidate));
+ }
+ }
}
- if depth >= MAX_SELECT_DEPTH {
- continue;
- }
- let instant = crate::tree::locator_deadline::from_operation(deadline)?;
+ let children = boundary_children(depth, search, || {
+ crate::tree::surface_read::elements(&candidate, "AXChildren", instant)
+ })?;
stack.extend(
- crate::tree::surface_read::elements(&candidate, "AXChildren", instant)?
+ children
.into_iter()
.rev()
.map(|child| (child, depth.saturating_add(1))),
);
}
- Ok(None)
+ Ok(selected)
}
-fn candidate_matches(
- candidate: &AXElement,
- value: &str,
- deadline: std::time::Instant,
-) -> Result<bool, AdapterError> {
- for attribute in ["AXTitle", "AXDescription"] {
- if crate::tree::surface_read::string(candidate, attribute, deadline)?
- .as_deref()
- .is_some_and(|text| text.eq_ignore_ascii_case(value))
- {
- return Ok(true);
- }
+fn boundary_children(
+ depth: u8,
+ search: SelectSearch,
+ read: impl FnOnce() -> Result<Vec<AXElement>, AdapterError>,
+) -> Result<Vec<AXElement>, AdapterError> {
+ if depth < MAX_SELECT_DEPTH {
+ return read();
+ }
+ if matches!(search, SelectSearch::MenuItem) {
+ return Ok(Vec::new());
+ }
+ if read()?.is_empty() {
+ return Ok(Vec::new());
}
- Ok(false)
+ Err(AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Collection selection search exceeded its depth budget",
+ )
+ .with_disposition(DeliverySemantics::not_delivered()))
}
fn activate_menu_item(candidate: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {
@@ -202,7 +232,13 @@ fn select_collection_candidate(
) -> Result<bool, AdapterError> {
deliver_candidate(
true,
- || select_candidate_attribute(candidate, deadline),
+ || {
+ use super::chain_delivery::DeliveryOutcome;
+ match super::container_select::select_within_container(candidate, deadline)? {
+ DeliveryOutcome::NotDelivered => Ok(None),
+ outcome => Ok(Some(outcome.was_verified())),
+ }
+ },
|| press_candidate(candidate, deadline),
)
}
@@ -235,38 +271,6 @@ fn deliver_candidate(
.with_disposition(DeliverySemantics::not_delivered()))
}
-fn select_candidate_attribute(
- candidate: &AXElement,
- deadline: Deadline,
-) -> Result<Option<bool>, AdapterError> {
- prepare(candidate, deadline)?;
- if !crate::actions::ax_helpers::is_attr_settable(candidate, "AXSelected", deadline)? {
- return Ok(None);
- }
- prepare(candidate, deadline)?;
- if !crate::actions::ax_helpers::set_ax_bool_or_err(candidate, "AXSelected", true, deadline)? {
- return Ok(None);
- }
- let instant =
- crate::tree::locator_deadline::from_operation(deadline).map_err(after_menu_delivery)?;
- let observed = crate::tree::surface_read::boolean(candidate, "AXSelected", instant)
- .map_err(after_menu_delivery)?;
- selected_readback(observed).map(Some)
-}
-
-fn selected_readback(observed: Option<bool>) -> Result<bool, AdapterError> {
- match observed {
- Some(false) => Err(AdapterError::new(
- ErrorCode::ActionFailed,
- "AXSelected write completed but the item remained unselected",
- )
- .with_disposition(DeliverySemantics::delivered_unverified())
- .with_suggestion("Inspect the selection before deciding whether to retry.")),
- Some(true) => Ok(true),
- None => Ok(false),
- }
-}
-
fn press_candidate(candidate: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {
prepare(candidate, deadline)?;
crate::actions::ax_helpers::try_ax_action_or_err(candidate, "AXPress", deadline)
diff --git a/crates/macos/src/actions/select_menu_tests.rs b/crates/macos/src/actions/select_menu_tests.rs
index 8af162557..65961fc43 100644
--- a/crates/macos/src/actions/select_menu_tests.rs
+++ b/crates/macos/src/actions/select_menu_tests.rs
@@ -76,13 +76,3 @@ fn uncertain_collection_selection_never_falls_back_to_press() {
assert_eq!(presses.get(), 0);
}
}
-
-#[test]
-fn selected_readback_distinguishes_contradiction_from_missing_evidence() {
- assert_eq!(
- selected_readback(Some(false)).unwrap_err().disposition,
- DeliverySemantics::delivered_unverified()
- );
- assert!(selected_readback(Some(true)).unwrap());
- assert!(!selected_readback(None).unwrap());
-}
diff --git a/crates/macos/src/actions/select_name.rs b/crates/macos/src/actions/select_name.rs
new file mode 100644
index 000000000..ac966811e
--- /dev/null
+++ b/crates/macos/src/actions/select_name.rs
@@ -0,0 +1,280 @@
+use agent_desktop_core::{AdapterError, ErrorCode, EvidenceRequirements, LocatorEvidence};
+
+pub(crate) fn collection_target(
+ element: &crate::tree::AXElement,
+ root: &crate::tree::AXElement,
+ value: &str,
+ deadline: std::time::Instant,
+) -> Result<Option<crate::tree::AXElement>, AdapterError> {
+ let (read, stats) = candidate_read(element, deadline)?;
+ let named = evidence_matches(&read.evidence, value, stats)?;
+ if !named && !text_value_matches(element, &read.attrs, value, deadline)? {
+ return Ok(None);
+ }
+ collection_owner(
+ element,
+ root,
+ named,
+ |node| {
+ Ok((
+ crate::tree::surface_read::string(node, "AXRole", deadline)?,
+ crate::tree::surface_read::element(node, "AXParent", deadline)?,
+ ))
+ },
+ crate::tree::capabilities::same_element,
+ )
+}
+
+fn collection_owner<T: Clone>(
+ element: &T,
+ root: &T,
+ named: bool,
+ mut read: impl FnMut(&T) -> Result<(Option<String>, Option<T>), AdapterError>,
+ same: impl Fn(&T, &T) -> bool,
+) -> Result<Option<T>, AdapterError> {
+ let mut selectable = None;
+ let mut row = None;
+ let mut current = element.clone();
+ for _ in 0..8 {
+ if same(&current, root) {
+ return Ok(row.or(selectable));
+ }
+ let (role, parent) = read(&current)?;
+ if row.is_none() && role.as_deref() == Some("AXRow") {
+ row = Some(current.clone());
+ }
+ if role.as_deref().is_some_and(|role| {
+ super::container_select::role_activates_by_selection(
+ crate::tree::roles::ax_role_to_str(role),
+ )
+ }) {
+ selectable.get_or_insert_with(|| current.clone());
+ } else if named
+ && selectable.is_none()
+ && same(&current, element)
+ && !matches!(
+ role.as_deref(),
+ Some("AXTextField" | "AXTextArea" | "AXSecureTextField")
+ )
+ {
+ selectable = Some(current.clone());
+ }
+ let Some(parent) = parent else {
+ return Err(incomplete("owner_parent_missing"));
+ };
+ current = parent;
+ }
+ Err(incomplete("owner_depth_limit"))
+}
+
+fn text_value_matches(
+ element: &crate::tree::AXElement,
+ attrs: &crate::tree::NodeAttrs,
+ value: &str,
+ deadline: std::time::Instant,
+) -> Result<bool, AdapterError> {
+ if attrs.role.as_deref() != Some("AXTextField") {
+ return Ok(false);
+ }
+ if attrs.subrole.as_deref() == Some("AXSecureTextField") {
+ return Ok(false);
+ }
+ Ok(
+ crate::tree::surface_read::string(element, "AXValue", deadline)?
+ .is_some_and(|text| text.eq_ignore_ascii_case(value)),
+ )
+}
+
+pub(crate) fn matches(
+ element: &crate::tree::AXElement,
+ value: &str,
+ deadline: std::time::Instant,
+) -> Result<bool, AdapterError> {
+ let (read, stats) = candidate_read(element, deadline)?;
+ evidence_matches(&read.evidence, value, stats)
+}
+
+fn candidate_read(
+ element: &crate::tree::AXElement,
+ deadline: std::time::Instant,
+) -> Result<
+ (
+ crate::tree::query::node_read::NodeRead,
+ agent_desktop_core::LocatorStats,
+ ),
+ AdapterError,
+> {
+ let mut usage = crate::tree::observation_usage::ObservationUsage::with_defaults();
+ let mut stats = agent_desktop_core::LocatorStats::default();
+ let mut requirements = EvidenceRequirements {
+ role: true,
+ name: true,
+ description: true,
+ ..Default::default()
+ };
+ requirements.ref_evidence.actions = true;
+ let read = crate::tree::query::node_read::read_node(
+ element,
+ crate::tree::query::node_read_context::NodeReadContext {
+ tree: &crate::tree::TreeBuildContext::empty(false),
+ stats: &mut stats,
+ usage: &mut usage,
+ requirements,
+ deadline,
+ child_plan: crate::tree::query::child_read_plan::ChildReadPlan::boundary_aware(
+ 0,
+ crate::tree::child_labels::MAX_LABEL_ELEMENTS,
+ 1,
+ 0,
+ ),
+ },
+ )?;
+ if read.invalid_element {
+ return Err(AdapterError::stale_ref(
+ "Selection candidate became invalid",
+ ));
+ }
+ Ok((read, stats))
+}
+
+fn evidence_matches(
+ evidence: &LocatorEvidence,
+ value: &str,
+ stats: agent_desktop_core::LocatorStats,
+) -> Result<bool, AdapterError> {
+ matches_evidence(evidence, value).map_err(|mut error| {
+ if let Some(details) = error
+ .details
+ .as_mut()
+ .and_then(serde_json::Value::as_object_mut)
+ {
+ details.insert("query_stats".into(), serde_json::json!(stats));
+ }
+ error
+ })
+}
+
+fn matches_evidence(evidence: &LocatorEvidence, value: &str) -> Result<bool, AdapterError> {
+ let actions = evidence
+ .ref_evidence
+ .available_actions
+ .known()
+ .ok_or_else(|| incomplete("actions_unknown"))?;
+ if !actions
+ .iter()
+ .any(|action| action == agent_desktop_core::capability::CLICK)
+ {
+ return Ok(false);
+ }
+ if evidence.name.is_unknown() || evidence.description.is_unknown() {
+ return Err(incomplete(if evidence.name.is_unknown() {
+ "name_unknown"
+ } else {
+ "description_unknown"
+ }));
+ }
+ Ok([&evidence.name, &evidence.description]
+ .into_iter()
+ .any(|field| {
+ field
+ .known()
+ .is_some_and(|name| name.eq_ignore_ascii_case(value))
+ }))
+}
+
+fn incomplete(phase: &str) -> AdapterError {
+ AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Selection candidate evidence was incomplete",
+ )
+ .with_details(
+ serde_json::json!({ "kind": "selection_evidence", "phase": phase, "complete": false }),
+ )
+ .with_disposition(agent_desktop_core::DeliverySemantics::not_delivered())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use agent_desktop_core::{IdentifierEvidence, LocatorField, LocatorRefEvidence};
+
+ fn owner(roles: &[&str], named: bool) -> Result<Option<usize>, AdapterError> {
+ collection_owner(
+ &0,
+ &(roles.len() - 1),
+ named,
+ |index| Ok((Some(roles[*index].into()), Some(index + 1))),
+ |left, right| left == right,
+ )
+ }
+
+ #[test]
+ fn collection_label_selects_its_row_not_the_editable_field_or_wrapper_cell() {
+ assert_eq!(
+ owner(&["AXTextField", "AXCell", "AXRow", "AXOutline"], false).unwrap(),
+ Some(2)
+ );
+ assert_eq!(
+ owner(&["AXTextField", "AXCell", "AXTable"], false).unwrap(),
+ Some(1)
+ );
+ assert_eq!(owner(&["AXTextField", "AXOutline"], false).unwrap(), None);
+ assert_eq!(owner(&["AXTextField", "AXOutline"], true).unwrap(), None);
+ assert_eq!(owner(&["AXButton", "AXList"], true).unwrap(), Some(0));
+ assert_eq!(
+ owner(&["AXRow", "AXRow", "AXOutline"], true).unwrap(),
+ Some(0)
+ );
+ }
+
+ #[test]
+ fn collection_owner_must_reach_the_requested_root_before_delivery() {
+ let missing = collection_owner(
+ &0,
+ &2,
+ true,
+ |_| Ok((Some("AXRow".into()), None)),
+ |left, right| left == right,
+ );
+ assert_eq!(missing.unwrap_err().code, ErrorCode::AppUnresponsive);
+ let mut reads = 0;
+ let cycle = collection_owner(
+ &0,
+ &2,
+ true,
+ |_| {
+ reads += 1;
+ Ok((Some("AXRow".into()), Some(0)))
+ },
+ |left, right| left == right,
+ );
+ assert_eq!(cycle.unwrap_err().code, ErrorCode::AppUnresponsive);
+ assert_eq!(reads, 8);
+ }
+
+ #[test]
+ fn selection_requires_a_known_canonical_label_and_an_actionable_target() {
+ let mut evidence = LocatorEvidence {
+ role: LocatorField::Known("treeitem".into()),
+ name: LocatorField::Known("Math".into()),
+ description: LocatorField::Absent,
+ value: LocatorField::Unknown,
+ identifiers: IdentifierEvidence::absent(),
+ states: LocatorField::Unknown,
+ ref_evidence: LocatorRefEvidence {
+ bounds: LocatorField::Unknown,
+ available_actions: LocatorField::Known(vec!["Click".into()]),
+ },
+ };
+ assert!(matches_evidence(&evidence, "math").unwrap());
+ assert!(!matches_evidence(&evidence, "All").unwrap());
+ evidence.ref_evidence.available_actions = LocatorField::Known(vec![]);
+ assert!(!matches_evidence(&evidence, "Math").unwrap());
+ evidence.ref_evidence.available_actions = LocatorField::Known(vec!["Click".into()]);
+ evidence.name = LocatorField::Unknown;
+ assert_eq!(
+ matches_evidence(&evidence, "Math").unwrap_err().code,
+ ErrorCode::AppUnresponsive
+ );
+ }
+}
diff --git a/crates/macos/src/actions/select_search.rs b/crates/macos/src/actions/select_search.rs
new file mode 100644
index 000000000..6f918beb0
--- /dev/null
+++ b/crates/macos/src/actions/select_search.rs
@@ -0,0 +1,9 @@
+/// What `find_named_descendant` is looking for. An open-menu search takes the
+/// first matching item, while a collection search must see every candidate to
+/// prove the match is unique — so only a collection search still reads children
+/// at the depth cap, where they decide whether the search can fail closed.
+#[derive(Clone, Copy)]
+pub(crate) enum SelectSearch {
+ MenuItem,
+ Collection,
+}
diff --git a/crates/macos/src/lib.rs b/crates/macos/src/lib.rs
index fd2e857b4..7f63e0729 100644
--- a/crates/macos/src/lib.rs
+++ b/crates/macos/src/lib.rs
@@ -12,3 +12,4 @@ pub use adapter::MacOSAdapter;
pub use input::clipboard::helper_entry_from_env as clipboard_helper_from_env;
pub use system::cocoa_runtime::ensure_cocoa_multithreaded;
pub use system::permission_helper::entry_from_env as permission_prompt_helper_from_env;
+pub use tree::retained::RetainedRefSession;
diff --git a/crates/macos/src/system/renderer_activation.rs b/crates/macos/src/system/renderer_activation.rs
index ddf249191..c34f7b111 100644
--- a/crates/macos/src/system/renderer_activation.rs
+++ b/crates/macos/src/system/renderer_activation.rs
@@ -1,47 +1,72 @@
+use crate::tree::renderer_probe;
use agent_desktop_core::{AdapterError, Deadline, DeliverySemantics, ErrorCode, ProcessIdentity};
+use std::time::Duration;
+
+const ENHANCED_ACTIVATION_DELAY: Duration = Duration::from_secs(2);
pub(crate) fn activate(process: ProcessIdentity, deadline: Deadline) -> Result<(), AdapterError> {
let identity =
crate::system::process_identity::require_core(&process).map_err(not_delivered)?;
let application = crate::tree::element_for_pid(identity.pid());
+ let attribute = renderer_probe::activation_attribute(
+ &application,
+ instant(deadline).map_err(not_delivered)?,
+ )
+ .map_err(not_delivered)?
+ .ok_or_else(|| {
+ not_delivered(AdapterError::not_supported(
+ "renderer accessibility activation",
+ ))
+ })?;
let current = crate::tree::surface_read::boolean(
&application,
- "AXManualAccessibility",
+ attribute,
instant(deadline).map_err(not_delivered)?,
)
.map_err(not_delivered)?;
if current == Some(true) {
return Ok(());
}
- set_manual_accessibility(&application, deadline)
+ enable_attribute(&application, attribute, deadline)
}
-fn set_manual_accessibility(
+fn enable_attribute(
application: &crate::tree::AXElement,
+ attribute_name: &str,
deadline: Deadline,
) -> Result<(), AdapterError> {
use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};
- let attribute = CFString::new("AXManualAccessibility");
+ let settle_delay = if attribute_name == renderer_probe::ENHANCED {
+ ENHANCED_ACTIVATION_DELAY
+ } else {
+ Duration::ZERO
+ };
+ if deadline.remaining() <= settle_delay {
+ return Err(not_delivered(deadline.timeout_error()));
+ }
+ let attribute = CFString::new(attribute_name);
let error = crate::tree::ax_ipc::set_attribute_value(
application,
attribute.as_concrete_TypeRef(),
CFBoolean::true_value().as_CFTypeRef(),
deadline,
)?;
- let delivered = crate::actions::ax_mutation::classify_result(
+ let readback = crate::tree::surface_read::boolean(
application,
- "AXManualAccessibility",
- "AXUIElementSetAttributeValue",
- error,
- )?;
+ attribute_name,
+ instant(deadline).map_err(uncertain)?,
+ )
+ .map_err(uncertain)?;
+ let delivered = activation_delivered(application, attribute_name, error, readback)?;
if !delivered {
return Err(AdapterError::new(
ErrorCode::ActionNotSupported,
- "Renderer does not support AXManualAccessibility activation",
+ "Renderer did not enable accessibility activation",
)
.with_disposition(DeliverySemantics::not_delivered()));
}
+ std::thread::sleep(deadline.remaining().min(settle_delay));
if deadline.is_expired() {
return Err(deadline
.timeout_error()
@@ -50,6 +75,35 @@ fn set_manual_accessibility(
Ok(())
}
+fn activation_delivered(
+ application: &crate::tree::AXElement,
+ attribute: &str,
+ error: i32,
+ readback: Option<bool>,
+) -> Result<bool, AdapterError> {
+ if readback == Some(true) {
+ return Ok(true);
+ }
+ let delivered = crate::actions::ax_mutation::classify_result(
+ application,
+ attribute,
+ "AXUIElementSetAttributeValue",
+ error,
+ )?;
+ if delivered && readback == Some(false) {
+ return Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "Renderer accessibility activation was not reflected in the attribute value",
+ )
+ .with_disposition(DeliverySemantics::delivered_unverified()));
+ }
+ Ok(delivered)
+}
+
+fn uncertain(error: AdapterError) -> AdapterError {
+ error.with_disposition(DeliverySemantics::uncertain())
+}
+
fn instant(deadline: Deadline) -> Result<std::time::Instant, AdapterError> {
std::time::Instant::now()
.checked_add(deadline.remaining_slice(std::time::Duration::from_millis(250))?)
@@ -59,3 +113,77 @@ fn instant(deadline: Deadline) -> Result<std::time::Instant, AdapterError> {
fn not_delivered(error: AdapterError) -> AdapterError {
error.with_disposition(DeliverySemantics::not_delivered())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn observed_activation_overrides_a_setters_not_implemented_response() {
+ let application = crate::tree::AXElement(std::ptr::null_mut());
+ assert!(
+ activation_delivered(
+ &application,
+ renderer_probe::ENHANCED,
+ accessibility_sys::kAXErrorNotImplemented,
+ Some(true),
+ )
+ .unwrap()
+ );
+ assert!(
+ !activation_delivered(
+ &application,
+ renderer_probe::ENHANCED,
+ accessibility_sys::kAXErrorNotImplemented,
+ Some(false),
+ )
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn enhanced_activation_with_insufficient_budget_never_touches_native_handle() {
+ let application = crate::tree::AXElement(std::ptr::null_mut());
+ let deadline = Deadline::after(1_000).unwrap();
+ let error = enable_attribute(&application, renderer_probe::ENHANCED, deadline).unwrap_err();
+ assert_eq!(error.code, ErrorCode::Timeout);
+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());
+ }
+
+ #[test]
+ fn reported_success_with_disabled_readback_is_not_activation_success() {
+ let application = crate::tree::AXElement(std::ptr::null_mut());
+ let error = activation_delivered(
+ &application,
+ renderer_probe::ENHANCED,
+ accessibility_sys::kAXErrorSuccess,
+ Some(false),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::ActionFailed);
+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());
+ }
+
+ #[test]
+ fn missing_readback_keeps_legacy_success_and_preserves_real_failures() {
+ let application = crate::tree::AXElement(std::ptr::null_mut());
+ assert!(
+ activation_delivered(
+ &application,
+ renderer_probe::MANUAL,
+ accessibility_sys::kAXErrorSuccess,
+ None,
+ )
+ .unwrap()
+ );
+ let error = activation_delivered(
+ &application,
+ renderer_probe::ENHANCED,
+ accessibility_sys::kAXErrorCannotComplete,
+ None,
+ )
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert_eq!(error.disposition, DeliverySemantics::uncertain());
+ }
+}
diff --git a/crates/macos/src/tree/action_list.rs b/crates/macos/src/tree/action_list.rs
index cbe538ac7..7a25300e9 100644
--- a/crates/macos/src/tree/action_list.rs
+++ b/crates/macos/src/tree/action_list.rs
@@ -37,7 +37,7 @@ impl Default for AvailableActionsRead {
pub(crate) fn read_platform_available_actions(
el: &AXElement,
role: &str,
- has_scrollbars: bool,
+ attrs: &super::NodeAttrs,
deadline: std::time::Instant,
usage: &mut crate::tree::observation_usage::ObservationUsage,
) -> AvailableActionsRead {
@@ -77,11 +77,12 @@ pub(crate) fn read_platform_available_actions(
if has("AXScrollToVisible") {
push_unique(&mut read.actions, capability::SCROLL_TO);
}
- if has_scroll_mechanism(&has, has_scrollbars) {
+ if has_scroll_mechanism(&has, attrs.has_scrollbars) {
push_unique(&mut read.actions, capability::SCROLL);
}
- let value_settable = role_may_bear_value(role)
- && read_settable(el, kAXValueAttribute, deadline, &mut read).unwrap_or(false);
+ let value_settable = value_settable(role, attrs.states.control.readonly, || {
+ read_settable(el, kAXValueAttribute, deadline, &mut read)
+ });
if has("AXIncrement") || has("AXDecrement") || value_settable {
push_unique(&mut read.actions, capability::SET_VALUE);
}
@@ -163,6 +164,18 @@ fn role_may_bear_value(role: &str) -> bool {
)
}
+fn value_settable(
+ role: &str,
+ readonly: Option<bool>,
+ probe: impl FnOnce() -> Option<bool>,
+) -> bool {
+ role_may_bear_value(role)
+ && readonly
+ .map(|readonly| !readonly)
+ .or_else(probe)
+ .unwrap_or(false)
+}
+
fn role_may_accept_focus(role: &str) -> bool {
agent_desktop_core::roles::is_interactive_role(role)
|| matches!(
@@ -187,7 +200,7 @@ fn role_may_insert_text(role: &str) -> bool {
pub(crate) fn read_platform_available_actions(
_el: &AXElement,
_role: &str,
- _has_scrollbars: bool,
+ _attrs: &super::NodeAttrs,
_deadline: std::time::Instant,
_usage: &mut crate::tree::observation_usage::ObservationUsage,
) -> AvailableActionsRead {
@@ -221,6 +234,26 @@ fn has_scroll_mechanism(has: &impl Fn(&str) -> bool, has_scrollbars: bool) -> bo
#[cfg(test)]
mod tests {
+ #[test]
+ fn value_capability_reuses_observed_settability_and_probes_only_unknown_controls() {
+ for (readonly, expected) in [(Some(true), false), (Some(false), true)] {
+ assert_eq!(
+ super::value_settable("textfield", readonly, || panic!("duplicate AX read")),
+ expected
+ );
+ }
+ let mut calls = 0;
+ assert!(super::value_settable("textfield", None, || {
+ calls += 1;
+ Some(true)
+ }));
+ assert_eq!(calls, 1);
+ assert!(!super::value_settable("group", None, || panic!(
+ "inapplicable value read"
+ )));
+ assert!(!super::value_settable("textfield", None, || None));
+ }
+
#[cfg(target_os = "macos")]
use super::{AvailableActionsRead, record_error};
use super::{
diff --git a/crates/macos/src/tree/capabilities.rs b/crates/macos/src/tree/capabilities.rs
index 82c6f783d..df86876d0 100644
--- a/crates/macos/src/tree/capabilities.rs
+++ b/crates/macos/src/tree/capabilities.rs
@@ -19,6 +19,21 @@ impl<T> NativeRead<T> {
}
}
+#[cfg(target_os = "macos")]
+fn read_with_recovery<T>(
+ deadline: std::time::Instant,
+ mut read: impl FnMut() -> NativeRead<T>,
+) -> NativeRead<T> {
+ super::read_recovery::read(deadline, || {
+ let result = read();
+ match result.error {
+ Some(error) => Err(error),
+ None => Ok(result),
+ }
+ })
+ .unwrap_or_else(NativeRead::failure)
+}
+
#[cfg(target_os = "macos")]
mod imp {
use super::NativeRead;
@@ -35,19 +50,32 @@ mod imp {
deadline: std::time::Instant,
) -> NativeRead<bool> {
let cf_attr = CFString::new(attr);
- let (err, settable) =
- crate::tree::ax_ipc::is_attribute_settable(el, cf_attr.as_concrete_TypeRef(), deadline);
- if err == kAXErrorSuccess {
- NativeRead::success(settable)
- } else {
- NativeRead::failure(err)
- }
+ super::read_with_recovery(deadline, || {
+ let (err, settable) = crate::tree::ax_ipc::is_attribute_settable(
+ el,
+ cf_attr.as_concrete_TypeRef(),
+ deadline,
+ );
+ if err == kAXErrorSuccess {
+ NativeRead::success(settable)
+ } else {
+ NativeRead::failure(err)
+ }
+ })
}
pub(crate) fn copy_action_names_with_status(
el: &AXElement,
deadline: std::time::Instant,
usage: &mut crate::tree::observation_usage::ObservationUsage,
+ ) -> NativeRead<Vec<String>> {
+ super::read_with_recovery(deadline, || copy_action_names_once(el, deadline, usage))
+ }
+
+ fn copy_action_names_once(
+ el: &AXElement,
+ deadline: std::time::Instant,
+ usage: &mut crate::tree::observation_usage::ObservationUsage,
) -> NativeRead<Vec<String>> {
let (err, actions_ref) = crate::tree::ax_ipc::copy_action_names(el, deadline);
if err != kAXErrorSuccess {
@@ -128,4 +156,51 @@ mod tests {
assert_eq!(strings.error, Some(-1));
assert_eq!(flag.error, Some(-1));
}
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn capability_read_recovers_only_transient_failures_within_a_fixed_attempt_bound() {
+ use accessibility_sys::{
+ kAXErrorAPIDisabled, kAXErrorCannotComplete, kAXErrorFailure, kAXErrorInvalidUIElement,
+ };
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+ let mut reads = 0;
+ let recovered = super::read_with_recovery(deadline, || {
+ reads += 1;
+ if reads < 3 {
+ NativeRead::failure(kAXErrorCannotComplete)
+ } else {
+ NativeRead::success(false)
+ }
+ });
+ assert_eq!(reads, 3);
+ assert_eq!(recovered.value, Some(false));
+ assert_eq!(recovered.error, None);
+ for code in [
+ kAXErrorCannotComplete,
+ kAXErrorAPIDisabled,
+ kAXErrorInvalidUIElement,
+ kAXErrorFailure,
+ ] {
+ let mut reads = 0;
+ let result = super::read_with_recovery::<bool>(deadline, || {
+ reads += 1;
+ NativeRead::failure(code)
+ });
+ assert_eq!(reads, if code == kAXErrorCannotComplete { 3 } else { 1 });
+ assert_eq!(result.error, Some(code));
+ assert_eq!(result.value, None);
+ }
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn expired_capability_budget_never_calls_native_reader() {
+ let result =
+ super::read_with_recovery::<bool>(std::time::Instant::now(), || panic!("expired read"));
+ assert_eq!(
+ result.error,
+ Some(accessibility_sys::kAXErrorCannotComplete)
+ );
+ }
}
diff --git a/crates/macos/src/tree/element_bounds.rs b/crates/macos/src/tree/element_bounds.rs
index ab5381268..d18681e7c 100644
--- a/crates/macos/src/tree/element_bounds.rs
+++ b/crates/macos/src/tree/element_bounds.rs
@@ -1,4 +1,4 @@
-use agent_desktop_core::Rect;
+use agent_desktop_core::{AdapterError, Deadline, ErrorCode, Rect};
use super::AXElement;
@@ -41,3 +41,219 @@ pub(crate) fn read_bounds_with_deadline(
) -> Result<Option<Rect>, agent_desktop_core::AdapterError> {
Ok(None)
}
+
+pub(crate) fn owning_window_bounds(
+ element: &AXElement,
+ deadline: Deadline,
+) -> Result<Option<Rect>, AdapterError> {
+ crate::tree::attributes::set_messaging_timeout(element, deadline)?;
+ let window = first_owning_container(|attribute| {
+ crate::tree::attributes::copy_element_attr_result(element, attribute, deadline)
+ })
+ .map_err(|(attribute, error)| read_error(attribute, error))?;
+ if deadline.is_expired() {
+ return Err(deadline.timeout_error());
+ }
+ let Some(window) = window else {
+ return Ok(None);
+ };
+ crate::tree::element_bounds::read_bounds_with_deadline(
+ &window,
+ super::locator_deadline::from_operation(deadline)?,
+ )
+}
+
+pub(crate) fn clips_descendants(role: &str) -> bool {
+ matches!(
+ role,
+ "AXWindow" | "AXScrollArea" | "AXWebArea" | "AXSheet" | "AXPopover"
+ )
+}
+
+pub(crate) fn intersect_rects(left: Rect, right: Rect) -> Option<Rect> {
+ let x = left.x.max(right.x);
+ let y = left.y.max(right.y);
+ let width = (left.x + left.width).min(right.x + right.width) - x;
+ let height = (left.y + left.height).min(right.y + right.height) - y;
+ (width > 0.0 && height > 0.0).then_some(Rect {
+ x,
+ y,
+ width,
+ height,
+ })
+}
+
+pub(crate) fn clipped_viewport(
+ parent: Option<Rect>,
+ role: &str,
+ bounds: Option<Rect>,
+) -> Option<Rect> {
+ if !clips_descendants(role) {
+ return parent;
+ }
+ let parent = parent?;
+ let bounds = bounds?;
+ Some(intersect_rects(parent, bounds).unwrap_or(Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ }))
+}
+
+pub(crate) fn ancestor_viewport(
+ element: &AXElement,
+ deadline: Deadline,
+) -> Result<Option<Rect>, AdapterError> {
+ let mut viewport = owning_window_bounds(element, deadline)?;
+ if viewport.is_none() {
+ return Ok(None);
+ }
+ let instant = super::locator_deadline::from_operation(deadline)?;
+ let mut current = super::surface_read::element(element, "AXParent", instant)?;
+ for _ in 0..super::element::ABSOLUTE_MAX_DEPTH {
+ let Some(parent) = current else {
+ return Ok(viewport);
+ };
+ let Some(role) = super::surface_read::string(&parent, "AXRole", instant)? else {
+ return Ok(None);
+ };
+ if role == "AXApplication" {
+ return Ok(viewport);
+ }
+ if clips_descendants(&role) {
+ viewport = clipped_viewport(
+ viewport,
+ &role,
+ read_bounds_with_deadline(&parent, instant)?,
+ );
+ }
+ if role == "AXWindow" {
+ return Ok(viewport);
+ }
+ current = super::surface_read::element(&parent, "AXParent", instant)?;
+ }
+ Err(AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Clipping ancestry exceeded its bounded depth",
+ ))
+}
+
+/// The viewport an element is clipped by. `AXTopLevelUIElement` is not a
+/// substitute: for menu content it resolves to the menu bar, a 29-point strip
+/// that reports every open menu item as offscreen. An element with no window is
+/// drawn on its own surface, so its clipping viewport is simply unknown.
+fn first_owning_container(
+ mut read: impl FnMut(&'static str) -> Result<Option<AXElement>, i32>,
+) -> Result<Option<AXElement>, (&'static str, i32)> {
+ read("AXWindow").map_err(|error| ("AXWindow", error))
+}
+
+fn read_error(attribute: &str, error: i32) -> AdapterError {
+ AdapterError::new(
+ if error == accessibility_sys::kAXErrorCannotComplete {
+ ErrorCode::Timeout
+ } else if error == accessibility_sys::kAXErrorAPIDisabled {
+ ErrorCode::PermDenied
+ } else if error == accessibility_sys::kAXErrorInvalidUIElement {
+ ErrorCode::StaleRef
+ } else {
+ ErrorCode::ActionFailed
+ },
+ format!("Could not read {attribute} for live state"),
+ )
+ .with_details(serde_json::json!({ "attribute": attribute, "ax_error": error }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn rect(x: f64, width: f64) -> Rect {
+ Rect {
+ x,
+ y: 0.0,
+ width,
+ height: 100.0,
+ }
+ }
+
+ #[test]
+ fn only_clipping_containers_narrow_the_viewport() {
+ let window = Some(rect(0.0, 500.0));
+ assert_eq!(
+ clipped_viewport(window, "AXGroup", Some(rect(20.0, 10.0))),
+ window
+ );
+ assert_eq!(
+ clipped_viewport(window, "AXScrollArea", Some(rect(20.0, 100.0))),
+ Some(rect(20.0, 100.0))
+ );
+ }
+
+ #[test]
+ fn disjoint_viewports_remain_known_empty_through_descendants() {
+ let empty = clipped_viewport(
+ Some(rect(0.0, 100.0)),
+ "AXScrollArea",
+ Some(rect(200.0, 100.0)),
+ );
+ assert_eq!(
+ crate::tree::state_reader::offscreen(Some(rect(-50.0, 500.0)), empty),
+ Some(true)
+ );
+ let nested = clipped_viewport(empty, "AXScrollArea", Some(rect(-50.0, 500.0)));
+ assert_eq!(
+ crate::tree::state_reader::offscreen(Some(rect(-50.0, 500.0)), nested),
+ Some(true)
+ );
+ }
+
+ #[test]
+ fn missing_clipping_geometry_is_unknown_not_empty() {
+ assert_eq!(
+ clipped_viewport(Some(rect(0.0, 100.0)), "AXScrollArea", None),
+ None
+ );
+ assert_eq!(
+ clipped_viewport(None, "AXScrollArea", Some(rect(0.0, 100.0))),
+ None
+ );
+ }
+ /// A menu item's `AXTopLevelUIElement` is the menu bar, whose 29-point height
+ /// clips every open menu item. A window-less element therefore reports no
+ /// clipping viewport rather than a wrong one.
+ #[test]
+ fn a_window_less_element_reports_no_clipping_viewport() {
+ let mut attributes = Vec::new();
+ let container = first_owning_container(|attribute| {
+ attributes.push(attribute);
+ Ok(None)
+ })
+ .unwrap();
+
+ assert!(container.is_none());
+ assert_eq!(attributes, ["AXWindow"]);
+ }
+
+ #[test]
+ fn incomplete_window_read_never_falls_through_to_a_weaker_container() {
+ for error in [
+ accessibility_sys::kAXErrorCannotComplete,
+ accessibility_sys::kAXErrorInvalidUIElement,
+ ] {
+ let calls = std::cell::Cell::new(0);
+ let result = first_owning_container(|_| {
+ calls.set(calls.get() + 1);
+ Err(error)
+ });
+
+ let failure = match result {
+ Err(failure) => failure,
+ Ok(_) => panic!("incomplete AXWindow read must fail"),
+ };
+ assert_eq!(failure, ("AXWindow", error));
+ assert_eq!(calls.get(), 1);
+ }
+ }
+}
diff --git a/crates/macos/src/tree/empty_text.rs b/crates/macos/src/tree/empty_text.rs
new file mode 100644
index 000000000..9fb6513e9
--- /dev/null
+++ b/crates/macos/src/tree/empty_text.rs
@@ -0,0 +1,95 @@
+#[cfg(target_os = "macos")]
+pub(crate) fn eligible(role: Option<&str>, subrole: Option<&str>) -> bool {
+ matches!(role, Some("AXTextField" | "AXTextArea")) && subrole != Some("AXSecureTextField")
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) fn read(
+ element: &super::AXElement,
+ deadline: impl super::ax_ipc::AxDeadline,
+) -> Result<Option<String>, i32> {
+ use core_foundation::{
+ base::{CFType, TCFType},
+ string::CFString,
+ };
+ let attribute = CFString::new("AXNumberOfCharacters");
+ let (error, value) =
+ super::ax_ipc::copy_attribute_value(element, attribute.as_concrete_TypeRef(), deadline);
+ let owned = (!value.is_null()).then(|| unsafe { CFType::wrap_under_create_rule(value) });
+ decode(error, owned.as_ref())
+}
+
+#[cfg(target_os = "macos")]
+fn decode(
+ error: i32,
+ value: Option<&core_foundation::base::CFType>,
+) -> Result<Option<String>, i32> {
+ if error != accessibility_sys::kAXErrorSuccess {
+ return if matches!(
+ error,
+ accessibility_sys::kAXErrorNoValue | accessibility_sys::kAXErrorAttributeUnsupported
+ ) {
+ Ok(None)
+ } else {
+ Err(error)
+ };
+ }
+ Ok(value
+ .filter(|value| zero_count(value))
+ .map(|_| String::new()))
+}
+
+#[cfg(target_os = "macos")]
+fn zero_count(value: &core_foundation::base::CFType) -> bool {
+ value
+ .downcast::<core_foundation::number::CFNumber>()
+ .and_then(|number| number.to_f64())
+ == Some(0.0)
+}
+
+#[cfg(all(test, target_os = "macos"))]
+mod tests {
+ use super::*;
+ use core_foundation::{base::TCFType, boolean::CFBoolean, number::CFNumber, string::CFString};
+
+ #[test]
+ fn only_nonsecure_text_with_numeric_zero_can_supply_empty_evidence() {
+ assert!(eligible(Some("AXTextField"), Some("AXSearchField")));
+ assert!(eligible(Some("AXTextArea"), None));
+ for (role, subrole) in [
+ (None, None),
+ (Some("AXButton"), None),
+ (Some("AXSecureTextField"), None),
+ (Some("AXTextField"), Some("AXSecureTextField")),
+ ] {
+ assert!(!eligible(role, subrole));
+ }
+ assert!(zero_count(&CFNumber::from(0_i64).as_CFType()));
+ for count in [1.0, -1.0, 0.5, f64::NAN] {
+ assert!(!zero_count(&CFNumber::from(count).as_CFType()));
+ }
+ assert!(!zero_count(&CFString::new("0").as_CFType()));
+ assert!(!zero_count(&CFBoolean::false_value().as_CFType()));
+ }
+
+ #[test]
+ fn missing_or_failed_character_counts_never_prove_empty() {
+ use accessibility_sys::*;
+ let zero = CFNumber::from(0_i64).as_CFType();
+ assert_eq!(
+ decode(kAXErrorSuccess, Some(&zero)),
+ Ok(Some(String::new()))
+ );
+ assert_eq!(decode(kAXErrorSuccess, None), Ok(None));
+ for error in [kAXErrorNoValue, kAXErrorAttributeUnsupported] {
+ assert_eq!(decode(error, Some(&zero)), Ok(None));
+ }
+ for error in [
+ kAXErrorCannotComplete,
+ kAXErrorFailure,
+ kAXErrorInvalidUIElement,
+ ] {
+ assert_eq!(decode(error, Some(&zero)), Err(error));
+ }
+ }
+}
diff --git a/crates/macos/src/tree/hit_test.rs b/crates/macos/src/tree/hit_test.rs
index d4a0a2318..dd8482077 100644
--- a/crates/macos/src/tree/hit_test.rs
+++ b/crates/macos/src/tree/hit_test.rs
@@ -286,25 +286,8 @@ mod imp {
Ok(None)
}
- pub(super) fn intersect_rects(left: Rect, right: Rect) -> Option<Rect> {
- let x = left.x.max(right.x);
- let y = left.y.max(right.y);
- let right_edge = (left.x + left.width).min(right.x + right.width);
- let bottom_edge = (left.y + left.height).min(right.y + right.height);
- (right_edge > x && bottom_edge > y).then_some(Rect {
- x,
- y,
- width: right_edge - x,
- height: bottom_edge - y,
- })
- }
-
- fn clips_descendants(role: &str) -> bool {
- matches!(
- role,
- "AXWindow" | "AXScrollArea" | "AXWebArea" | "AXSheet" | "AXPopover"
- )
- }
+ use crate::tree::element_bounds::clips_descendants;
+ pub(super) use crate::tree::element_bounds::intersect_rects;
pub(super) fn remember_ancestor(visited: &mut Vec<AXElement>, current: &AXElement) -> bool {
if visited
diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rs
index 2ee11f268..7247bc3be 100644
--- a/crates/macos/src/tree/mod.rs
+++ b/crates/macos/src/tree/mod.rs
@@ -13,6 +13,7 @@ pub(crate) mod element;
pub(crate) mod element_bounds;
pub(crate) mod element_dedupe;
pub(crate) mod element_name;
+pub(crate) mod empty_text;
pub(crate) mod hit_test;
pub(crate) mod locator_deadline;
pub(crate) mod native_id;
@@ -29,8 +30,10 @@ pub(crate) mod node_identifiers;
pub(crate) mod node_semantic_states;
pub(crate) mod observation_usage;
pub(crate) mod query;
+#[cfg(target_os = "macos")]
+pub(crate) mod read_recovery;
pub(crate) mod readonly;
-mod renderer_probe;
+pub(crate) mod renderer_probe;
pub(crate) mod resolve;
pub(crate) mod resolve_ax_read;
mod resolve_bounds;
@@ -39,6 +42,8 @@ mod resolve_errors;
mod resolve_read_context;
mod resolve_roots;
mod resolve_search;
+pub(crate) mod retained;
+mod retained_store;
pub(crate) mod roles;
pub(crate) mod state_reader;
pub(crate) mod surface_inventory;
diff --git a/crates/macos/src/tree/node_attribute_fetch.rs b/crates/macos/src/tree/node_attribute_fetch.rs
index 07de1dd8a..e6acd8144 100644
--- a/crates/macos/src/tree/node_attribute_fetch.rs
+++ b/crates/macos/src/tree/node_attribute_fetch.rs
@@ -65,7 +65,7 @@ mod imp {
return failed_node_attribute_read(kAXErrorFailure, requested_count, false, 1);
}
let mut batch_reads = 1;
- let fallback_reads = 0;
+ let mut fallback_reads = 0;
let mut texts: [Option<String>; 17] = Default::default();
let mut labelled_by_text = None;
@@ -168,11 +168,13 @@ mod imp {
},
);
} else if let Some(values) = created_cf_array(value_result) {
+ let mut absent_value = false;
match values.into_iter().next() {
- Some(item) if node_attribute_decode::is_null(&item) => {}
+ Some(item) if node_attribute_decode::is_null(&item) => absent_value = true,
Some(item) => {
if let Some(error) = node_attribute_decode::slot_error(&item) {
status.record_native_slot_error(VALUE, error);
+ absent_value = error == accessibility_sys::kAXErrorNoValue;
} else {
match node_attribute_decode::text(VALUE, &item, usage) {
Some(value) if value.complete => {
@@ -185,6 +187,15 @@ mod imp {
}
None => status.record_slot_error(VALUE, kAXErrorFailure),
}
+ if absent_value
+ && crate::tree::empty_text::eligible(role.as_deref(), subrole.as_deref())
+ {
+ fallback_reads += 1;
+ match crate::tree::empty_text::read(element, deadline) {
+ Ok(value) => texts[VALUE] = value,
+ Err(error) => status.record_slot_error(VALUE, error),
+ }
+ }
} else {
status.record_slot_error(VALUE, kAXErrorFailure);
}
diff --git a/crates/macos/src/tree/query/child_source.rs b/crates/macos/src/tree/query/child_source.rs
index aea2e6319..46bb504f7 100644
--- a/crates/macos/src/tree/query/child_source.rs
+++ b/crates/macos/src/tree/query/child_source.rs
@@ -6,7 +6,7 @@ use super::{
const CANONICAL_CHILDREN: &str = "AXChildren";
const READ_ATTEMPTS: usize = 3;
-pub(super) fn read_resilient(
+pub(crate) fn read_resilient(
attributes: &[&str],
deadline: std::time::Instant,
mut read_attribute: impl FnMut(&str) -> ChildRead,
@@ -185,4 +185,56 @@ mod tests {
assert_eq!(attempts, 3);
assert!(!selected.complete);
}
+
+ #[test]
+ fn window_surface_recovers_without_losing_read_failure_evidence() {
+ let mut attempts = 0;
+ let selected = read_resilient(
+ &["AXWindows"],
+ std::time::Instant::now() + std::time::Duration::from_secs(60),
+ |attribute| {
+ assert_eq!(attribute, "AXWindows");
+ attempts += 1;
+ if attempts == 1 {
+ let mut failed = read(0, false, ChildSourceAvailability::Unknown);
+ failed.status.health.cannot_complete = 1;
+ failed
+ } else {
+ read(1, true, ChildSourceAvailability::Available)
+ }
+ },
+ );
+ assert_eq!(attempts, 2);
+ assert!(selected.complete);
+ assert_eq!(selected.elements.len(), 1);
+ assert_eq!(selected.status.health.cannot_complete, 1);
+ }
+
+ #[test]
+ fn window_surface_does_not_retry_terminal_or_complete_reads() {
+ for outcome in ["empty", "permission", "invalid", "expired"] {
+ let mut attempts = 0;
+ let deadline = std::time::Instant::now()
+ + std::time::Duration::from_secs(if outcome == "expired" { 0 } else { 60 });
+ let selected = read_resilient(&["AXWindows"], deadline, |_| {
+ attempts += 1;
+ let mut result = read(
+ 0,
+ outcome == "empty",
+ if outcome == "empty" {
+ ChildSourceAvailability::Available
+ } else {
+ ChildSourceAvailability::Unknown
+ },
+ );
+ result.status.api_disabled = outcome == "permission";
+ result.status.invalid_element = outcome == "invalid";
+ result
+ });
+ assert_eq!(attempts, 1, "{outcome}");
+ assert_eq!(selected.complete, outcome == "empty", "{outcome}");
+ assert_eq!(selected.status.api_disabled, outcome == "permission");
+ assert_eq!(selected.status.invalid_element, outcome == "invalid");
+ }
+ }
}
diff --git a/crates/macos/src/tree/query/mod.rs b/crates/macos/src/tree/query/mod.rs
index 0415db495..cd0d68dbe 100644
--- a/crates/macos/src/tree/query/mod.rs
+++ b/crates/macos/src/tree/query/mod.rs
@@ -5,7 +5,7 @@ pub(crate) mod child_read_budget;
pub(crate) mod child_read_plan;
mod child_read_status;
mod child_read_telemetry;
-mod child_source;
+pub(crate) mod child_source;
mod child_source_availability;
mod evidence_fields;
mod node_evidence;
@@ -55,11 +55,17 @@ pub(crate) fn observe_tree(
let (tree, renderer_ready, stats) =
traversal::LocatorTraversal::new(&request, resolved.context, deadline)
.build(resolved.element, resolved.source)?;
+ tracing::debug!(?stats, "tree: native observation completed");
let looked_deep_enough = observation_reached_tree_end(&stats, &request);
- if resolved.activation_eligible && tree.is_complete() && !renderer_ready && looked_deep_enough {
+ if renderer_ready || (resolved.activation_eligible && tree.is_complete()) {
if let Some(instance) = resolved.process_instance.as_deref() {
- if crate::tree::renderer_probe::activation_supported(resolved.pid, instance, deadline)?
- {
+ if crate::tree::renderer_probe::activation_required(
+ resolved.pid,
+ instance,
+ renderer_ready,
+ tree.is_complete() && looked_deep_enough,
+ deadline,
+ )? {
return Err(renderer_activation_required(resolved.pid, stats));
}
}
@@ -69,7 +75,7 @@ pub(crate) fn observe_tree(
fn renderer_activation_required(pid: i32, stats: agent_desktop_core::LocatorStats) -> AdapterError {
let mut error = AdapterError::renderer_accessibility_activation_required(
- "The application exposes renderer activation but no web accessibility surface",
+ "The application requires accessibility activation before its surface is ready",
);
if let Some(details) = error
.details
@@ -126,7 +132,10 @@ fn resolve_root(
})?;
let context =
crate::tree::TreeBuildContext::for_pid_with_deadline(pid, true, deadline)?
- .child_context(entry.geometry.bounds);
+ .child_context(crate::tree::element_bounds::ancestor_viewport(
+ &element,
+ request.deadline,
+ )?);
Ok(ResolvedRoot {
element,
source,
@@ -243,6 +252,7 @@ mod tests {
process_instance: Some(process_instance),
},
identity: RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("Save".into()),
value: None,
diff --git a/crates/macos/src/tree/query/node_read.rs b/crates/macos/src/tree/query/node_read.rs
index 6199e0165..917ed0918 100644
--- a/crates/macos/src/tree/query/node_read.rs
+++ b/crates/macos/src/tree/query/node_read.rs
@@ -68,11 +68,7 @@ pub(crate) fn read_node(
let value = (!secure).then(|| attrs.value.clone()).flatten();
let actions = if let Some(actions) = requirements.ref_evidence.actions.then(|| {
crate::tree::action_list::read_platform_available_actions(
- element,
- &role,
- attrs.has_scrollbars,
- deadline,
- usage,
+ element, &role, &attrs, deadline, usage,
)
}) {
stats.reads.counts.action_reads += 1;
@@ -200,7 +196,7 @@ pub(crate) fn read_node(
} else {
LocatorField::Unknown
},
- identifiers,
+ identifiers: crate::tree::retained::evidence(element, identifiers),
states: if !requirements.states || read.status.states_unknown() {
LocatorField::Unknown
} else {
diff --git a/crates/macos/src/tree/query/traversal.rs b/crates/macos/src/tree/query/traversal.rs
index 46416903e..9a0edaf26 100644
--- a/crates/macos/src/tree/query/traversal.rs
+++ b/crates/macos/src/tree/query/traversal.rs
@@ -92,7 +92,7 @@ impl LocatorTraversal {
logical_depth,
self.request.max_logical_depth,
);
- let read = read_node(
+ let mut read = read_node(
&element,
super::node_read_context::NodeReadContext {
tree: &self.context,
@@ -145,8 +145,15 @@ impl LocatorTraversal {
)
} else {
self.usage.claim_edges(loaded_child_count);
- let (children, complete) =
- self.visit_children(read.child_read, (child_logical_depth, raw_depth))?;
+ let original_viewport = self.context.window_bounds;
+ self.context.window_bounds = crate::tree::element_bounds::clipped_viewport(
+ original_viewport,
+ read.attrs.role.as_deref().unwrap_or(""),
+ read.attrs.bounds,
+ );
+ let result = self.visit_children(read.child_read, (child_logical_depth, raw_depth));
+ self.context.window_bounds = original_viewport;
+ let (children, complete) = result?;
(children, None, complete)
};
self.arena.ancestors.remove(&pointer);
@@ -154,6 +161,9 @@ impl LocatorTraversal {
if !subtree_complete {
self.arena.mark_incomplete();
}
+ if let Some(token) = crate::tree::retained::capture(&element)? {
+ read.evidence.identifiers = read.evidence.identifiers.with_retained_object(token);
+ }
Ok(Some(ObservedSubtree::new(
read.evidence,
children,
diff --git a/crates/macos/src/tree/read_recovery.rs b/crates/macos/src/tree/read_recovery.rs
new file mode 100644
index 000000000..b45f9e6e5
--- /dev/null
+++ b/crates/macos/src/tree/read_recovery.rs
@@ -0,0 +1,70 @@
+use std::time::{Duration, Instant};
+
+pub(crate) fn read<T>(
+ deadline: Instant,
+ mut observe: impl FnMut() -> Result<T, i32>,
+) -> Result<T, i32> {
+ for attempt in 0..3 {
+ if Instant::now() >= deadline {
+ return Err(accessibility_sys::kAXErrorCannotComplete);
+ }
+ let result = observe();
+ if Instant::now() >= deadline {
+ return Err(accessibility_sys::kAXErrorCannotComplete);
+ }
+ if !matches!(result, Err(accessibility_sys::kAXErrorCannotComplete)) || attempt == 2 {
+ return result;
+ }
+ std::thread::sleep(
+ deadline
+ .saturating_duration_since(Instant::now())
+ .min(Duration::from_millis(1)),
+ );
+ }
+ Err(accessibility_sys::kAXErrorCannotComplete)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use accessibility_sys::{
+ kAXErrorAPIDisabled, kAXErrorCannotComplete, kAXErrorFailure, kAXErrorInvalidUIElement,
+ };
+
+ #[test]
+ fn transient_read_returns_the_fresh_value() {
+ let mut reads = 0;
+ let value = read(Instant::now() + Duration::from_secs(60), || {
+ reads += 1;
+ if reads == 1 {
+ Err(kAXErrorCannotComplete)
+ } else {
+ Ok("textfield")
+ }
+ });
+ assert_eq!(value, Ok("textfield"));
+ assert_eq!(reads, 2);
+ }
+
+ #[test]
+ fn only_transport_failures_retry_and_attempts_are_bounded() {
+ for (error, expected) in [
+ (kAXErrorCannotComplete, 3),
+ (kAXErrorFailure, 1),
+ (kAXErrorInvalidUIElement, 1),
+ (kAXErrorAPIDisabled, 1),
+ ] {
+ let mut calls = 0;
+ let result = read::<()>(Instant::now() + Duration::from_secs(60), || {
+ calls += 1;
+ Err(error)
+ });
+ assert_eq!(result, Err(error));
+ assert_eq!(calls, expected);
+ }
+ assert_eq!(
+ read::<()>(Instant::now(), || panic!("expired read")),
+ Err(kAXErrorCannotComplete)
+ );
+ }
+}
diff --git a/crates/macos/src/tree/renderer_probe.rs b/crates/macos/src/tree/renderer_probe.rs
index 12bf411a2..b09ec3ba5 100644
--- a/crates/macos/src/tree/renderer_probe.rs
+++ b/crates/macos/src/tree/renderer_probe.rs
@@ -1,8 +1,13 @@
use agent_desktop_core::{AdapterError, ErrorCode};
-pub(crate) fn activation_supported(
+pub(crate) const MANUAL: &str = "AXManualAccessibility";
+pub(crate) const ENHANCED: &str = "AXEnhancedUserInterface";
+
+pub(crate) fn activation_required(
pid: i32,
process_instance: &str,
+ web_surface: bool,
+ absence_proven: bool,
deadline: std::time::Instant,
) -> Result<bool, AdapterError> {
if !crate::system::process_identity::matches_instance(pid, process_instance)? {
@@ -11,12 +16,58 @@ pub(crate) fn activation_supported(
));
}
let application = super::element_for_pid(pid);
- super::locator_deadline::prepare(&application, deadline)?;
- let read = super::capabilities::is_attr_settable_with_status(
- &application,
- "AXManualAccessibility",
- deadline,
- );
+ activation_needed(
+ web_surface,
+ absence_proven,
+ |attribute| attribute_supported(&application, attribute, deadline),
+ |attribute| super::surface_read::boolean(&application, attribute, deadline),
+ )
+}
+
+fn activation_needed(
+ web_surface: bool,
+ absence_proven: bool,
+ supported: impl FnMut(&str) -> Result<bool, AdapterError>,
+ mut enabled: impl FnMut(&str) -> Result<Option<bool>, AdapterError>,
+) -> Result<bool, AdapterError> {
+ let Some(attribute) = choose_attribute(supported)? else {
+ return Ok(false);
+ };
+ if !web_surface && attribute == MANUAL {
+ return Ok(absence_proven);
+ }
+ let enabled = enabled(attribute)?;
+ if !web_surface {
+ return Ok(enabled == Some(false));
+ }
+ Ok(enabled.map_or(attribute == ENHANCED, |enabled| !enabled))
+}
+
+pub(crate) fn activation_attribute(
+ application: &super::AXElement,
+ deadline: std::time::Instant,
+) -> Result<Option<&'static str>, AdapterError> {
+ choose_attribute(|attribute| attribute_supported(application, attribute, deadline))
+}
+
+fn choose_attribute(
+ mut supported: impl FnMut(&str) -> Result<bool, AdapterError>,
+) -> Result<Option<&'static str>, AdapterError> {
+ for attribute in [MANUAL, ENHANCED] {
+ if supported(attribute)? {
+ return Ok(Some(attribute));
+ }
+ }
+ Ok(None)
+}
+
+fn attribute_supported(
+ application: &super::AXElement,
+ attribute: &str,
+ deadline: std::time::Instant,
+) -> Result<bool, AdapterError> {
+ super::locator_deadline::prepare(application, deadline)?;
+ let read = super::capabilities::is_attr_settable_with_status(application, attribute, deadline);
super::locator_deadline::remaining(deadline)?;
match (read.value, read.error) {
(Some(value), None) => Ok(value),
@@ -64,6 +115,165 @@ fn is_unsupported(error: i32) -> bool {
mod tests {
use super::*;
+ #[test]
+ fn shallow_observation_requires_explicit_mode_evidence_not_renderer_absence() {
+ for (mode, enabled, expected) in [
+ (MANUAL, Some(false), false),
+ (ENHANCED, Some(false), true),
+ (ENHANCED, Some(true), false),
+ (ENHANCED, None, false),
+ ] {
+ assert_eq!(
+ activation_needed(
+ false,
+ false,
+ |attribute| Ok(attribute == mode),
+ |_| {
+ assert_ne!(mode, MANUAL);
+ Ok(enabled)
+ },
+ )
+ .unwrap(),
+ expected
+ );
+ }
+ }
+
+ #[test]
+ fn readable_web_tree_still_requires_enhanced_mode_when_disabled() {
+ for (enabled, expected) in [(Some(false), true), (Some(true), false), (None, true)] {
+ let required = activation_needed(
+ true,
+ true,
+ |attribute| Ok(attribute == ENHANCED),
+ |attribute| {
+ assert_eq!(attribute, ENHANCED);
+ Ok(enabled)
+ },
+ )
+ .unwrap();
+ assert_eq!(required, expected);
+ }
+ }
+
+ #[test]
+ fn native_enhanced_mode_requires_explicit_disabled_readback() {
+ for (enabled, expected) in [(Some(false), true), (Some(true), false), (None, false)] {
+ assert_eq!(
+ activation_needed(
+ false,
+ true,
+ |attribute| Ok(attribute == ENHANCED),
+ |_| Ok(enabled),
+ )
+ .unwrap(),
+ expected
+ );
+ }
+ }
+
+ #[test]
+ fn legacy_renderer_without_a_web_surface_keeps_activation_retry() {
+ assert!(
+ activation_needed(
+ false,
+ true,
+ |attribute| Ok(attribute == MANUAL),
+ |_| panic!("a missing renderer must continue waiting for its tree"),
+ )
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn readable_legacy_renderer_does_not_require_a_readable_manual_flag() {
+ assert!(
+ !activation_needed(
+ true,
+ true,
+ |attribute| Ok(attribute == MANUAL),
+ |_| Ok(None),
+ )
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn unsupported_renderer_does_not_read_an_activation_value() {
+ assert!(
+ !activation_needed(
+ true,
+ true,
+ |_| Ok(false),
+ |_| panic!("unsupported attributes must not be read"),
+ )
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn activation_value_errors_are_not_treated_as_disabled_mode() {
+ for code in [
+ ErrorCode::PermDenied,
+ ErrorCode::Timeout,
+ ErrorCode::StaleRef,
+ ] {
+ let error = activation_needed(
+ true,
+ true,
+ |attribute| Ok(attribute == ENHANCED),
+ |_| Err(AdapterError::new(code.clone(), "read failed")),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ }
+ }
+
+ #[test]
+ fn enhanced_activation_is_available_to_native_apps_that_advertise_it() {
+ let mut queried = Vec::new();
+ assert_eq!(
+ choose_attribute(|attribute| {
+ queried.push(attribute.to_owned());
+ Ok(attribute == ENHANCED)
+ })
+ .unwrap(),
+ Some(ENHANCED)
+ );
+ assert_eq!(queried, [MANUAL, ENHANCED]);
+ assert_eq!(
+ choose_attribute(|attribute| Ok(attribute == ENHANCED)).unwrap(),
+ Some(ENHANCED)
+ );
+ }
+
+ #[test]
+ fn manual_activation_keeps_precedence_and_does_not_require_a_web_surface() {
+ {
+ let mut queried = Vec::new();
+ assert_eq!(
+ choose_attribute(|attribute| {
+ queried.push(attribute.to_owned());
+ Ok(true)
+ })
+ .unwrap(),
+ Some(MANUAL)
+ );
+ assert_eq!(queried, [MANUAL]);
+ }
+ }
+
+ #[test]
+ fn inconclusive_manual_probe_does_not_fall_through_to_another_mutation() {
+ let error = choose_attribute(|_| {
+ Err(inconclusive_probe(
+ accessibility_sys::kAXErrorCannotComplete,
+ ))
+ })
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::Timeout);
+ }
+
#[test]
fn unsupported_probe_results_do_not_request_activation() {
for error in [
diff --git a/crates/macos/src/tree/resolve.rs b/crates/macos/src/tree/resolve.rs
index 7f9a8d471..3e7aa4957 100644
--- a/crates/macos/src/tree/resolve.rs
+++ b/crates/macos/src/tree/resolve.rs
@@ -48,6 +48,7 @@ pub(crate) fn resolve_locator_anchor_with_deadline(
#[cfg(target_os = "macos")]
fn verify_process_instance(entry: &RefEntry) -> Result<(), AdapterError> {
+ super::retained::validate(entry.identity.retained_object.as_deref())?;
let Some(instance) = entry.process.process_instance.as_deref() else {
return Err(AdapterError::stale_ref(
"Saved target has no process instance identity",
diff --git a/crates/macos/src/tree/resolve_search.rs b/crates/macos/src/tree/resolve_search.rs
index 893be96d0..8bf33b1c2 100644
--- a/crates/macos/src/tree/resolve_search.rs
+++ b/crates/macos/src/tree/resolve_search.rs
@@ -221,7 +221,7 @@ fn collect_elements_recursive(
match read.evidence.role.known() {
Some(role) => {
if role == &context.entry.identity.role {
- match match_native_or_text_identity(context.entry, &read.evidence) {
+ match super::retained::candidate_match(element, context.entry, &read.evidence)? {
IdentityMatch::Match => {
push_unique(context.matches, element.clone());
}
@@ -277,7 +277,7 @@ fn candidate_identity(
}
let matched = match read.evidence.role.known() {
Some(role) if role == &entry.identity.role => {
- let identity = match_native_or_text_identity(entry, &read.evidence);
+ let identity = super::retained::candidate_match(element, entry, &read.evidence)?;
if identity == IdentityMatch::Unknown && provisional_geometry_candidate(entry) {
IdentityMatch::Match
} else {
diff --git a/crates/macos/src/tree/resolve_tests.rs b/crates/macos/src/tree/resolve_tests.rs
index a77be285c..d071a615c 100644
--- a/crates/macos/src/tree/resolve_tests.rs
+++ b/crates/macos/src/tree/resolve_tests.rs
@@ -26,6 +26,7 @@ pub(super) fn entry(
process_instance: Some("test-instance".into()),
},
identity: RefEntryIdentity {
+ retained_object: None,
role: "cell".into(),
name: Some("Investors".into()),
value: None,
diff --git a/crates/macos/src/tree/retained.rs b/crates/macos/src/tree/retained.rs
new file mode 100644
index 000000000..bf6a311f9
--- /dev/null
+++ b/crates/macos/src/tree/retained.rs
@@ -0,0 +1,158 @@
+use super::AXElement;
+use super::retained_store::RetainedStore;
+use agent_desktop_core::{
+ AdapterError, DeliverySemantics, ErrorCode, IdentifierEvidence, IdentityMatch, RefEntry,
+};
+use std::cell::RefCell;
+use std::marker::PhantomData;
+use std::rc::Rc;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
+
+thread_local! {
+ static STORE: RefCell<Option<RetainedStore>> = const { RefCell::new(None) };
+}
+
+/// Owns retained AX identity on the calling thread until dropped.
+pub struct RetainedRefSession {
+ _owner_thread: PhantomData<Rc<()>>,
+}
+
+impl RetainedRefSession {
+ pub fn capture_count(&self) -> usize {
+ STORE.with(|slot| {
+ slot.borrow()
+ .as_ref()
+ .map_or(0, RetainedStore::capture_count)
+ })
+ }
+
+ pub fn retain(&self, live: &std::collections::HashSet<String>) {
+ STORE.with(|slot| {
+ if let Some(store) = slot.borrow_mut().as_mut() {
+ store.retain(live);
+ }
+ });
+ }
+
+ pub fn start() -> Result<Self, AdapterError> {
+ let pid = i32::try_from(std::process::id())
+ .map_err(|_| AdapterError::internal("Host PID exceeds pid_t"))?;
+ let process = crate::system::process_identity::token_for_pid(pid)?
+ .ok_or_else(|| AdapterError::internal("Host process identity is unavailable"))?;
+ let generation = NEXT_GENERATION
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
+ next.checked_add(1)
+ })
+ .map_err(|_| AdapterError::internal("Retained identity generation exhausted"))?;
+ STORE.with(|slot| {
+ let mut slot = slot.borrow_mut();
+ if slot.is_some() {
+ return Err(AdapterError::internal(
+ "This thread already owns retained refs",
+ ));
+ }
+ *slot = Some(RetainedStore::new(format!("{pid}:{process}:{generation}")));
+ Ok(Self {
+ _owner_thread: PhantomData,
+ })
+ })
+ }
+}
+
+impl Drop for RetainedRefSession {
+ fn drop(&mut self) {
+ STORE.with(|slot| {
+ slot.borrow_mut().take();
+ });
+ }
+}
+
+#[cfg(target_os = "macos")]
+pub(super) fn element_hash(element: &AXElement) -> u64 {
+ if element.0.is_null() {
+ return 0;
+ }
+ unsafe { core_foundation::base::CFHash(element.0.cast()) as u64 }
+}
+
+#[cfg(not(target_os = "macos"))]
+pub(super) fn element_hash(_element: &AXElement) -> u64 {
+ 0
+}
+
+pub(crate) fn capture(element: &AXElement) -> Result<Option<String>, AdapterError> {
+ STORE.with(|slot| {
+ slot.borrow_mut()
+ .as_mut()
+ .map(|store| store.capture(element))
+ .transpose()
+ })
+}
+
+pub(crate) fn evidence(element: &AXElement, identifiers: IdentifierEvidence) -> IdentifierEvidence {
+ STORE.with(|slot| {
+ match slot
+ .borrow()
+ .as_ref()
+ .and_then(|store| store.lookup(element))
+ {
+ Some(token) => identifiers.with_retained_object(token.to_owned()),
+ None => identifiers,
+ }
+ })
+}
+
+pub(crate) fn validate(token: Option<&str>) -> Result<(), AdapterError> {
+ let Some(token) = token else {
+ return Ok(());
+ };
+ let found = STORE.with(|slot| {
+ slot.borrow()
+ .as_ref()
+ .is_some_and(|store| store.contains_token(token))
+ });
+ if found {
+ Ok(())
+ } else {
+ Err(AdapterError::new(
+ ErrorCode::StaleRef,
+ "The native object owner is no longer available",
+ )
+ .with_suggestion("Take a fresh snapshot in the active session")
+ .with_disposition(DeliverySemantics::not_delivered()))
+ }
+}
+
+pub(crate) fn matches(token: &str, element: &AXElement) -> Result<bool, AdapterError> {
+ validate(Some(token))?;
+ Ok(STORE.with(|slot| {
+ slot.borrow()
+ .as_ref()
+ .and_then(|store| store.lookup(element))
+ .is_some_and(|actual| actual == token)
+ }))
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) fn candidate_match(
+ element: &AXElement,
+ entry: &RefEntry,
+ evidence: &agent_desktop_core::LocatorEvidence,
+) -> Result<IdentityMatch, AdapterError> {
+ if let Some(token) = entry.identity.retained_object.as_deref() {
+ return Ok(if matches(token, element)? {
+ IdentityMatch::Match
+ } else {
+ IdentityMatch::NoMatch
+ });
+ }
+ Ok(super::resolve_search::match_native_or_text_identity(
+ entry, evidence,
+ ))
+}
+
+#[cfg(all(test, target_os = "macos"))]
+#[path = "retained_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/tree/retained_store.rs b/crates/macos/src/tree/retained_store.rs
new file mode 100644
index 000000000..9a8dd547f
--- /dev/null
+++ b/crates/macos/src/tree/retained_store.rs
@@ -0,0 +1,127 @@
+use super::{AXElement, retained::element_hash};
+use agent_desktop_core::AdapterError;
+use std::collections::{HashMap, HashSet};
+
+const MAX_OBJECTS: usize = 65_536;
+
+pub(super) struct RetainedStore {
+ generation: String,
+ buckets: HashMap<u64, Vec<(String, AXElement)>>,
+ count: usize,
+ tokens: HashSet<String>,
+}
+
+#[cfg(all(test, target_os = "macos"))]
+mod tests {
+ use super::*;
+
+ fn app(pid: i32) -> AXElement {
+ AXElement(unsafe { accessibility_sys::AXUIElementCreateApplication(pid) })
+ }
+
+ #[test]
+ fn a_hash_bucket_collision_cannot_alias_another_native_object() {
+ let target = app(i32::try_from(std::process::id()).unwrap());
+ let mut store = RetainedStore::new("host".into());
+ store
+ .buckets
+ .insert(element_hash(&target), vec![("host:1".into(), app(1))]);
+ store.count = 1;
+ store.tokens.insert("host:1".into());
+ assert!(store.lookup(&target).is_none());
+ assert_eq!(store.capture(&target).unwrap(), "host:2");
+ assert_eq!(store.lookup(&target), Some("host:2"));
+ }
+
+ #[test]
+ fn capacity_refuses_new_objects_without_evicting_existing_identity() {
+ let target = app(i32::try_from(std::process::id()).unwrap());
+ let mut store = RetainedStore::new("host".into());
+ let token = store.capture(&target).unwrap();
+ store
+ .tokens
+ .extend((2..=MAX_OBJECTS).map(|index| format!("host:{index}")));
+ assert_eq!(store.capture(&target).unwrap(), token);
+ assert!(store.capture(&app(1)).is_err());
+ assert_eq!(store.tokens.len(), MAX_OBJECTS);
+ assert_eq!(store.lookup(&target), Some(token.as_str()));
+ }
+
+ #[test]
+ fn pruning_releases_unsaved_objects_without_reusing_their_tokens() {
+ let target = app(i32::try_from(std::process::id()).unwrap());
+ let other = app(1);
+ let mut store = RetainedStore::new("host".into());
+ let keep = store.capture(&target).unwrap();
+ let discard = store.capture(&other).unwrap();
+ store.retain(&HashSet::from([keep.clone()]));
+ assert!(store.contains_token(&keep));
+ assert!(!store.contains_token(&discard));
+ assert!(store.lookup(&other).is_none());
+ let fresh = store.capture(&other).unwrap();
+ assert_ne!(fresh, discard);
+ assert_eq!(store.capture_count(), 3);
+ assert_eq!(store.tokens.len(), 2);
+ }
+}
+
+impl RetainedStore {
+ pub(super) fn new(generation: String) -> Self {
+ Self {
+ generation,
+ buckets: HashMap::new(),
+ count: 0,
+ tokens: HashSet::new(),
+ }
+ }
+
+ pub(super) fn lookup(&self, element: &AXElement) -> Option<&str> {
+ self.buckets
+ .get(&element_hash(element))?
+ .iter()
+ .find(|(_, saved)| crate::tree::same_element(saved, element))
+ .map(|(token, _)| token.as_str())
+ }
+
+ pub(super) fn capture(&mut self, element: &AXElement) -> Result<String, AdapterError> {
+ if element.0.is_null() {
+ return Err(AdapterError::stale_ref(
+ "Cannot retain a null native object",
+ ));
+ }
+ if let Some(token) = self.lookup(element) {
+ return Ok(token.to_owned());
+ }
+ if self.tokens.len() >= MAX_OBJECTS {
+ return Err(AdapterError::internal("Retained object capacity exhausted")
+ .with_suggestion("End this session and take a fresh snapshot in a new session"));
+ }
+ self.count = self
+ .count
+ .checked_add(1)
+ .ok_or_else(|| AdapterError::internal("Retained token space exhausted"))?;
+ let token = format!("{}:{}", self.generation, self.count);
+ self.tokens.insert(token.clone());
+ self.buckets
+ .entry(element_hash(element))
+ .or_default()
+ .push((token.clone(), element.clone()));
+ Ok(token)
+ }
+
+ pub(super) fn contains_token(&self, token: &str) -> bool {
+ self.tokens.contains(token)
+ }
+
+ pub(super) fn capture_count(&self) -> usize {
+ self.count
+ }
+
+ pub(super) fn retain(&mut self, live: &HashSet<String>) {
+ self.buckets.retain(|_, bucket| {
+ bucket.retain(|(token, _)| live.contains(token));
+ !bucket.is_empty()
+ });
+ self.tokens.retain(|token| live.contains(token));
+ }
+}
diff --git a/crates/macos/src/tree/retained_tests.rs b/crates/macos/src/tree/retained_tests.rs
new file mode 100644
index 000000000..32cd64302
--- /dev/null
+++ b/crates/macos/src/tree/retained_tests.rs
@@ -0,0 +1,157 @@
+use super::*;
+use agent_desktop_core::{LocatorField, LocatorRefEvidence};
+
+fn app(pid: i32) -> AXElement {
+ AXElement(unsafe { accessibility_sys::AXUIElementCreateApplication(pid) })
+}
+
+fn entry(token: Option<String>) -> RefEntry {
+ RefEntry {
+ process: agent_desktop_core::RefProcess {
+ pid: agent_desktop_core::ProcessId::new(1),
+ process_instance: None,
+ },
+ identity: agent_desktop_core::RefEntryIdentity {
+ retained_object: token,
+ role: "button".into(),
+ name: Some("Target".into()),
+ value: None,
+ description: None,
+ native_id: None,
+ },
+ geometry: agent_desktop_core::RefGeometry {
+ bounds: None,
+ bounds_hash: None,
+ },
+ capabilities: agent_desktop_core::RefCapabilities {
+ states: Vec::new(),
+ available_actions: Vec::new(),
+ },
+ source: agent_desktop_core::RefSource {
+ source_app: None,
+ source_window_id: None,
+ source_window_title: None,
+ source_window_bounds_hash: None,
+ source_surface: agent_desktop_core::SnapshotSurface::Window,
+ },
+ scope: agent_desktop_core::RefScope {
+ root_ref: None,
+ path_is_absolute: false,
+ path: Default::default(),
+ },
+ }
+}
+
+fn text_evidence(name: &str) -> agent_desktop_core::LocatorEvidence {
+ agent_desktop_core::LocatorEvidence {
+ role: LocatorField::Known("button".into()),
+ name: LocatorField::Known(name.into()),
+ description: LocatorField::Absent,
+ value: LocatorField::Absent,
+ identifiers: IdentifierEvidence::absent(),
+ states: LocatorField::Absent,
+ ref_evidence: LocatorRefEvidence {
+ bounds: LocatorField::Absent,
+ available_actions: LocatorField::Absent,
+ },
+ }
+}
+
+#[test]
+fn retention_uses_native_equality_and_expires_with_its_owner() {
+ let pid = i32::try_from(std::process::id()).unwrap();
+ let element = app(pid);
+ assert!(capture(&element).unwrap().is_none());
+ let owner = RetainedRefSession::start().unwrap();
+ assert!(RetainedRefSession::start().is_err());
+ let first = capture(&element).unwrap().unwrap();
+ let same = capture(&app(pid)).unwrap().unwrap();
+ assert_eq!(first, same);
+ assert!(matches(&first, &app(pid)).unwrap());
+ assert!(!matches(&first, &app(1)).unwrap());
+ assert!(capture(&AXElement(std::ptr::null_mut())).is_err());
+ assert_eq!(
+ evidence(&element, IdentifierEvidence::absent()).retained_object(),
+ Some(first.as_str())
+ );
+ drop(owner);
+ assert_eq!(
+ validate(Some(&first)).unwrap_err().code,
+ agent_desktop_core::ErrorCode::StaleRef
+ );
+ let _replacement_owner = RetainedRefSession::start().unwrap();
+ let replacement = capture(&element).unwrap().unwrap();
+ assert_ne!(replacement, first);
+ assert!(validate(Some(&first)).is_err());
+}
+
+#[test]
+fn candidate_match_prefers_native_identity_over_matching_text_evidence() {
+ let pid = i32::try_from(std::process::id()).unwrap();
+ let _owner = RetainedRefSession::start().unwrap();
+ let token = capture(&app(pid)).unwrap().unwrap();
+ let retained_entry = entry(Some(token));
+ let matching_text = text_evidence("Target");
+ assert_eq!(
+ candidate_match(&app(pid), &retained_entry, &matching_text).unwrap(),
+ agent_desktop_core::IdentityMatch::Match
+ );
+ assert_eq!(
+ candidate_match(&app(1), &retained_entry, &matching_text).unwrap(),
+ agent_desktop_core::IdentityMatch::NoMatch
+ );
+}
+
+#[test]
+fn candidate_match_fails_closed_on_a_stale_token() {
+ let pid = i32::try_from(std::process::id()).unwrap();
+ let owner = RetainedRefSession::start().unwrap();
+ let token = capture(&app(pid)).unwrap().unwrap();
+ drop(owner);
+ let _replacement = RetainedRefSession::start().unwrap();
+ let error =
+ candidate_match(&app(pid), &entry(Some(token)), &text_evidence("Target")).unwrap_err();
+ assert_eq!(error.code, agent_desktop_core::ErrorCode::StaleRef);
+ assert_eq!(
+ error.message,
+ "The native object owner is no longer available"
+ );
+ assert_eq!(
+ error.suggestion.as_deref(),
+ Some("Take a fresh snapshot in the active session")
+ );
+ assert_eq!(
+ error.disposition,
+ agent_desktop_core::DeliverySemantics::not_delivered()
+ );
+}
+
+#[test]
+fn tokenless_candidates_keep_the_legacy_identity_rules() {
+ let pid = i32::try_from(std::process::id()).unwrap();
+ let tokenless = entry(None);
+ assert_eq!(
+ candidate_match(&app(pid), &tokenless, &text_evidence("Target")).unwrap(),
+ agent_desktop_core::IdentityMatch::Match
+ );
+ assert_eq!(
+ candidate_match(&app(pid), &tokenless, &text_evidence("Other")).unwrap(),
+ agent_desktop_core::IdentityMatch::NoMatch
+ );
+}
+
+#[test]
+fn retention_cannot_cross_threads() {
+ let _owner = RetainedRefSession::start().unwrap();
+ let token = capture(&app(i32::try_from(std::process::id()).unwrap()))
+ .unwrap()
+ .unwrap();
+ std::thread::spawn(move || {
+ assert_eq!(
+ validate(Some(&token)).unwrap_err().code,
+ agent_desktop_core::ErrorCode::StaleRef
+ );
+ })
+ .join()
+ .unwrap();
+}
diff --git a/crates/macos/src/tree/state_reader.rs b/crates/macos/src/tree/state_reader.rs
index 2471f4226..43d8adf1e 100644
--- a/crates/macos/src/tree/state_reader.rs
+++ b/crates/macos/src/tree/state_reader.rs
@@ -29,7 +29,7 @@ pub(crate) fn states_from_element(
if ctx.is_secure_text {
states.push(state::SECURE.into());
}
- if is_expanded(attrs) {
+ if expanded_from_attrs(attrs) == Some(true) {
states.push(state::EXPANDED.into());
}
if super::roles::is_toggleable_role(role) {
@@ -66,13 +66,28 @@ pub(crate) fn states_from_element(
states
}
-fn is_expanded(attrs: &NodeAttrs) -> bool {
- attrs
- .states
- .control
- .expanded
- .or(attrs.states.control.disclosing)
- .unwrap_or(false)
+pub(crate) fn expanded_from_attrs(attrs: &NodeAttrs) -> Option<bool> {
+ expanded_state(
+ attrs.role.as_deref(),
+ attrs
+ .states
+ .control
+ .expanded
+ .or(attrs.states.control.disclosing),
+ attrs.value.as_deref(),
+ )
+}
+
+pub(crate) fn expanded_state(
+ native_role: Option<&str>,
+ explicit: Option<bool>,
+ value: Option<&str>,
+) -> Option<bool> {
+ explicit.or_else(|| {
+ (native_role == Some("AXDisclosureTriangle"))
+ .then(|| value.and_then(parse_checked_value))
+ .flatten()
+ })
}
pub(crate) fn parse_checked_value(value: &str) -> Option<bool> {
@@ -102,7 +117,9 @@ fn value_is_indeterminate(value: Option<&str>) -> bool {
pub(crate) fn offscreen(bounds: Option<Rect>, window_bounds: Option<Rect>) -> Option<bool> {
let (el, win) = bounds.zip(window_bounds)?;
Some(
- el.x + el.width <= win.x
+ win.width <= 0.0
+ || win.height <= 0.0
+ || el.x + el.width <= win.x
|| el.x >= win.x + win.width
|| el.y + el.height <= win.y
|| el.y >= win.y + win.height,
diff --git a/crates/macos/src/tree/state_reader_tests.rs b/crates/macos/src/tree/state_reader_tests.rs
index baaf6e85b..e4c9b1aa7 100644
--- a/crates/macos/src/tree/state_reader_tests.rs
+++ b/crates/macos/src/tree/state_reader_tests.rs
@@ -153,3 +153,22 @@ fn emitted_tokens_over_representative_inputs_are_vocabulary_members() {
fn assert_states_in_vocabulary_rejects_bogus_token() {
state::assert_states_in_vocabulary(&["zzz_bogus_state_token".to_string()]);
}
+
+#[test]
+fn disclosure_value_is_role_scoped_and_explicit_state_wins() {
+ use super::expanded_state;
+ let role = Some("AXDisclosureTriangle");
+ assert_eq!(expanded_state(role, None, Some("1")), Some(true));
+ assert_eq!(expanded_state(role, None, Some("0")), Some(false));
+ assert_eq!(expanded_state(role, Some(false), Some("1")), Some(false));
+ for value in [None, Some("2"), Some("unknown")] {
+ assert_eq!(expanded_state(role, None, value), None);
+ }
+ for role in [None, Some("AXButton"), Some("AXRow"), Some("AXTextField")] {
+ assert_eq!(expanded_state(role, None, Some("1")), None);
+ }
+ let mut attrs = sample_attrs();
+ attrs.role = Some("AXDisclosureTriangle".into());
+ attrs.value = Some("1".into());
+ assert_eq!(super::expanded_from_attrs(&attrs), Some(true));
+}
diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs
index 6daebd9b0..868878ac9 100644
--- a/crates/macos/src/tree/surface_inventory.rs
+++ b/crates/macos/src/tree/surface_inventory.rs
@@ -20,10 +20,36 @@ pub(crate) fn list_surfaces_for_pid(
collect_window_surfaces(&window, "focused-window", deadline, &mut surfaces)?;
}
+ complete_menu_inventory(&mut surfaces, |surfaces| {
+ if let Some(menu) = super::surfaces::menu_element_for_pid(pid, deadline)? {
+ push_menu_surface(
+ &menu,
+ "context_menu",
+ "resolved/menu".into(),
+ deadline,
+ surfaces,
+ )?;
+ }
+ Ok(())
+ })?;
+
ensure_before_deadline(deadline)?;
Ok(surfaces)
}
+fn complete_menu_inventory(
+ surfaces: &mut Vec<SurfaceInfo>,
+ discover: impl FnOnce(&mut Vec<SurfaceInfo>) -> Result<(), AdapterError>,
+) -> Result<(), AdapterError> {
+ if !surfaces
+ .iter()
+ .any(|surface| matches!(surface.kind.as_str(), "menu" | "context_menu"))
+ {
+ discover(surfaces)?;
+ }
+ Ok(())
+}
+
fn collect_app_surfaces(
children: &[AXElement],
deadline: Instant,
diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs
index e300f06af..476aad841 100644
--- a/crates/macos/src/tree/surface_inventory_tests.rs
+++ b/crates/macos/src/tree/surface_inventory_tests.rs
@@ -11,3 +11,41 @@ fn expired_deadline_fails_before_accessibility_inventory() {
assert_eq!(error.code.as_str(), "TIMEOUT");
}
+
+fn surface(kind: &str) -> SurfaceInfo {
+ SurfaceInfo {
+ id: kind.into(),
+ kind: kind.into(),
+ title: None,
+ item_count: None,
+ }
+}
+
+#[test]
+fn shared_menu_discovery_preserves_other_surfaces_and_existing_menu_ids() {
+ let mut surfaces = vec![surface("sheet")];
+ complete_menu_inventory(&mut surfaces, |surfaces| {
+ surfaces.push(surface("context_menu"));
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(surfaces.len(), 2);
+ assert_eq!(surfaces[0].kind, "sheet");
+ assert_eq!(surfaces[1].kind, "context_menu");
+
+ for kind in ["menu", "context_menu"] {
+ let mut surfaces = vec![surface(kind)];
+ complete_menu_inventory(&mut surfaces, |_| panic!("must not duplicate menus")).unwrap();
+ assert_eq!(surfaces.len(), 1);
+ assert_eq!(surfaces[0].id, kind);
+ }
+}
+
+#[test]
+fn incomplete_shared_discovery_is_not_reported_as_an_empty_inventory() {
+ let mut surfaces = Vec::new();
+ let error = complete_menu_inventory(&mut surfaces, |_| Err(AdapterError::permission_denied()))
+ .unwrap_err();
+ assert_eq!(error.code.as_str(), "PERM_DENIED");
+ assert!(surfaces.is_empty());
+}
diff --git a/crates/macos/src/tree/surface_read.rs b/crates/macos/src/tree/surface_read.rs
index 90755e3af..53339d633 100644
--- a/crates/macos/src/tree/surface_read.rs
+++ b/crates/macos/src/tree/surface_read.rs
@@ -6,12 +6,22 @@ pub(crate) fn elements(
attribute: &str,
deadline: Instant,
) -> Result<Vec<super::AXElement>, AdapterError> {
- let read = super::query::child_read::read_attribute_children(
- element,
- attribute,
- agent_desktop_core::ObservationBudget::default().max_children_per_node,
- deadline,
- );
+ elements_with_reader(attribute, deadline, |attribute| {
+ super::query::child_read::read_attribute_children(
+ element,
+ attribute,
+ agent_desktop_core::ObservationBudget::default().max_children_per_node,
+ deadline,
+ )
+ })
+}
+
+fn elements_with_reader(
+ attribute: &str,
+ deadline: Instant,
+ read_attribute: impl FnMut(&str) -> super::query::child_read::ChildRead,
+) -> Result<Vec<super::AXElement>, AdapterError> {
+ let read = super::query::child_source::read_resilient(&[attribute], deadline, read_attribute);
ensure_before_deadline(deadline)?;
if read.status.api_disabled {
return Err(map_error(attribute, accessibility_sys::kAXErrorAPIDisabled));
@@ -197,4 +207,22 @@ mod tests {
fn native_ax_error_is_absent_without_any_native_failure() {
assert_eq!(native_ax_error(false, false, 0), None);
}
+
+ #[test]
+ fn surface_read_recovers_transient_failure_before_reporting_missing_windows() {
+ let mut calls = 0;
+ let result = elements_with_reader(
+ "AXWindows",
+ Instant::now() + std::time::Duration::from_secs(60),
+ |attribute| {
+ assert_eq!(attribute, "AXWindows");
+ calls += 1;
+ let mut read = super::super::query::child_read::ChildRead::empty(calls > 1);
+ read.status.health.cannot_complete = u64::from(calls == 1);
+ read
+ },
+ );
+ assert_eq!(calls, 2);
+ assert!(result.unwrap().is_empty());
+ }
}
diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs
index 2e7797e60..a3f7ac26a 100644
--- a/crates/macos/src/tree/surfaces.rs
+++ b/crates/macos/src/tree/surfaces.rs
@@ -84,34 +84,51 @@ fn find_menu_descendant(
root: AXElement,
deadline: Instant,
) -> Result<Option<AXElement>, AdapterError> {
- let mut stack = vec![(root, 0_u8)];
+ find_menu_descendant_with(root, deadline, |element| {
+ let role = surface_read::string(element, "AXRole", deadline)?;
+ if role.as_deref() == Some("AXMenuBar") {
+ return Ok((false, Vec::new()));
+ }
+ if role.as_deref() == Some("AXMenu")
+ && surface_read::boolean(element, "AXVisible", deadline)? != Some(false)
+ {
+ return Ok((true, Vec::new()));
+ }
+ Ok((
+ false,
+ surface_read::elements(element, "AXChildren", deadline)?,
+ ))
+ })
+}
+
+fn find_menu_descendant_with<T>(
+ root: T,
+ deadline: Instant,
+ mut inspect: impl FnMut(&T) -> Result<(bool, Vec<T>), AdapterError>,
+) -> Result<Option<T>, AdapterError> {
+ let mut pending = std::collections::VecDeque::from([root]);
+ let mut incomplete = None;
let mut visited = 0_usize;
- while let Some((element, depth)) = stack.pop() {
+ while let Some(element) = pending.pop_front() {
surface_read::ensure_before_deadline(deadline)?;
visited += 1;
if visited > MAX_SURFACE_NODES {
return Err(surface_limit_error());
}
- if depth > 8 {
- continue;
- }
- let role = surface_read::string(&element, "AXRole", deadline)?;
- if role.as_deref() == Some("AXMenuBar") {
- continue;
- }
- if role.as_deref() == Some("AXMenu")
- && surface_read::boolean(&element, "AXVisible", deadline)? != Some(false)
- {
+ let (is_menu, children) = match inspect(&element) {
+ Ok(observed) => observed,
+ Err(error) if error.code == ErrorCode::AppUnresponsive => {
+ incomplete.get_or_insert(error);
+ continue;
+ }
+ Err(error) => return Err(error),
+ };
+ if is_menu {
return Ok(Some(element));
}
- stack.extend(
- surface_read::elements(&element, "AXChildren", deadline)?
- .into_iter()
- .rev()
- .map(|child| (child, depth.saturating_add(1))),
- );
+ pending.extend(children);
}
- Ok(None)
+ incomplete.map_or(Ok(None), Err)
}
#[cfg(target_os = "macos")]
@@ -266,4 +283,86 @@ mod tests {
assert_eq!(error.code, ErrorCode::AppUnresponsive);
assert_eq!(error.details.expect("limit details")["complete"], false);
}
+
+ #[test]
+ fn menus_beyond_eight_wrappers_remain_discoverable() {
+ let deadline = Instant::now() + std::time::Duration::from_secs(5);
+ for target_depth in [9, 11, 30] {
+ let found = find_menu_descendant_with(0, deadline, |depth| {
+ Ok((*depth == target_depth, vec![depth + 1]))
+ })
+ .unwrap();
+ assert_eq!(found, Some(target_depth));
+ }
+ }
+
+ #[test]
+ fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() {
+ let mut reads = 0;
+ let error = find_menu_descendant_with(
+ 0,
+ Instant::now() + std::time::Duration::from_secs(5),
+ |node| {
+ reads += 1;
+ Ok((false, vec![*node]))
+ },
+ )
+ .unwrap_err();
+ assert_eq!(reads, MAX_SURFACE_NODES);
+ assert_eq!(error.details.unwrap()["complete"], false);
+ }
+
+ #[test]
+ fn expired_menu_search_never_reads_a_node() {
+ let result = find_menu_descendant_with::<()>((), Instant::now(), |_| {
+ panic!("expired search must not call AX")
+ });
+ assert_eq!(result.unwrap_err().code, ErrorCode::Timeout);
+ }
+
+ #[test]
+ fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() {
+ let result = find_menu_descendant_with(
+ 0,
+ Instant::now() + std::time::Duration::from_secs(5),
+ |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Err(surface_limit_error()),
+ 2 => Ok((true, vec![])),
+ _ => unreachable!(),
+ },
+ );
+ assert_eq!(result.unwrap(), Some(2));
+ }
+
+ #[test]
+ fn an_incomplete_branch_cannot_prove_menu_absence() {
+ let result = find_menu_descendant_with(
+ 0,
+ Instant::now() + std::time::Duration::from_secs(5),
+ |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Err(surface_limit_error()),
+ _ => Ok((false, vec![])),
+ },
+ );
+ assert_eq!(result.unwrap_err().details.unwrap()["complete"], false);
+ }
+
+ #[test]
+ fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() {
+ let deadline = Instant::now() + std::time::Duration::from_secs(5);
+ let found = find_menu_descendant_with(0, deadline, |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Ok((false, vec![1])),
+ _ => Ok((true, vec![])),
+ });
+ assert_eq!(found.unwrap(), Some(2));
+ let denied = find_menu_descendant_with(0, deadline, |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")),
+ _ => panic!("permission failure must stop all further AX reads"),
+ });
+ assert_eq!(denied.unwrap_err().code, ErrorCode::PermDenied);
+ }
}
diff --git a/crates/macos/src/tree/text_attributes.rs b/crates/macos/src/tree/text_attributes.rs
index 5034b7120..69b1bae27 100644
--- a/crates/macos/src/tree/text_attributes.rs
+++ b/crates/macos/src/tree/text_attributes.rs
@@ -92,6 +92,14 @@ mod imp {
);
if error != kAXErrorSuccess {
release_if_present(value);
+ if error == accessibility_sys::kAXErrorNoValue {
+ let role = copy_string_attr_result(el, "AXRole", deadline)?;
+ let subrole = copy_string_attr_result(el, "AXSubrole", deadline)?;
+ if crate::tree::empty_text::eligible(role.as_deref(), subrole.as_deref()) {
+ return crate::tree::empty_text::read(el, deadline)
+ .map(|value| value.map(|text| BoundedString::from_owned(text, usage)));
+ }
+ }
return if is_absent_error(error) {
Ok(None)
} else {
diff --git a/crates/macos/tests/retained_fixture.rs b/crates/macos/tests/retained_fixture.rs
new file mode 100644
index 000000000..076e70465
--- /dev/null
+++ b/crates/macos/tests/retained_fixture.rs
@@ -0,0 +1,169 @@
+#![cfg(target_os = "macos")]
+
+use agent_desktop_core::{
+ Deadline, IdentityPredicate, LocatorMaterialization, LocatorQuery, LocatorResolveRequest,
+ LocatorSelection, ObservationOps, ObservationRoot, RefEntry, WindowFilter, resolve_query,
+};
+use agent_desktop_macos::{MacOSAdapter, RetainedRefSession};
+use std::io::{BufRead, Write};
+
+fn capture(
+ adapter: &MacOSAdapter,
+ window: &agent_desktop_core::WindowInfo,
+ id: &str,
+ value: &str,
+) -> RefEntry {
+ let resolution = resolve_query(
+ adapter,
+ &LocatorQuery {
+ identity: IdentityPredicate {
+ role: Some("textfield".into()),
+ native_id: Some(id.into()),
+ value: Some(value.into()),
+ ..Default::default()
+ },
+ exact: true,
+ ..Default::default()
+ },
+ ObservationRoot::Window(window),
+ &LocatorResolveRequest {
+ selection: LocatorSelection::First,
+ deadline: Deadline::after(5000).unwrap(),
+ max_raw_depth: 50,
+ materialization: LocatorMaterialization::SelectedMatches,
+ surface: None,
+ },
+ )
+ .unwrap();
+ assert_eq!(resolution.matches.len(), 1);
+ let ref_id = resolution.matches[0].data.ref_id.as_deref().unwrap();
+ let entry = resolution
+ .refmap
+ .as_ref()
+ .unwrap()
+ .get(ref_id)
+ .unwrap()
+ .clone();
+ assert!(entry.identity.retained_object.is_some());
+ entry
+}
+
+fn read(
+ adapter: &MacOSAdapter,
+ entry: &RefEntry,
+) -> Result<Option<String>, agent_desktop_core::ErrorCode> {
+ let deadline = Deadline::after(5000).unwrap();
+ let handle = adapter
+ .resolve_element_strict(entry, deadline)
+ .map_err(|error| error.code)?;
+ let live = adapter
+ .get_live_element(&handle, deadline)
+ .map_err(|error| error.code)?;
+ assert_eq!(
+ live.identity.identifiers.retained_object(),
+ entry.identity.retained_object.as_deref()
+ );
+ Ok(live.state.value)
+}
+
+#[test]
+#[ignore = "read-only Xcode identity diagnostic; requires stage labels on stdin"]
+fn retained_xcode_identity() {
+ let window_id = std::env::var("AGENT_DESKTOP_TEST_WINDOW").unwrap();
+ let _owner = RetainedRefSession::start().unwrap();
+ let adapter = MacOSAdapter::new();
+ let windows = adapter
+ .list_windows(
+ &WindowFilter {
+ app: Some("Xcode".into()),
+ ..Default::default()
+ },
+ Deadline::after(5000).unwrap(),
+ )
+ .unwrap();
+ let window = windows
+ .iter()
+ .find(|window| window.id == window_id)
+ .unwrap();
+ let original = capture(&adapter, window, "title", "cursorcamapp.swift");
+ println!("ready: adapter retained original Xcode file label");
+ std::io::stdout().flush().unwrap();
+ let mut stages = Vec::new();
+ for line in std::io::stdin().lock().lines() {
+ let stage = line.unwrap();
+ if stage == "quit" {
+ break;
+ }
+ let value = read(&adapter, &original);
+ println!("stage={stage} original={value:?}");
+ match stage.as_str() {
+ "initial" => assert_eq!(value, Ok(Some("CursorCamApp.swift".into()))),
+ "filtered" => assert_eq!(value, Err(agent_desktop_core::ErrorCode::StaleRef)),
+ "restored" => assert!(
+ value == Ok(Some("CursorCamApp.swift".into()))
+ || value == Err(agent_desktop_core::ErrorCode::StaleRef)
+ ),
+ _ => panic!("Unexpected diagnostic stage"),
+ }
+ stages.push(stage);
+ std::io::stdout().flush().unwrap();
+ }
+ assert_eq!(stages, ["initial", "filtered", "restored"]);
+}
+
+#[test]
+#[ignore = "read-only adapter diagnostic; requires owned RefChurnView and stage labels on stdin"]
+fn retained_fixture_identity() {
+ let window_id = std::env::var("AGENT_DESKTOP_TEST_WINDOW").unwrap();
+ let owner = RetainedRefSession::start().unwrap();
+ let adapter = MacOSAdapter::new();
+ let windows = adapter
+ .list_windows(
+ &WindowFilter {
+ app: Some("AgentDeskFixture".into()),
+ ..Default::default()
+ },
+ Deadline::after(5000).unwrap(),
+ )
+ .unwrap();
+ let window = windows
+ .iter()
+ .find(|window| window.id == window_id)
+ .unwrap();
+ let alpha = capture(&adapter, window, "shared-title", "alpha");
+ let stable = capture(&adapter, window, "stable-editor", "stable value");
+ println!("ready: adapter retained Alpha and stable editor");
+ std::io::stdout().flush().unwrap();
+ let mut stages = Vec::new();
+ for line in std::io::stdin().lock().lines() {
+ let stage = line.unwrap();
+ if stage == "quit" {
+ break;
+ }
+ let alpha_value = read(&adapter, &alpha);
+ let stable_value = read(&adapter, &stable);
+ println!("stage={stage} alpha={alpha_value:?} stable={stable_value:?}");
+ if stage == "initial" {
+ assert_eq!(alpha_value, Ok(Some("Alpha".into())));
+ } else {
+ assert_eq!(alpha_value, Err(agent_desktop_core::ErrorCode::StaleRef));
+ }
+ let expected = if stage == "edited" {
+ "retained-control"
+ } else {
+ "Stable value"
+ };
+ assert_eq!(stable_value, Ok(Some(expected.into())));
+ stages.push(stage);
+ std::io::stdout().flush().unwrap();
+ }
+ assert_eq!(
+ stages,
+ ["initial", "filtered", "restored", "edited", "cleared"]
+ );
+ drop(owner);
+ assert_eq!(
+ read(&adapter, &stable),
+ Err(agent_desktop_core::ErrorCode::StaleRef)
+ );
+}
diff --git a/docs/json-output.md b/docs/json-output.md
index 2bb670102..1b5fabc79 100644
--- a/docs/json-output.md
+++ b/docs/json-output.md
@@ -57,6 +57,15 @@ Inspect `disposition.retry` before retrying or choosing an alternative action, r
- Focusing an inactive text field can change its selection. A pre-focus range cannot establish the expected insertion into a nonempty field; such a result is explicitly unverified rather than falsely contradicted.
- A settle-loop pacing budget does not replace the caller's deadline for native reads. Tests assert deadline identity rather than arbitrary remaining-time thresholds.
+## Find result shape
+
+`find` match objects report the element's actual accessibility `name`. Elements
+without an accessible name omit `name` entirely; their content stays in `value`.
+Earlier output synthesized a display name — falling back to `value` or
+`description`, then a `(unnamed <role>)` placeholder — so consumers that treated
+`name` as always present must tolerate its absence and apply their own fallback
+to `role` or `value`.
+
## Error codes
| Code | Meaning |
diff --git a/docs/plans/2026-09-19-native-reliability-evaluation-plan.md b/docs/plans/2026-09-19-native-reliability-evaluation-plan.md
new file mode 100644
index 000000000..d435280fe
--- /dev/null
+++ b/docs/plans/2026-09-19-native-reliability-evaluation-plan.md
@@ -0,0 +1,267 @@
+# Native reliability: real-app baseline and minimal repairs
+
+Date: 2026-09-19
+Status: active; bounded live trials completed, repeated acceptance suite incomplete
+
+## Outcome and boundaries
+
+Make snapshot → qualified ref → supported headless action dependable in real
+macOS apps. Recover routine target changes internally when identity is sufficient;
+never choose a lookalike or repeat a possibly delivered action to improve a score.
+The calling agent still owns task intent and the observation/action loop.
+
+Use Numbers and disposable documents as the active real-app evaluation. Do not
+spend this phase on TextEdit or other easy-app demonstrations. Keep the existing
+fixture to reproduce discovered failures, not as proof of real-app completion.
+All mutations target owned test documents/windows only. No activation, physical
+pointer movement, synthesized keyboard/mouse input, or clipboard-based typing.
+A visual cursor overlay is allowed; its animation is not delivery evidence.
+
+This phase adds no app-specific production automation, browser backend, generic
+workflow engine, dependency, fuzzy identity matcher, or replacement test framework.
+No publishing, commit, or push is part of this plan. Preserve existing Chromium
+activation edits and unrelated assets/icon.png. Record the exact dirty diff and
+binary hash; do not label an uncommitted build only by its HEAD commit.
+
+## Current assessment
+
+Initial provisional engineering confidence: **6/10**, not a measured completion score.
+Strong foundations exist: strict resolution, shared actionability/auto-wait,
+delivery dispositions, verification scopes, and native fixture coverage.
+Real-app completion, persistent document mutation, and failure recovery across
+UI changes are not yet demonstrated by a frozen repeatable suite.
+
+The earlier **8/10 provisional assessment is withdrawn**: it was not earned by
+the declared acceptance suite. Current measured overall score: **not established**.
+The execution trajectory and frozen tasks are in
+[acceptance v1](../../tests/real-apps/acceptance-v1.md).
+Current evidence and failures are retained in the
+Numbers, Xcode and native-command reports under `docs/solutions/runtime-errors/`.
+Numbers editing, formulas and persistence remain required even as command coverage
+expands to other complex apps.
+
+## Additional command coverage authorized during execution
+
+Use owned SF Symbols and Xcode windows alongside Numbers. Evaluate scrolling and
+saved-ref continuity, scroll-to, named selection, menu discovery, expansion and
+collapse. Apply the same headless and independent-outcome requirements. Record
+drag's policy refusal separately from actual drag-and-drop completion; a correct
+refusal cannot satisfy the requested drag task. Do not add physical input to make
+an unsupported headless command pass.
+
+Menu trials must observe app activation through the entire delivery and settling
+period. Native AX success and menu presence do not by themselves prove headless
+delivery. If unrelated foreground activity prevents attribution, mark that trial
+unqualified and retain the events rather than infer a clean pass.
+
+Prior evidence is a hypothesis source, not a current failure inventory:
+- The September 16 Numbers probe reported chooser naming, selection, startup,
+ mutation-timeout and editor-write problems.
+- Current code already contains selection-aware presses, AXSelectedCells, and
+ separate read/mutation timeout slices. Reproduce before proposing changes.
+- Historical Numbers editor writes returned AX success without committing text;
+ physical typing worked but violates this task's headless contract.
+- The current Comet repair demonstrates that readable AX plus native success
+ can still require renderer activation. It does not prove native app reliability.
+
+## Caller-facing acceptance constraint
+
+Use unmodified Agent Desktop responses for model-driven interaction. No custom
+Python/JSON tree extraction, external ref selection, hidden target repair, or
+application-specific wrapper in the calling workflow. Use documented snapshot,
+skeleton, drill, find, action and verification commands directly. Record response
+size, call count, missing identity/context and recovery instructions as usability
+evidence. Raw AX and document-model probes are separate diagnostic/oracle paths;
+they must not choose refs for or silently rescue the evaluated interaction.
+Automated replay alone does not establish that a model can operate the CLI.
+
+## Phase 1 — freeze the experiment before repairing behavior
+
+1. Build/copy an immutable release binary and isolate AGENT_DESKTOP_HOME, session,
+ trace and output paths. Record commit, diff hash, binary hash, macOS/app versions,
+ permissions, process instance, window identity and initial accessibility modes.
+2. Audit/reuse tests/e2e interaction locking, bounded subprocess execution, JSON
+ parsing, safe-semantic guards and traces. Add only the small real-app scenario
+ runner/result record that is missing. No dashboard or driver/plugin abstraction.
+3. Identify/create disposable seed documents. Setup may use native document
+ scripting strictly to prepare owned fixtures; report it separately and never
+ count it as Agent Desktop task success. Setup must also preserve headless policy.
+ If a safe seed cannot be prepared without focus changes, report that prerequisite
+ blocked; do not silently foreground the application or touch existing documents.
+4. Establish an independent oracle before scoring a case: raw AX selection/state
+ reads and, for Numbers content/formulas/dimensions, read-only document-model
+ queries. Capture the pre-state and verify the oracle detects a known different
+ seed value. Do not assume AX text readback means document commit.
+5. Run each frozen case once for discovery, then ten clean baseline repetitions.
+ Keep every attempt. A failed run followed by a successful rerun stays a failure.
+ Version case definitions when evidence requires a corrected test.
+
+## Initial cases and outcome oracles
+
+| ID | Scenario | Required effect |
+|---|---|---|
+| N1 | Discover Numbers document, skeleton, drill to table | Correct owned document/table and actionable identity evidence |
+| N2 | Snapshot cell, select via ref with Numbers background | Raw table selection identifies that exact sheet/table/cell |
+| N3 | Change selection or scroll, then act on saved ref | Original target recovered, or explicit ambiguity/removal result |
+| N4 | Enter unique text and numeric values, commit editor | Document model has exact values in exact cells; neighbors unchanged |
+| N5 | Enter formula over known inputs | Stored formula and calculated result both match |
+| N6 | Switch sheets with repeated table/control names | Correct sheet changes; no writes to the lookalike table |
+| N7 | Change table dimensions through exposed semantic control | Document row/column counts change, not only displayed AX text |
+| N8 | Save, close owned document, reopen | Values/formula persist; no other document altered |
+
+Freeze exact step recipes, timeouts, seed checksums and oracle expectations after
+capability discovery and before the repeated baseline. Unsupported behavior remains
+visible as unmet task coverage; it is not silently dropped from the denominator.
+Numbers template selection is a separate capability probe if the grid is absent
+from AX; do not make unrelated cases depend on an unobservable chooser selection.
+
+## Cross-command consistency gate
+
+Test public command relationships directly using their unmodified responses:
+- list-windows → snapshot --window-id → find in that window → ref action must
+ preserve window ID and process generation. Different window capabilities
+ (listed, readable, actionable) must be explicit rather than inferred identical.
+- snapshot/find refs → get/is/root drill/action must identify the same element
+ within its owning session. Mutable control state must not masquerade as stable
+ identity; genuine replacement or ambiguity must fail safely and consistently.
+- Advertised available_actions → matching command preflight and dispatch must
+ agree for unchanged state and the same headless policy. Record native advertised
+ support without observable effect as an unmet capability contract, not a pass.
+- click/toggle/check/uncheck and type/set-value/clear must share applicable
+ capability, resolution, delivery and verification rules; preserve intentional
+ semantic differences such as replacement versus insertion.
+- CLI/batch/high-level FFI must use the same core contract. Reuse existing
+ window inventory/resolution, native capability readers, ref resolver and action
+ execution rather than creating an all-purpose new registry or parallel helpers.
+
+Classify disagreement under unchanged conditions as a defect. Record explicit
+intervening UI changes separately; do not call every dynamic-state change a
+contradiction or conceal a transient read failure as an empty successful result.
+For each actual divergence, fix the lowest existing shared boundary and add a
+paired-command regression proving agreement and a changed-state negative case.
+
+## Phase 2 — assign every failure to the correct boundary
+
+Use matched clean-state trials, never an AX retry after a possibly delivered AD
+mutation. Compare the same logical element, native role/attributes/actions,
+selection/editor state, foreground state, timeout and accessibility mode.
+
+| Evidence | Diagnosis and permitted next step |
+|---|---|
+| Raw tree exposes target/capability; AD omits or mislabels it | Inspect macOS traversal/mapping; if raw adapter output is correct, inspect core filtering/ref allocation |
+| AD resolves a different target or rejects identity | Compare saved evidence to live identity; separate adapter resolution from core ref storage/scope rules |
+| AD never dispatches although target is supported and ready | Trace core preflight/policy/wait decisions and adapter live-read answers |
+| Same target and preconditions: raw semantic mutation works, AD native dispatch fails | Adapter mechanism, preparation, timeout or verification candidate; reproduce before editing |
+| Native dispatch works but AD reports the wrong disposition/effect | Trace adapter classification and core postcondition handling separately |
+| Raw and AD both return success with no effect | Investigate AX prerequisites/commit semantics; not enough evidence to blame either implementation |
+| Raw and AD both cannot perform operation | Record current platform limitation or unresolved prerequisite; no physical fallback |
+| Saved result differs from AX field readback | Commit/oracle gap; element verification must not claim document persistence |
+
+Raw AX probe is a small independent Swift helper using ApplicationServices, not
+Agent Desktop internals or its normalization. Capture attribute/action names,
+settable flags, native errors, selected target identity, elapsed time and pre/post
+state. Allow mutations only in the owned document. Read-only scripting is an
+oracle, never the evaluated action path. Change one precondition at a time and
+repeat successful/failed conditions before attributing causality.
+
+If core vs adapter remains unclear, use a minimal adapter-level diagnostic test
+on the same owned target plus a scripted PlatformAdapter mock reproducing the
+returned reads/errors. Do not add a production bypass API to facilitate diagnosis.
+
+## Phase 3 — smallest shared repair, one failure class at a time
+
+Prioritize demonstrated blockers by number of frozen cases helped and blast radius:
+1. Incorrect target/capability evidence preventing a supported action.
+2. Incorrect readiness/selection/commit handling where raw AX proves a working path.
+3. Safe stale-target recovery with sufficient stable identity.
+4. Misclassified delivery, false verification or duplicate retries.
+Safety defects take precedence over this ordering whenever observed.
+
+Patch the macOS adapter when the defect is platform-specific. Patch core only
+when the cross-platform contract is wrong and reproduce it with a mock. Reuse
+existing resolution, deadline, lease and verification helpers; do not add another
+retry loop or increase all timeouts. No app-name production special cases.
+
+Before every repair, record: failing case, cause, affected callers, behavior kept
+unchanged, deterministic regression, real-app acceptance check, and rollback diff.
+An unchanged post-state after a short wait is not universal proof of non-delivery.
+In particular audit selection fallback for delayed side effects: do not broadly
+continue after unverified AXPress or turn unknown delivery into a safe retry.
+
+Tests exercise stable identity, replacement with the same identity, removed target,
+lookalike ambiguity, delayed readiness, delayed effect after native timeout,
+unsupported attributes, read failures and deadline exhaustion only as implicated
+by the repair. Use scripted responses/clock control at existing seams rather than
+wall-clock sleeps. Assert target identity, native dispatch count and disposition,
+not just ok=true. Failed core preflight must cause zero native mutation calls.
+
+## Phase 4 — verification and repeatability
+
+- Serialize complete document-edit workflows; per-command locking is insufficient
+ for an app with one active editor. Never automate concurrently with another run.
+- Poll explicit readiness/effect predicates under a bounded deadline. No fixed
+ sleeps as the success oracle and no automatic rerun-until-green in the evaluator.
+- Capture and inspect same-window screenshots before and after text mutations.
+ Compare the exact requested token against visible editor text, AX readback and
+ the document model. Distinguish seeded content from action results, and visible
+ editor changes from committed cell values. Conflicting evidence stays unresolved.
+- Capture foreground changes throughout the run, physical pointer samples and
+ available delivery/input instrumentation. Endpoint equality alone cannot prove
+ no temporary side effects. Report monitoring limitations and user interference.
+ Interference invalidates a run separately; retain its evidence and count.
+- Keep raw logs local/redacted; owned content only. Record pass, task failure,
+ unsupported, prerequisite blocked, contaminated and not-run distinctly.
+- Compare immutable before/after binaries against equivalent fresh seeds in
+ alternating order. Report per-case counts, workflow completion and p50/p95
+ CLI latency separately from model/tool/overlay overhead.
+- Run focused regression, workspace tests, fmt, Clippy, release size and core
+ dependency-isolation checks. Run applicable permissioned semantic/native gates;
+ first inspect their setup for app activation. A gate that violates headless
+ constraints is blocked, not silently run or counted green.
+- Run the existing performance comparison with compatible scenarios and a
+ same-window supplement where name-based probes are ambiguous. Review artifacts;
+ explain intentional cold costs and investigate warm regressions.
+- After fixes, require 30 consecutive valid runs of each claimed supported case
+ across at least three independently reset batches. Failures remain in totals;
+ a subsequent new revision starts a separately identified acceptance series.
+ This is a local gate, not a statistically established universal success rate.
+
+## Scorecard and exit criteria
+
+Keep the provisional 6/10 distinct from the first measured score. After the baseline,
+score each category from frozen cases, showing numerator/denominator and evidence:
+
+| Category | Points | Measurement |
+|---|---:|---|
+| Real-app task completion | 4 | Mean per-case verified completion fraction; unsupported/incomplete tasks do not pass |
+| Safe recovery | 2 | Predeclared recoverable scenarios complete; ambiguity/removal cases correctly refuse |
+| Delivery and verification correctness | 2 | Reported scope/disposition agrees with independent observed outcome |
+| Headless compliance | 1 | No prohibited effects with sufficient monitoring; unknown evidence earns no credit |
+| Repeatability | 1 | Fraction of eligible cases completing all required reset batches |
+
+Do not inflate the total with fixture counts or hide a weak app behind another app's
+success rate. Publish per-app/category results, coverage and unsupported task gaps.
+An incomplete denominator is an incomplete score, not a rounded-up rating.
+Any wrong-target mutation, duplicate non-idempotent effect, false verified claim,
+or prohibited input/focus effect is a hard release failure regardless of score.
+
+Target 8/10: measured coverage and all claimed supported cases meet the repeated
+acceptance gate with no safety failure. Target 9/10 additionally needs a second
+native app, recovery perturbations and persistent outcomes across separate runs.
+Passing the entire declared suite may be labeled local acceptance complete.
+It does not establish universal reliability or Playwright parity. Any 10/10 label
+must explicitly state this limited scope and retain unmet required tasks.
+
+## Deliverables and stop rules
+
+Deliver a small runnable real-app evaluator, frozen case definitions, baseline and
+candidate JSON results, core/adapter/platform failure ledger, minimal tested fixes,
+and a concise report with measured score, headless evidence and unresolved limits.
+
+First execution milestone is the Numbers baseline and differential diagnosis.
+If cell editing fails in raw AX under all tested allowed preconditions, preserve
+it as an unmet Numbers task and improve proven AD defects; do not spend the whole
+project searching for physical or private-API workarounds. If independent outcome
+verification is unavailable, report the case unverified rather than upgrading it.
+Finish each repair with its live reproduction and blast-radius checks before
+starting another. Stop adding infrastructure once the evidence loop is runnable.
diff --git a/docs/plans/2026-09-20-retained-native-ref-identity.md b/docs/plans/2026-09-20-retained-native-ref-identity.md
new file mode 100644
index 000000000..db2de925a
--- /dev/null
+++ b/docs/plans/2026-09-20-retained-native-ref-identity.md
@@ -0,0 +1,381 @@
+# Retain native identity across commands
+
+Status: core and native retention implemented; persistent CLI host pending; unqualified.
+
+## Decision
+
+Keep the native accessibility object observed for each ref alive in a headless
+command host. Start the host automatically for the selected snapshot namespace;
+explicit sessions use their existing namespace. Ordinary snapshot/action usage
+must not require users to manage a daemon. This deliberately advances the small
+part of the deferred daemon phase needed for ref identity, not the entire phase.
+
+The user delegated this architecture decision on September 20 after the Xcode
+and isolated fixture reproductions. No further architecture approval is needed.
+
+The current resolver mistakes a repeated AXIdentifier plus reused position for
+identity. The retained-object Xcode probe preserved the original object while
+the CLI returned the replacement. Neither matching mutable values nor searching
+more broadly solves this general case. The fixture reproduces it without AXRow.
+Evidence: ../solutions/runtime-errors/2026-09-20-xcode-filter-ref-alias.md.
+
+## Smallest implementation boundary
+
+1. First prove retained identity and current-tree membership on the existing
+ RefChurnView, including replacement, restoration and ordinary same-ref edits.
+ A retained object can remain readable after removal; readability alone must
+ never authorize an action. Use native equality, not pointer addresses or
+ hashes, to compare a retained object with candidates in its original scope.
+ Also test native object reuse for different backing items: retention is not
+ assumed to solve virtualization by itself.
+2. Capture handles during the observation that creates refs. Retaining an object
+ found later through the existing heuristic resolver would preserve the bug.
+ Keep all native objects on their owning thread. Core carries opaque evidence;
+ platform code owns native objects and validates live process/window/scope.
+ Use the shared resolver for get, is, actions, snapshot roots and find roots.
+3. Keep CLI as a thin transport into the existing typed command dispatcher,
+ preflight, leases, deadlines, delivery dispositions and JSON envelopes. Batch
+ uses that same path. FFI already has a thread-local owned-handle registry;
+ reuse its ownership pattern and consolidate only the genuinely shared part.
+ Do not route existing in-process FFI native handles through a second IPC hop.
+
+Use stdlib local sockets and existing private endpoint/spawn patterns from the
+cursor overlay where applicable; do not couple identity retention to the overlay
+GUI or its lifecycle. No new dependency, service framework, alternate action
+engine, private AX serialization API, or app-specific identity rule.
+
+## Failure and lifecycle contract
+
+- Bind retained tokens to host generation, snapshot namespace, process instance
+ and source window. Never serialize a raw native pointer as identity.
+- A dead/restarted host invalidates its refs. Return STALE_REF with fresh-snapshot
+ recovery; never silently downgrade a retained ref to heuristic matching.
+- A removed target cannot resolve to another object with identical attributes.
+ Recovery may find the same object after movement; it cannot choose a lookalike.
+- Scoped re-drill releases invalidated descendants and preserves sibling refs.
+ Session end releases its objects; idle expiry bounds implicit-host lifetime.
+ Capacity exhaustion must be explicit, not silent identity weakening.
+- Validate private endpoint ownership, namespace and protocol version. Bound
+ request size, connection/read/write time and queue time within command budgets.
+ Serialize execution on the owner thread; concurrent startup needs one winner.
+- After a request may have reached the host, a lost reply is uncertain delivery.
+ Never automatically resubmit a mutation. Preserve the existing unsafe-retry
+ disposition rather than pretending transport failure means not delivered.
+- No app activation, physical input, cursor movement or clipboard insertion.
+ Retention changes identity, not interaction policy or platform capabilities.
+
+## Required evidence before enabling by default
+
+The first gate is the existing isolated churn fixture, with visible backing-value
+guards. Original refs must never read or write Beta after Alpha is removed.
+Same-ref stable-field edits must still work. Inspect screenshots and raw public
+responses; raw AX is a separate oracle. Test restoration and native object reuse
+explicitly before claiming stale recovery.
+
+Add deterministic checks at existing seams for host loss, cross-namespace refs,
+process/window replacement, scoped invalidation, concurrent startup, deadline
+exhaustion and lost mutation replies. Assert exact target and dispatch count,
+including zero mutation calls on identity failure. No sleep-based pass criteria.
+
+Then repeat the Xcode filter case headlessly without writing project labels.
+Run existing workspace, semantic fixture, CLI/batch/FFI conformance, dependency
+isolation, format, Clippy, release-size and performance gates. Measure cold host
+startup separately from warm commands. Finally run acceptance-v1 across Xcode
+and SF Symbols on one immutable candidate; D1 remains an unmet independent task.
+
+Retention does not establish universal identity for apps that recycle native
+objects, nor create semantic drag support. The provisional rating stays 8/10;
+only the declared acceptance evidence can justify a higher scoped rating.
+
+## First native gate results
+
+`tests/real-apps/retained-identity-probe.swift` compiled and ran against owned
+fixture PID 80361, window w-20092. It performs reads only; mutations used raw
+Agent Desktop CLI responses and refs from snapshot s3o796sfka9h13.
+
+All five explicit assertion stages passed: initial, filtered, restored, edited,
+and cleared. Initially the retained Alpha object occurs once in the live tree.
+After filtering it occurs zero times and reads return InvalidUIElement (-25202).
+Live Beta is never CFEqual to retained Alpha. Restoring Alpha creates a different
+native object; the original stays invalid. The stable editor remains the same
+native object through filtering, restoration and both text edits.
+
+This establishes the required distinction for this fixture: same-object edits
+remain addressable; destruction/recreation requires a fresh ref. It does not
+prove identity for virtualized controls or implement the product correction.
+The old CLI still returned Beta through the saved Alpha ref during filtering.
+
+The first trial's headless monitor was contaminated: target activation, several
+other foreground changes, physical input and pointer movement occurred. These
+session-wide events cannot be attributed by the monitor; this is not a headless
+pass. The second assertion trial was unmonitored and carries no headless claim.
+The viewed screenshot /tmp/ad-native-eval/retained-identity-restored.png showed
+the first trial's original backing values restored. Both trials restored values.
+
+## Core implementation checkpoint
+
+Observation identifier evidence now carries a separate opaque retained-object
+token. Snapshot projection preserves it internally without exposing it in the
+public tree; snapshot allocation and find materialization persist it in ref
+identity. Native IDs remain unchanged for queries. Saved retained identity takes
+precedence over repeated native IDs, while mutable values remain volatile.
+Hydration cannot substitute geometry when retained identity is missing.
+
+Four focused checks pass: replacement/host-generation rejection with editable
+values, equivalent snapshot/find persistence and serialization, empty-token
+refusal, and hydration without identity downgrade. Existing constructor changes
+initialize the optional field to None. No adapter produces these tokens yet;
+the live wrong-target bug therefore remains unresolved.
+
+Workspace tests passed with required local socket permissions; the earlier
+sandbox run failed 13 endpoint tests because local binding was prohibited.
+The final hydration guard passed its focused check after the workspace run.
+Clippy initially caught test-module placement; it was corrected and the final
+all-target check passed. Format and diff whitespace checks passed. Logs are in
+/tmp/ad-native-eval/retained-evidence-*.log. Native gates and performance comparison
+remain required after the adapter and host are connected.
+
+## Adapter and real Xcode checkpoint
+
+RetainedRefSession now owns a bounded thread-local native object store. Traversal
+captures actual observed objects; the resolver and live pre-dispatch reads use
+the same evidence. Native equality distinguishes objects within hash buckets;
+hashes are not identities. Dropping the owner invalidates its tokens. Tests cover
+owner replacement, cross-thread refusal, null objects, hash collision and capacity
+exhaustion. The store still needs snapshot/session lifecycle pruning and the CLI
+host. Default CLI behavior has not changed to use retention.
+
+The persistent adapter fixture test passed all five stages, including same-object
+edits. Its initial direct-adapter observation failed the existing accessibility
+readiness requirement; the test was corrected to use public core resolve_query.
+Workspace tests passed, seven retained-focused checks passed, and all-target
+Clippy passed. Fixture values were visually verified restored before closing it.
+The fixture monitor had no prohibited events but did not cover the complete
+67-second assertion trial, so it is not a full headless qualification.
+
+Real Xcode: PID 24741, w-19740, user-opened cursor-cam project. The ignored
+retained_xcode_identity diagnostic performs read-only core/adapter calls;
+filter mutations use raw public CLI responses from the immutable baseline.
+First, Strict + FullRefMap timed out after five seconds, with a matching label
+observed but incomplete reads. This failed trial remains an open broad-query
+reliability issue. First + SelectedMatches then captured the original label.
+
+During that second trial:
+
+- Initial retained ref read CursorCamApp.swift.
+- Public CLI set-value on navigator filter e246 applied CursorCamAppDelegate.
+- Retained ref returned STALE_REF; baseline public get on e267 incorrectly
+ returned CursorCamAppDelegate.swift in that same filtered state.
+- Public clear restored the navigator. The retained ref remained STALE_REF,
+ consistent with destruction/recreation; it never attached to the replacement.
+- The three-stage adapter diagnostic passed. No file-label mutation was attempted.
+- Viewed /tmp/ad-native-eval/retained-xcode-filtered.png and
+ /tmp/ad-native-eval/retained-xcode-restored.png: filtered list and full restored
+ list agree with expected effects; the navigator filter is empty again.
+
+The first observation monitor was contaminated by session-wide physical activity.
+A separate 120-second monitor was started before the second trial's initial read
+and filter mutation. It recorded no Xcode activation, but session-wide input,
+pointer changes and other-app activations later in its interval. Therefore it
+does not qualify as a clean headless trial. This is a real-app adapter safety result, not a CLI repair or an
+overall reliability score. Performance and final CLI acceptance remain pending.
+
+## Internal command host checkpoint
+
+CLI execution now returns its result independently of output emission. An internal
+stdio host, enabled only by AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1, holds the native
+owner and accepts newline-delimited JSON arrays of CLI arguments. It invokes the
+same parser, policies, dispatcher and envelope construction as normal commands.
+Requests cannot switch session namespaces; incomplete/oversized requests do not
+dispatch. Reply failure stops the stream without replaying a command.
+
+This is a testable transport integration step, not the automatic host lifecycle.
+Normal invocations still require automatic connection/startup, deadline and idle
+handling, pruning, session-end cleanup, and the remaining acceptance gates.
+# Scoped drill and internal-host Xcode checkpoint
+
+Performance follow-up (supersedes the three-round regression signal below):
+ten alternating rounds before optimization measured full Xcode snapshots at
+574.2ms vs baseline 622.0ms and depth-30 at 595.1ms vs 574.3ms. The large earlier
+slowdown did not reproduce. Diagnostics identified a duplicate AXValue
+settability query: state observation and action discovery queried it separately.
+Action discovery now reuses the same observation's known readonly result; an
+unknown result still performs the native probe. No cross-command cache is used.
+Observed settability reads fell from 390 to 354 with 210 nodes and 143 refs.
+
+The benchmark now retains immutable binaries, isolates AGENT_DESKTOP_HOME instead
+of HOME, retains every timing, and requires every snapshot to be complete and
+shape-stable before reporting a comparable shape. Tests cover inconsistent and
+incomplete samples. Ten alternating optimized-versus-previous rounds passed:
+depth-30 medians 276.1/282.7ms, full interactive 271.0/272.6ms. A separate ten-round
+optimized-versus-merge-base run passed with full interactive 599.7/588.3ms,
+depth-30 577.4/583.7ms, skeleton 262.0/257.2ms, first-button find 384.8/373.4ms.
+All snapshots in both runs were complete with stable, matching shapes. Absolute
+latencies varied between runs; these results do not establish a universal latency
+bound or identify the cause of the original short-run spike.
+
+Final comparison: `/tmp/ad-native-eval/perf-final-baseline/report.html`.
+Raw before/after: `/tmp/ad-native-eval/perf-settable-ab.json`.
+Candidate SHA256: `4def83f565ae1375e9d28476eebfbb68afc3c2036b641ea045893d95ad53b831`.
+Baseline SHA256: `dbc6036607681ee73b0e66a23d895864b793ba0be2278237cf76bc7984b1cbe0`.
+Eleven action-list tests and benchmark tests passed; all-target clippy passed.
+
+Input lifecycle: the internal stdio host now bounds idle input at 15 minutes and
+an in-progress frame at five seconds using poll under an absolute deadline.
+Buffered requests remain separate; input expiry stops before dispatch and returns
+TIMEOUT/not_delivered. Existing lost-reply handling still prevents replay.
+Eight host tests cover buffered frames, partial-frame expiry, expired idle input,
+size limits, session isolation, and lost replies. A real process with stdin held
+open after one `[` exited in 5.783 seconds without executing a command. That probe
+first exposed INTERNAL/unknown classification; the subsequent fix and envelope
+test require TIMEOUT/not_delivered. At this checkpoint output backpressure was still unbounded, and
+automatic socket startup/routing remains pending. No desktop state was changed
+by this input-lifecycle probe.
+
+Host retention lifecycle follow-up: before the next request after each 4,096
+new captures, the internal host reads retained tokens from all saved snapshots
+in its selected namespace under the existing ref-store lock. It drops objects
+with no saved token. Inventory/read failures abort pruning and prevent that
+request from dispatching; they never turn a partial inventory into eviction.
+Tokens use a monotonically increasing counter and explicit live membership, so
+pruned tokens cannot alias subsequently captured objects. The 65,536-object
+capacity remains a fail-closed bound. Six focused core and eight native tests,
+including namespace isolation, corrupt inventory, pruning and token non-reuse,
+passed; all-target clippy passed. This is still internal-host lifecycle work,
+not automatic CLI transport.
+
+The release performance comparison finished before this pruning change:
+`/tmp/ad-native-eval/retained-recovery-perf/report.html` (three read-only Xcode
+rounds; fixture intentionally skipped). Every case succeeded. Full snapshot
+median was 2,374.6ms vs 977.0ms baseline, depth-30 828.5ms vs 658.7ms, skeleton
+273.1ms vs 275.0ms, first-button find 365.6ms vs 365.2ms. Full-snapshot regression
+signal is unresolved: full-snapshot shapes differed by one node/ref, so the
+report marks that comparison non-equivalent. Depth-30 shapes matched and its
+median increased 25.8%. Three rounds cannot establish the cause. This run does not
+exercise the internal host or qualify its memory lifecycle.
+
+Follow-up: the post-write AXRole failure originated in `ax_helpers::element_role`
+inside `set_dynamic_verified`, after the setter had completed. The existing
+capability read retry loop is now shared through `tree/read_recovery.rs`; role
+reads use it too. Only kAXErrorCannotComplete retries, at most three reads under
+the original deadline. Setter delivery and mutation retry behavior are unchanged.
+Deterministic tests check recovery, terminal error classes, attempt limits, and
+expired budgets. Workspace library tests and all-target clippy passed. The first
+sandboxed macOS run had six socket-permission failures; the authorized workspace
+run passed. Both logs are retained under `/tmp/ad-native-eval/read-recovery-*`.
+
+New internal-host candidate `/tmp/ad-native-eval/read-recovery-candidate`:
+Xcode snapshot `s1go8vsir5pm7h`, filter `e3`; set-value CursorCamAppDelegate and
+clear both returned delivered_verified (149ms and 54ms lease holds). Screenshot
+`/tmp/ad-native-eval/read-recovery-restored.png` was viewed and confirms restoration.
+This live run did not expose retry counts and therefore does not prove a transient
+failure occurred during it. Host closed normally; no files were edited in Xcode.
+
+Candidate `/tmp/ad-native-eval/scoped-drill-candidate`, SHA256
+`6cfcd744c8e0fda3d0ca6b70180e9f4896623ca869d605b70c3149f2892a877d`.
+The previous internal-host navigator drill failed with a CoreGraphics inventory
+timeout. Inspection found that `resolve_result_window` enumerated all apps despite
+having a source app. It now supplies the existing app filter while retaining exact
+window-ID and PID checks. All 14 snapshot-ref tests pass, including the source-app
+filter assertion. Formatting and diff checks pass.
+
+Live Xcode window `w-19740`: skeleton `s1ww1okjjddk91`, navigator root `e2`
+drilled successfully. Its `e39` represented CursorCamApp.swift. Setting navigator
+filter `e3` to CursorCamAppDelegate returned APP_UNRESPONSIVE for AXRole (-25204),
+with the requested value in post-state and delivered_unverified/unsafe disposition.
+The write was not retried. Reading old `e39` returned STALE_REF instead of the
+remaining Delegate label. Clearing `e3` returned delivered_verified; a screenshot
+at `/tmp/ad-native-eval/scoped-drill-restored.png` was viewed and confirmed the
+empty filter, restored navigator, and unchanged editor selection.
+
+Two real-app value-wait checks: empty value matched in 15ms; an absent value
+returned TIMEOUT under a 200ms budget with matched=false. These are single-run
+checks, not qualification of all waits. The 60-second monitor contained unrelated
+input and activation of PID 35000, so it cannot qualify headless execution.
+The internal host was closed after restoration. Automatic ordinary-CLI hosting,
+repeated acceptance runs, and the new performance baseline remain pending.
+
+## Output backpressure process gate
+
+A child-process probe reproduced a shutdown hang: the host detected its write
+timeout, but global StdoutLock buffered bytes blocked process exit until the caller
+drained stdout. The previous release remained alive after eight seconds; draining
+65,768 bytes released it. The host now owns an unbuffered File cloned from stdout,
+with a local BufWriter above the deadline writer, so buffer flushing stays bounded.
+
+The process regression limits the output socket buffer, leaves output unread and
+stdin open, and queues a second request. It requires exit 1, timeout diagnostics,
+and an unfinished first frame without a second response. The final implementation
+passes. Ten host unit tests pass. Logs are under /tmp/ad-native-eval/host-process-fix.log,
+host-unit-final.log and host-clippy-final.log. Automatic ordinary CLI routing and
+real-app acceptance remain incomplete; this check does not raise the rating.
+
+## Separate-connection server checkpoint
+
+The internal host can now listen on a private Unix socket while keeping the
+same RetainedRefSession on its owner thread across connections. Each connection
+accepts exactly one request; malformed input or a lost client does not terminate
+the owner. The socket requires an absolute path under an owner-only directory,
+checks peer UID, and bounds idle, frame and output waits. It uses the same parser,
+dispatcher, retention pruning and output envelope as the stdio host.
+
+Eleven host unit tests passed. Two child-process checks passed in 5.69 seconds:
+unread-output termination and malformed-client recovery followed by separate
+version requests, including rejection of a second queued request on one connection.
+The initial sandboxed socket-binding run failed; the authorized local-socket run
+passed. Logs: /tmp/ad-native-eval/host-socket-tests.log and host-socket-process.log.
+Test children were reaped. Automatic client routing, endpoint discovery, startup
+serialization, request-context transport and queue-budget enforcement are still
+pending. The socket mode remains internal and is not enabled for normal commands.
+
+## Experimental automatic client checkpoint
+
+With AGENT_DESKTOP_INTERNAL_HOST_CLIENT=1, separate CLI processes now discover or
+start a private socket host and forward requests through the existing parser and
+dispatcher. Startup and host ownership use the existing FileLock. Endpoint identity
+includes protocol, executable metadata, state root, namespace and helper path;
+the server compares the full identity, not merely its socket-name hash. Requests
+carry working directory and agent identity. Startup failures are not replayed;
+lost replies return delivery_uncertain/unsafe. No default routing is enabled yet.
+
+Twelve focused unit checks passed, including rejection of wrong identity or
+namespace before changing working directory. Three process checks passed in
+5.68 seconds, including two simultaneous initial CLI invocations and confirmed
+same-PID reuse by a subsequent invocation. Test hosts were terminated. Logs:
+/tmp/ad-native-eval/host-client-final-tests.log, host-client-process.log and
+host-client-clippy.log. The first log intentionally filters unit tests; the second
+is the unfiltered three-process-test run. All-target Clippy passed.
+
+Before default routing: replace the experimental fixed response timeout with
+command-aware queue and execution budgets, bound connection establishment, test
+restart/stale refs and namespace isolation through the client, and run real Xcode
+acceptance. Batch namespace changes, session-end release, cancellation, diagnostic
+forwarding and per-command environment behavior also need review. These are
+unfinished integration requirements, not a claim that the product ref bug is fixed.
+
+## Closeout at user request
+
+Work stopped after finishing the in-progress deadline boundary. The experimental
+client derives a total budget from typed command arguments and optional post-action
+wait, carries an absolute monotonic expiry, and uses remaining time for startup
+and response waiting. The server rejects expired requests before dispatch and
+passes remaining time into the existing CommandContext deadline. Unix connection
+establishment is nonblocking and deadline bounded. Lost replies remain uncertain
+and are never replayed. Sleep commands retain their requested duration plus the
+standard preflight allowance; response delivery has a bounded grace period.
+
+Final focused results: 15 host unit tests and three process tests pass, including
+an expired session-start request that returns TIMEOUT/not_delivered and creates
+no session artifact. Concurrent startup and same-PID reuse still pass. All-target
+Clippy, formatting and diff checks pass. Logs: /tmp/ad-native-eval/host-budget-tests.log,
+host-budget-process.log, host-budget-clippy.log and final-workspace.log.
+
+The client is still experimental behind AGENT_DESKTOP_INTERNAL_HOST_CLIENT=1.
+Do not enable default routing based on this checkpoint. Remaining work includes
+restart/stale-ref tests through the client, real Xcode acceptance, batch namespace
+handling, session-end release, cancellation and diagnostics/environment parity.
+Post-action wait shares the total transport budget; independent primary-phase
+queue accounting needs review. The final host integration has not received a new
+performance baseline or full real-app qualification. Prior performance measurements
+do not qualify it. No commit, push or release was made. Provisional rating remains
+8/10; the requested 10/10 objective was not achieved.
diff --git a/docs/solutions/runtime-errors/2026-09-19-numbers-reliability-baseline.md b/docs/solutions/runtime-errors/2026-09-19-numbers-reliability-baseline.md
new file mode 100644
index 000000000..eeb43f656
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-19-numbers-reliability-baseline.md
@@ -0,0 +1,351 @@
+---
+module: agent-desktop
+date: 2026-09-19
+problem_type: runtime_error
+tags: [numbers, reliability, macos]
+---
+
+# Numbers reliability baseline: direct model-facing CLI
+
+Status: the follow-up timed sprint reached **7.5/10 provisional engineering
+confidence**, from the user's 6/10 baseline. The full repeated acceptance gate
+remains incomplete; this is not a measured overall success rate. Earlier results
+below are retained chronologically, including failures.
+
+The [native initialization follow-up](2026-09-20-native-accessibility-initialization.md)
+repairs missing cells after a cold launch. Text replacement and commit remain unmet.
+
+The subsequent [Xcode evaluation](2026-09-19-xcode-headless-evaluation.md) adds
+verified persistent editor changes, an absent-live-bounds repair, and shared
+deep-menu discovery/inventory repairs. It does not replace the Numbers gaps.
+
+## Boundaries
+
+The evaluation uses disposable `AD Reliability.numbers`, with duplicate
+`Eval Grid` tables on two sheets and known guard values. Setup scripting and
+independent document reads are not counted as Agent Desktop task completion.
+After the user clarified the evaluation contract, all target selection used
+unmodified public CLI responses. No external JSON extractor selected refs.
+The earlier Python-filtered discovery output is not caller-facing acceptance
+evidence. TextEdit exploration is excluded; the active evaluation is Numbers.
+
+Baseline binary SHA-256:
+`d8e6e24ed24d8a8f99233880bd9317abbd8220cf6c58cf63d3989335d45ce5b2`.
+It includes the preceding Chromium activation repair. Run artifacts and the
+baseline diff are local under `/tmp/ad-native-eval`.
+
+## Observations
+
+| Case | Evidence | Status |
+|---|---|---|
+| N1 discovery | Raw skeleton returned 79 refs; direct table drill exposed rows/cells | Usable, noisy; no compactness claim |
+| N2 cell click | Initial click timed out at the CG/AX window bridge before dispatch; later same ref succeeded and entered edit mode | Mixed; failed attempt retained |
+| N3 original cell ref after click | `seed-target` became `seed-target, Is Editing`; original ref-root drill returned STALE_REF | Unresolved identity gap |
+| N4 editor replacement | `set-value` returned ACTION_FAILED after AXValue success with unchanged text | Task failed; false verified claim avoided |
+| N4 editor insertion | Separate `type` trial returned ACTION_FAILED after AXSelectedText success with unchanged text | Task failed; no physical fallback |
+| N5 formula | Headless cell editing not established | Not run; dependent task blocked |
+| N6 sheet switch | AX click changed active sheet; independent model confirmed both guard cells intact | Switch worked |
+| N6 command agreement | Same ref: `is checked=true`, `get states=[]` | Proven core defect; repaired |
+| N6 read resolution | `get` repeatedly timed out at approximately 750 ms while `is` later resolved the same ref | Proven unused core deadline budget; repaired |
+| N7 table dimensions | Original incrementor ref changed 8→9→8 rows; document model confirmed 9 and guard values after first change | Positive live evidence, no 30-run claim |
+| N8 persistence | Background Save menu was reported disabled; close/reopen task not completed | Not run to completion |
+
+Raw AX independently reopened the unchanged B2 editor and wrote AXValue. Native
+return was success, but the before/after value remained `seed-target`. The editor
+advertises writable AXValue and AXSelectedText. This establishes a native no-op
+under the tested conditions, not an adapter-only defect or proof that no allowed
+semantic path can ever work. Independent Numbers reads confirmed B2 and C2
+unchanged. Raw AX is a diagnostic path, not a successful substitute action.
+
+Window availability was intermittent: raw AX also failed to find the owned
+window during one failure, while the document model still reported it visible.
+Later both readers found it. Startup/lifecycle/native availability remains
+unresolved; do not attribute all empty listings to Agent Desktop.
+
+## Repairs and blast radius
+
+1. `get` used saved ref states and bounds after resolving the live element.
+ It now uses the same adapter live-state/bounds reads used by `is`. Native read
+ failures propagate; the existing fallback for adapters without live support
+ is preserved. No new state cache or command-specific platform reader exists.
+2. One-shot ref resolution used a 750 ms polling slice, but never polled.
+ It now passes its existing caller deadline to strict resolution. The shared
+ helper also serves pointer preparation, so that path is included in workspace
+ regression coverage. No deadline is enlarged beyond the caller's budget;
+ action polling retains its original slices, identity rules and retry safety.
+3. Surface array reads bypassed the existing bounded read-recovery helper used
+ by tree traversal. They now reuse it for AXWindows, menus and sheets. Recovery
+ is limited to three read attempts inside the original absolute deadline;
+ permission denial and invalid native handles remain terminal. No mutation
+ retry behavior changes. A surface-boundary regression fails with the previous
+ one-shot read and passes with recovery; additional tests cover terminal errors,
+ empty windows, expired budget and retained native failure telemetry.
+
+Six deterministic regressions cover checked-state transitions in both directions,
+live geometry, unsupported-read compatibility, failed-read propagation, caller
+budget preservation, and no native resolution after expiry. State/error tests
+failed against the old getter. The budget test explicitly checks effective
+capping rather than the nominal timeout label and failed against the old helper.
+No test sleeps or browser/app process is required by these regressions.
+
+The candidate's public batch response on the original Numbers sheet ref now
+returns `get states=[checked]`, `is checked=true`, and `get value=true` together.
+This proves the observed contradiction is fixed; it does not establish all-command
+consistency or complete Numbers automation.
+
+The reverse live transition also passed: the original Sheet 1 ref returned empty
+states and `checked=false`, while Eval Other returned `[checked]` and
+`checked=true`. The independent document model reported Eval Other active and
+both sheet guard values unchanged.
+
+Validation: the full workspace test run passed (2,237 reported passes, four
+ignored, including subprocess test invocations); Clippy with warnings denied,
+formatting and diff checks passed. The candidate executable is 3,072,144 bytes,
+SHA-256 `70154de6eb4e089885736c2266c2895f4f7eac52dd79d46700616a93cc4c9af2`.
+
+The required performance comparison ran against main with passive Numbers
+observations and the activating fixture skipped. All 24 observation commands
+succeeded with matching snapshot shapes. Three-round baseline/candidate median
+milliseconds: interactive snapshot 1322/699, skeleton 469/500, depth-30 734/810,
+first-button find 463/492. These small samples and native timing variability do
+not prove universal performance equivalence or a speedup. The changed getter
+intentionally performs live reads where it previously returned cached fields.
+Report: `/tmp/ad-native-eval/performance/report.html`.
+
+## Remaining evidence required
+
+Visual follow-up: earlier editor probes lacked screenshot verification. A new
+controlled attempt captured the owned window before and after requesting
+`visual-check-0919` through `set-value @srksb992r2n4y:e1`. Both screenshots show
+`other-sheet-guard` in Eval Other / Eval Grid / B2; the document model and AX
+readback agree. That visible string was inserted by fixture setup, not this
+replacement. The CLI returned ACTION_FAILED with delivered_unverified and unsafe
+retry after AXValue reported success. This attempt establishes no visible change
+at the observation times; it does not prove every Numbers editing path fails.
+Artifacts: `/tmp/ad-native-eval/numbers-visible-check.png` and
+`/tmp/ad-native-eval/numbers-after-visual-check.png`.
+
+Further native diagnosis on Sheet 1 / Eval Grid / B2: AXSelectedTextRange changed
+from `{11,0}` to `{0,11}` and AXSelectedText became `seed-target`. A subsequent
+raw AXSelectedText write requested `selection-probe-0919`, returned native success,
+but after two seconds still exposed `seed-target`. The screenshot and document
+model also retained the seed and unchanged neighbor. This rules out an empty
+selection as the sole cause for this trial. Screenshot:
+`/tmp/ad-native-eval/numbers-after-selection-replace.png`.
+
+The preceding CLI AXPress returned `APP_UNRESPONSIVE`, delivery_uncertain and
+unsafe retry, but fresh raw AX found the editor open. It was not retried. This
+is direct evidence that native timeout does not mean non-delivery. Two earlier
+find calls failed while reading AXWindows; subsequent raw AX and CLI reads
+recovered. Screenshots confirmed the owned window remained present. The surface
+read repair addresses the missing bounded recovery, but does not establish that
+every observed native stall fits within the caller deadline.
+
+One sheet transition passed same-ref get/is consistency. Six malformed batch
+requests were rejected before execution because the caller used `ref` outside
+`args` instead of `args.ref_id`; these are driver mistakes, not completed trials.
+No repeated acceptance series has been completed.
+
+The surface-recovery candidate passed the full workspace suite, Clippy with
+warnings denied, formatting and diff checks. Release size remains 3,072,144
+bytes; SHA-256 is
+`862804a33c4aeb4864a5fc182e8b9f1e0473fad1d6f844746c5aefba2d5eec9f`.
+A live candidate find still failed after repeated AXWindows read errors, while
+a subsequent window-scoped snapshot succeeded with 168 refs and complete=true.
+Do not describe bounded retries as a complete fix for native availability.
+
+The follow-up required performance run completed all 24 observation commands,
+but interactive snapshot shapes differed (candidate 4 nodes/1 ref versus base
+84 nodes/79 refs in the recorded sample). Therefore its latency comparison is
+inconclusive. Skeleton and depth-30 recorded shapes matched. Preserve the report
+at `/tmp/ad-native-eval/surface-performance/report.html`; investigate scope and
+completeness before making a performance-equivalence claim.
+
+A separate raw AXWindows timing probe alternated 250 ms and one-second timeouts
+across count, paged-value and single-value reads. All 18 calls succeeded; the
+slowest was approximately 56 ms. This did not reproduce the slow-read hypothesis
+and does not justify changing the shared IPC slice. Numbers already reported
+AXEnhancedUserInterface=true and AXFrontmost=false; AXManualAccessibility was
+unsupported. No accessibility-mode or foreground-state write was made.
+
+## Repeatability runner and fresh-process trial
+
+`tests/real-apps/numbers-sheets.sh` consumes manually selected qualified refs,
+prints/saves original CLI JSON, screenshots every transition, checks both sheet
+values with public waits, and stops on failure. It never parses responses or
+replays a failed mutation. Its failure-stop regression and shell syntax check pass.
+This is a command runner requiring evidence review, not an automatic success judge.
+
+The first ten-transition attempt stopped on its first click with native
+`kAXErrorCannotComplete`, delivery_uncertain and unsafe retry. Its immediate
+screenshot still showed Eval Other; a later independent document read showed
+Sheet 1 active with both guards intact. Keep this as a failed timely command
+with a subsequently observed effect, not a clean transition or safe retry.
+Evidence: `/tmp/ad-numbers-sheets.st8KXa`.
+
+A one-second process sample found the main thread waiting in the normal event
+loop and a HIServices support thread suspended beneath
+`SOME_OTHER_THREAD_SWALLOWED_AT_LEAST_ONE_EXCEPTION`. This is diagnostic evidence,
+not a demonstrated cause. Only the owned document was open. It was closed for
+fixture reset, the empty app quit, and the seed reopened with activates=false.
+The foreground PID remained 860 at both endpoints. New Numbers PID 72620 and
+window w-16255 replaced PID 19934/window w-15245; old refs must not be reused.
+
+In the fresh process, screenshot-visible cells were absent from both CLI find
+and raw AX; AXEnhancedUserInterface was false. Enabling the advertised flag
+returned -25208 but read back true, and the cell became discoverable. The next
+headless CLI cell click completed in 143 ms with delivered_verified. A new editor
+set-value attempt requesting `fresh-process-0919` still failed verification:
+AX, screenshot and document model retained `seed-target`, with neighbor unchanged.
+Images: `/tmp/ad-native-eval/fresh-before.png` and
+`/tmp/ad-native-eval/fresh-after-set.png`.
+
+The follow-up flag off/on comparison was not a reversible grid-hiding A/B:
+after initialization, cells stayed exposed with the flag false. Their names
+changed to include table/row/column context when false, and shortened again when
+true. Mode was restored to true; Numbers remained non-frontmost. This supports
+an initialization/identity-mode hypothesis, but is insufficient to enable enhanced
+mode for every native app or claim it fixes text insertion. Repeat cold starts
+before changing the shared activation policy.
+
+A second cold start (PID 77926, window w-16288) exposed the grid immediately:
+the first skeleton returned complete=true, 80 refs and the Eval Grid table.
+Enhanced mode read true without a diagnostic write in that process. Consequently
+the first cold-start observation is not a reproducible activation defect. Do not
+broaden native activation based on it. Initialization timing and other AX clients
+remain uncontrolled factors.
+
+## Goal completion audit
+
+The requested 10/10 native-app reliability is not achieved. The three shared
+repairs have deterministic regressions and passing workspace checks, but this
+does not establish complete task coverage. The sheet repeatability run failed;
+cell replacement failed in both direct AX and CLI trials across process resets;
+formula entry and saved/reopened edited content remain uncompleted. Stable cell
+identity across editing and continuous headless monitoring also remain unproven.
+No release, commit or push was performed.
+
+The essential external blocker is a working semantic text-write/commit path for
+Numbers under the required background conditions. AXValue and AXSelectedText
+advertise support and report native success without the requested value becoming
+visible or appearing in the document model. Verified full-range selection did
+not repair replacement. A working independent raw AX reproduction or a change
+in Numbers' accessibility behavior is needed before an adapter fix can honestly
+claim to solve this operation. No physical input, focus stealing, application
+scripting writes or speculative private-API fallback was added to the product.
+
+The first follow-up document query used `Sheet1` and failed. The actual name is
+`Sheet 1`; a fresh inventory and corrected read returned `seed-target`,
+`neighbor-guard`, and `other-sheet-guard`. Do not treat that failed oracle query
+as evidence about document contents.
+
+- Repeat supported cases from clean seeds and test both sheet transitions.
+- Resolve stable grid identity before relaxing any name-based matching rule.
+- Diagnose Numbers headless editor/commit prerequisites through matched raw AX
+ trials; do not replace them with keyboard synthesis or scripting writes.
+- Establish save/reopen and formula completion, or retain them as unmet coverage.
+- Complete continuous foreground/input monitoring. Before/after samples and
+ semantic-only command traces do not prove absence of transient side effects;
+ concurrent user pointer movement prevents a global pointer-stability claim.
+- Report full test/performance results separately from task completion. The
+ planned 30-run, three-reset-batch acceptance gate has not been satisfied.
+
+## Twenty-minute sprint, 2026-09-19
+
+Timebox: 23:37:59–23:57:59 UTC. Score progression: 6.0 initially, 6.5 after
+deterministic core repairs, 7.0 after repeated sheet transitions and workspace
+validation, 7.5 after independently verified row transitions. The requested
+8/10 acceptance level has not been established.
+
+Six additional failure classes were repaired with failing-before/passing-after
+regressions:
+
+1. `get text/value` no longer substitutes stale snapshot content when a supported
+ live reader reports an absent value. Unsupported-reader fallback remains.
+2. `is --enabled` respects explicit live enabled evidence; unknown is reported
+ as inapplicable rather than optimistically enabled, consistent with waits.
+3. `wait --element` uses the shared ref loader, so a missing pinned ref produces
+ the same STALE_REF recovery contract as other ref commands.
+4. Ref resolution and wait predicates reject successful observations arriving
+ after the caller's deadline. Tests expire the supplied deadline rather than
+ asserting fragile elapsed-time thresholds.
+5. Actionability polling honors an explicit non-retryable disposition.
+6. macOS live observation recovers transient CannotComplete reads up to three
+ attempts inside the original deadline. Permission, stale-handle, unrelated
+ incomplete evidence and explicit non-retryable errors remain terminal.
+ Recovery only repeats reads; it never repeats a delivered mutation.
+
+The sixth case was reproduced live: a row-count change took effect in Numbers,
+but the command failed on its post-action read. Screenshot and document-model
+inspection confirmed nine rows. No blind mutation retry was attempted. The
+candidate recovered observation in deterministic injected tests; the subsequent
+live series passed, without establishing that all native stalls are recoverable.
+
+Final immutable binary: `/tmp/ad-native-eval/sprint-final`, SHA-256
+`7ede8cb02945a561033f01f9688e7b74b1a36b3b6b3d24f552e20c3afb74d0d4`.
+Size: 3,072,144 bytes. No production changes followed this build.
+
+Live evidence on the owned Numbers document:
+
+- Ten sheet transitions passed using the original qualified refs. Public wait,
+ get and is responses agreed. Independent final document reads confirmed the
+ active sheet and unchanged guards. Raw JSON and ten screenshots are retained
+ under `/tmp/ad-numbers-sheets.BCbdHd`; first/last pairs were visually reviewed.
+ Runner labels are positional: `sheet-1` files show Eval Other and `other` files
+ show Sheet 1 because those refs were supplied in that order.
+- Ten row transitions (8→9→8, five cycles) passed using the original incrementor
+ ref. Every change was followed by public wait/get and an independent read-only
+ document-model check of row count and both guard values. Runner:
+ `/tmp/ad-native-eval/sprint-rows.sh`. Final screenshot was visually reviewed:
+ `/tmp/ad-native-eval/sprint-rows-final.png`; eight rows and guards are intact.
+
+Full workspace tests passed with native process visibility, Clippy with warnings
+denied passed, formatting/diff checks passed, and core dependency isolation held.
+The initial sandbox-only full run failed two process-level CLI tests during
+native preflight; the native-visible rerun passed. The separate headless semantic
+fixture gate passed seven assertions, including a silent no-op and exactly-once
+effects. These fixture results do not replace real-app coverage.
+
+Final required performance comparison: five rounds, 40/40 successful observations
+with matching recorded shapes. Base/candidate median milliseconds: interactive
+snapshot 613.5/562.1, skeleton 371.0/372.5, depth-30 529.2/551.7, first-button find
+347.8/346.4. Report: `/tmp/ad-native-eval/sprint-final-performance/report.html`.
+The activating benchmark fixture was skipped; semantic fixture tests ran
+separately. Small samples do not establish performance equivalence.
+
+Remaining gaps: cell replacement/commit, formula and save/reopen completion,
+stable grid identity across editing, repeated reset batches, a second complex
+native app, and continuous foreground/pointer monitoring. A transient snapshot
+offscreen/geometry discrepancy was observed but not reproduced under controlled
+conditions; no speculative geometry change was made. Twenty successful warm
+transitions across two operations are useful evidence, not universal reliability.
+All changes remain local on `codex/fix-chromium-ax-activation`; no release or push.
+## Follow-up: semantic commit probe, September 20 UTC
+
+The owned Numbers process/window remained PID 77926 / w-16288. A fresh public
+find returned B2 as `@s2gs3slvqloag0:e1`. One click using the visibility candidate
+returned uncertain AXPress delivery; no retry was made. Fresh find and the
+screenshot `activation-numbers-editor.png` confirmed the B2 editor was open.
+
+Using immutable `activation-candidate` (SHA-256
+`49c75115e6600306ee42947484bc0982126585c0a137909f3d9745740fe84ab7`),
+`set-value @s2nelupcc724hz:e1 commit-probe-0920` returned ACTION_FAILED:
+AXValue reported success but post-state still contained `seed-target`.
+A separately selected neighbor ref, `@s3qfcpezf9cbvy:e1`, was clicked once
+to leave B2 semantically and test whether a commit would expose the replacement.
+This click returned delivered_verified. The independent document read returned
+eight rows, B2=`seed-target`, C2=`neighbor-guard`. Screenshot
+`/tmp/ad-native-eval/numbers-after-semantic-commit.png` agrees and shows C2 selected.
+
+Result: **0/1 replacement-and-leave-editor trials passed on this candidate**.
+The setter failure cannot be explained solely by omitting a subsequent cell
+selection in this trial. Formula entry and persistence remain unmet. The new
+Xcode menu verification repair must not be counted as a Numbers text-edit pass.
+No synthesized input, focus activation or document-scripting write was used.
+
+The independent probe now records app-level focused-element ancestry. After
+the neighbor click, AXFocusedUIElement was an AXTextArea whose immediate parent
+was `neighbor-guard, Is Editing`, then row 2 and Eval Grid. The app exposed
+this hierarchy with Numbers in the background (foreground PID 860 at both
+endpoints). Thus this observation does not justify increasing the adapter's
+three-level focus ancestry walk or replacing semantic input with key events.
diff --git a/docs/solutions/runtime-errors/2026-09-19-xcode-headless-evaluation.md b/docs/solutions/runtime-errors/2026-09-19-xcode-headless-evaluation.md
new file mode 100644
index 000000000..a16cab888
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-19-xcode-headless-evaluation.md
@@ -0,0 +1,232 @@
+---
+module: agent-desktop
+date: 2026-09-19
+problem_type: runtime_error
+tags: [macos, accessibility, headless, xcode, reliability]
+---
+
+# Xcode headless editor and menu evaluation
+
+This follow-up adds a second complex native app without replacing the unresolved
+Numbers cases. Overall engineering confidence remains provisional at 7.5/10;
+neither the repeated acceptance gate nor universal reliability is established.
+
+## Scope and build
+
+Xcode 26.0, PID 17836, process identity `macos-proc-v1:1789862351:629080`.
+Only `/tmp/ad-native-eval/AD Reliability.swift` was edited. Xcode was launched
+through the CLI without activation. Opening the disposable file with `open -g`
+was setup, not a completed Agent Desktop operation. All evaluated interactions
+used refs selected directly from unmodified CLI JSON. No custom JSON extraction,
+keyboard synthesis, pointer input or clipboard insertion was used.
+
+Immutable binary: `/tmp/ad-native-eval/bounds-candidate`, SHA-256
+`fb11a6615075439c5fb2562d85194015c54e2fe29ca722f4a0e338484559c033`.
+State root: `/tmp/ad-native-eval/xcode-state`.
+
+## Outcomes
+
+| Case | Result and independent evidence |
+|---|---|
+| Discover editor | Window w-17124; skeleton then root drill returned Source Editor at `@s32ke2z9l0724g:e7` with SetValue and TypeText |
+| Replace text | Original ref accepted AXValue replacement of seed-target with verified-headless; fresh get, screenshot and file read agreed; neighbor-guard retained |
+| Insert text | Same ref accepted AXSelectedText insertion of a trailing comment; screenshot and file read contained exactly one insertion |
+| Close document | Original Close ref e3 accepted AXPress, honestly reported delivered_unverified; subsequent list-windows showed only Welcome to Xcode |
+| Persistence | Background setup reopened the file as w-17140; fresh find and screenshot retained both edits and the guard. This is independent persistence verification, not an all-CLI reopen workflow |
+| Closed-window ref | Original editor ref refused before and after reopening; returned APP_UNRESPONSIVE after its deadline with resolution_window_bridge_miss. No substitution into the replacement window occurred |
+| Editor options menu | CLI e14 timed out before dispatch because live hidden state was unavailable; no action was delivered |
+| Deep menu discovery | Raw AX subsequently exposed a menu at depth nine; repaired snapshot returned 20 refs, inventory returned the same menu, and a menu-item click dismissed it |
+
+Screenshots were captured and visually reviewed under `/tmp/ad-native-eval`:
+`xcode-before.png`, `xcode-after-set.png`, `xcode-after-type.png`,
+`xcode-after-raw-menu.png`, `xcode-reopened.png`, and
+`xcode-after-raw-show-menu.png`.
+
+## Menu diagnosis: native and adapter limitations
+
+Independent `ax_probe.swift` inspection found an AXMenuButton advertising
+AXShowMenu and AXPress with valid geometry. AXHidden and AXExpanded both returned
+-25205 (unsupported). Apple documents AXHidden as an application-level attribute:
+[kAXHiddenAttribute](https://developer.apple.com/documentation/applicationservices/kaxhiddenattribute).
+
+The adapter's aggregate state-completeness flag becomes false when the expandable
+role lacks expanded evidence. Core then treats absent typed hidden evidence as
+unknown visibility. Thus expansion evidence affects click eligibility. This is
+a real coupling to investigate; no visibility gate was relaxed in this pass.
+
+A direct raw AXPress trial on the owned window returned -25204 after about
+1505 ms. No menu surface appeared and the screenshot showed the editor. After
+closing/reopening the document, a separate AXShowMenu trial also returned -25204
+after about 1505 ms. CLI list-surfaces returned an empty array, but the screenshot
+then showed the editor options menu open. This establishes an effect despite the
+native timeout and a menu-discovery gap at that observation. Neither uncertain
+action was retried. Foreground PID was 860 at both endpoints of both raw trials;
+this is not continuous headless monitoring. The initial interpretation of the
+second trial as no effect was corrected after visual inspection. Removing the
+preflight block alone still does not solve delivery classification or discovery.
+
+A later raw button inspection showed no children and a paired screenshot showed
+the menu had disappeared. Therefore the empty CLI list and visible screenshot
+are not proof of a simultaneous AX omission: asynchronous opening, dismissal or
+client lifetime may explain the discrepancy. Keep this as a discovery/timing
+investigation, not a validated traversal repair.
+
+The closed-ref error also remains unresolved. Current resolution verifies an
+exact CoreGraphics record before matching AXWindows. A retained native window
+record may explain why the closed window is classified as temporarily inaccessible
+instead of stale; that hypothesis requires independent CoreGraphics evidence.
+No title-based retargeting or weakened window identity was introduced.
+
+## Shared getter repair and validation
+
+`get --property bounds` previously returned saved coordinates when the supported
+live reader returned no rectangle. A deterministic regression reproduced that
+stale success. The two-line fix preserves the distinction between absent live
+geometry (JSON null) and an unsupported live reader (existing snapshot fallback).
+Native read errors still propagate. A live get on the reopened Xcode editor
+returned its current rectangle normally.
+
+The focused observation suite passed 19 tests. The full workspace suite passed
+with native process visibility; log `/tmp/ad-native-eval/bounds-workspace-tests.log`.
+Clippy with warnings denied, formatting, release build and diff checks passed.
+Release build emitted an existing SDK-discovery warning; it completed successfully.
+
+Required passive Numbers performance comparison completed 24/24 observations
+with matching recorded shapes. Base/candidate median ms: interactive 554.2/524.1,
+skeleton 359.7/378.9, depth-30 544.3/527.7, find 346.2/330.2. Three rounds are
+insufficient to claim statistical equivalence. Report:
+`/tmp/ad-native-eval/bounds-performance/report.html`. The activating fixture was
+skipped. All changes remain local; no release, commit or push occurred.
+
+## Confirmed deep-menu repair
+
+A subsequent read-only raw AX probe located the open menu at depth nine below
+the owned window, with a submenu at depth eleven. The corresponding screenshot
+`xcode-menu-held.png` showed it open. This resolved the earlier timing uncertainty:
+the adapter's descendant search silently skipped nodes deeper than eight.
+
+The shared menu resolver now traverses by its existing 2,048-node and absolute
+deadline budgets, without the unrelated depth cutoff. Cycles terminate with an
+explicit incomplete-search error. Deterministic tests at depths 9, 11 and 30
+failed before the repair and passed afterward; an expired deadline performs no
+read, and a cyclic tree cannot turn into a successful empty result.
+
+The first repaired snapshot exposed 20 menu refs, but list-surfaces still
+returned empty because inventory used separate shallow discovery. Inventory now
+uses the shared resolver when its existing discovery found no menu. Existing
+surface IDs and non-menu entries are preserved, and already discovered menus
+are not duplicated. Tests cover preservation and error propagation.
+
+Live final verification on raw-AX-prepared menu state:
+
+- `list-surfaces`: context_menu, id resolved/menu, 16 immediate children.
+- `snapshot --surface menu`: 20 refs including four submenu descendants.
+- Click Show Editor Only by its menu ref: AXPress accepted; screenshot confirmed
+ the view changed and menu closed. Its delivered_unverified result was checked
+ independently rather than promoted based on native success.
+- On a separately prepared menu, clicking Canvas requested restoration of the
+ earlier view setting. A fresh list-surfaces returned empty after dismissal;
+ the restored Canvas state was not independently read back.
+
+Menu opening itself still uses raw AX in these trials and remains an unmet
+CLI capability under the observed preflight conditions. No uncertain action
+was replayed, and no visibility safety gate was weakened. The helper now records
+raw menu depth and supports a bounded 15-second client hold for diagnostics.
+
+Final candidate `/tmp/ad-native-eval/menu-inventory-candidate`, SHA-256:
+`26e20ce385f91f1c6bc67e651930005d7acfe3091868fb28aea45f9f25c1a783`.
+The final workspace suite passed; log
+`/tmp/ad-native-eval/menu-inventory-workspace-tests.log`. Clippy with warnings
+denied, formatting and diff checks passed. The surface test selection passed
+13 tests, including native-read recovery cases inherited from the preceding work.
+
+One empty-menu inventory probe on Numbers completed in 0.23 seconds wall time.
+Comet was not running, so its dense-browser latency remains untested. An earlier
+Xcode performance attempt had zero successful observations on both revisions:
+the app had two background windows and unscoped commands correctly returned
+AMBIGUOUS_TARGET. The evaluation-owned welcome window was closed before the final
+comparison; no user document was closed to make that benchmark pass.
+
+Final semantic gate passed seven assertions on the final binary, including
+exactly-once effects, silent no-op rejection and background fixture operation;
+log `/tmp/ad-native-eval/menu-safe-semantic.log`. Final screenshot
+`xcode-final.png` was visually reviewed; the file retains the guard and both edits.
+
+Final three-round baseline comparison completed 48/48 observations across Numbers
+and Xcode with matching recorded tree shapes. Xcode base/candidate median ms:
+interactive 262.0/259.1, skeleton 225.4/223.4, depth-30 258.5/259.7, find
+229.9/243.8. Numbers: interactive 556.0/735.7, skeleton 418.5/393.1, depth-30
+533.5/600.8, find 366.7/367.6. Report:
+`/tmp/ad-native-eval/menu-inventory-performance/report.html`. The Numbers delta
+requires follow-up; successful commands and matching shapes do not establish
+latency equivalence.
+
+A seven-round isolation check compared the final binary with bounds-candidate
+(the build immediately before the menu repairs): 56/56 observations passed with
+matching shapes. Earlier/final Numbers medians were 524.0/505.8 ms interactive,
+377.8/382.9 skeleton, 520.4/526.6 depth-30, and 344.6/346.7 find. This did not
+reproduce the large median regression attributable to the menu-only delta;
+skeleton p95 remained higher (403.6/466.2 ms), so no blanket performance claim
+is made. Raw comparison: `/tmp/ad-native-eval/menu-only-numbers-performance.json`.
+## Follow-up: visibility and menu delivery, September 20 UTC
+
+The earlier editor-options failure is now reproduced and repaired at two
+separate macOS adapter boundaries. These are additional local changes, not a
+claim that Numbers editing or the repeated acceptance gate is complete.
+
+1. With the earlier binary, `wait --predicate actionable` on
+ `@s2anr09ovh7k3f:e1` timed out because missing expansion state also made
+ visibility unknown. The native state read itself was complete. The repaired
+ reader retains known hidden-state evidence independently of unknown
+ expansion state. With `/tmp/ad-native-eval/visibility-candidate`, the same
+ wait passed in 104 ms. Its subsequent single click opened the menu but
+ returned APP_UNRESPONSIVE / delivery_uncertain after AXPress timed out.
+2. A screenshot, raw AX, list-surfaces and a fresh menu snapshot all confirmed
+ that menu was open. Raw AX showed it as a direct AXMenu child of the clicked
+ AXMenuButton, with AXHidden=false and positive geometry. The existing
+ activation verifier observed only focus and selection transitions, so it
+ missed this effect.
+3. The shared activation observation now also reads direct owned menus on
+ native menu controls. Only a known closed-to-visible transition verifies
+ delivery. Unknown reads, an already-open menu, a hidden or zero-size menu,
+ and menus elsewhere in the app cannot establish this condition. The existing
+ deadline, single mutation and uncertain-outcome rules are retained.
+
+The immutable `/tmp/ad-native-eval/activation-candidate` has SHA-256
+`49c75115e6600306ee42947484bc0982126585c0a137909f3d9745740fe84ab7`.
+One live click using the original qualified ref returned delivered_verified,
+one semantic AXPress step, and the resolved/menu surface with 16 immediate
+items. `/tmp/ad-native-eval/activation-xcode-menu.png` independently shows the
+menu open. This is **1/1 candidate menu-opening trials**, not the required
+30 repetitions across three reset batches. A later attempted menu-item click
+on the earlier snapshot safely timed out because that menu had disappeared;
+retain this failed attempt rather than treating it as a completed menu action.
+
+The focused activation tests cover every known/unknown before/after menu-state
+combination and visibility/geometry negatives. The visibility tests preserve
+unknown native evidence and unknown expansion state. Full workspace tests,
+Clippy with warnings denied, formatting and diff checks passed. The seven
+permissioned safe-semantic assertions passed on this exact candidate, including
+single button effect and rejection of silent text-insertion no-ops. These gates
+do not prove Numbers document mutation.
+
+The required three-round comparison completed all 48 observation commands with
+matching recorded snapshot shapes in Numbers and Xcode. Artifacts:
+`/tmp/ad-native-eval/activation-performance/report.html`. Base/candidate medians
+in milliseconds were Numbers interactive 525.6/524.5, skeleton 379.2/368.2,
+depth-30 531.4/535.2 and find 343.9/385.0; Xcode interactive 262.5/273.6,
+skeleton 219.6/218.5, depth-30 265.2/265.4 and find 241.3/244.4. The Numbers
+find sample was about 12% slower; neither changed activation function runs in
+find. Three samples do not establish equivalence or identify its cause. The
+new activation reads need action-specific latency coverage beyond this passive
+comparison. Live menu opening took about 2.93 seconds, including native timeout;
+this repair improves outcome recognition, not that native waiting time.
+
+A seven-round isolated comparison against the prior menu-inventory candidate
+completed 56/56 observations with matching recorded shapes. The Numbers find
+regression did not reproduce: prior/new medians 399.9/395.5 ms. Other prior/new
+medians were interactive 623.0/638.1, skeleton 425.6/448.7 and depth-30
+619.4/622.1. Artifact:
+`/tmp/ad-native-eval/activation-only-numbers-performance.json`. This bounds the
+observed variation but does not establish statistical equivalence. The final
+binary is 3,088,656 bytes and core's dependency tree contains no platform crates.
diff --git a/docs/solutions/runtime-errors/2026-09-20-capability-read-recovery.md b/docs/solutions/runtime-errors/2026-09-20-capability-read-recovery.md
new file mode 100644
index 000000000..2c7d2fcbe
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-capability-read-recovery.md
@@ -0,0 +1,88 @@
+---
+title: Recover transient capability reads before selection delivery
+module: macos adapter
+problem_type: runtime_error
+tags: [xcode, capability, recovery, headless]
+date: 2026-09-20
+---
+
+# Capability read recovery
+
+The previous candidate intermittently failed Xcode collection selection with
+APP_UNRESPONSIVE and a generic incomplete-evidence message. No action was
+delivered. Adding phase and query-stat diagnostics to selection errors identified
+`actions_unknown`, four cannot-complete reads, one native-read failure and no
+deadline exhaustion. This was reproduced by scanning for an absent diagnostic
+label, so the diagnostic itself made no selection. Two subsequent scans on the
+same diagnostic candidate completed with expected ELEMENT_NOT_FOUND.
+
+The capability boundary had no retry for AXUIElementCopyActionNames or
+AXUIElementIsAttributeSettable. These readers are shared by action-list
+observation, readonly checks, renderer probes and advertised-action checks.
+They now retry only kAXErrorCannotComplete, at most three calls, respecting the
+same absolute deadline. Backoff is capped at 1 ms and remaining time. Mutation
+APIs are unchanged and never enter this helper. All other native errors remain
+terminal. Returned CF arrays are released by the existing per-attempt reader.
+
+Deterministic tests cover transient-transient-success including a legitimate
+false result, persistent transient failures capped at three calls, terminal
+permission/invalid-element/generic failures with one call, and no native call
+after an already expired deadline. Existing selection diagnostics now distinguish
+unknown actions/name/description from missing ancestry or its depth limit.
+
+## Live evidence
+
+Candidate `/tmp/ad-native-eval/capability-recovery-candidate`, SHA-256
+`4ea254eb2ddaa095df58d84c9874875c3fcf2e1caf3de51765dea33b510e95af`.
+Public CLI only, raw responses, namespace `/tmp/ad-native-eval/xcode-state`.
+Xcode PID 24741, w-19740, instance macos-proc-v1:1789875340:341343.
+
+- Three independent absent-label scans of collection `@s21x71bw3p1ld3:e1`
+ returned expected ELEMENT_NOT_FOUND / not_delivered. No incomplete-evidence
+ failure recurred in these three scans. This is not statistical qualification.
+- Select CursorCamApp.swift succeeded with semantic verified delivery; select
+ CursorCamAppDelegate.swift restored the original row using the same ref.
+- Select cursor-cam retained AMBIGUOUS_TARGET / not_delivered for duplicate names.
+- The 45-second monitor recorded zero activations, all input deltas zero and
+ unchanged pointer; foreground PID 35000 remained unchanged and Xcode survived.
+- Viewed `/tmp/ad-native-eval/capability-xcode-alternate.png` showed the alternate
+ row selected while the editor still displayed CursorCamAppDelegate. File
+ opening is still unresolved; row-selection verification does not prove opening.
+
+Full workspace, lint and focused capability tests passed. All code stays local.
+Exact-candidate native fixture passed all seven assertions, including background
+ownership, exactly-once effects and rejection of silent text no-ops. Performance
+comparison completed three rounds against the merge base: interactive snapshot
+p50 811.8 vs 772.2 ms; skeleton 282.1 vs 313.0 ms; depth-30 1094.5 vs 680.2 ms;
+find 394.2 vs 415.8 ms. All commands succeeded with matching reported shapes.
+The deep-snapshot slowdown remains unexplained and is an open regression concern;
+this small sample does not establish causality or approve the latency increase.
+Artifacts: `/tmp/ad-native-eval/capability-recovery-semantic.log` and
+`/tmp/ad-native-eval/capability-recovery-performance/app-xcode.json`.
+
+Provisional rating remains 8/10; repeated qualification,
+unnamed-row recovery after geometry changes and remaining application tasks
+remain open.
+
+## Additional column-drilling trial
+
+Same immutable candidate, public raw CLI responses, snapshot `s287cvyqznmcqt`:
+
+- Skeleton returned 22 refs; inspector e9, editor e5, debug e7 and navigator e2
+ each drilled successfully with complete=true and the same window context.
+- Inspector Tab e44 remained readable after all other columns were drilled.
+- Exact textfield name Tab scoped to inspector returned one match; the same
+ query scoped to editor returned zero without truncation.
+- Inspector Text Settings e40 collapsed and expanded through the same ref,
+ both delivered_verified. A live get between actions showed no expanded state.
+- Re-drilling inspector invalidated e44 with safe STALE_REF. Replacement e152
+ returned value 4; editor e53 still returned states; the independent scoped-find
+ ref `@s2rmk0kyenv31d:e1` also still returned value 4.
+- The 60-second monitor covering initial drills and disclosure interactions
+ recorded no activation, no pointer change and zero input-event deltas.
+ Foreground PID 35000 remained unchanged. Later read-only checks and screenshot
+ were outside that monitor interval.
+- Viewed `/tmp/ad-native-eval/xcode-drill-final.png`: original file and selected
+ row retained, inspector Text Settings expanded. No source editing was attempted.
+
+This is one additional successful trial, not the repeated acceptance campaign.
diff --git a/docs/solutions/runtime-errors/2026-09-20-collection-label-selection.md b/docs/solutions/runtime-errors/2026-09-20-collection-label-selection.md
new file mode 100644
index 000000000..53936f09e
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-collection-label-selection.md
@@ -0,0 +1,85 @@
+---
+title: Select collection rows by live editable labels without changing ref identity
+module: macos adapter
+problem_type: runtime_error
+tags: [xcode, selection, ambiguity, headless]
+date: 2026-09-20
+---
+
+# Collection label selection
+
+Xcode Project Navigator exposes file names as AXTextField values inside cells
+and rows. Canonical names intentionally exclude mutable field values. Therefore
+the old collection selection search failed to find a file visible in snapshot.
+Broadening canonical identity would weaken stale-ref safety across all commands.
+
+Collection selection now accepts a live non-secure AXTextField value as a query
+match, then resolves its owning selectable member within the requested root.
+The nearest row takes precedence over its wrapper cell. A field without a
+selectable owner is never pressed. Existing canonically named button-only list
+items remain supported. The ancestry walk must reach the requested collection;
+missing parents and cycles fail before delivery.
+
+The search checks the bounded collection before mutating, coalesces matches for
+the same owner and refuses multiple owners with AMBIGUOUS_TARGET/not_delivered.
+Depth truncation with remaining children cannot prove uniqueness. Menus retain
+their separate name-based matching. Ref naming/identity rules are unchanged.
+Collection delivery reuses the shared guarded container-selection path instead
+of a duplicate AXSelected implementation.
+
+## Candidates and observed outcomes
+
+Initial candidate `/tmp/ad-native-eval/collection-label-candidate`, SHA-256
+`44914c3b5d5f4c032b1dd37b08e947b7070f606fe616148c0e3cbd51bbe578a1`:
+
+- Public find returned Project Navigator `@s21x71bw3p1ld3:e1` in Xcode
+ w-19740, PID 24741, process instance macos-proc-v1:1789875340:341343.
+- Selecting CursorCamAppDelegate.swift succeeded with semantic verified delivery.
+- Selecting cursor-cam returned AMBIGUOUS_TARGET with safe non-delivery; both
+ project and group have that label. Screenshot `/tmp/ad-native-eval/xcode-label-selection.png`
+ was viewed and showed CursorCamAppDelegate selected afterward.
+- The 45-second monitor had zero activations/input deltas and no pointer change;
+ foreground PID 35000 remained unchanged.
+- Reading old unnamed row ref `@s2j42fiokeiy6k:e38` failed bounds mismatch after
+ the earlier window resize (14 identity candidates, none matching geometry).
+ This remains a stale-recovery limitation, not a passing recovery trial.
+
+Final candidate after extracting the same ancestor walk for deterministic tests:
+`/tmp/ad-native-eval/collection-label-final-candidate`, SHA-256
+`1a4972e3c06606bedcf4829d3eb89edff0ddca957924d8704746c1d113ce4f0c`:
+
+- Selecting CursorCamApp.swift failed APP_UNRESPONSIVE with incomplete selection
+ evidence, not_delivered/safe. Retain this failure; do not infer its cause from
+ the generic error. It was not silently retried or counted as successful.
+- Selecting CursorCamAppDelegate.swift succeeded, and cursor-cam remained safely
+ ambiguous. The 30-second monitor recorded no activation/input/pointer change,
+ with foreground PID 35000 unchanged. The duplicate check followed this monitor.
+- SF Symbols outline `@s3jplttya4mw7g:e1` selected Math then All using the same
+ ref. Both reported semantic verified delivery. Viewed screenshot
+ `/tmp/ad-native-eval/collection-math.png` showed Math and 78 symbols.
+ These SF Symbols actions were not covered by a headless monitor, so they prove
+ functional regression behavior only, not complete headless qualification.
+
+## Regression coverage and outstanding work
+
+Deterministic tests exercise the production ancestor walk with scripted nodes:
+field/cell/row ownership, table-cell ownership, refusing ownerless editable
+fields even when named, preserving named button items, nearest nested row,
+missing parent and an eight-read bound on cyclic ancestry. Existing tests retain
+canonical label evidence and uncertain-delivery refusal coverage.
+
+Full workspace tests, clippy, format and diff checks passed on the final source.
+The safe-semantic fixture passed all seven assertions on the exact final hash;
+log `/tmp/ad-native-eval/collection-label-final-semantic.log`.
+Xcode's read-only performance comparison completed 12/12 candidate and baseline
+calls with matching corresponding tree shapes. Candidate/base p50 ms:
+interactive 291.4/283.1, skeleton 197.1/195.8, depth-30 288.8/296.2 and first-button
+find 241.0/224.1. Find tail latency remained high in both (p95 2112.8/2960.3 ms);
+this is not proof of uniformly low latency. Report:
+`/tmp/ad-native-eval/collection-label-performance/report.html`.
+The production changes remain local.
+
+File opening after selection, the intermittent incomplete-evidence failure,
+unnamed-row recovery after geometry changes and repeated qualification remain
+unresolved. No source edits, build/run actions or physical input were used in
+Xcode. The provisional rating remains 8/10 and the goal remains active.
diff --git a/docs/solutions/runtime-errors/2026-09-20-descendant-delivery-stop.md b/docs/solutions/runtime-errors/2026-09-20-descendant-delivery-stop.md
new file mode 100644
index 000000000..32e79c948
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-descendant-delivery-stop.md
@@ -0,0 +1,61 @@
+---
+title: Stop descendant activation after unverified delivery
+module: macos adapter
+problem_type: runtime_error
+tags: [activation, delivery, reliability, headless]
+date: 2026-09-20
+---
+
+# Descendant activation delivery stop
+
+The click and semantic toggle activation chains share activate_descendant. Its
+child/action loop returned only verified outcomes. An accepted native action
+with no observed effect returned DeliveredUnverified, but the loop discarded
+that result and tried another action or sibling before eventually reporting
+NotDelivered. This contradicted the outer chain's no-retry delivery contract.
+
+The loop now uses the existing DeliveryOutcome::terminates_chain predicate.
+Unverified delivery is retained and stops further mutation; unsupported actions
+still allow discovery of a supported sibling. No new fallback or native action
+is introduced. This can expose an unverified result where the previous code
+silently attempted additional mutations; it does not solve Xcode file opening.
+
+The production loop is exercised directly by two deterministic tests: an
+unsupported action followed by unverified delivery makes exactly two calls on
+the first child, and unsupported first-child actions can reach a verified second
+child without touching a third. The first test fails under the previous
+was_verified predicate.
+
+## Validation
+
+Focused regression test and clippy passed. Formatting passed. The first workspace
+run inside the sandbox failed two CLI event-wait process tests while reading
+missing response data; that failure is retained in
+`/tmp/ad-native-eval/descendant-stop-workspace.log`. The native-access full
+workspace run passed, including both new regression tests, with its log at
+`/tmp/ad-native-eval/descendant-stop-workspace-native.log`.
+
+Immutable candidate `/tmp/ad-native-eval/descendant-stop-candidate`, SHA-256
+`5f2bf71761548cd6cbb58b8161b0fbc2dc4bfee033f9d30fec603f93613a2115`.
+The owned background semantic fixture passed all seven assertions on this binary.
+This fixture covers general delivery regressions, not the descendant fault path;
+that path is covered by the deterministic loop tests.
+
+The ten-round merge-base comparison completed with all 80 commands successful.
+Candidate/base p50 milliseconds: interactive snapshot 301.9/306.6, skeleton
+211.1/203.9, depth-30 296.6/298.5, find 230.5/231.1. Reported first-success shapes
+matched. The deep-snapshot slowdown did not reproduce; no performance-specific
+code change was justified by these results. Skeleton median increased 7.2 ms in
+this sample. The runs show substantial between-run latency variation and do not
+establish its cause. Report and JSON are under
+`/tmp/ad-native-eval/descendant-stop-performance/`.
+
+Before this repair, a ten-round read-only A/B isolated capability recovery from
+the preceding collection-label candidate. Deep-snapshot p50 was 693.1 vs 716.7 ms
+and p95 958.5 vs 817.2 ms. The earlier 1094.5 ms median did not recur in that
+comparison. Find p50 was 449.0 vs 397.4 ms. All 80 commands succeeded. This does
+not prove absence of a regression against merge-base or explain the long tails.
+Raw aggregate: `/tmp/ad-native-eval/capability-isolated-perf.json`.
+
+Rating remains provisional 8/10; broad repeatability and file activation remain
+unqualified.
diff --git a/docs/solutions/runtime-errors/2026-09-20-find-name-value-consistency.md b/docs/solutions/runtime-errors/2026-09-20-find-name-value-consistency.md
new file mode 100644
index 000000000..09eb22e15
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-find-name-value-consistency.md
@@ -0,0 +1,34 @@
+---
+module: agent-desktop-core
+date: 2026-09-20
+problem_type: runtime_error
+tags: [find, naming, numbers, consistency]
+---
+
+# Find output invented names from editable content
+
+The owned Numbers editor has no accessible name and value `seed-target`.
+Role-only find returned `name: seed-target`, but exact name search returned
+zero matches. Raw AX confirmed AXTitle was absent and AXValue was seed-target.
+
+Both preliminary match formatting and selected-match hydration substituted
+value, description or synthetic placeholder text into the output name. The
+matcher correctly kept these fields separate. The repair removes those output
+fallbacks and omits empty names through the existing match data serializer.
+Values remain available under `value` and searchable with `--value`. Matching,
+ref identity, recovery and native mutation paths are unchanged.
+
+The Rust field remains String; JSON consumers must now tolerate an omitted name
+for unnamed or unknown-name matches. This deliberately changes the misleading
+output contract. No extra display-label field or name-matching fallback is added.
+The test-only snapshot matcher now uses the same match data serializer.
+
+Regression checks cover known, absent, empty and unknown names while preserving
+values; selected hydration also verifies omitted unknown names. Workspace and
+focused find tests, formatting and Clippy pass. An initial sandbox core run had
+13 loopback-permission failures; the escalated workspace run passed all tests.
+
+Live candidate `f04ade8e00bac484be1a150b5c01fcc2110b7d6d58f396e3ae71e1cc42fd5a0e`
+returned one Numbers editor for table-rooted exact value search, with value
+seed-target and no name. Qualified ref: `@s1msk6byapmamx:e1`.
+This repairs output/query consistency; Numbers text mutation remains unresolved.
diff --git a/docs/solutions/runtime-errors/2026-09-20-locator-hydration-budget.md b/docs/solutions/runtime-errors/2026-09-20-locator-hydration-budget.md
new file mode 100644
index 000000000..1336916a3
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-locator-hydration-budget.md
@@ -0,0 +1,49 @@
+---
+module: agent-desktop-core
+date: 2026-09-20
+problem_type: runtime_error
+tags: [locator, deadline, hydration, sf-symbols]
+---
+
+# Discovery consumed the selected-ref hydration budget
+
+Public `find --app 'SF Symbols' --role button --first` failed after approximately
+five seconds with `Selected locator hydration exceeded its deadline`. This also
+failed all three rounds on both revisions in the canonical-find performance run.
+
+`resolve_query_attempt` gave discovery the entire operation deadline. The macOS
+observer reads the whole bounded tree before core evaluates selection. A valid
+first match could therefore exist before an incomplete later branch, yet the
+selected match could no longer be re-resolved and hydrated into a usable ref.
+
+Selected-ref materialization now reserves up to one second, limited to half the
+remaining duration, within the existing deadline. It uses Deadline::capped;
+hydration retains the original deadline. Count and non-materializing queries
+keep their full discovery budget. Selection completeness and identity checks
+remain unchanged. No extra timeout, mutation retry, native special case or
+alternate dispatcher is added.
+
+This deliberately gives discovery less time when hydration is required. Dense
+queries whose match appears only near the old deadline may still fail. Native
+early termination on a proven selected prefix remains a potential future repair;
+this change does not implement it or promise arbitrary dense-tree coverage.
+
+The deadline regression uses structural capped-deadline assertions, without
+sleeping or tight timing tolerances. Eighty-three locator tests, full workspace
+tests, formatting, diff checks and Clippy passed. The completed performance
+comparison is `/tmp/ad-native-eval/hydration-budget-performance/report.html`.
+SF Symbols first-button find passed all three candidate rounds (p50 4079.8 ms)
+and failed all three baseline rounds. All snapshot modes succeeded on both;
+depth-30 shapes differ, so their latency is not content-equivalent. The script's
+SF Symbols failure marker includes baseline failures; it is not a candidate
+find failure. Three trials do not establish the repeated acceptance suite.
+
+Immutable candidate `hydration-budget-candidate`, SHA-256
+`5199dd002b17c9c56e67e22cbf9cd713aaf4dd832a0a6bfdbe7decd67bf105e8`,
+returned a first-match ref twice in 4.26 and 3.96 seconds. The first ref,
+`@spfk598h1ofka:e1`, resolved with public get in 29 ms. No click was attempted.
+Find reported the scrollbar button offscreen while get-states returned an empty
+array; record this state-evidence discrepancy separately, not as proven parity.
+
+The original goal remains incomplete: Numbers text writes and commits, repeated
+cross-app acceptance, and fully headless menu/drag completion are not established.
diff --git a/docs/solutions/runtime-errors/2026-09-20-native-acceptance-audit.md b/docs/solutions/runtime-errors/2026-09-20-native-acceptance-audit.md
new file mode 100644
index 000000000..d0db30f69
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-native-acceptance-audit.md
@@ -0,0 +1,42 @@
+---
+module: agent-desktop
+date: 2026-09-20
+problem_type: runtime_error
+tags: [acceptance, reliability, numbers, headless]
+---
+
+# Acceptance audit after the shared reliability repairs
+
+The full requested outcome is not achieved. The earlier 8/10 judgment has been
+withdrawn. No measured overall score exists under the evaluation plan. The
+frozen trajectory is [acceptance v1](../../../tests/real-apps/acceptance-v1.md).
+
+| Requirement | Current evidence | Verdict |
+|---|---|---|
+| N1 Numbers discovery | Cold-start skeleton now exposes table and scoped cell find | Improved; repeated acceptance missing |
+| N2 exact cell selection | Public AXPress and raw selected-cell evidence | Bounded success; earlier failures retained |
+| N3 saved cell ref through edit | Original `@s2afdbd2ja0t3j:e1` currently returns STALE_REF after editor opens | Unmet |
+| N4 text/numeric commit | Public editor setter and raw AX setter both report native success with unchanged seed-target | Unmet |
+| N5 formula | No working text commit path established | Not run to completion |
+| N6 duplicate-name sheets | Scoped transitions verified; repeated runner also retained a failed transition | Incomplete |
+| N7 dimensions | Earlier document oracle verified row count changes and guard preservation | Bounded success only |
+| N8 Numbers persistence | No successful edited values/formula to persist | Unmet |
+| Cross-command consistency | Live get, canonical find names and root viewport repaired | Tested cases pass; not all commands proven |
+| Scrolling and selection | SF Symbols saved-ref scroll cycles and named category selection verified | Bounded success only |
+| Menu headlessness | Xcode effects observed; SF Symbols trial included target activation | No universal headless pass |
+| Drag completion | Headed-only refusal is correct policy behavior | Requested headless task unmet |
+| Other complex native app | Xcode text replacement/insertion and persisted file verified | Does not replace Numbers requirements |
+| Thirty runs across three resets | Not completed for all supported cases | Incomplete |
+| Latest code gates | Workspace, Clippy, fmt, native semantic seven assertions, live paired reads | Pass at window-context candidate |
+| Latest performance | Candidate observations succeed on Numbers and SF Symbols; partial deep trees differ | Bounded comparison, not full task acceptance |
+| Release/push | No publishing performed | Local branch only |
+
+Numbers cell ref identity needs additional stable evidence before relaxing any
+matching rule. The cell has mutable title content and an editing suffix; row and
+column ranges exist in raw AX but are not currently stored as table-scoped ref
+identity. Globally ignoring cell names, using coordinates alone, or stripping an
+English suffix would risk wrong-target resolution across sheets and tables.
+
+Numbers text mutation is separately unresolved at the native boundary. A stable
+cell identity repair would not make the no-op editor setter commit text. Retain
+both failures instead of counting one repair as completion of the other.
diff --git a/docs/solutions/runtime-errors/2026-09-20-native-accessibility-initialization.md b/docs/solutions/runtime-errors/2026-09-20-native-accessibility-initialization.md
new file mode 100644
index 000000000..46bddf819
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-native-accessibility-initialization.md
@@ -0,0 +1,148 @@
+---
+module: agent-desktop-macos
+date: 2026-09-20
+problem_type: runtime_error
+tags: [numbers, accessibility, initialization, headless]
+---
+
+# Native accessibility initialization hides Numbers cells
+
+## Reproduction
+
+The owned document is `/tmp/ad-native-eval/AD Reliability.numbers`. Reopening it
+in the background produced Numbers PID 10520, window w-17920. The screenshot
+showed the seeded grid, but both Agent Desktop find and an independent raw AX
+walk exposed no cells or tables. The canvas AXScrollArea had only scrollbars.
+Raw AX reported AXEnhancedUserInterface=false and settable=true; manual
+accessibility was unsupported. A separate raw enhanced-mode write returned
+-25208, but readback became true and the cell became discoverable immediately.
+This repeats the earlier missing-grid/disabled-mode observation on a new process.
+
+The exposed editor advertised AXShowMenu, TSAccessibilityAddCommentAction and
+TSAccessibilityDeselectAllAction, with writable AXValue and AXSelectedText. It
+exposed no confirm action. No new text write or speculative custom action was
+attempted. The document oracle retained seed-target, neighbor-guard, eight rows
+and five columns. The missing-grid diagnosis does not solve text commit.
+
+## Shared repair and blast radius
+
+The existing capability probe considered enhanced mode only when a web surface
+was already observed. Native apps exposing the same supported attribute were
+excluded. The probe now considers an explicitly advertised enhanced attribute
+for native apps as well. Native activation requires a readable false value;
+true and unknown values do not request activation. Legacy manual-activation
+precedence and Chromium's existing readiness behavior remain unchanged.
+
+The existing core activation lease, process-generation validation, setter
+readback, deadline and two-second enhanced-mode settling delay are reused.
+There is no app-name special case, new dependency, physical input or app
+activation call. Unsupported apps receive no activation write. The broader
+native capability probe is a deliberate blast-radius change: native apps with
+advertised disabled enhanced mode can now receive an initialization write.
+
+The first candidate's observation gate still required a sufficiently deep completed traversal
+when no web surface is present. A shallow skeleton alone is not guaranteed to
+initialize a native app. Full find/snapshot coverage is improved; do not claim
+all observation forms had reached parity at that point.
+
+## Controlled candidate check
+
+Only the owned Numbers window was open; the unchanged document was closed
+gracefully and reopened in the background as setup. New PID 25567, generation
+`macos-proc-v1:1789867656:421528`, window w-18040.
+
+Baseline `/tmp/ad-native-eval/menu-sibling-candidate` returned zero cell matches
+for exact seed-target in this fresh process. Candidate
+`/tmp/ad-native-eval/native-init-candidate`, SHA-256
+`0dba97c4b8d3d1b0249b769e1d3beb8c853f1f20f3e862a5fcd9b4377668c87a`,
+ran the same public find and returned the correct cell in approximately 2.88 s.
+No raw AX setter was used in this candidate process. A second find completed in
+0.45 s; the first qualified ref `@s1krllq8xd4krk:e1` still read selected state.
+
+The 30-second monitor recorded foreground PID 2058 at both ends and no activation
+events. Session-wide input activity occurred and cannot be attributed to the
+agent by these counters. Source inspection confirms this path writes only the
+accessibility attribute, not physical input. Screenshot
+`numbers-native-init-candidate.png` and the independent document oracle confirm
+unchanged seeded values and dimensions. This is one candidate cold-start trial,
+not the repeated acceptance suite.
+
+Artifacts under `/tmp/ad-native-eval/`: `numbers-native-init-monitor.jsonl`,
+`numbers-reopened.png`, `numbers-native-init-candidate.png`,
+`native-init-workspace.log`, `native-init-clippy.log`,
+`native-init-safe-semantic.log`, and `native-init-performance/`.
+
+Twenty-six focused activation-related tests and Clippy passed. The isolated
+native semantic gate passed seven assertions on the exact candidate, including
+one-shot button effects, text binding updates, silent-no-op rejection and no
+fixture foreground activation. Full workspace and performance results must be
+read from the corresponding completed logs; no Numbers edit success is implied.
+
+## Shallow initialization follow-up
+
+The window-root probe now checks advertised mode even after shallow traversal.
+Missing renderer evidence still requires a complete traversal ending before the
+depth cap for the manual protocol. Native enhanced mode instead requires explicit
+disabled readback. Element-root traversal without web content remains ineligible.
+The regression `shallow_observation_requires_explicit_mode_evidence_not_renderer_absence`
+covers disabled, enabled and unknown enhanced mode and the shallow manual case.
+
+Candidate `/tmp/ad-native-eval/shallow-init-candidate` has SHA-256
+`1463071575bfa2e162686e328ce750f4538da45d93fe335ce67b053c9bb03d98`.
+Fresh Numbers PID 46296, window w-18244, was opened in the background after
+graceful closure of the sole owned document. The old native-init candidate's
+first skeleton exposed no table. The new candidate's skeleton exposed
+`@s1god9wm90dl5i:e2`, Eval Grid, eight rows and five columns, in 2.77 seconds.
+Public find rooted at that exact ref returned the selected seed-target cell in
+54 ms. No raw setter initialized this process. The 30-second monitor recorded
+other app activations but none for Numbers; session input activity is unattributed.
+This is one matched old/new cold-start trial, not the full repeated acceptance suite.
+
+Twenty-seven focused activation tests, full workspace tests, Clippy and formatting
+passed. Logs use the `shallow-init-` prefix under `/tmp/ad-native-eval/`.
+The isolated native semantic gate passed all seven assertions on this exact
+binary, including text binding changes and rejection of a silent no-op without
+retry. Core dependency isolation passes and release size is 3,088,656 bytes.
+The completed performance report is `shallow-init-performance/report.html`.
+Numbers completed all 24 observations with matching snapshot shapes; depth-30
+p50 was 22.9% slower, while the other p50 samples were slightly faster. SF Symbols
+revealed a regression: both full snapshot modes failed in all candidate rounds
+while baseline snapshots succeeded; skeletons succeeded on both. The public
+candidate command reproduced TIMEOUT, accessibility deadline exhausted before IPC.
+The new probe had run after incomplete traversal consumed the deadline. Its gate
+now preserves the existing incomplete-tree return path; only complete native
+observations probe activation. This follow-up requires new live validation.
+The SF Symbols button find failed on both versions and remains unresolved.
+
+## Direct cell and editor write outcome on the same process
+
+The public `set-value @s2afdbd2ja0t3j:e1 direct-cell-0920` was rejected before
+delivery: the cell exposes no SetValue capability. Raw AX confirms AXValue is
+absent and not writable. Public click on this ref opened the editor successfully.
+Find under the table returned editor `@s4xc5dnexktei:e1` with seed-target value.
+Setting this editor to direct-editor-0920 returned ACTION_FAILED after native
+AXValue success, because readback remained seed-target. A matched raw AXValue
+write to raw-editor-0920 also returned native success in 0.077 ms and retained
+seed-target. This reproduces the failed write outside Agent Desktop.
+
+The viewed `shallow-editor-set.png` shows seed-target in B2. Independent document
+readback confirms seed-target, neighbor-guard, eight rows and five columns.
+Neither a committed edit nor persistence is proven. Do not add automatic retry
+or reinterpret native success as task completion. The process remains in cell
+editing state; future probes must observe that state before acting.
+
+## Candidate after partial-tree guard
+
+`canonical-find-candidate`, SHA-256
+`f04ade8e00bac484be1a150b5c01fcc2110b7d6d58f396e3ae71e1cc42fd5a0e`,
+restored the same SF Symbols public snapshot to success in 2.95 seconds with
+`complete:false`, `truncated:true`, 979 observed nodes and 81 refs. The incomplete
+grid remains explicitly marked; this does not claim complete grid discovery.
+Full workspace tests, focused find tests, formatting, diff checks and Clippy
+passed. The completed `canonical-find-performance/` comparison restored SF Symbols
+snapshot success in all rounds. Interactive and skeleton shapes match baseline;
+depth-30 shapes differ (985 versus 949 nodes), so that latency pair is not a
+content-equivalence result. Numbers completed all 24 observations with matching
+snapshot shapes; its earlier depth-30 slowdown did not repeat (547 versus 561 ms
+p50). SF Symbols first-button find still failed on both versions; its separate
+hydration-budget diagnosis and candidate are recorded in the adjacent report.
diff --git a/docs/solutions/runtime-errors/2026-09-20-native-command-reliability.md b/docs/solutions/runtime-errors/2026-09-20-native-command-reliability.md
new file mode 100644
index 000000000..d8565a47e
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-native-command-reliability.md
@@ -0,0 +1,205 @@
+---
+module: agent-desktop
+date: 2026-09-20
+problem_type: runtime_error
+tags: [native, scrolling, refs, identity, headless, reliability]
+---
+
+# Native command evaluation: scrolling and ref continuity
+
+The evaluation now includes command-level scenarios as requested: scroll,
+scroll-to, select, expand/collapse and drag policy. A failed Numbers text edit
+remains an unmet task; it does not erase independently demonstrated command
+improvements. These bounded trials do not establish universal reliability.
+
+## Environment and ownership
+
+SF Symbols 7.0 was not running before this probe. Agent Desktop launched it
+without activation: PID 57617, process generation
+`macos-proc-v1:1789865265:554603`, window w-17404, title All. Its native symbol
+collection contains 6,984 items. Only this newly opened window was operated.
+The namespace is `/tmp/ad-native-eval/symbols-state`.
+
+Pages was not installed, so no Pages evaluation was run. Xcode and Numbers
+retain their separate evidence ledgers. No app installation was attempted.
+
+Baseline for this repair: `/tmp/ad-native-eval/activation-candidate`, SHA-256
+`49c75115e6600306ee42947484bc0982126585c0a137909f3d9745740fe84ab7`.
+Candidate: `/tmp/ad-native-eval/scroll-ref-candidate`, SHA-256
+`f7ae0196e788acdbeca3f5dcc6c86c942ce347f2b7f81ec0dc4c1d8d49759276`.
+Both include earlier local repairs; neither is the unmodified main release.
+
+## Reproduction and minimal repair
+
+1. An original skeleton exposed the main grid's scroll area as
+ `@s3p24n9238yc7t:e44` and its scrollbar as `@s3p24n9238yc7t:e47`, value 0.
+2. Headless `scroll ...:e44 --direction down --amount 1` returned
+ delivered_verified. Before/after screenshots independently showed the
+ viewport changing from the first symbols to sports symbols.
+3. `get ...:e47 --property value` then failed after five seconds in broad
+ resolution, with 9,969 attribute batches. A fresh snapshot and fresh ref
+ read showed the same scrollbar geometry and value `0.10000000149011612`.
+4. Core's shared mutable-value role list omitted `scrollbar` and `handle`.
+ Consequently, the old value 0 was treated as stable identity and rejected
+ the same live scrollbar after a legitimate scroll.
+5. The production repair adds those two canonical roles to
+ `is_mutable_value_role`. No timeout, fuzzy matching, path trust, geometry
+ requirement, native identifier precedence or ambiguity rule was relaxed.
+6. The original pre-scroll ref then returned the live value successfully on
+ the candidate. The test for value-independent identity failed before the
+ repair and passed afterward. Matching values alone remain insufficient
+ identity; distinct named scroll controls remain distinct.
+
+This is a core identity-classification defect, not an AX delivery defect.
+All users of the shared ref-identity helpers receive the correction, including
+macOS resolution and locator hydration. Changed geometry without stable identity
+still requires safe refusal; the fix does not promise arbitrary thumb recovery.
+
+## Observed command outcomes
+
+| Scenario | Outcome | Evidence and limits |
+|---|---|---|
+| Native grid scroll down | Baseline 1/1 effect verified | Semantic AX path and before/after screenshots |
+| Original scrollbar get after scroll | Baseline 0/1, candidate 1/1 | Same original qualified ref; changed live value |
+| Five down/up cycles with original refs | Candidate 10/10 scrolls, 10/10 reads | Every read alternated between 0.10000000149011612 and 0; no response rewriting or retry after failure |
+| Scroll-to original offscreen Math item | 1/1 verified | Math visible in screenshot; original ref get-states returned no offscreen state |
+| Headless ref drag | 1/1 expected policy refusal | POLICY_DENIED, not_delivered, retry safe; no headed input invoked |
+| Physical drag-and-drop effect | Not run | Requires headed policy, outside the strict headless trial |
+| Select Math by the original outline ref | Baseline failed; repaired candidate 4/4 category transitions | Canonical child labels now reused; original selected-row refs verified each transition; Math screenshot confirms 78 symbols |
+| Expand Weight combobox | Failed | Advertised Expand, but no readable expansion state; action chain refused without delivery |
+
+The ten-scroll sequence is one continuous batch, not the planned 30 runs across
+three independent resets. Native action acknowledgments plus AX values were
+checked on every step. Screenshots independently verified the initial real
+scroll and offscreen-target result, not every step of the repeated sequence.
+
+Artifacts under `/tmp/ad-native-eval/`:
+
+- `symbols-before-scroll.png`
+- `symbols-after-scroll.png`
+- `symbols-scroll-to-math.png`
+- `scroll-ref-workspace-tests.log`
+- `scroll-ref-safe-semantic.log`
+
+Focused identity tests, full workspace tests, Clippy with warnings denied,
+formatting and diff checks passed. The seven native semantic assertions passed
+on the exact candidate, including single button delivery and rejection of a
+silent text-insertion no-op. Performance comparison results are recorded below
+when complete; do not infer a performance pass from unit tests.
+
+The scroll candidate comparison completed at `scroll-ref-performance/report.html`.
+Numbers completed 24/24 observations with matching shapes; interactive p50 was
+523.5 ms baseline versus 611.1 ms candidate, while skeleton/depth-30/find were
+405.5/524.2/352.3 ms versus baseline 418/535.1/353.3 ms. SF Symbols find-button
+failed on both versions and depth-30 shapes differed, so that app did not pass
+the complete comparison. Xcode was no longer running and was skipped.
+
+## Canonical collection selection repair
+
+The old `select` searched only AXTitle and AXDescription, whereas snapshots
+derive the Math row's name from child content. On the original outline ref
+`@s3p24n9238yc7t:e2`, selecting Math returned ELEMENT_NOT_FOUND before mutation.
+The macOS selection search now uses the same bounded `read_node` name evidence
+as snapshots. Candidates must advertise Click; inert text cannot become an
+action target merely because its text matches. Unknown evidence fails closed.
+Missing collection items now explicitly report not_delivered.
+
+Candidate `/tmp/ad-native-eval/select-name-candidate`, SHA-256
+`78bbc858c3ea81d595e38402f41e2290eda1bf6586b1dab1e42f0651757d33e1`,
+completed Math, All, Math, All using the original outline ref. Every result
+reported delivered_verified, and subsequent original-row reads confirmed
+selected. `symbols-selected-math.png` independently shows Math and 78 symbols.
+This remains four transitions in one app process, not a cross-app acceptance
+score. Menu selection also uses this shared search; its live regression coverage
+is still outstanding. Existing first-match behavior and the depth-eight search
+limit remain review items, not claimed solved by canonical naming.
+
+Eight focused selection tests, Clippy, formatting and diff checks passed.
+The sandboxed workspace run failed two CLI event-wait tests; the complete
+workspace suite passed when run with macOS observation access. Logs are
+`select-name-workspace.log` and `select-name-workspace-native.log`.
+The native safety suite stopped before testing because foreground identity was
+missing or ambiguous (`select-name-safe-semantic.log`); it is not a pass.
+The exact-candidate performance comparison is under `select-name-performance`.
+
+That comparison completed and its generated HTML was reviewed. Numbers passed
+all 24 observations with matching first-snapshot shapes. Candidate/baseline p50
+in milliseconds: interactive 584.3/548.0, skeleton 429.5/407.2, depth-30
+523.6/592.0, find 387.4/353.1. These three-round samples are not an isolated
+measurement of the selection change. SF Symbols again failed find-button on
+both versions and had differing depth-30 shapes; no complete performance pass
+is claimed. Fixture comparison was skipped after the foreground guard failed.
+
+## Raw AX disclosure diagnosis
+
+A separate read-only Swift probe confirmed that both outer and inner Weight
+controls are AXPopUpButton, publish AXShowMenu and AXPress, and return
+kAXErrorAttributeUnsupported (-25205) for AXExpanded and AXDisclosing. The outer
+control has an inner AXPopUpButton child; the inner control has no children
+while closed. Family has the same structure. No raw mutation was performed.
+This supports testing native menu-opening semantics rather than blindly toggling
+AXPress when expansion state is unknown. No expansion repair is claimed yet.
+
+The diagnostic initially refused its title guard: raw AX exposes the title
+`All – 6,984 Symbols`, while list-windows reports `All`. AXIsProcessTrusted was
+true and AXWindows succeeded. Retargeting the exact observed raw title allowed
+inspection. The probe source is `/tmp/ad-native-eval/symbols-disclosure-probe.swift`.
+
+### Monitored native menu trial and discovery defect
+
+A separate raw AXShowMenu trial kept its client alive for ten seconds and
+registered NSWorkspace activation notifications. It checked that the inner
+Weight popup had no children and SF Symbols was not frontmost. AX returned
+success. A targeted Agent Desktop drill then exposed nine menu items under both
+outer and inner popups. The new outer ref was `@s3p24n9238yc7t:e75`, inner e76.
+
+Foreground PID started at 2058; activation events were 860, 2058, then 57617;
+the ending foreground PID was 57617 (SF Symbols). This trial did not preserve
+the background state and cannot qualify as a headless success. Other foreground
+activity occurred, so these observations alone cannot attribute every activation
+to AX. No menu-opening fallback was added. Later raw observation showed popup
+children empty again; no further menu mutation was performed.
+
+Despite the targeted drill exposing the menu, app-wide `snapshot --surface menu`
+failed at the unrelated 6,984-item grid: AXChildren loaded_count 4096, incomplete.
+The shared search aborted immediately on that branch. It now searches
+breadth-first and defers AppUnresponsive branch errors while inspecting siblings.
+A positively observed menu can be returned; otherwise the incomplete error is
+preserved. Permission errors and deadlines remain terminal, and the 2,048-node
+limit remains. This changes observation only, not native action delivery or policy.
+
+The sibling-menu regression failed before the repair and passed afterward.
+Seven surface-search tests passed, including unknown absence, cycles, deep menus,
+deadlines and terminal permission errors. Candidate
+`/tmp/ad-native-eval/menu-sibling-candidate` has SHA-256
+`105540fcf083bd93ac835cbc9ddf8d1a7af472557bf8270b1675a0d641bb8f67`.
+With the real menu subsequently gone, the candidate retained the incomplete
+search error. Positive live discovery on this candidate is unverified; the menu
+was not reopened to manufacture a passing trial.
+
+Clippy, formatting and diff checks passed. The sandboxed library run hit thirteen
+loopback-binding tests denied by the sandbox. The full workspace run with required
+access and the read-only performance comparison are recorded in
+`menu-sibling-workspace-native.log` and `menu-sibling-performance/`.
+The complete workspace run passed. The performance report completed and was
+reviewed: Numbers was no longer running and was skipped. SF Symbols interactive
+and skeleton shapes matched, with candidate/baseline p50 3067.0/3081.8 ms and
+295.0/339.8 ms. Depth-30 shapes differed and find-button failed on both versions.
+This is not a complete performance or live-menu acceptance pass.
+
+## Stronger headless observation
+
+`tests/real-apps/headless_probe.swift` observes activation notifications,
+session-wide input counters and sampled pointer position. It is a bounded,
+read-only diagnostic, not a driver or scoring framework. Its counter arithmetic
+self-test and Swift compilation passed. It records no key contents.
+
+A 60-second monitored Numbers trial completed two sheet transitions using
+original refs. Public waits and screenshots confirmed both states; the final
+document oracle returned Sheet 1, seed-target, neighbor-guard and other-sheet-guard.
+The monitor recorded 2,999 pointer samples and activation events for three other
+PIDs, none for Numbers. Input counts increased during unrelated foreground
+activity. Therefore the evidence supports no observed Numbers activation, but
+cannot establish clean input isolation or attribute those events to an agent.
+Preserve `/tmp/ad-native-eval/numbers-headless-monitor.jsonl` and the two
+`monitored-*.png` screenshots. No rating credit is inferred from unknown attribution.
diff --git a/docs/solutions/runtime-errors/2026-09-20-nested-scroll-visibility.md b/docs/solutions/runtime-errors/2026-09-20-nested-scroll-visibility.md
new file mode 100644
index 000000000..0ebaf0dc3
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-nested-scroll-visibility.md
@@ -0,0 +1,69 @@
+---
+module: agent-desktop-macos
+date: 2026-09-20
+problem_type: runtime_error
+tags: [scroll-to, clipping, false-success, regression]
+---
+
+# Scroll-to must verify the scroll viewport
+
+An owned AppKit fixture placed a button outside a 300x100 scroll viewport but
+inside its 500x632 window. The previous immutable window-context candidate
+returned a verified skipped step, not_delivered/safe, while the inspected
+`/tmp/ad-native-eval/nested-before.png` showed no button. The target advertised
+only AXPress: the experiment's initial custom action override was not exposed
+by AppKit and was removed from the retained fixture. No acknowledged custom
+scroll action is needed to reproduce the failure.
+
+Root cause: ancestor-scroll fallback calculated direction against AXWindow.
+When the target was inside that rectangle it returned SatisfiedNoDelivery,
+without checking the actual clipping ancestors. AXScrollToVisible verification
+also used window intersection alone.
+
+The repair reuses scroll::find_scroll_area for the nearest viewport and the
+existing hit-test ancestor-clipping reader for positive visibility verification.
+Unknown/clipped geometry cannot become verified success. The pre-existing
+missing-AXWindow refusal is preserved. No physical delivery, activation,
+app-specific condition or new abstraction was introduced. Nested outer-viewport
+cases that cannot be resolved still fail rather than falsely verifying.
+
+The repaired candidate actually scrolled the button into view, confirmed in
+`nested-after.png`. The final candidate was retested with the retained plain
+NSButton fixture: original ref @s3rcpysuegza8h:e2 returned delivered_verified,
+and inspected `nested-final-after.png` showed the button. The monitor recorded
+unrelated input and app changes, but no fixture activation; that final trial
+is contaminated for strict headless qualification.
+
+Final candidate `/tmp/ad-native-eval/nested-final-candidate`, SHA-256
+3714c3f3903d22ea430eb48a9f5645ca41bfc6b0f7d5f93f48ff7856fa882a1c.
+Workspace, clippy and formatting checks passed. The focused geometry regression
+covers a target inside its window but above its scroll viewport. Live fixture
+before/after evidence covers the actual routing, not just rectangle arithmetic.
+
+The preceding candidate d1b13c390e0a2e8eb78a1e92e562e88e13e082d891a963fcc9331a56501c14e3
+also scrolled the saved Math ref in SF Symbols into view. Its forty-five-second
+observer recorded no activation, input events or pointer movement; screenshot
+`nested-sf-math.png` and same-ref get-states confirmed the result. Its seven
+semantic fixture assertions passed. Do not count these as final-candidate
+qualification: the missing-window guard was subsequently restored.
+
+Remaining consistency gap: snapshot/get offscreen inference still uses window
+bounds and does not uniformly represent nested clipping. This repair removes
+the observed scroll-to false success; it does not close that separate shared
+observation contract. Numbers editing and the full acceptance series remain
+uncompleted. All work is local; no commit, push or release.
+
+Final gates completed: seven semantic fixture assertions on the exact final
+hash, full workspace tests, clippy, format and diff checks. Core dependency
+inspection contained no platform crates. The release remains approximately
+3.1 MB. Read-only performance comparison completed at
+`/tmp/ad-native-eval/nested-final-performance/report.html`: candidate 24/24
+observations succeeded across Numbers and SF Symbols. Numbers shapes matched;
+candidate/base p50 milliseconds were 301.5/302.4 interactive, 236.6/233.4
+skeleton, 297.1/280.1 depth-30, and 218.2/225.8 find. The 17 ms depth-30 delta
+is recorded, not treated as statistically established equivalence from three
+rounds. SF Symbols snapshot medians remained near their three-second budget;
+partial depth-30 shapes differed (920 versus 954 nodes), so equal completeness
+is not claimed. First-button find succeeded 3/3 on candidate versus 0/3 on base,
+reflecting the earlier locator budget repair. No observation-path behavior was
+changed by this scroll-only patch.
diff --git a/docs/solutions/runtime-errors/2026-09-20-numbers-parameterized-text-operation.md b/docs/solutions/runtime-errors/2026-09-20-numbers-parameterized-text-operation.md
new file mode 100644
index 000000000..824a4e4ce
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-numbers-parameterized-text-operation.md
@@ -0,0 +1,111 @@
+---
+module: agent-desktop-macos
+date: 2026-09-20
+problem_type: runtime_error
+tags: [numbers, text, parameterized-accessibility, diagnosis]
+---
+
+# Numbers advertises a separate parameterized text operation
+
+The earlier probe enumerated actions and selected ordinary attributes, but omitted
+parameterized attributes. That was an investigation gap; setter no-ops did not
+exhaust the editor's advertised semantic contract.
+
+On owned Numbers PID 46296, the focused B2 AXTextArea advertises:
+
+- AXStringForRange
+- AXAttributedStringForRange
+- AXLineForIndex
+- AXReplaceRangeWithText
+- AXBoundsForRange
+- AXRangeForLine
+
+The writable ordinary attributes are AXFocused, AXSelectedText,
+AXSelectedTextRange, AXSelectedTextRanges and AXValue. Advertised actions remain
+AXShowMenu, TSAccessibilityAddCommentAction and TSAccessibilityDeselectAllAction.
+The value remains seed-target. No replacement or commit was attempted in this
+inventory probe, and no production dispatch path changed.
+
+The independent `tests/real-apps/ax_probe.swift` now records ordinary and
+parameterized attribute names, settable status for each advertised attribute,
+and AXIdentifier/AXDOMIdentifier readback. The editor, cell and table exposed
+neither identifier in this trial. This improves diagnostic coverage; it is not
+an application-specific driver or acceptance success.
+
+Apple's published AppKit parameterized-attribute index fetched through Context7
+did not supply this operation's argument format. The local AppKit SDK export
+list contains NSAccessibilityReplaceRangeWithTextParameterizedAttribute, while
+the public header search did not find its declaration. WebKit's maintained
+[test runner](https://github.com/WebKit/WebKit/blob/main/Tools/WebKitTestRunner/InjectedBundle/mac/AccessibilityUIElementMac.mm)
+invokes accessibilityReplaceRange:withText: directly inside the target process.
+That is evidence of a semantic operation, not the cross-process parameter format
+or proof that Numbers implements it correctly.
+
+## Cross-process contract and separate Numbers trial
+
+Disassembling the installed AppKit implementation in an owned disposable helper
+identified `_NSAccessibilityResultForReplaceRangeWithText`. It reads a dictionary
+using `NSAccessibilityReplacementRangeKey` and `NSAccessibilityReplacementTextKey`,
+extracts an NSRange, and invokes `accessibilityReplaceRange:withText:`. Reading
+those exported constants in the helper yielded `AXReplacementRange` and
+`AXReplacementText`. No debugger attached to Numbers.
+
+`tests/real-apps/replace_contract_fixture.m` supplies an owned background window
+with a receiver that logs the exact incoming range/text. The separate
+`replace_range_probe.swift` sends a CFDictionary containing an AXValue CFRange
+and CFString through AXUIElementCopyParameterizedAttributeValue. In PID 83111,
+the receiver logged `{0, 11}` and `contract-verified`; native result was success
+and true, and the actual text changed from seed-target to contract-verified.
+Foreground endpoints both remained PID 75875. This proves parameter transport,
+not the behavior of AppKit's inherited text implementation or Numbers.
+
+In the subsequent separate Numbers trial, a fresh public CLI find returned
+`@s19bkizkoef5ta:e1`, focused/selected and value seed-target. The older editor ref
+correctly refused after its geometry changed. The raw helper selected the unique
+AXTextArea with that seed value within the exact owned window. One replacement
+requested parameterized-0920 at range `{0, 11}`. AX returned success and true,
+but the editor still read seed-target. Independent document readback remained
+`seed-target, neighbor-guard, 8, 5`. The inspected screenshot
+`/tmp/ad-native-eval/parameterized-numbers.png` also showed seed-target in B2.
+
+The thirty-second observer recorded no Numbers activation, but recorded other
+app activations, pointer changes and session input. This is contaminated for
+clean headless qualification; unchanged foreground endpoints do not cure that.
+No automatic repeat or alternate setter followed the uncertain mutation.
+
+The default AppKit method observed in the helper obtains the current input
+context's client and calls insertText:replacementRange:. In the fixture's
+`--standard` mode (plain NSTextView, no receiver override), PID 83938 likewise
+returned native success and true but left seed-target unchanged after requesting
+standard-background. Foreground endpoints remained 75875. Thus a controlled
+background AppKit control reproduces the no-op with the validated payload; the
+custom receiver succeeds. Input-context routing is a supported hypothesis, not
+proof of Numbers' private implementation or a demonstrated headless remedy.
+No production fallback was added: this additional advertised operation has not
+demonstrated a working Numbers write, commit or persistence path. N4 remains
+failed and N5/N8 remain uncompleted.
+
+The checked diagnostic subsequently passed two writes in a fresh custom fixture:
+seed-target to `A😀B`, then to unicode-range-verified. Receiver logs confirmed
+UTF-16 ranges `{0, 11}` and `{0, 4}` respectively. A fresh standard fixture's
+unchanged readback correctly caused diagnostic exit 1 despite native success
+and true. All owned fixture processes were closed after their trials. These
+checks validate the diagnostic; they add no Agent Desktop acceptance passes.
+
+## Internal first-responder differential
+
+The fixture's `--standard-focused` trial (PID 84721) called makeFirstResponder
+on its own NSTextView. AppKit returned true and the window's firstResponder was
+the text view, while app.active and window.keyWindow remained false. The text
+view had an NSTextInputContext, but NSTextInputContext.currentInputContext was
+nil. The cross-process replacement requested responder-background once and
+returned native success and true; readback stayed seed-target, so the checked
+probe exited 1. Foreground endpoints both remained PID 860.
+
+This eliminates missing internal first-responder assignment as a sufficient
+explanation or remedy for the standard-control result. It supports the observed
+default AppKit route through the current input context. It does not establish
+Numbers' private implementation, nor authorize app activation, process injection
+or a new application-specific scripting backend. No production path changed.
+The distinct tested AXValue, AXSelectedText and parameterized replacement paths
+have still not supplied a working Numbers background write/commit prerequisite.
diff --git a/docs/solutions/runtime-errors/2026-09-20-ref-root-window-context.md b/docs/solutions/runtime-errors/2026-09-20-ref-root-window-context.md
new file mode 100644
index 000000000..7f63a388e
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-ref-root-window-context.md
@@ -0,0 +1,48 @@
+---
+module: agent-desktop-macos
+date: 2026-09-20
+problem_type: runtime_error
+tags: [states, viewport, find, snapshot, consistency]
+---
+
+# Ref-rooted observations used the element as its own viewport
+
+SF Symbols first-button find reported offscreen while get-states on the same ref
+returned an empty list. Its bounds were x=194, y=82, width=0, height=0. The owning
+window was x=0, y=30, width=1496, height=937.
+
+Element-root observation initialized TreeBuildContext with entry.geometry.bounds
+as window bounds. Selected-match hydration therefore clipped the zero-size button
+against itself. Live get instead read AXWindow. The mismatch was in observation
+context, not a changed element or a stale ref.
+
+The owning-window lookup and its existing tests move from action post-state code
+to tree/element_bounds.rs. Live state and element-root observation both use it.
+No fallback to AXTopLevelUIElement is introduced: window-less menus must not use
+the menu bar as their viewport. Failed AXWindow reads still propagate errors.
+Window-root observation retains the resolved window geometry.
+
+Candidate `/tmp/ad-native-eval/window-context-candidate`, SHA-256
+`2a4e3e248893e44432494c8b7d2a6d027ff8a76cc3058c52f029592eecaa6500`,
+returned no offscreen state for first-button ref `@sk3p38f86rkv8:e1`.
+Public get-states and a snapshot rooted at that same ref agreed. The Numbers
+table-rooted exact-value editor search still returned seed-target, focused and
+selected. No UI mutation was needed to verify this repair.
+
+Full workspace, Clippy, formatting and diff checks pass. The initial sandboxed
+macOS run had six socket-permission failures; the escalated workspace run passed.
+The existing owning-window tests cover absent windows and failed reads without
+weaker fallback. The native semantic suite passed all seven assertions on the
+exact candidate, including no fixture foreground activation. The completed
+`/tmp/ad-native-eval/window-context-performance/` comparison passed all candidate
+observations. Numbers snapshot shapes matched baseline; candidate/base p50 ms
+were 509.9/523.8 interactive, 376.2/373.8 skeleton, 523.5/529.6 depth-30 and
+346.7/359.8 first-button find. SF Symbols find passed 3/3 versus 0/3 baseline;
+its interactive and skeleton shapes matched, while depth-30 node counts differed.
+This establishes bounded regression evidence, not full-content equivalence or
+the thirty-run acceptance requirement.
+
+Blast radius: ref-rooted observation now performs an owning-window read and uses
+its current geometry. This changes inferred offscreen state for elements whose
+root geometry differed from their window. It does not establish clipping by
+every intermediate scroll container, or prove a zero-size control is clickable.
diff --git a/docs/solutions/runtime-errors/2026-09-20-scroll-to-acceptance-probe.md b/docs/solutions/runtime-errors/2026-09-20-scroll-to-acceptance-probe.md
new file mode 100644
index 000000000..dc0ba8eb9
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-scroll-to-acceptance-probe.md
@@ -0,0 +1,44 @@
+---
+module: agent-desktop-macos
+date: 2026-09-20
+problem_type: runtime_error
+tags: [scroll-to, sf-symbols, acceptance, headless]
+---
+
+# SF Symbols scroll-to acceptance probe
+
+Candidate: `/tmp/ad-native-eval/window-context-candidate`, SHA-256
+`2a4e3e248893e44432494c8b7d2a6d027ff8a76cc3058c52f029592eecaa6500`.
+PID 57617, process instance macos-proc-v1:1789865265:554603, window w-17404,
+namespace `/tmp/ad-native-eval/symbols-state`. Window observation reported
+unfocused, visible, bounds x116/y107/1496x937.
+
+The public skeleton returned All at `@s350voae14kj3g:e4`, selected and offscreen,
+and sidebar scrollbar `@s350voae14kj3g:e38` at 0.8000000715255737.
+The model selected the refs from the original JSON without extraction scripts.
+
+One `scroll-to @s350voae14kj3g:e4` returned delivered_verified through the
+semantic scroll_to_visible_verified step. `get` on the same ref returned only
+selected; its current bounds were x124/y124.5/203x40. The original scrollbar
+ref remained valid after the action and read 0.10000001639127731.
+Screenshot `/tmp/ad-native-eval/acceptance-scrollto-all.png` was inspected:
+All appeared at the top of the sidebar, partly underneath the translucent
+titlebar. This establishes movement and surviving refs, not unobstructed
+clickability or a full acceptance pass.
+
+The forty-five-second headless observer reported no activation events and
+foreground PID 83470 throughout. It also recorded pointer changes, keyboard,
+mouse drag and wheel activity. Attribution is unknown, so the trial is
+contaminated for strict headless acceptance. It does not count toward the
+thirty valid runs or establish a new overall score. The user was asked for an
+idle-desktop interval before repeating qualification, rather than relabeling
+environmental activity as a clean run.
+
+Source inspection found that scroll-to verifies intersection with the owning
+window, whereas pointer hit testing additionally clips against ancestors. That
+is a coverage concern for nested scroll areas, not a demonstrated defect in
+this trial: partial visibility is currently accepted, and no code change was
+made merely because the screenshot included a translucent titlebar.
+
+Numbers N4/N5/N8 remain uncompleted. This independent S4 probe does not replace
+those required outcomes.
diff --git a/docs/solutions/runtime-errors/2026-09-20-selection-delivery-guard.md b/docs/solutions/runtime-errors/2026-09-20-selection-delivery-guard.md
new file mode 100644
index 000000000..fe4998af0
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-selection-delivery-guard.md
@@ -0,0 +1,70 @@
+---
+title: Stop container-selection fallback after unverified delivery
+module: macos adapter
+problem_type: runtime_error
+tags: [selection, delivery, headless, retries]
+date: 2026-09-20
+---
+
+# Selection delivery guard
+
+Tracing the unresolved Xcode select-by-name failure exposed a prerequisite
+reliability defect in `actions/container_select.rs`. Direct AXSelected writes
+returned false when readback was not true, even after accepted delivery. The
+caller could then try container attributes. Container array writes also ignored
+native error classification and tried another attribute after an accepted but
+unverified write. This could duplicate effects or act on broader ancestors.
+
+The existing shared native mutation classifier now handles container writes.
+Both direct and container writes use one verification guard: only explicit
+non-delivery permits fallback; accepted but unverifiable delivery returns
+ACTION_FAILED with delivered_unverified / retry unsafe. No focus, cursor,
+clipboard or keyboard behavior changed. Successful verified selections and
+explicit unsupported paths retain their existing behavior.
+
+Immutable candidate: `/tmp/ad-native-eval/selection-delivery-candidate`, SHA-256
+`061572c91835ba8e9cf224c6e64352075b857d3674d9eb6164ec9ea16db505a2`.
+
+## Evidence
+
+Three container-selection tests passed, including a counted attempt loop that
+must stop after the first accepted write with failed readback. Unsupported
+delivery must not invoke readback; verified delivery succeeds. Full workspace,
+clippy with warnings denied, format and diff checks passed. Initial test runs
+exposed an explicit Result type omission and an assertion against the unrelated
+default-retry override flag; both test errors were corrected before final gates.
+Final workspace log: `/tmp/ad-native-eval/selection-delivery-workspace-verified.log`.
+
+The native diagnostic `tests/real-apps/selection_delivery_fixture.swift` exposes
+a row whose selected setter logs a write but whose getter remains false, plus a
+container setter that independently logs fallback writes. Public snapshot
+returned row `@s3dc99lneq3yhr:e2` in owned window w-19929, PID 35151.
+One public click returned ACTION_FAILED, delivered_unverified, retry unsafe.
+The native process logged exactly one `MUTATION direct-selection true` and no
+container-selection mutation. It was then closed after verifying its executable.
+
+The diagnostic fixture was already frontmost at monitor start. Its 30-second
+monitor recorded no additional activation/input/pointer movement, but this trial
+is not evidence of background operation. Its startup must not be reused as a
+headless acceptance fixture without correcting and verifying that behavior.
+
+The first standard safe-semantic suite attempt failed its initial process-token
+checkpoint before test actions; cleanup also refused the changed token. That
+attempt remains in `/tmp/ad-native-eval/selection-delivery-semantic.log`. A fresh
+trial began only after pgrep confirmed that no AgentDeskFixture process remained.
+The precise cause of the token change is not established.
+The fresh trial passed all seven semantic assertions on the exact candidate
+hash, including never bringing the fixture frontmost. Log:
+`/tmp/ad-native-eval/selection-delivery-semantic-run2.log`.
+
+Read-only Xcode performance completed three rounds per case, 12/12 candidate
+and baseline successes, with matching corresponding tree shapes. Candidate/base
+p50 ms: interactive 306.0/296.3, skeleton 203.9/200.9, depth-30 295.3/291.3,
+first-button find 256.1/222.5. Find p50 increased 33.6 ms; this small cumulative
+branch comparison cannot attribute the difference to this mutation-only guard.
+Report: `/tmp/ad-native-eval/selection-delivery-performance/report.html`.
+
+Xcode label matching and row-selection-versus-file-opening remain unresolved.
+This repair is a prerequisite for safely reusing the shared selection path,
+not proof of completing those tasks. Provisional rating remains 8/10; the goal
+is active and repeated acceptance coverage is still required. Nothing pushed.
diff --git a/docs/solutions/runtime-errors/2026-09-20-shared-clipping-state.md b/docs/solutions/runtime-errors/2026-09-20-shared-clipping-state.md
new file mode 100644
index 000000000..112c86e1a
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-shared-clipping-state.md
@@ -0,0 +1,82 @@
+---
+module: agent-desktop-macos
+date: 2026-09-20
+problem_type: runtime_error
+tags: [visibility, clipping, command-consistency]
+---
+
+# Shared clipping state across observation commands
+
+Snapshot traversal previously reused window bounds for every descendant.
+Live state and ref-root observation also used only the owning window. A native
+button clipped by a smaller scroll area therefore lacked offscreen state even
+after scroll-to had been repaired separately.
+
+Traversal now carries the effective clipping rectangle down each branch and
+restores the prior rectangle before visiting siblings, including error paths.
+Ref-root and live observations read clipping ancestors under the existing
+deadline. Rectangle intersection and clipping-role definitions are shared with
+the pointer hit-test implementation. No per-node ancestry IPC was added to a
+full traversal. Empty intersections remain known empty, while unknown ancestor
+geometry cannot become known again merely because a deeper container has bounds.
+
+The owned fixture now includes a visible sibling outside the scroll area.
+Candidate 9dedd81c6561a354a6550b328877a623f73f019306cbfdb33f62a1ea7d06c6c9
+reported offscreen consistently through snapshot, get, find and root snapshot;
+the sibling remained visible. On the same unchanged target/ref, the preceding
+nested-final candidate returned an empty state list. After semantic scroll-to,
+the same target ref became visible and the sibling stayed unchanged, confirmed
+by the inspected `/tmp/ad-native-eval/clipping-after.png`. The observer recorded
+no target activation but unrelated input, so that trial is not a clean headless
+qualification pass.
+
+Final candidate `/tmp/ad-native-eval/clipping-final-candidate`, hash
+f0ed9f26f9bf74b4d75e4004d3d773df91772e12301cd44c2013ae06fafadd5d,
+adds the unknown-ancestor preservation guard. Workspace tests, clippy and format
+passed. One previously saved anonymous scrollarea ref timed out with safe
+not-delivered STALE_REF evidence; it was not silently counted as recovery. A
+fresh snapshot ref successfully reset the fixture viewport. The saved button
+ref and a new exact find then both reported offscreen on the final candidate.
+Final semantic trial 1 stopped after five passes at the ownership checkpoint:
+fixture window identity changed. The cause was not established and the attempt
+is retained as failed. A separate fresh-fixture trial passed all seven assertions
+on the same final hash. Final performance completed: candidate SF Symbols
+observations succeeded 12/12; baseline first-button find failed 3/3. Snapshot
+interactive medians were 3063.9/3064.5 ms, skeleton 305.8/292.9 ms, depth-30
+3062.1/3072.1 ms, and candidate find 4099.2 ms. Partial depth-30 shapes differ;
+neither complete equivalence nor a clean aggregate baseline pass is claimed.
+
+Tests cover non-clipping groups, disjoint nested viewports and unknown geometry.
+The earlier candidate passed seven semantic assertions and SF Symbols read-only
+performance observations. Xcode was absent and skipped, not passed. Numbers is
+excluded from active testing by the user's explicit instruction. Provisional
+rating remains 8/10; these fixes do not establish repeated real-app acceptance.
+
+## Real-app S3 baseline on the final candidate
+
+SF Symbols PID 57617, window w-17404. The model chose outline
+@s1pw1hb4whof0b:e1 from a scoped find and Math @swkwt9hq8o9kg:e1 from an exact
+find. Selecting Math then All on the same outline returned delivered_verified
+for both transitions. Saved Math/All refs reported selected as appropriate;
+Math became unselected after returning to All. Inspected screenshots
+`/tmp/ad-native-eval/s3-final-math.png` and `s3-final-all.png` showed the expected
+78 and 6,984 symbol collections. The sixty-second observer reported no app
+activations, zero input-event deltas and no pointer movement, with the target
+still running and foreground PID 860 unchanged. Result: one successful S3
+baseline round trip, not the required thirty runs across three reset batches.
+
+S4 attempt 1 on the final candidate used the saved offscreen All ref
+@ssvl7e1srna75:e4. Scroll-to returned delivered_verified and get-states returned
+selected without offscreen. The requested screenshot failed with TIMEOUT:
+NSWorkspace app inventory timed out. The thirty-second monitor recorded input
+activity and target activation near its end. Attribution is unknown. The attempt
+is retained as unqualified/contaminated with incomplete visual verification, not
+a pass; SF Symbols mutations stopped while it was foreground.
+
+Xcode setup then launched PID 24741 without an activation flag and opened only
+the owned AD Reliability.swift file using background setup. List-windows exposed
+the owned file as w-19712 and a separate Welcome window. Exact find scoped to
+w-19712 returned Source Editor @s1j4qlrp4icwd:e1 with the expected guarded source.
+The setup observer recorded Xcode activation and input activity; its cause is
+unattributed. Discovery is functionally observed, but no clean background setup
+or X2 edit pass is claimed. Document edits were held while Xcode was foreground.
diff --git a/docs/solutions/runtime-errors/2026-09-20-xcode-empty-search-value.md b/docs/solutions/runtime-errors/2026-09-20-xcode-empty-search-value.md
new file mode 100644
index 000000000..3f931fa82
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-xcode-empty-search-value.md
@@ -0,0 +1,115 @@
+---
+title: Xcode search clears successfully but exposes no AXValue
+module: macos adapter
+problem_type: runtime_error
+tags: [xcode, value, verification, headless]
+date: 2026-09-20
+---
+
+# Empty search-field evidence gap
+
+Candidate `/tmp/ad-native-eval/descendant-stop-candidate`, SHA-256
+`5f2bf71761548cd6cbb58b8161b0fbc2dc4bfee033f9d30fec603f93613a2115`.
+Xcode PID 24741, window w-19740. Public CLI with raw responses, namespace
+`/tmp/ad-native-eval/xcode-state`; no response parser supplied action refs.
+
+## Observed behavior
+
+Debug filter `@s287cvyqznmcqt:e75` initially returned empty string. Set-value to
+ad_probe_93c217 verified, get returned that exact string, and a viewed screenshot
+showed it in the debug filter. Clear on the same ref verified and get returned
+empty string again.
+
+Project navigator filter `@s287cvyqznmcqt:e3` accepted CursorCamAppDelegate.
+The scoped navigator snapshot then contained just its parent groups and the
+matching file. Viewed screenshot confirmed the actual list changed. Clear on the
+same ref returned delivered_unverified with insufficient_evidence. No write was
+repeated. A subsequent get returned null, while a scoped snapshot showed the full
+original navigator tree and original selected row restored. The final screenshot
+was also viewed and showed both filters empty and the original editor retained.
+
+Artifacts:
+- `/tmp/ad-native-eval/xcode-debug-filter-filled.png`
+- `/tmp/ad-native-eval/xcode-navigator-filter-filled.png`
+- `/tmp/ad-native-eval/xcode-filter-restored.png`
+
+The 60-second monitor recorded zero activation, zero input-event deltas and no
+pointer change; foreground PID 35000 remained unchanged. Its interval covered the
+debug-filter round trip and navigator filtering. The subsequent restoration
+observations occurred after completion; do not extend the monitor claim to them.
+
+## Raw AX diagnosis
+
+Read-only bounded helper `/tmp/ad-native-eval/xcode-filter-read.swift` reported:
+
+```
+AXRole: success, AXTextField
+AXSubrole: success, AXSearchField
+AXDescription: success, Project navigator filter
+AXValue: -25212, nil
+AXNumberOfCharacters: success, 0
+AXPlaceholderValue: success, Filter
+```
+
+This is not a demonstrated dropped write. Xcode exposes no AXValue for the empty
+search control; Agent Desktop currently lacks a shared rule for using the native
+zero-character evidence. Any repair must preserve unknown versus empty: restrict
+it to nonsecure text roles, require a successful numeric zero character count,
+and never infer empty from timeout, unsupported count, positive count or secure
+content. Snapshot, get and post-action readback must share the rule. Trace both
+node_attribute_fetch's batch-value path and text_attributes' direct-value path
+before implementing; changing only verification would leave contradictory reads.
+
+## File activation lead ruled out
+
+Raw AX row actions remained AXShowDefaultUI and AXShowAlternateUI. Apple's
+[showDefaultUI documentation](https://developer.apple.com/documentation/appkit/nsaccessibility-swift.struct/action/showdefaultui)
+describes restoring the original/default UI, not opening a file. No new action
+mapping was added and no raw mutation was attempted. File opening remains open.
+
+Corrected the preceding repair's blast-radius note: activate_descendant is used
+by click and semantic toggle/check paths. Double-click is currently physical and
+does not use that helper. No source files in the Xcode project were edited.
+
+## Repair
+
+Added a shared macOS empty_text reader used by batch node hydration and direct
+typed value reads. Only missing values on nonsecure AXTextField/AXTextArea
+elements can trigger it. A successful numeric zero AXNumberOfCharacters yields
+empty string; positive, negative, fractional, boolean, string, absent and failed
+counts do not prove empty. Real read errors propagate. The existing deadline
+still governs the extra read; ordinary nonempty values add no IPC. Batch metrics
+record the fallback read.
+
+The negative test caught the initial reuse of the broad ax_absence classifier,
+which treats generic kAXErrorFailure as absence. The new count reader instead
+permits only NoValue and AttributeUnsupported as absent. The failed test run is
+retained in `/tmp/ad-native-eval/empty-text-workspace.log`.
+
+The first candidate (4e34fdbe5b1e760d9db2f41da95dc4b477ca7f18be660bed1dc55211e3bf12ff)
+passed a live set/filter/clear/get round trip on the original filter ref. Clear
+changed from delivered_unverified to delivered_verified, and get returned empty
+string. Scoped snapshot still omits empty values through the existing core
+observed_tree projection; it does not expose a contradictory nonempty value.
+Viewed `/tmp/ad-native-eval/empty-text-restored.png` showed the full original
+navigator and empty filters. The 60-second monitor recorded zero input events,
+zero activation and unchanged pointer/foreground. Final candidate checks follow
+the stricter native-error classification change above.
+
+Final candidate `/tmp/ad-native-eval/empty-text-final-candidate`, SHA-256
+`6e9626edf059424869caba2519b8bbb2d749c7443512e5c8045ca9c8809789c1`.
+Full workspace, clippy, formatting and diff whitespace checks passed after the
+classifier correction. Final-binary get on replacement filter ref e246 returned
+empty string. The final three-round merge-base performance check succeeded for
+all commands with matching reported shapes. Candidate/base p50 milliseconds:
+interactive snapshot 300.5/315.2, skeleton 201.2/205.2, depth-30 309.5/283.9,
+find 236.6/227.9. The fallback adds a character-count read only for eligible
+missing text values; depth-30 median was 25.6 ms higher in this small sample,
+with candidate p95 314.4 vs baseline 325.4 ms. This is not a statistical claim
+of equal performance. Artifacts are under
+`/tmp/ad-native-eval/empty-text-final-performance/`.
+
+The exact final binary passed all seven background semantic fixture assertions
+(`/tmp/ad-native-eval/empty-text-final-semantic.log`). No commit or release was
+performed. This closes the diagnosed empty-search-value verification gap; it
+does not qualify file opening or the full repeated application acceptance suite.
diff --git a/docs/solutions/runtime-errors/2026-09-20-xcode-filter-ref-alias.md b/docs/solutions/runtime-errors/2026-09-20-xcode-filter-ref-alias.md
new file mode 100644
index 000000000..a320c5f82
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-xcode-filter-ref-alias.md
@@ -0,0 +1,147 @@
+---
+title: Filtered Xcode row aliases an earlier editable-label ref
+module: core and macos resolution
+problem_type: runtime_error
+tags: [xcode, identity, stale-ref, wrong-target]
+date: 2026-09-20
+---
+
+# Confirmed wrong-target read after filtering
+
+Qualification failure, not a passing stale-recovery case. No wrong-target write
+was attempted. Candidate `/tmp/ad-native-eval/empty-text-final-candidate`, SHA-256
+`6e9626edf059424869caba2519b8bbb2d749c7443512e5c8045ca9c8809789c1`.
+Namespace `/tmp/ad-native-eval/xcode-state`, Xcode PID 24741, w-19740.
+
+## Reproduction through public CLI
+
+Drill navigator root `@s287cvyqznmcqt:e2`. Its result contains:
+
+- e265: unnamed treeitem for CursorCamApp.swift
+- e267: AXTextField, native ID title, value CursorCamApp.swift
+- e268: unnamed treeitem for CursorCamAppDelegate.swift
+- e270: AXTextField, native ID title, value CursorCamAppDelegate.swift
+
+Using the same immutable binary and namespace:
+
+```
+set-value @s287cvyqznmcqt:e246 CursorCamAppDelegate
+get @s287cvyqznmcqt:e267 --property value
+get @s287cvyqznmcqt:e268 --property states
+clear @s287cvyqznmcqt:e246
+get @s287cvyqznmcqt:e267 --property value
+```
+
+The first get incorrectly returned CursorCamAppDelegate.swift. The saved Delegate
+row e268 instead returned safe STALE_REF with five identity candidates and no
+matching bounds. Clear verified; the final get returned CursorCamApp.swift again.
+Thus the original App field ref aliases another logical row while filtering.
+The 45-second monitor recorded no activation, physical input or pointer change.
+
+## Independent native comparison
+
+`/tmp/ad-native-eval/xcode-retained-row.swift` uniquely found and retained the
+original App AXTextField before filtering. The helper performs no mutation.
+After a separate public CLI filter action, it reread the retained object:
+
+```
+retained AXValue: error=0, value=Optional(CursorCamApp.swift)
+```
+
+The CLI get on e267 during that same filtered state again returned
+CursorCamAppDelegate.swift. This distinguishes native object preservation from
+Agent Desktop's re-identification error. The filter was then cleared once and get
+confirmed its original empty value. This second diagnostic trial was not covered
+by the first trial's monitor and must not inherit its headless evidence.
+
+## Root cause and repair constraints
+
+Core ref_identity::identity_match returns Match immediately when the saved native
+identifier occurs in the candidate's identifiers. Both fields advertise title.
+The macOS resolver permits path-based resolution with identifier/bounds evidence;
+the replacement field occupies the original path and geometry. The stored
+RefEntryIdentity has no row-context identity or native-identifier uniqueness
+evidence. Mutable text values intentionally do not identify text fields, so
+comparing all field values would break legitimate same-ref edits.
+
+The correction must preserve a distinction between an editable control's value
+and the identity of the collection item containing it. Simply disabling the
+path optimization is insufficient: a broad search can still match the repeated
+title identifier and the same bounds. Likewise, a filename/Xcode-specific check
+would leave the same bug in other collections. Do not globally freeze text-field
+values, silently rename the canonical role, or count a wrong-target refusal as
+full task completion.
+
+Required regression outcomes: unchanged row resolves; filtering/removing it
+cannot resolve to a replacement with the same role/native ID/path/bounds;
+restoration recovers the original logical row; legitimate edits to an ordinary
+text field remain usable through its original ref. Resolution must agree across
+get, action, scoped snapshot and find roots. Snapshot capture and resolution both
+need the same additional identity evidence; the platform/core boundary must be
+reviewed before adding fields. Product repair remains pending.
+
+## Native identity inventory and implementation constraints
+
+A fresh raw attribute-name/value probe confirmed the field exposes AXIdentifier
+title, but no AXURL, AXDocument or AXDOMIdentifier. Its AXCell parent has no
+identifier/name/value. The AXOutlineRow parent likewise has no identifier/name/
+value; AXIndex is positional. The enclosing outline has identifier project
+navigator. This rules out a simple switch to an already-exposed document URL.
+Raw helper: `/tmp/ad-native-eval/xcode-row-read.swift`.
+
+Current references serialize process, element identity, geometry, source and
+path, but no containing-item identity. Native objects themselves are not retained
+across CLI processes. The raw retained-object experiment proves a long-lived
+handle can preserve the original object for this scenario, but adding a daemon
+is a separate architectural change and not a minimal adapter patch.
+
+Do not promote CFHash to a unique runtime identifier: Core Foundation hashes may
+collide and the current identifier shortcut would treat equality as identity.
+Do not globally require unchanged values: ordinary text inputs must remain
+editable through the same ref. Do not rely on broad-search uniqueness: after
+filtering, only the wrong editable label can remain in the original position.
+
+The next implementation must capture containing-item evidence at observation
+time and validate it before resolving a descendant control. The decisive tests
+must include repeated native IDs and identical replacement geometry, plus normal
+text editing on an unchanged item. A row label may itself be editable; any label
+derived from the target's value must explicitly account for that rather than
+silently freezing a mutable value. Until that contract is implemented and tested,
+these navigator label refs are not safe mutation targets after collection changes.
+
+## Isolated reproduction surface
+
+Added opt-in `AGENT_DESKTOP_FIXTURE_REF_CHURN=1` mode to the existing fixture.
+RefChurnView has Alpha and Beta fields with the same shared-title native ID, a
+Filter rows/Restore rows button, a separately named stable editor and visible
+backing-value labels. Filtering removes Alpha and moves Beta into its position.
+The default fixture mode remains selected unless this environment variable is 1.
+
+Built with `AGENT_DESKTOP_FIXTURE_BACKGROUND_BUNDLE=1` using the existing build
+script, and launched with `AGENT_DESKTOP_FIXTURE_NO_ACTIVATE=1`. The inspected
+fixture PID was 75044, instance macos-proc-v1:1789879561:749580, window w-19980.
+Snapshot s1wegvust2ghvt exposed e1 filter button, e2 Alpha, e3 Beta, e4 stable
+editor. On the same candidate used above:
+
+1. Click e1 reported delivered_unverified; read e2 returned Beta, establishing
+ the filtering effect without repeating the mutation.
+2. Click e1 to restore; read e2 returned Alpha.
+3. Set e4 to updated-stable, get e4 returned updated-stable, then set e4 back to
+ Stable value. Both writes verified through the same ref.
+4. Viewed `/tmp/ad-native-eval/ref-churn-restored.png`; all three backing-value
+ labels retained their original values.
+
+The 45-second monitor recorded no activation, no pointer movement and zero input
+events, with foreground PID 860 unchanged. This covers interaction, not launch.
+The fixture was closed by TERM only after verifying its exact executable path;
+the owning process handle reported terminal exit 143.
+
+This fixture demonstrates the defect outside Xcode without a collection-row
+native role, so a patch restricted to AXRow ancestry is insufficient. Its normal
+same-ref editor is the control case that an eventual correction must preserve.
+It is a reproducible failing product scenario, not a passing acceptance result.
+
+After adding this mode, the default background fixture passed its existing seven
+semantic assertions using the same production binary. Log:
+`/tmp/ad-native-eval/ref-churn-default-regression.log`. No production code changed
+in this fixture-only step.
diff --git a/docs/solutions/runtime-errors/2026-09-20-xcode-project-disclosure.md b/docs/solutions/runtime-errors/2026-09-20-xcode-project-disclosure.md
new file mode 100644
index 000000000..cec9637a3
--- /dev/null
+++ b/docs/solutions/runtime-errors/2026-09-20-xcode-project-disclosure.md
@@ -0,0 +1,110 @@
+---
+title: Xcode project drilling and disclosure-state consistency
+module: macos adapter
+problem_type: runtime_error
+tags: [xcode, accessibility, headless, disclosure, scoped-refs]
+date: 2026-09-20
+---
+
+# Xcode project probe
+
+The user opened cursor-cam in Xcode, PID 24741, window w-19740. This probe
+used public Agent Desktop JSON and model-selected refs, without parsing wrappers.
+Project source was not edited and no build/run was requested. Raw AX was used
+only for separate read-only diagnosis. The provisional rating remains 8/10;
+these trials do not establish the repeated acceptance denominator.
+
+## Reproduced and fixed
+
+Candidate `clipping-final-candidate` advertised Expand/Collapse on navigator
+disclosures, but `expand @s2j42fiokeiy6k:e44` failed with ACTION_FAILED,
+not_delivered: "All chain steps exhausted". Raw AX showed
+AXDisclosureTriangle with AXValue 0 or 1 and absent AXExpanded/AXDisclosing.
+The adapter's action verifier and snapshot state reader ignored this value.
+
+The shared state reader now interprets AXValue only for AXDisclosureTriangle,
+and only when explicit expanded/disclosing evidence is absent. Snapshot states,
+live-state completeness and disclosure action verification reuse that rule.
+Unknown/mixed values remain unknown; other roles never inherit it. The existing
+single-delivery semantic chain is unchanged. No focus or input fallback was added.
+Tests cover true/false, explicit precedence, missing/mixed values and other roles.
+
+Repaired immutable candidate: `/tmp/ad-native-eval/disclosure-candidate`, SHA-256
+`1d68e0d6d5f71e9bcc046f19a3b2c22ee31a3bf7dc49b2f6bad121513783b39c`.
+The original disclosure ref expanded, get reported expanded, and the same ref
+collapsed. Screenshot `/tmp/ad-native-eval/xcode-disclosure-expanded.png` was
+viewed and showed MenuBarManager and SettingsPopoverManager under MenuBar.
+The 45-second monitor reported no activations, zero input deltas and unchanged
+pointer; foreground PID 35000 stayed unchanged and Xcode remained running.
+
+## Column and command checks
+
+- Skeleton `s1a9jwgx9ts97p` provided navigator e2, editor e5, debug e7 and
+ inspector e9. Inspector, editor and debug drills succeeded on the pre-fix
+ candidate; navigator drill had already succeeded under `s2j42fiokeiy6k:e2`.
+- Inspector exact find of textfield Tab returned one match with value 4;
+ the same query rooted at editor e5 returned zero matches. The inspector child
+ e44 still returned 4 after drilling editor and debug siblings.
+- On the repaired candidate, editor-scoped Source Editor find returned one
+ match, and debug-scoped VariablesViewFilter find returned one match.
+- Re-drilling inspector e9 replaced its child refs. Old e44 failed STALE_REF
+ with safe not-delivered disposition; replacement e100 returned 4. Untouched
+ editor child e53 still resolved. No mutation was attempted with the stale ref.
+- Inspector Text Settings e96 collapsed and expanded with the same ref; get
+ reported the intermediate empty state. Editor scrollarea e52 scrolled down
+ and up with the same ref. Both commands reported semantic verified delivery.
+ Viewed screenshots `xcode-editor-scrolled.png` and `xcode-editor-restored.png`
+ under `/tmp/ad-native-eval/` showed the source viewport moving and returning
+ to line 1, respectively. The second 45-second monitor also reported zero
+ activations/input deltas and unchanged pointer/foreground PID 35000.
+
+These are individual supporting trials, not thirty-run qualification. Older
+refs were intentionally retained across the candidate change; fresh-candidate
+full baseline/reset series is still required.
+
+## Other findings retained
+
+`select` on Project Navigator with CursorCamApp.swift returned ELEMENT_NOT_FOUND
+despite the nested textfield exposing that value. Canonical child labels read
+static text, while this navigator exposes editable textfield values. Do not
+blindly broaden stable identity to all mutable values or click editable labels.
+This inconsistency is unresolved.
+
+Clicking the file row reported verified selection and visibly selected it, but
+the editor remained on CursorCamAppDelegate.swift. Selection is not proof of
+opening a file. Xcode displayed Preparing Editor Functionality throughout.
+No duplicate activation was attempted to force the result.
+
+Setting Project navigator filter to CursorCam visibly filtered the tree.
+Clearing it reported delivered_unverified because the empty value was absent;
+the final viewed screenshot showed the original unfiltered tree and empty
+filter. Earlier monitors included external-session input and activation of
+multiple apps; attribution was unavailable, so those trials are not clean
+headless qualification. The file row selection remains CursorCamApp; the editor
+remains CursorCamAppDelegate. No project contents were changed.
+
+## Validation and limits
+
+- Five focused disclosure tests passed. Full `cargo test --workspace` passed
+ with macOS access (`disclosure-workspace-unsandboxed.log`). The sandboxed
+ attempt failed two CLI event-wait batch tests before that rerun; retained at
+ `disclosure-workspace.log` rather than erased.
+- Clippy with warnings denied, format and diff checks passed.
+- Owned safe-semantic fixture passed all seven checks on the exact candidate
+ hash (`disclosure-semantic.log`).
+- Read-only three-round performance comparison:
+ `/tmp/ad-native-eval/disclosure-performance/report.html`.
+ Xcode candidate/base p50 ms: interactive 261.7/265.7, skeleton 175.3/188.9,
+ depth-30 278.8/258.5, first-button find 202.8/205.1. All 12 candidate and
+ baseline calls succeeded and respective tree shapes matched. Depth-30 was
+ 20.3 ms slower; this small sample cannot isolate its cause within the cumulative
+ branch diff. No extra per-node AX reads were added by this repair.
+- SF Symbols candidate calls all succeeded; baseline first-button find failed
+ all three rounds. Deep partial-tree shapes differed (937 vs 930), so this is
+ not a clean aggregate performance pass or completeness-equivalence claim.
+
+Headless InteractionPolicy already defaults both focus stealing and cursor
+movement to false. This repair keeps that policy and adds no physical path.
+This is not proof that arbitrary AX actions in arbitrary apps cannot activate
+their app. Menus, file opening, semantic drag and repeated cross-app acceptance
+remain outstanding; no 10/10 claim is supported. All changes remain local.
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.md
new file mode 100644
index 000000000..8a197e3b7
--- /dev/null
+++ b/docs/solutions/runtime-errors/chromium-readable-tree-with-inactive-ax-actions.md
@@ -0,0 +1,112 @@
+---
+title: A readable Chromium AX tree does not prove its actions are active
+date: 2026-09-19
+category: runtime-errors
+module: macos renderer accessibility activation
+problem_type: integration_issue
+component: platform_adapter
+severity: high
+tags: [macos, chromium, accessibility, headless, renderer-activation]
+---
+
+# A readable Chromium AX tree does not prove its actions are active
+
+## Reproduction
+
+Comet 152 exposed a complete web accessibility tree and advertised `AXPress`,
+but clicks on links, a plain HTML button, and a checkbox returned native success
+without changing the page. Native browser tabs worked. An independent Swift
+probe reproduced the web failures using `AXUIElementPerformAction` directly.
+
+The same local HTML controls worked through raw AX in an isolated Chrome 153
+profile. Comet reported `AXEnhancedUserInterface = false`; Chrome reported true.
+Both reported `AXManualAccessibility` unsupported.
+
+Enabling enhanced accessibility made the same Comet controls work. Agent
+Desktop's unchanged semantic click then opened the original Hacker News article.
+Disabling enhanced accessibility reproduced the no-op button and checkbox.
+This was an activation problem, not a website-specific targeting problem.
+
+## Root cause
+
+The observation path considered an observed `webarea` sufficient readiness.
+It only requested activation when the web tree was absent, and the macOS
+activation implementation supported only `AXManualAccessibility`.
+
+Chromium's application implementation initially enables a limited accessibility
+mode on an AX role read. Its `AXEnhancedUserInterface` setter requests complete
+mode after a two-second debounce. Reading the flag back as true does not mean
+that debounce has finished. The live probe measured usable checkbox state
+appearing approximately 2.02 seconds after the write.
+
+The setter also returned `kAXErrorNotImplemented` after applying the flag.
+Chromium handles the attribute before forwarding the setter to its superclass;
+the observed readback is necessary to recognize the applied change.
+
+Primary sources:
+
+- [Chromium application accessibility activation and two-second debounce](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/chrome_browser_application_mac.mm)
+- [Chromium activation regression tests](https://chromium.googlesource.com/chromium/src/+/refs/tags/133.0.6917.1/chrome/browser/chrome_browser_application_mac_browsertest.mm)
+- [Chromium asynchronous accessibility action semantics](https://chromium.googlesource.com/chromium/src/+/main/docs/accessibility/browser/how_a11y_works_3.md)
+
+## Repair boundary
+
+- Reuse the existing renderer activation signal, interaction lease, deadline,
+ and observation retry. Keep the policy and click implementation unchanged.
+- Preserve manual accessibility preference for renderers that support it.
+- Permit enhanced accessibility fallback only after observing a web surface.
+ Finder also advertises this attribute, so support alone is not evidence of
+ a renderer and must not activate native apps.
+- Check the selected mode even when web content is already readable.
+- Read the flag back after a write. A matching value can establish activation
+ despite the setter's unsupported response; contradictory readback cannot.
+- Wait out Chromium's two-second enhanced-mode debounce within the existing
+ deadline. Reject insufficient budgets before writing. Already-enabled modes
+ do not pay this startup delay.
+- Preserve older manual-mode implementations whose readable web tree exists
+ but whose manual activation flag has no readable value.
+
+This does not add browser-name checks, DOM automation, physical click fallbacks,
+or a new command/API. The general click result can still be
+`delivered_unverified`; callers must inspect the requested effect. The overlay
+ripple also remains a delivery visualization, not proof of page navigation.
+
+## Verification
+
+Deterministic unit tests cover attribute selection, native-app exclusion,
+already-enabled modes, legacy missing readback, missing renderer retries,
+capability/read failures, contradictory setter readback, applied changes despite
+unsupported return codes, and insufficient-budget rejection before native I/O.
+These cases use fake capability/readback results or null handles and do not
+depend on browser startup, global UI state, or exact wall-clock timing.
+
+Live tests are separate: begin with enhanced mode disabled, snapshot with the
+release binary, perform one semantic click, and read the actual page state.
+Compare a button, checkbox, and link on an isolated local page, plus a native
+browser control. Observe foreground PID and physical pointer separately from
+the cursor overlay. Do not claim pointer stability when concurrent user input
+changes it during the measurement.
+
+### Results on the final release build
+
+- `cargo test --workspace`: 2,231 passed, zero failed, four ignored.
+- Formatting, Clippy with warnings denied, core dependency isolation, and
+ whitespace checks passed. The release executable is 3,072,144 bytes.
+- Cold Comet activation followed by semantic checkbox press changed `0` to `1`;
+ a subsequent link press changed the URL to `#destination`. Earlier cold button
+ activation changed its output text. Raw AX and Agent Desktop both reproduced
+ the disabled-mode failure; enabling the mode also opened the Hacker News article.
+- The overlay was enabled. Foreground PID and physical pointer were unchanged
+ across the final checkbox/link actions. Finder's enhanced mode remained false.
+- The required performance script ran with the activating native fixture skipped
+ to preserve strict headless operation. Its application-name probes were unusable:
+ Finder had no window, and Comet had multiple windows. A supplemental alternating
+ five-round comparison used the same explicit Comet window and immutable binaries.
+ All 30 snapshots succeeded with matching ref counts. Warm median milliseconds
+ were baseline/fixed: default 627/563, skeleton 582/614, depth-30 588/615.
+ These small samples do not establish a universal performance bound; they show
+ no repeated two-second warm penalty. Cold enhanced activation intentionally pays
+ Chromium's two-second debounce plus the existing observation retry.
+
+Local probe artifacts are under `/tmp/comet-ax-probe`; raw trees may contain
+private browser content and should not be published.
diff --git a/scripts/perf-baseline-compare.sh b/scripts/perf-baseline-compare.sh
index da59d5971..5edeba970 100755
--- a/scripts/perf-baseline-compare.sh
+++ b/scripts/perf-baseline-compare.sh
@@ -42,7 +42,8 @@ echo "== perf compare: HEAD ${head_sha} vs base ${base_sha} -> ${out}"
echo "== building HEAD release binary"
cargo build --release -p agent-desktop >/dev/null
-head_bin="$repo/target/release/agent-desktop"
+head_bin="$out/head-agent-desktop"
+cp "$repo/target/release/agent-desktop" "$head_bin"
echo "== building base release binary (${base_sha}) in a temporary worktree"
wt="$out/base-worktree"
@@ -69,7 +70,8 @@ cleanup() {
}
trap cleanup EXIT
(cd "$wt" && cargo build --release -p agent-desktop >/dev/null)
-base_bin="$wt/target/release/agent-desktop"
+base_bin="$out/base-agent-desktop"
+cp "$wt/target/release/agent-desktop" "$base_bin"
if [ "$skip_fixture" -ne 1 ]; then
echo "== fixture A/B (${rounds} rounds; actions run against the fixture only)"
diff --git a/scripts/perf_ab_probe.py b/scripts/perf_ab_probe.py
index d4707eaab..380b16ee7 100755
--- a/scripts/perf_ab_probe.py
+++ b/scripts/perf_ab_probe.py
@@ -8,7 +8,7 @@ Modes:
arbitrary real apps (Slack, Chrome, ...). Never dispatches
actions.
-Each binary runs under an isolated HOME so cross-revision store formats
+Each binary runs under an isolated state root so cross-revision store formats
never collide. Rounds alternate between binaries to cancel machine drift.
"""
import argparse
@@ -27,7 +27,8 @@ ENVS = {}
def env_for(binary):
if binary not in ENVS:
env = dict(os.environ)
- env["HOME"] = tempfile.mkdtemp(prefix="ad-perf-home-")
+ env["AGENT_DESKTOP_HOME"] = tempfile.mkdtemp(prefix="ad-perf-state-")
+ env.pop("AGENT_DESKTOP_SESSION", None)
ENVS[binary] = env
return ENVS[binary]
@@ -129,8 +130,9 @@ def collect(binaries, cases_for, rounds):
env = envelope(proc)
ok = bool(env.get("ok"))
results[label].setdefault(name, []).append((elapsed, ok))
- if ok and name.startswith("snapshot") and name not in shapes[label]:
- shapes[label][name] = tree_stats(env)
+ if name.startswith("snapshot"):
+ complete = ok and env.get("data", {}).get("complete") is True
+ shapes[label].setdefault(name, []).append(tree_stats(env) if complete else None)
return results, shapes
@@ -139,11 +141,16 @@ def summarize(results, shapes):
for label, cases in results.items():
for name, samples in cases.items():
times = sorted(t for t, ok in samples if ok)
+ observed = shapes[label].get(name, [])
+ stable_shape = observed[0] if observed and all(shape == observed[0] for shape in observed) else None
report.setdefault(name, {})[label] = {
"p50_ms": round(statistics.median(times), 1) if times else None,
"p95_ms": round(times[math.ceil(len(times) * 0.95) - 1], 1) if times else None,
"ok_rate": sum(1 for _, ok in samples if ok) / len(samples),
- "shape": shapes[label].get(name),
+ "shape": stable_shape,
+ "observed_shapes": observed,
+ "complete_rate": sum(shape is not None for shape in observed) / len(observed) if observed else None,
+ "samples_ms": [round(elapsed, 1) for elapsed, _ in samples],
}
return report
@@ -171,7 +178,8 @@ def main():
json.dump(payload, handle, indent=1)
json.dump(payload, sys.stdout, indent=1)
print()
- if any(side["ok_rate"] < 1.0 for case in report.values() for side in case.values()):
+ if any(side["ok_rate"] < 1.0 or side["complete_rate"] not in (None, 1.0)
+ for case in report.values() for side in case.values()):
raise SystemExit(1)
diff --git a/scripts/perf_ab_probe_test.py b/scripts/perf_ab_probe_test.py
index e10056969..eb57c7ff9 100644
--- a/scripts/perf_ab_probe_test.py
+++ b/scripts/perf_ab_probe_test.py
@@ -44,6 +44,20 @@ def check_report_and_cases():
assert "FAIL" in html and "not revision A/B" in html and "Refs re-resolvable" in html
+def check_all_snapshot_shapes_and_completeness():
+ results = {"HEAD": {"snapshot": [(1, True), (2, True)]}}
+ for observed, expected, complete in [
+ ([(2, 1, 1), (2, 1, 1)], (2, 1, 1), 1.0),
+ ([(2, 1, 1), (3, 1, 2)], None, 1.0),
+ ([(2, 1, 1), None], None, 0.5),
+ ]:
+ summary = probe.summarize(results, {"HEAD": {"snapshot": observed}})["snapshot"]["HEAD"]
+ assert summary["shape"] == expected
+ assert summary["complete_rate"] == complete
+ assert summary["observed_shapes"] == observed
+
+
if __name__ == "__main__":
check_balanced_order_and_percentile()
check_report_and_cases()
+ check_all_snapshot_shapes_and_completeness()
diff --git a/scripts/perf_report_html.py b/scripts/perf_report_html.py
index eab7559d7..1f9790cf4 100644
--- a/scripts/perf_report_html.py
+++ b/scripts/perf_report_html.py
@@ -40,7 +40,7 @@ def live_report(payload):
intro = (f'<p>{escape(str(payload.get("app", "unknown app")))}; '
f'{escape(str(payload.get("rounds", "unknown")))} rounds. '
'Latency uses successful samples only. OK rate includes failures; 100% OK does not verify action effects. '
- 'Shape = [nodes, depth, refs] from the first successful snapshot, not proof of identical content. '
+ 'Shape = [nodes, depth, refs], reported only when every snapshot is complete and has the same shape; not proof of identical content. '
'Deltas require successful runs and matching known snapshot shapes.</p>')
return intro + (table(['Case', 'Side', 'p50 ms', 'p95 ms', 'OK %', 'Shape', 'p50 delta'], rows)
if rows else '<p>No case measurements available.</p>')
diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.md
index cb7b0e8fe..053fff439 100644
--- a/skills/agent-desktop/references/commands-observation.md
+++ b/skills/agent-desktop/references/commands-observation.md
@@ -139,6 +139,10 @@ agent-desktop click @s8f3k2p9:e5 --debug --screenshot /tmp/click-visual.html
## find
+Results use the same accessible `name` as name matching. Unnamed elements omit
+`name`; their current content remains in `value`. Use `--value` to locate editable
+content, rather than treating that content as the element's name.
+
Search elements by role, name, value, or text content.
```bash
@@ -223,13 +227,20 @@ agent-desktop get @s8f3k2p9:e1 --property title
| Property | Returns |
|----------|---------|
-| `text` | Accessible name/label (default) |
+| `text` | Current text value, an alias of `value` (default) |
| `value` | Current value (text content, slider position, etc.) |
| `title` | Window or element title |
| `bounds` | `{ x, y, width, height }` rectangle |
| `role` | Element role string |
| `states` | Array of active states |
+`text`, `value`, `bounds`, and `states` use live reads when the adapter supports
+them. An absent live value or bounds returns `null`; it does not resurrect
+snapshot text or coordinates. For these properties, snapshot fallback applies
+only when the adapter does not support that live read. State reads retain the
+snapshot fallback when live state is unavailable. Native read failures remain
+errors. Use `title` for the saved element name.
+
## is
Check a boolean state on an element.
@@ -253,6 +264,9 @@ agent-desktop is @s8f3k2p9:e6 --property selected
| `expanded` | Disclosure/tree item is expanded |
| `selected` | Selectable element is selected |
+For `enabled`, an unknown native value returns `result: false` with
+`applicable: false`. This means unknown, not known to be disabled.
+
**Output:**
```json
{ "data": { "ref": "@s8f3k2p9:e3", "property": "checked", "result": true } }
diff --git a/src/Cargo.toml b/src/Cargo.toml
index 541dabe03..eda20610c 100644
--- a/src/Cargo.toml
+++ b/src/Cargo.toml
@@ -17,6 +17,7 @@ tracing-subscriber.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
agent-desktop-macos = { path = "../crates/macos" }
+libc.workspace = true
[target.'cfg(target_os = "windows")'.dependencies]
agent-desktop-windows = { path = "../crates/windows" }
@@ -40,5 +41,9 @@ path = "tests/conformance.rs"
name = "cli_process"
path = "tests/cli_process.rs"
+[[test]]
+name = "command_host_process"
+path = "tests/command_host_process.rs"
+
[lints]
workspace = true
diff --git a/src/batch/preparation.rs b/src/batch/preparation.rs
index 26e4b06e2..d7af53db7 100644
--- a/src/batch/preparation.rs
+++ b/src/batch/preparation.rs
@@ -103,3 +103,33 @@ fn limit_error(message: &str, details: Value) -> AppError {
.with_disposition(DeliverySemantics::not_delivered())
.into()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_pinned_namespace_rejects_foreign_item_sessions_before_dispatch() {
+ let context = CommandContext::default().with_pinned_session_namespace();
+ match prepare(
+ r#"[{"command":"version","session":"other"}]"#,
+ &PermissionReport::default(),
+ &context,
+ ) {
+ Ok(_) => panic!("a foreign item session must be rejected"),
+ Err(error) => assert!(
+ error
+ .to_string()
+ .contains("cannot switch snapshot namespaces")
+ ),
+ }
+ let prepared = prepare(
+ r#"[{"command":"version"}]"#,
+ &PermissionReport::default(),
+ &context,
+ )
+ .unwrap();
+ assert_eq!(prepared.len(), 1);
+ assert_eq!(prepared[0].context.session_id(), None);
+ }
+}
diff --git a/src/command_host.rs b/src/command_host.rs
new file mode 100644
index 000000000..1e4d192c9
--- /dev/null
+++ b/src/command_host.rs
@@ -0,0 +1,292 @@
+use agent_desktop_core::{AppError, output::Response, session::resolve_active_session};
+use clap::Parser;
+use std::io::Write;
+#[cfg(test)]
+use std::io::{BufRead, Read};
+use std::os::fd::AsFd;
+
+const MAX_REQUEST_BYTES: u64 = 1_048_576;
+const RETAINED_PRUNE_INTERVAL: usize = 4_096;
+const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(900);
+const IO_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
+
+pub(crate) fn is_host_process() -> bool {
+ std::env::var("AGENT_DESKTOP_INTERNAL_COMMAND_HOST").as_deref() == Ok("1")
+}
+
+#[path = "command_host_budget.rs"]
+mod budget;
+
+#[path = "command_host_client.rs"]
+mod client;
+#[path = "command_host_connect.rs"]
+mod connect;
+#[path = "command_host_endpoint.rs"]
+mod endpoint;
+#[path = "command_host_input.rs"]
+mod input;
+#[path = "command_host_output.rs"]
+mod output;
+#[path = "command_host_request.rs"]
+mod request;
+#[path = "command_host_socket.rs"]
+mod socket;
+
+pub(crate) fn forward(
+ cli: &crate::Cli,
+ command: &crate::Commands,
+) -> Result<serde_json::Value, AppError> {
+ client::forward(cli, command)
+}
+
+pub(crate) fn run() -> Result<(), AppError> {
+ let session =
+ resolve_active_session(None, std::env::var("AGENT_DESKTOP_SESSION").ok().as_deref())?;
+ let owner = agent_desktop_macos::RetainedRefSession::start()?;
+ let store = agent_desktop_core::refs_store::RefStore::for_session(session.as_deref())?;
+ let mut next_prune = RETAINED_PRUNE_INTERVAL;
+ let identity = endpoint::identity(session.as_deref())?;
+ let socket_path = std::env::var_os("AGENT_DESKTOP_INTERNAL_HOST_SOCKET");
+ let execute = |bytes: &[u8]| {
+ if owner.capture_count() >= next_prune {
+ match store.retained_object_tokens() {
+ Ok(tokens) => owner.retain(&tokens),
+ Err(error) => {
+ tracing::warn!(%error, "retained-token inventory failed; pruning deferred");
+ }
+ }
+ next_prune = owner
+ .capture_count()
+ .saturating_add(RETAINED_PRUNE_INTERVAL);
+ }
+ if socket_path.is_some() {
+ request::execute(bytes, &identity, session.as_deref())
+ } else {
+ execute_request(bytes, session.as_deref())
+ }
+ };
+ if let Some(ref path) = socket_path {
+ return socket::run(std::path::Path::new(&path), execute);
+ }
+ let input = std::io::stdin();
+ let output = std::fs::File::from(std::io::stdout().as_fd().try_clone_to_owned()?);
+ let mut input = std::io::BufReader::new(input.lock());
+ serve_frames(
+ || {
+ input::read_frame(
+ &mut input,
+ MAX_REQUEST_BYTES as usize,
+ IDLE_TIMEOUT,
+ IO_TIMEOUT,
+ )
+ },
+ std::io::BufWriter::new(output::BoundedWriter::new(output, IO_TIMEOUT)?),
+ execute,
+ )?;
+ Ok(())
+}
+
+fn execute_request(bytes: &[u8], session: Option<&str>) -> Response {
+ let result = parse_request(bytes, session);
+ match result {
+ Ok((cli, command)) => {
+ let name = command.name();
+ crate::response(name, crate::execute(cli, command))
+ }
+ Err(error) => crate::response("unknown", Err(error)),
+ }
+}
+
+fn parse_request(
+ bytes: &[u8],
+ session: Option<&str>,
+) -> Result<(crate::Cli, crate::Commands), AppError> {
+ let args: Vec<String> = serde_json::from_slice(bytes).map_err(|_| {
+ AppError::invalid_input("Host request must be a JSON array of CLI arguments")
+ })?;
+ let mut cli =
+ crate::Cli::try_parse_from(std::iter::once("agent-desktop".to_owned()).chain(args))
+ .map_err(|error| {
+ AppError::invalid_input(crate::diagnostic::bounded_text(&error.to_string(), 512))
+ })?;
+ let selected = resolve_active_session(cli.identity.session.as_deref(), session)?;
+ if selected.as_deref() != session {
+ return Err(AppError::invalid_input(
+ "A command host cannot switch snapshot namespaces",
+ ));
+ }
+ let command = cli
+ .command
+ .take()
+ .ok_or_else(|| AppError::invalid_input("Host request requires a command"))?;
+ Ok((cli, command))
+}
+
+#[cfg(test)]
+fn serve(
+ mut input: impl BufRead,
+ output: impl Write,
+ execute: impl FnMut(&[u8]) -> Response,
+) -> Result<(), AppError> {
+ serve_frames(
+ || {
+ let mut bytes = Vec::new();
+ input
+ .by_ref()
+ .take(MAX_REQUEST_BYTES + 1)
+ .read_until(b'\n', &mut bytes)?;
+ Ok(bytes)
+ },
+ output,
+ execute,
+ )
+}
+
+fn serve_frames(
+ mut read_frame: impl FnMut() -> std::io::Result<Vec<u8>>,
+ mut output: impl Write,
+ mut execute: impl FnMut(&[u8]) -> Response,
+) -> Result<(), AppError> {
+ loop {
+ let bytes = read_frame().map_err(|error| {
+ if error.kind() == std::io::ErrorKind::TimedOut {
+ AppError::Adapter(
+ agent_desktop_core::AdapterError::timeout(
+ "Command host request did not arrive before its input deadline",
+ )
+ .with_disposition(agent_desktop_core::DeliverySemantics::not_delivered()),
+ )
+ } else {
+ AppError::from(error)
+ }
+ })?;
+ if bytes.is_empty() {
+ return Ok(());
+ }
+ let oversized = bytes.len() as u64 > MAX_REQUEST_BYTES;
+ let incomplete = bytes.last() != Some(&b'\n');
+ let response = if oversized || incomplete {
+ crate::response(
+ "unknown",
+ Err(AppError::invalid_input(
+ "Host request is oversized or lacks its newline terminator",
+ )),
+ )
+ } else {
+ execute(&bytes)
+ };
+ serde_json::to_writer(&mut output, &response).map_err(|error| {
+ std::io::Error::new(
+ error.io_error_kind().unwrap_or(std::io::ErrorKind::Other),
+ error,
+ )
+ })?;
+ output.write_all(b"\n")?;
+ output.flush()?;
+ if oversized || incomplete {
+ return Ok(());
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn repeated_commands_reuse_dispatch_and_preserve_envelopes() {
+ let mut output = Vec::new();
+ serve(
+ std::io::Cursor::new(b"[\"version\"]\n[\"version\"]\n"),
+ &mut output,
+ |bytes| execute_request(bytes, None),
+ )
+ .unwrap();
+ let responses: Vec<serde_json::Value> = output
+ .split(|byte| *byte == b'\n')
+ .filter(|line| !line.is_empty())
+ .map(|line| serde_json::from_slice(line).unwrap())
+ .collect();
+ assert_eq!(responses.len(), 2);
+ assert!(
+ responses
+ .iter()
+ .all(|response| response["ok"] == true && response["command"] == "version")
+ );
+ }
+
+ #[test]
+ fn incomplete_or_oversized_frames_never_dispatch() {
+ for bytes in [
+ b"[\"version\"]".to_vec(),
+ vec![b'x'; MAX_REQUEST_BYTES as usize + 1],
+ ] {
+ let mut output = Vec::new();
+ serve(std::io::Cursor::new(bytes), &mut output, |_| {
+ panic!("must not dispatch")
+ })
+ .unwrap();
+ let response: serde_json::Value = serde_json::from_slice(&output).unwrap();
+ assert_eq!(response["error"]["code"], "INVALID_ARGS");
+ assert_eq!(
+ response["error"]["disposition"]["delivery"],
+ "not_delivered"
+ );
+ }
+ }
+
+ #[test]
+ fn request_cannot_cross_session_namespace() {
+ assert!(parse_request(b"[\"--session\",\"other\",\"version\"]", Some("owner")).is_err());
+ assert!(parse_request(b"[\"--session\",\"owner\",\"version\"]", Some("owner")).is_ok());
+ assert!(parse_request(b"[\"version\"]", Some("owner")).is_ok());
+ }
+
+ #[test]
+ fn a_lost_reply_never_replays_the_command() {
+ let mut attempts = 0;
+ let error = serve(std::io::Cursor::new(b"[]\n[]\n"), RejectWrites, |_| {
+ attempts += 1;
+ Response::ok("click", serde_json::json!({}))
+ })
+ .unwrap_err();
+ assert!(
+ matches!(error, AppError::Io(error) if error.kind() == std::io::ErrorKind::BrokenPipe)
+ );
+ assert_eq!(attempts, 1);
+ }
+
+ #[test]
+ fn a_frame_timeout_never_dispatches_or_reads_another_request() {
+ let mut reads = 0;
+ let error = serve_frames(
+ || {
+ reads += 1;
+ Err(std::io::ErrorKind::TimedOut.into())
+ },
+ Vec::new(),
+ |_| panic!("timed-out frame must not dispatch"),
+ )
+ .unwrap_err();
+ let response = crate::response("host", Err(error));
+ let response = serde_json::to_value(response).unwrap();
+ assert_eq!(response["error"]["code"], "TIMEOUT");
+ assert_eq!(
+ response["error"]["disposition"]["delivery"],
+ "not_delivered"
+ );
+ assert_eq!(reads, 1);
+ }
+
+ struct RejectWrites;
+
+ impl Write for RejectWrites {
+ fn write(&mut self, _bytes: &[u8]) -> std::io::Result<usize> {
+ Err(std::io::ErrorKind::BrokenPipe.into())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+}
diff --git a/src/command_host_budget.rs b/src/command_host_budget.rs
new file mode 100644
index 000000000..b99feb38c
--- /dev/null
+++ b/src/command_host_budget.rs
@@ -0,0 +1,126 @@
+use agent_desktop_core::{AdapterError, AppError, Deadline};
+use std::time::Duration;
+
+pub(super) fn expires_at(cli: &crate::Cli, command: &crate::Commands) -> Result<u64, AppError> {
+ let budget = budget_ms(cli, command)?;
+ Deadline::detached_after(budget)?;
+ now()?
+ .checked_add(
+ budget
+ .checked_mul(1_000_000)
+ .ok_or_else(|| AppError::invalid_input("Command host budget is too large"))?,
+ )
+ .ok_or_else(|| AppError::invalid_input("Command host deadline is too large"))
+}
+
+pub(super) fn remaining(expires_ns: u64) -> Result<Duration, AppError> {
+ remaining_at(expires_ns, now()?)
+}
+
+fn remaining_at(expires_ns: u64, now_ns: u64) -> Result<Duration, AppError> {
+ match expires_ns
+ .checked_sub(now_ns)
+ .filter(|remaining| *remaining > 0)
+ {
+ Some(remaining) => Ok(Duration::from_nanos(remaining)),
+ None => Err(AdapterError::timeout("Command host request expired before dispatch").into()),
+ }
+}
+
+fn now() -> Result<u64, AppError> {
+ let mut time = libc::timespec {
+ tv_sec: 0,
+ tv_nsec: 0,
+ };
+ if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut time) } != 0 {
+ return Err(std::io::Error::last_os_error().into());
+ }
+ u64::try_from(time.tv_sec)
+ .ok()
+ .and_then(|seconds| seconds.checked_mul(1_000_000_000))
+ .and_then(|seconds| seconds.checked_add(time.tv_nsec as u64))
+ .ok_or_else(|| AppError::Internal("Monotonic clock is outside its supported range".into()))
+}
+
+fn budget_ms(cli: &crate::Cli, command: &crate::Commands) -> Result<u64, AppError> {
+ use crate::Commands;
+ let primary = match command {
+ Commands::Click(a)
+ | Commands::DoubleClick(a)
+ | Commands::TripleClick(a)
+ | Commands::RightClick(a)
+ | Commands::Clear(a)
+ | Commands::Focus(a)
+ | Commands::Toggle(a)
+ | Commands::Check(a)
+ | Commands::Uncheck(a)
+ | Commands::Expand(a)
+ | Commands::Collapse(a)
+ | Commands::ScrollTo(a) => a.timeout_ms,
+ Commands::Type(a) => a.timeout_ms,
+ Commands::SetValue(a) => a.timeout_ms,
+ Commands::Select(a) => a.timeout_ms,
+ Commands::Scroll(a) => a.timeout_ms,
+ Commands::Hover(a) => a.timeout_ms,
+ Commands::Drag(a) => a.timeout_ms,
+ Commands::Wait(a) => match a.mode.ms {
+ Some(ms) => ms
+ .checked_add(5000)
+ .ok_or_else(|| AppError::invalid_input("Wait is too long"))?,
+ None => a.timeout,
+ },
+ Commands::Launch(a) => a.timeout,
+ Commands::Batch(a) => a.timeout_ms,
+ _ => agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS,
+ };
+ let post_wait = crate::build_wait_selector(cli)?.map_or(0, |wait| wait.timeout_ms);
+ primary
+ .checked_add(post_wait)
+ .ok_or_else(|| AppError::invalid_input("Combined command budget is too large"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::Parser;
+
+ #[test]
+ fn queue_time_is_not_refunded_and_expiry_is_terminal() {
+ assert_eq!(
+ remaining_at(8000, 2000).unwrap(),
+ Duration::from_nanos(6000)
+ );
+ for now in [8000, 9000] {
+ assert_eq!(remaining_at(8000, now).unwrap_err().code(), "TIMEOUT");
+ }
+ }
+
+ #[test]
+ fn budgets_follow_typed_arguments_including_post_action_waits() {
+ for (args, expected) in [
+ (vec!["ad", "click", "@s123:e1", "--timeout-ms", "123"], 123),
+ (
+ vec!["ad", "wait", "--text", "absent", "--timeout", "250"],
+ 250,
+ ),
+ (vec!["ad", "wait", "100"], 5100),
+ (vec!["ad", "batch", "[]", "--timeout-ms", "80000"], 80000),
+ (
+ vec![
+ "ad",
+ "click",
+ "@s123:e1",
+ "--wait-for",
+ "button",
+ "--wait-timeout",
+ "900",
+ ],
+ 5900,
+ ),
+ ] {
+ let mut cli = crate::Cli::try_parse_from(args).unwrap();
+ let command = cli.command.take().unwrap();
+ assert_eq!(budget_ms(&cli, &command).unwrap(), expected);
+ }
+ }
+}
diff --git a/src/command_host_client.rs b/src/command_host_client.rs
new file mode 100644
index 000000000..1c4df0b7b
--- /dev/null
+++ b/src/command_host_client.rs
@@ -0,0 +1,203 @@
+use agent_desktop_core::{AdapterError, AppError, Deadline, DeliverySemantics};
+use std::io::{BufReader, BufWriter, Write};
+use std::os::unix::net::UnixStream;
+use std::os::unix::process::CommandExt;
+use std::path::Path;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+pub(super) fn forward(
+ cli: &crate::Cli,
+ command: &crate::Commands,
+) -> Result<serde_json::Value, AppError> {
+ let expires_ns = super::budget::expires_at(cli, command).map_err(crate::pre_dispatch_error)?;
+ agent_desktop_core::validate_state_root_env()?;
+ let session = agent_desktop_core::session::resolve_active_session(
+ cli.identity.session.as_deref(),
+ std::env::var("AGENT_DESKTOP_SESSION").ok().as_deref(),
+ )?;
+ let identity = super::endpoint::identity(session.as_deref())?;
+ let path = super::endpoint::path(&identity)?;
+ let request = super::request::HostRequest {
+ expires_ns,
+ identity,
+ args: std::env::args_os()
+ .skip(1)
+ .map(|arg| {
+ arg.into_string()
+ .map_err(|_| AppError::invalid_input("Host arguments must be UTF-8"))
+ })
+ .collect::<Result<_, _>>()?,
+ directory: std::env::current_dir()?,
+ agent_id: cli
+ .identity
+ .agent_id
+ .clone()
+ .or_else(|| std::env::var("AGENT_DESKTOP_AGENT_ID").ok()),
+ };
+ let mut payload = serde_json::to_vec(&request)?;
+ payload.push(b'\n');
+ if payload.len() > super::MAX_REQUEST_BYTES as usize {
+ return Err(AppError::invalid_input(
+ "Command host request exceeds its size limit",
+ ));
+ }
+ let remaining = super::budget::remaining(expires_ns).map_err(crate::pre_dispatch_error)?;
+ let stream = connect_or_start(&path, session.as_deref(), remaining.min(super::IO_TIMEOUT))
+ .map_err(crate::pre_dispatch_error)?;
+ let remaining = super::budget::remaining(expires_ns).map_err(crate::pre_dispatch_error)?;
+ exchange(stream, &payload, remaining).map_err(|error| {
+ AdapterError::internal("Command host reply was lost; the command may have executed")
+ .with_platform_detail(error.to_string())
+ .with_disposition(DeliverySemantics::uncertain())
+ .into()
+ })
+}
+
+fn exchange(
+ stream: UnixStream,
+ payload: &[u8],
+ remaining: Duration,
+) -> Result<serde_json::Value, AppError> {
+ let reply_deadline = Instant::now() + remaining + Duration::from_secs(2);
+ let mut output = BufWriter::new(super::output::BoundedWriter::new(
+ stream.try_clone()?,
+ remaining.min(super::IO_TIMEOUT),
+ )?);
+ output.write_all(payload)?;
+ output.flush()?;
+ let reply = super::input::read_frame(
+ &mut BufReader::new(stream),
+ 64 * 1024 * 1024,
+ reply_deadline.saturating_duration_since(Instant::now()),
+ super::IO_TIMEOUT,
+ )?;
+ if reply.last() != Some(&b'\n') || reply.len() > 64 * 1024 * 1024 {
+ return Err(AppError::invalid_input(
+ "Command host reply is incomplete or oversized",
+ ));
+ }
+ let value: serde_json::Value = serde_json::from_slice(&reply)?;
+ if value["version"] != agent_desktop_core::output::ENVELOPE_VERSION || !value["ok"].is_boolean()
+ {
+ return Err(AppError::invalid_input(
+ "Command host reply has an invalid envelope",
+ ));
+ }
+ Ok(value)
+}
+
+fn connect(path: &Path, deadline: Instant) -> Result<Option<UnixStream>, AppError> {
+ if !super::endpoint::validate_socket(path)? {
+ return Ok(None);
+ }
+ match super::connect::connect(path, deadline) {
+ Ok(stream) => Ok(Some(stream)),
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused
+ ) =>
+ {
+ Ok(None)
+ }
+ Err(error) => Err(error.into()),
+ }
+}
+
+fn connect_or_start(
+ path: &Path,
+ session: Option<&str>,
+ budget: Duration,
+) -> Result<UnixStream, AppError> {
+ let deadline = Instant::now() + budget;
+ if let Some(stream) = connect(path, deadline)? {
+ return Ok(stream);
+ }
+ let _startup = agent_desktop_core::FileLock::acquire(
+ &path.with_extension("start.lock"),
+ Deadline::from_duration(deadline.saturating_duration_since(Instant::now()))?,
+ "command host startup",
+ )?;
+ if let Some(stream) = connect(path, deadline)? {
+ return Ok(stream);
+ }
+ let mut command = Command::new(std::env::current_exe()?);
+ command
+ .env("AGENT_DESKTOP_INTERNAL_COMMAND_HOST", "1")
+ .env("AGENT_DESKTOP_INTERNAL_HOST_SOCKET", path)
+ .env_remove("AGENT_DESKTOP_INTERNAL_HOST_CLIENT")
+ .env_remove("AGENT_DESKTOP_AGENT_ID")
+ .env_remove("AGENT_DESKTOP_SESSION")
+ .process_group(0)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ if let Some(session) = session {
+ command.env("AGENT_DESKTOP_SESSION", session);
+ }
+ let mut child = command.spawn()?;
+ let result = loop {
+ if Instant::now() >= deadline {
+ break Err(AppError::from(AdapterError::timeout(
+ "Command host startup timed out",
+ )));
+ }
+ match child.try_wait() {
+ Ok(Some(_)) => {
+ break Err(AppError::Internal(
+ "Command host exited during startup".into(),
+ ));
+ }
+ Ok(None) => {}
+ Err(error) => break Err(error.into()),
+ }
+ match connect(path, deadline) {
+ Ok(Some(stream)) => break Ok(stream),
+ Ok(None) => std::thread::sleep(Duration::from_millis(10)),
+ Err(error) => break Err(error),
+ }
+ };
+ if result.is_err() {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Read;
+
+ fn replied(bytes: &[u8]) -> Result<serde_json::Value, AppError> {
+ let bytes = bytes.to_vec();
+ let (client, mut server) = UnixStream::pair().unwrap();
+ std::thread::spawn(move || {
+ let mut request = [0_u8; 64];
+ let _ = server.read(&mut request);
+ let _ = server.write_all(&bytes);
+ });
+ exchange(client, b"{}\n", Duration::from_secs(30))
+ }
+
+ #[test]
+ fn a_reply_without_its_newline_boundary_is_rejected() {
+ let error = replied(br#"{"version":"2.4","ok":true}"#).unwrap_err();
+ assert!(error.to_string().contains("incomplete or oversized"));
+ }
+
+ #[test]
+ fn a_reply_with_an_invalid_envelope_is_rejected() {
+ for reply in [
+ br#"{"version":"9.9","ok":true}"#.as_slice(),
+ br#"{"version":"2.4","ok":"yes"}"#.as_slice(),
+ br#"{"version":"2.4"}"#.as_slice(),
+ ] {
+ let mut framed = reply.to_vec();
+ framed.push(b'\n');
+ let error = replied(&framed).unwrap_err();
+ assert!(error.to_string().contains("invalid envelope"));
+ }
+ }
+}
diff --git a/src/command_host_connect.rs b/src/command_host_connect.rs
new file mode 100644
index 000000000..2c9333c32
--- /dev/null
+++ b/src/command_host_connect.rs
@@ -0,0 +1,82 @@
+use std::io;
+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+use std::os::unix::ffi::OsStrExt;
+use std::os::unix::net::UnixStream;
+use std::path::Path;
+use std::time::Instant;
+
+pub(super) fn connect(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
+ if Instant::now() >= deadline {
+ return Err(io::ErrorKind::TimedOut.into());
+ }
+ let bytes = path.as_os_str().as_bytes();
+ let mut address = libc::sockaddr_un {
+ sun_len: 0,
+ sun_family: libc::AF_UNIX as libc::sa_family_t,
+ sun_path: [0; 104],
+ };
+ if bytes.contains(&0) || bytes.len() >= address.sun_path.len() {
+ return Err(io::ErrorKind::InvalidInput.into());
+ }
+ for (target, source) in address.sun_path.iter_mut().zip(bytes) {
+ *target = *source as libc::c_char;
+ }
+ address.sun_len = (std::mem::offset_of!(libc::sockaddr_un, sun_path) + bytes.len() + 1) as u8;
+ let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0) };
+ if raw < 0 {
+ return Err(io::Error::last_os_error());
+ }
+ let socket = unsafe { OwnedFd::from_raw_fd(raw) };
+ if unsafe { libc::fcntl(raw, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 {
+ return Err(io::Error::last_os_error());
+ }
+ let stream = UnixStream::from(socket);
+ stream.set_nonblocking(true)?;
+ let result = unsafe {
+ libc::connect(
+ stream.as_raw_fd(),
+ (&address as *const libc::sockaddr_un).cast(),
+ address.sun_len as libc::socklen_t,
+ )
+ };
+ if result < 0 {
+ let error = io::Error::last_os_error();
+ if !matches!(error.raw_os_error(), Some(libc::EINPROGRESS | libc::EINTR)) {
+ return Err(error);
+ }
+ super::input::wait_ready(stream.as_raw_fd(), libc::POLLOUT, deadline)?;
+ if let Some(error) = stream.take_error()? {
+ return Err(error);
+ }
+ }
+ if Instant::now() >= deadline {
+ return Err(io::ErrorKind::TimedOut.into());
+ }
+ stream.set_nonblocking(false)?;
+ Ok(stream)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::os::unix::net::UnixListener;
+ use std::time::Duration;
+
+ #[test]
+ fn expired_connection_budget_does_not_enqueue_a_client() {
+ let path = std::env::temp_dir().join(format!("ad-connect-{}.sock", std::process::id()));
+ let listener = UnixListener::bind(&path).unwrap();
+ listener.set_nonblocking(true).unwrap();
+ assert_eq!(
+ connect(&path, Instant::now()).unwrap_err().kind(),
+ io::ErrorKind::TimedOut
+ );
+ assert_eq!(
+ listener.accept().unwrap_err().kind(),
+ io::ErrorKind::WouldBlock
+ );
+ let stream = connect(&path, Instant::now() + Duration::from_secs(10)).unwrap();
+ let _accepted = listener.accept().unwrap();
+ assert!(stream.peer_addr().is_ok());
+ }
+}
diff --git a/src/command_host_endpoint.rs b/src/command_host_endpoint.rs
new file mode 100644
index 000000000..ea515ff08
--- /dev/null
+++ b/src/command_host_endpoint.rs
@@ -0,0 +1,129 @@
+use agent_desktop_core::AppError;
+use std::hash::{Hash, Hasher};
+use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt};
+use std::path::{Path, PathBuf};
+
+pub(super) fn identity(session: Option<&str>) -> Result<String, AppError> {
+ let executable = std::env::current_exe()?;
+ let metadata = std::fs::metadata(&executable)?;
+ Ok(serde_json::to_string(&serde_json::json!({
+ "protocol": 1,
+ "root": agent_desktop_core::session::agent_desktop_dir()?,
+ "session": session,
+ "executable": executable,
+ "revision": [metadata.dev(), metadata.ino(), metadata.size()],
+ "modified": [metadata.mtime(), metadata.mtime_nsec()],
+ "helper": std::env::var_os("AGENT_DESKTOP_MACOS_HELPER_PATH"),
+ }))?)
+}
+
+pub(super) fn path(identity: &str) -> Result<PathBuf, AppError> {
+ let parent = std::env::temp_dir();
+ match validate_directory(&parent) {
+ Ok(()) => {}
+ Err(AppError::Io(error)) => return Err(error.into()),
+ Err(_) => {
+ return Err(AppError::invalid_input(
+ "Command host requires a private per-user temporary directory",
+ ));
+ }
+ }
+ let directory = parent.join(format!("agent-desktop-host-{}", unsafe { libc::geteuid() }));
+ match std::fs::DirBuilder::new().mode(0o700).create(&directory) {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(error) => return Err(error.into()),
+ }
+ validate_directory(&directory)?;
+ let mut hash = std::collections::hash_map::DefaultHasher::new();
+ identity.hash(&mut hash);
+ Ok(directory.join(format!("{:016x}.sock", hash.finish())))
+}
+
+pub(super) fn validate_directory(path: &Path) -> Result<(), AppError> {
+ let metadata = std::fs::symlink_metadata(path)?;
+ if !metadata.is_dir()
+ || metadata.file_type().is_symlink()
+ || metadata.uid() != unsafe { libc::geteuid() }
+ || metadata.mode() & 0o077 != 0
+ {
+ return Err(AppError::invalid_input(
+ "Command host directory must be private to the current user",
+ ));
+ }
+ Ok(())
+}
+
+pub(super) fn validate_socket(path: &Path) -> Result<bool, AppError> {
+ let metadata = match std::fs::symlink_metadata(path) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(error) => return Err(error.into()),
+ };
+ if !metadata.file_type().is_socket()
+ || metadata.uid() != unsafe { libc::geteuid() }
+ || metadata.mode() & 0o077 != 0
+ {
+ return Err(AppError::invalid_input(
+ "Command host endpoint is not a private socket",
+ ));
+ }
+ Ok(true)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+ use std::os::unix::net::UnixListener;
+ use std::sync::atomic::{AtomicU64, Ordering};
+
+ fn test_dir() -> PathBuf {
+ static NEXT: AtomicU64 = AtomicU64::new(0);
+ let path = std::env::temp_dir().join(format!(
+ "ad-endpoint-test-{}-{}",
+ std::process::id(),
+ NEXT.fetch_add(1, Ordering::Relaxed)
+ ));
+ std::fs::create_dir(&path).unwrap();
+ path
+ }
+
+ #[test]
+ fn directory_validation_rejects_every_non_private_arm() {
+ let loose = test_dir();
+ std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o755)).unwrap();
+ assert!(validate_directory(&loose).is_err());
+
+ let file = loose.join("file");
+ std::fs::write(&file, b"x").unwrap();
+ assert!(validate_directory(&file).is_err());
+
+ let target = test_dir();
+ let link = std::env::temp_dir().join(format!("ad-endpoint-link-{}", std::process::id()));
+ std::os::unix::fs::symlink(&target, &link).unwrap();
+ assert!(validate_directory(&link).is_err());
+
+ let private = test_dir();
+ std::fs::set_permissions(&private, std::fs::Permissions::from_mode(0o700)).unwrap();
+ assert!(validate_directory(&private).is_ok());
+ }
+
+ #[test]
+ fn socket_validation_rejects_non_sockets_and_loose_modes() {
+ let dir = test_dir();
+ let missing = dir.join("missing.sock");
+ assert!(!validate_socket(&missing).unwrap());
+
+ let file = dir.join("file.sock");
+ std::fs::write(&file, b"x").unwrap();
+ assert!(validate_socket(&file).is_err());
+
+ let socket = dir.join("ok.sock");
+ let _listener = UnixListener::bind(&socket).unwrap();
+ std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o644)).unwrap();
+ assert!(validate_socket(&socket).is_err());
+ std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600)).unwrap();
+ assert!(validate_socket(&socket).unwrap());
+ }
+}
diff --git a/src/command_host_input.rs b/src/command_host_input.rs
new file mode 100644
index 000000000..5bf711dab
--- /dev/null
+++ b/src/command_host_input.rs
@@ -0,0 +1,125 @@
+use std::io::{self, BufRead, BufReader, Read};
+use std::os::fd::AsRawFd;
+use std::time::{Duration, Instant};
+
+pub(super) fn read_frame(
+ input: &mut BufReader<impl Read + AsRawFd>,
+ limit: usize,
+ idle: Duration,
+ frame: Duration,
+) -> io::Result<Vec<u8>> {
+ let mut deadline = Instant::now() + idle;
+ let mut bytes = Vec::new();
+ loop {
+ if Instant::now() >= deadline {
+ return Err(io::ErrorKind::TimedOut.into());
+ }
+ if input.buffer().is_empty() {
+ wait_ready(input.get_ref().as_raw_fd(), libc::POLLIN, deadline)?;
+ }
+ if Instant::now() >= deadline {
+ return Err(io::ErrorKind::TimedOut.into());
+ }
+ let available = input.fill_buf()?;
+ if available.is_empty() {
+ return Ok(bytes);
+ }
+ if bytes.is_empty() {
+ deadline = Instant::now() + frame;
+ }
+ let count = available
+ .iter()
+ .position(|byte| *byte == b'\n')
+ .map_or(available.len(), |index| index + 1)
+ .min(limit.saturating_add(1).saturating_sub(bytes.len()));
+ bytes.extend_from_slice(&available[..count]);
+ input.consume(count);
+ if bytes.last() == Some(&b'\n') || bytes.len() > limit {
+ return Ok(bytes);
+ }
+ }
+}
+
+pub(super) fn wait_ready(fd: std::os::fd::RawFd, events: i16, deadline: Instant) -> io::Result<()> {
+ loop {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ return Err(io::ErrorKind::TimedOut.into());
+ }
+ let timeout = i32::try_from(remaining.as_millis().saturating_add(1)).unwrap_or(i32::MAX);
+ let mut poll = libc::pollfd {
+ fd,
+ events,
+ revents: 0,
+ };
+ let result = unsafe { libc::poll(&mut poll, 1, timeout) };
+ if result > 0 {
+ return if poll.revents & libc::POLLNVAL == 0 {
+ Ok(())
+ } else {
+ Err(io::ErrorKind::InvalidInput.into())
+ };
+ }
+ if result < 0 {
+ let error = io::Error::last_os_error();
+ if error.kind() != io::ErrorKind::Interrupted {
+ return Err(error);
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Write;
+ use std::os::unix::net::UnixStream;
+
+ #[test]
+ fn buffered_requests_are_separate_and_do_not_wait_for_more_input() {
+ let (mut sender, receiver) = UnixStream::pair().unwrap();
+ sender.write_all(b"[]\n[\"version\"]\n").unwrap();
+ let mut input = BufReader::new(receiver);
+ let budget = Duration::from_secs(60);
+ assert_eq!(
+ read_frame(&mut input, 100, budget, budget).unwrap(),
+ b"[]\n"
+ );
+ assert_eq!(
+ read_frame(&mut input, 100, budget, budget).unwrap(),
+ b"[\"version\"]\n"
+ );
+ }
+
+ #[test]
+ fn a_partial_frame_has_a_deadline_even_while_its_sender_stays_connected() {
+ let (mut sender, receiver) = UnixStream::pair().unwrap();
+ sender.write_all(b"[").unwrap();
+ let error = read_frame(
+ &mut BufReader::new(receiver),
+ 100,
+ Duration::from_secs(60),
+ Duration::ZERO,
+ )
+ .unwrap_err();
+ assert_eq!(error.kind(), io::ErrorKind::TimedOut);
+ }
+
+ #[test]
+ fn expired_idle_budget_does_not_consume_a_queued_request() {
+ let (mut sender, receiver) = UnixStream::pair().unwrap();
+ sender.write_all(b"[]\n").unwrap();
+ let mut input = BufReader::new(receiver);
+ assert_eq!(
+ read_frame(&mut input, 100, Duration::ZERO, Duration::ZERO)
+ .unwrap_err()
+ .kind(),
+ io::ErrorKind::TimedOut
+ );
+ let budget = Duration::from_secs(60);
+ assert_eq!(
+ read_frame(&mut input, 100, budget, budget).unwrap(),
+ b"[]\n"
+ );
+ }
+}
diff --git a/src/command_host_output.rs b/src/command_host_output.rs
new file mode 100644
index 000000000..57760674e
--- /dev/null
+++ b/src/command_host_output.rs
@@ -0,0 +1,126 @@
+use std::io::{self, Write};
+use std::os::fd::AsRawFd;
+use std::time::{Duration, Instant};
+
+pub(super) struct BoundedWriter<W: Write + AsRawFd> {
+ output: W,
+ original_flags: i32,
+ timeout: Duration,
+ deadline: Option<Instant>,
+}
+
+impl<W: Write + AsRawFd> BoundedWriter<W> {
+ pub(super) fn new(output: W, timeout: Duration) -> io::Result<Self> {
+ let original_flags = unsafe { libc::fcntl(output.as_raw_fd(), libc::F_GETFL) };
+ if original_flags < 0 {
+ return Err(io::Error::last_os_error());
+ }
+ if unsafe {
+ libc::fcntl(
+ output.as_raw_fd(),
+ libc::F_SETFL,
+ original_flags | libc::O_NONBLOCK,
+ )
+ } < 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(Self {
+ output,
+ original_flags,
+ timeout,
+ deadline: None,
+ })
+ }
+
+ fn attempt<T>(&mut self, mut operation: impl FnMut(&mut W) -> io::Result<T>) -> io::Result<T> {
+ let deadline = *self
+ .deadline
+ .get_or_insert_with(|| Instant::now() + self.timeout);
+ loop {
+ if Instant::now() >= deadline {
+ return Err(io::ErrorKind::TimedOut.into());
+ }
+ match operation(&mut self.output) {
+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
+ super::input::wait_ready(self.output.as_raw_fd(), libc::POLLOUT, deadline)?;
+ }
+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
+ result => return result,
+ }
+ }
+ }
+}
+
+impl<W: Write + AsRawFd> Write for BoundedWriter<W> {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ self.attempt(|output| output.write(bytes))
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.attempt(Write::flush)?;
+ self.deadline = None;
+ Ok(())
+ }
+}
+
+impl<W: Write + AsRawFd> Drop for BoundedWriter<W> {
+ fn drop(&mut self) {
+ unsafe { libc::fcntl(self.output.as_raw_fd(), libc::F_SETFL, self.original_flags) };
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Read;
+ use std::os::unix::net::UnixStream;
+
+ #[test]
+ fn output_deadline_stops_dispatch_after_one_command() {
+ let (sender, _unread_receiver) = UnixStream::pair().unwrap();
+ let writer = BoundedWriter::new(sender, Duration::from_millis(20)).unwrap();
+ let mut calls = 0;
+ let error = super::super::serve(io::Cursor::new(b"[]\n[]\n"), writer, |_| {
+ calls += 1;
+ agent_desktop_core::output::Response::ok(
+ "snapshot",
+ serde_json::json!({
+ "tree": "x".repeat(4 * 1024 * 1024),
+ }),
+ )
+ })
+ .unwrap_err();
+ assert!(matches!(error, agent_desktop_core::AppError::Io(error)
+ if error.kind() == io::ErrorKind::TimedOut));
+ assert_eq!(calls, 1);
+ }
+
+ #[test]
+ fn complete_frames_reset_the_budget_and_restore_nonblocking_mode() {
+ for initially_nonblocking in [false, true] {
+ let (sender, mut receiver) = UnixStream::pair().unwrap();
+ sender.set_nonblocking(initially_nonblocking).unwrap();
+ {
+ let mut writer =
+ BoundedWriter::new(sender.try_clone().unwrap(), Duration::from_secs(60))
+ .unwrap();
+ let flags = unsafe { libc::fcntl(sender.as_raw_fd(), libc::F_GETFL) };
+ assert!(flags >= 0);
+ assert_ne!(flags & libc::O_NONBLOCK, 0);
+ writer.write_all(b"one\n").unwrap();
+ assert!(writer.deadline.is_some());
+ writer.flush().unwrap();
+ assert!(writer.deadline.is_none());
+ writer.write_all(b"two\n").unwrap();
+ writer.flush().unwrap();
+ }
+ let flags = unsafe { libc::fcntl(sender.as_raw_fd(), libc::F_GETFL) };
+ assert!(flags >= 0);
+ assert_eq!(flags & libc::O_NONBLOCK != 0, initially_nonblocking);
+ let mut bytes = [0; 8];
+ receiver.read_exact(&mut bytes).unwrap();
+ assert_eq!(&bytes, b"one\ntwo\n");
+ }
+ }
+}
diff --git a/src/command_host_request.rs b/src/command_host_request.rs
new file mode 100644
index 000000000..72100cf79
--- /dev/null
+++ b/src/command_host_request.rs
@@ -0,0 +1,81 @@
+use agent_desktop_core::{AppError, output::Response};
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub(super) struct HostRequest {
+ pub identity: String,
+ pub args: Vec<String>,
+ pub directory: PathBuf,
+ pub agent_id: Option<String>,
+ pub expires_ns: u64,
+}
+
+pub(super) fn execute(bytes: &[u8], identity: &str, session: Option<&str>) -> Response {
+ match prepare(bytes, identity, session) {
+ Ok((cli, command, deadline)) => crate::response(
+ command.name(),
+ crate::execute_with_deadline(cli, command, Some(deadline)),
+ ),
+ Err(error) => crate::response("unknown", Err(crate::pre_dispatch_error(error))),
+ }
+}
+
+fn prepare(
+ bytes: &[u8],
+ identity: &str,
+ session: Option<&str>,
+) -> Result<(crate::Cli, crate::Commands, agent_desktop_core::Deadline), AppError> {
+ let request: HostRequest = serde_json::from_slice(bytes)
+ .map_err(|_| AppError::invalid_input("Invalid command host request envelope"))?;
+ if request.identity != identity {
+ return Err(AppError::invalid_input(
+ "Command host identity does not match the caller",
+ ));
+ }
+ if !request.directory.is_absolute() {
+ return Err(AppError::invalid_input(
+ "Command host working directory must be absolute",
+ ));
+ }
+ let (mut cli, command) = super::parse_request(&serde_json::to_vec(&request.args)?, session)?;
+ if cli.identity.agent_id.is_none() {
+ cli.identity.agent_id = request.agent_id;
+ }
+ let deadline =
+ agent_desktop_core::Deadline::from_duration(super::budget::remaining(request.expires_ns)?)?;
+ std::env::set_current_dir(&request.directory)?;
+ Ok((cli, command, deadline))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn wrong_identity_or_namespace_never_changes_the_working_directory() {
+ let before = std::env::current_dir().unwrap();
+ for (identity, args) in [
+ ("another executable", vec!["version"]),
+ ("owner", vec!["--session", "other", "version"]),
+ ] {
+ let bytes = serde_json::to_vec(&HostRequest {
+ identity: identity.into(),
+ args: args.into_iter().map(str::to_owned).collect(),
+ directory: PathBuf::from("/"),
+ agent_id: None,
+ expires_ns: u64::MAX,
+ })
+ .unwrap();
+ let response = execute(&bytes, "owner", Some("mine"));
+ let response = serde_json::to_value(response).unwrap();
+ assert_eq!(response["ok"], false);
+ assert_eq!(
+ response["error"]["disposition"]["delivery"],
+ "not_delivered"
+ );
+ assert_eq!(std::env::current_dir().unwrap(), before);
+ }
+ }
+}
diff --git a/src/command_host_socket.rs b/src/command_host_socket.rs
new file mode 100644
index 000000000..3aa3ccdd8
--- /dev/null
+++ b/src/command_host_socket.rs
@@ -0,0 +1,107 @@
+use agent_desktop_core::{AppError, output::Response};
+use std::io::{self, BufReader, BufWriter};
+use std::os::fd::AsRawFd;
+use std::os::unix::fs::PermissionsExt;
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::Path;
+use std::time::Instant;
+
+pub(super) fn run(path: &Path, mut execute: impl FnMut(&[u8]) -> Response) -> Result<(), AppError> {
+ validate_parent(path)?;
+ let _owner = agent_desktop_core::FileLock::acquire(
+ &path.with_extension("owner.lock"),
+ agent_desktop_core::Deadline::after(1000)?,
+ "command host ownership",
+ )?;
+ if super::endpoint::validate_socket(path)? {
+ std::fs::remove_file(path)?;
+ }
+ let listener = UnixListener::bind(path)?;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
+ listener.set_nonblocking(true)?;
+ loop {
+ match super::input::wait_ready(
+ listener.as_raw_fd(),
+ libc::POLLIN,
+ Instant::now() + super::IDLE_TIMEOUT,
+ ) {
+ Err(error) if error.kind() == io::ErrorKind::TimedOut => return Ok(()),
+ result => result?,
+ }
+ let stream = match listener.accept() {
+ Ok((stream, _)) => stream,
+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => continue,
+ Err(error) => return Err(error.into()),
+ };
+ if let Err(error) = serve_connection(stream, &mut execute) {
+ tracing::warn!(%error, "command host connection ended without a complete reply");
+ }
+ }
+}
+
+fn validate_parent(path: &Path) -> Result<(), AppError> {
+ let parent = path
+ .parent()
+ .filter(|_| path.is_absolute())
+ .ok_or_else(|| AppError::invalid_input("Command host socket requires an absolute path"))?;
+ super::endpoint::validate_directory(parent)
+}
+
+fn serve_connection(
+ stream: UnixStream,
+ execute: impl FnMut(&[u8]) -> Response,
+) -> Result<(), AppError> {
+ let mut uid = 0;
+ let mut gid = 0;
+ if unsafe { libc::getpeereid(stream.as_raw_fd(), &mut uid, &mut gid) } != 0 {
+ return Err(io::Error::last_os_error().into());
+ }
+ if uid != unsafe { libc::geteuid() } {
+ return Err(AppError::invalid_input(
+ "Command host peer has a different owner",
+ ));
+ }
+ let mut input = BufReader::new(stream.try_clone()?);
+ let mut consumed = false;
+ super::serve_frames(
+ || {
+ if consumed {
+ return Ok(Vec::new());
+ }
+ consumed = true;
+ super::input::read_frame(
+ &mut input,
+ super::MAX_REQUEST_BYTES as usize,
+ super::IO_TIMEOUT,
+ super::IO_TIMEOUT,
+ )
+ },
+ BufWriter::new(super::output::BoundedWriter::new(
+ stream,
+ super::IO_TIMEOUT,
+ )?),
+ execute,
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{Read, Write};
+
+ #[test]
+ fn each_connection_dispatches_only_one_request() {
+ let (server, mut client) = UnixStream::pair().unwrap();
+ client.write_all(b"[]\n[]\n").unwrap();
+ let mut calls = 0;
+ serve_connection(server, |_| {
+ calls += 1;
+ Response::ok("version", serde_json::json!({}))
+ })
+ .unwrap();
+ let mut bytes = Vec::new();
+ client.read_to_end(&mut bytes).unwrap();
+ assert_eq!(calls, 1);
+ assert_eq!(bytes.iter().filter(|byte| **byte == b'\n').count(), 1);
+ }
+}
diff --git a/src/dispatch/session.rs b/src/dispatch/session.rs
index 546aa3003..f463674d7 100644
--- a/src/dispatch/session.rs
+++ b/src/dispatch/session.rs
@@ -27,6 +27,11 @@ pub(crate) fn dispatch(
}
SessionAction::End(e) => {
let id = resolve_end_session_id(e.id, context.session_id())?;
+ if context.session_namespace_is_pinned() && Some(id.as_str()) != context.session_id() {
+ return Err(AppError::invalid_input(
+ "A command host cannot end a foreign session",
+ ));
+ }
let value = session::execute(session::SessionAction::End { id: id.clone() })?;
adapter
.update_cursor_overlay(&CursorOverlayControl::disable(id))
@@ -34,6 +39,9 @@ pub(crate) fn dispatch(
Ok(value)
}
SessionAction::List => session::execute(session::SessionAction::List),
+ SessionAction::Gc(_) if context.session_namespace_is_pinned() => Err(
+ AppError::invalid_input("A command host cannot run global session garbage collection"),
+ ),
SessionAction::Gc(g) => session::execute(session::SessionAction::Gc {
older_than_secs: g.older_than,
ended_only: g.ended,
diff --git a/src/dispatch/session_tests.rs b/src/dispatch/session_tests.rs
index 9338c12e9..1b692ec66 100644
--- a/src/dispatch/session_tests.rs
+++ b/src/dispatch/session_tests.rs
@@ -1,6 +1,7 @@
use super::resolve_end_session_id;
-use crate::cli_args::session::{SessionAction, SessionArgs, SessionEndArgs};
+use crate::cli_args::session::{SessionAction, SessionArgs, SessionEndArgs, SessionGcArgs};
use crate::dispatch::test_support::{FailingOverlayAdapter, HomeGuard};
+use crate::test_noop_ops::NoopAdapter;
use agent_desktop_core::context::CommandContext;
use agent_desktop_core::session::{ArtifactsMode, SessionTraceMode, StartSessionOptions};
@@ -63,3 +64,67 @@ fn session_end_reports_uncertain_when_overlay_teardown_fails_after_persisting()
assert!(ended.ended_at.is_some());
assert!(home.path().join("sessions").join(manifest.id).is_dir());
}
+
+#[test]
+fn a_pinned_namespace_rejects_foreign_session_end_and_global_gc() {
+ let context = CommandContext::default().with_pinned_session_namespace();
+ let foreign_end = super::dispatch(
+ SessionArgs {
+ action: SessionAction::End(SessionEndArgs {
+ id: Some("other".into()),
+ }),
+ },
+ &NoopAdapter,
+ &context,
+ )
+ .expect_err("ending a foreign session must be rejected");
+ assert_eq!(foreign_end.code(), "INVALID_ARGS");
+ assert!(
+ foreign_end
+ .to_string()
+ .contains("cannot end a foreign session")
+ );
+
+ let global_gc = super::dispatch(
+ SessionArgs {
+ action: SessionAction::Gc(SessionGcArgs {
+ older_than: None,
+ ended: false,
+ }),
+ },
+ &NoopAdapter,
+ &context,
+ )
+ .expect_err("global gc must be rejected in a pinned namespace");
+ assert_eq!(global_gc.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn a_pinned_namespace_still_allows_ending_its_own_session() {
+ let _home = HomeGuard::new();
+ let manifest = agent_desktop_core::session::start_session(StartSessionOptions {
+ trace: SessionTraceMode::Off,
+ artifacts: ArtifactsMode::Events,
+ name: None,
+ })
+ .unwrap();
+ let context = CommandContext::new(Some(manifest.id.clone()), None, false)
+ .unwrap()
+ .with_pinned_session_namespace();
+ let result = super::dispatch(
+ SessionArgs {
+ action: SessionAction::End(SessionEndArgs {
+ id: Some(manifest.id.clone()),
+ }),
+ },
+ &NoopAdapter,
+ &context,
+ );
+ if let Err(error) = &result {
+ assert!(!error.to_string().contains("foreign session"));
+ }
+ let ended = agent_desktop_core::session::read_manifest(&manifest.id)
+ .unwrap()
+ .expect("manifest remains readable");
+ assert!(ended.ended_at.is_some());
+}
diff --git a/src/main.rs b/src/main.rs
index 31cb15211..79f34f4fa 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -3,6 +3,8 @@
mod batch;
mod cli;
mod cli_args;
+#[cfg(target_os = "macos")]
+mod command_host;
mod command_policy;
mod diagnostic;
mod dispatch;
@@ -42,6 +44,15 @@ fn main() -> ExitCode {
if let Some(exit_code) = run_permission_prompt_helper() {
return exit_code;
}
+ #[cfg(target_os = "macos")]
+ if command_host::is_host_process() {
+ init_tracing(false);
+ return match command_host::run() {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(AppError::Io(error)) => report_output_failure(error),
+ Err(error) => finish("host", Err(error)),
+ };
+ }
run()
}
@@ -100,20 +111,38 @@ fn run() -> ExitCode {
};
let cmd_name = cmd.name();
-
- if let Err(err) = cli.visual_debug.validate(&cmd) {
- return finish(cmd_name, Err(err));
+ #[cfg(target_os = "macos")]
+ if std::env::var("AGENT_DESKTOP_INTERNAL_HOST_CLIENT").as_deref() == Ok("1") {
+ return match command_host::forward(&cli, &cmd) {
+ Ok(response) => match emit_response(&response) {
+ Err(error) => report_output_failure(error),
+ Ok(()) if response["ok"] == true => ExitCode::SUCCESS,
+ Ok(()) => ExitCode::FAILURE,
+ },
+ Err(error) => finish(cmd_name, Err(error)),
+ };
}
+ finish(cmd_name, execute(cli, cmd))
+}
- if let Err(err) = agent_desktop_core::validate_state_root_env() {
- return finish(cmd_name, Err(pre_dispatch_error(err)));
- }
+fn execute(cli: Cli, cmd: Commands) -> Result<serde_json::Value, AppError> {
+ execute_with_deadline(cli, cmd, None)
+}
+fn execute_with_deadline(
+ cli: Cli,
+ cmd: Commands,
+ deadline: Option<agent_desktop_core::Deadline>,
+) -> Result<serde_json::Value, AppError> {
+ if let Some(deadline) = deadline.filter(|deadline| deadline.is_expired()) {
+ return Err(pre_dispatch_error(deadline.timeout_error().into()));
+ }
+ cli.visual_debug.validate(&cmd)?;
+ agent_desktop_core::validate_state_root_env().map_err(pre_dispatch_error)?;
match cmd {
- Commands::Version => finish(
- cmd_name,
- agent_desktop_core::commands::version::execute().map_err(pre_dispatch_error),
- ),
+ Commands::Version => {
+ agent_desktop_core::commands::version::execute().map_err(pre_dispatch_error)
+ }
Commands::Skills(a) => {
let result = match a.action.unwrap_or(SkillsAction::List) {
SkillsAction::List => agent_desktop_core::commands::skills::list(),
@@ -126,45 +155,38 @@ fn run() -> ExitCode {
},
),
};
- finish(cmd_name, result.map_err(pre_dispatch_error))
+ result.map_err(pre_dispatch_error)
}
cmd => {
- let wait_selector = match build_wait_selector(&cli) {
- Ok(wait_selector) => wait_selector,
- Err(error) => return finish(cmd_name, Err(error)),
- };
- let session_id = match resolve_active_session(
+ let wait_selector = build_wait_selector(&cli)?;
+ let session_id = resolve_active_session(
cli.identity.session.as_deref(),
std::env::var("AGENT_DESKTOP_SESSION").ok().as_deref(),
- ) {
- Ok(session_id) => session_id,
- Err(err) => {
- return finish(cmd_name, Err(pre_dispatch_error(err)));
- }
- };
- let context = match CommandContext::new(session_id, cli.trace, cli.trace_strict) {
- Ok(context) => context
- .with_headed(cli.interaction.headed)
- .with_wait_selector(wait_selector.clone()),
- Err(err) => {
- return finish(cmd_name, Err(pre_dispatch_error(err)));
- }
- };
+ )
+ .map_err(pre_dispatch_error)?;
+ let context = CommandContext::new(session_id, cli.trace, cli.trace_strict)
+ .map_err(pre_dispatch_error)?
+ .with_headed(cli.interaction.headed)
+ .with_wait_selector(wait_selector.clone());
let agent_id = cli
.identity
.agent_id
.clone()
.or_else(|| std::env::var("AGENT_DESKTOP_AGENT_ID").ok());
- let context = match context.with_agent_id(agent_id) {
- Ok(context) => context,
- Err(err) => return finish(cmd_name, Err(pre_dispatch_error(err))),
- };
+ let mut context = context
+ .with_agent_id(agent_id)
+ .map_err(pre_dispatch_error)?;
+ #[cfg(target_os = "macos")]
+ if command_host::is_host_process() {
+ context = context.with_pinned_session_namespace();
+ }
+ if let Some(deadline) = deadline {
+ context = context.with_inherited_deadline(deadline);
+ }
if let Some(wait) = wait_selector.as_ref() {
- if let Err(err) = validate_wait_for_command(&cmd, wait) {
- return finish(cmd_name, Err(err));
- }
+ validate_wait_for_command(&cmd, wait)?;
}
- run_with_adapter(cmd, cmd_name, &context, &cli.visual_debug)
+ execute_with_adapter(cmd, &context, &cli.visual_debug, deadline)
}
}
}
@@ -211,58 +233,55 @@ fn validate_wait_for_command(cmd: &Commands, wait: &WaitSelector) -> Result<(),
Ok(())
}
-fn run_with_adapter(
+fn execute_with_adapter(
mut cmd: Commands,
- cmd_name: &str,
context: &CommandContext,
debug: &visual_debug::options::DebugOptions,
-) -> ExitCode {
+ deadline: Option<agent_desktop_core::Deadline>,
+) -> Result<serde_json::Value, AppError> {
let adapter = build_adapter();
let adapter: &dyn agent_desktop_core::PlatformAdapter = &adapter;
let report = if command_policy::requires_permission_report(&cmd) {
- match agent_desktop_core::Deadline::standard()
+ match deadline
+ .map_or_else(agent_desktop_core::Deadline::standard, Ok)
.map_err(AppError::from)
.and_then(|deadline| adapter.permission_report(deadline).map_err(AppError::from))
{
Ok(report) => report,
- Err(err) => return finish(cmd_name, Err(pre_dispatch_error(err))),
+ Err(err) => return Err(pre_dispatch_error(err)),
}
} else {
agent_desktop_core::PermissionReport::default()
};
- if let Err(err) = command_policy::preflight(&cmd, &report) {
- return finish(cmd_name, Err(err));
- }
- if let Err(err) = command_policy::preflight_context(&cmd, context) {
- return finish(cmd_name, Err(err));
- }
+ command_policy::preflight(&cmd, &report)?;
+ command_policy::preflight_context(&cmd, context)?;
if debug.debug && report.screen_recording_denied() {
- return finish(
- cmd_name,
- Err(pre_dispatch_error(
- AdapterError::new(
- ErrorCode::PermDenied,
- "Visual debug requires Screen Recording permission",
- )
- .with_suggestion(
- report
- .screen_recording_suggestion()
- .unwrap_or("Grant Screen Recording permission and retry"),
- )
- .into(),
- )),
- );
+ return Err(pre_dispatch_error(
+ AdapterError::new(
+ ErrorCode::PermDenied,
+ "Visual debug requires Screen Recording permission",
+ )
+ .with_suggestion(
+ report
+ .screen_recording_suggestion()
+ .unwrap_or("Grant Screen Recording permission and retry"),
+ )
+ .into(),
+ ));
}
let capture = match visual_debug::DebugCapture::prepare(&mut cmd, debug, adapter, context) {
Ok(capture) => capture,
- Err(error) => return finish(cmd_name, Err(pre_dispatch_error(error))),
+ Err(error) => return Err(pre_dispatch_error(error)),
};
+ if let Some(deadline) = deadline.filter(|deadline| deadline.is_expired()) {
+ return Err(pre_dispatch_error(deadline.timeout_error().into()));
+ }
let mut result = dispatch::dispatch(cmd, adapter, &report, context);
if let Some(capture) = capture {
capture.finish(&mut result, adapter, context);
}
- finish(cmd_name, result)
+ result
}
fn pre_dispatch_error(error: AppError) -> AppError {
@@ -278,22 +297,21 @@ fn pre_dispatch_error(error: AppError) -> AppError {
}
fn finish(cmd_name: &str, result: Result<serde_json::Value, AppError>) -> ExitCode {
+ let response = response(cmd_name, result);
+ if let Err(write_err) = emit_response(&response) {
+ return report_output_failure(write_err);
+ }
+ if response.ok {
+ ExitCode::SUCCESS
+ } else {
+ ExitCode::FAILURE
+ }
+}
+
+fn response(cmd_name: &str, result: Result<serde_json::Value, AppError>) -> Response {
match result {
- Ok(data) => {
- if let Err(write_err) = emit_response(&Response::ok(cmd_name, data)) {
- return report_output_failure(write_err);
- }
- ExitCode::SUCCESS
- }
- Err(e) => {
- if let Err(write_err) = emit_response(&Response::err(
- cmd_name,
- agent_desktop_core::ErrorPayload::from_app_error(&e),
- )) {
- return report_output_failure(write_err);
- }
- ExitCode::FAILURE
- }
+ Ok(data) => Response::ok(cmd_name, data),
+ Err(error) => Response::err(cmd_name, ErrorPayload::from_app_error(&error)),
}
}
@@ -302,7 +320,7 @@ fn report_output_failure(write_err: std::io::Error) -> ExitCode {
ExitCode::FAILURE
}
-fn emit_response(response: &Response) -> std::io::Result<()> {
+fn emit_response(response: &impl serde::Serialize) -> std::io::Result<()> {
let stdout = std::io::stdout();
let mut writer = BufWriter::new(stdout.lock());
serde_json::to_writer(&mut writer, response).map_err(std::io::Error::other)?;
diff --git a/src/tests/command_host_process.rs b/src/tests/command_host_process.rs
new file mode 100644
index 000000000..02896aa29
--- /dev/null
+++ b/src/tests/command_host_process.rs
@@ -0,0 +1,296 @@
+#![cfg(target_os = "macos")]
+
+use std::io::{Read, Write};
+use std::os::fd::{AsRawFd, OwnedFd};
+use std::os::unix::net::UnixStream;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+fn host_identity(directory: &std::path::Path) -> String {
+ use std::os::unix::fs::MetadataExt;
+ let executable = std::path::Path::new(env!("CARGO_BIN_EXE_agent-desktop"));
+ let metadata = std::fs::metadata(executable).unwrap();
+ serde_json::json!({
+ "protocol": 1,
+ "root": directory,
+ "session": null,
+ "executable": executable,
+ "revision": [metadata.dev(), metadata.ino(), metadata.size()],
+ "modified": [metadata.mtime(), metadata.mtime_nsec()],
+ "helper": std::env::var_os("AGENT_DESKTOP_MACOS_HELPER_PATH"),
+ })
+ .to_string()
+}
+
+fn future_deadline() -> u64 {
+ let mut time = libc::timespec {
+ tv_sec: 0,
+ tv_nsec: 0,
+ };
+ assert_eq!(
+ unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut time) },
+ 0
+ );
+ time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64 + 60_000_000_000
+}
+
+struct HostProcess(std::process::Child);
+
+impl Drop for HostProcess {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+}
+
+#[test]
+fn socket_host_survives_a_bad_client_and_serves_separate_invocations() {
+ use std::os::unix::fs::DirBuilderExt;
+ let directory = std::path::Path::new("/tmp").join(format!(
+ "ad-host-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::DirBuilder::new()
+ .mode(0o700)
+ .create(&directory)
+ .unwrap();
+ let socket = directory.join("h.sock");
+ let mut child = HostProcess(
+ Command::new(env!("CARGO_BIN_EXE_agent-desktop"))
+ .env("AGENT_DESKTOP_INTERNAL_COMMAND_HOST", "1")
+ .env("AGENT_DESKTOP_INTERNAL_HOST_SOCKET", &socket)
+ .env_remove("AGENT_DESKTOP_SESSION")
+ .env("AGENT_DESKTOP_HOME", &directory)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap(),
+ );
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ if UnixStream::connect(&socket).is_ok() {
+ break;
+ }
+ if child.0.try_wait().unwrap().is_some() {
+ let mut diagnostic = String::new();
+ child
+ .0
+ .stdout
+ .take()
+ .unwrap()
+ .read_to_string(&mut diagnostic)
+ .unwrap();
+ child
+ .0
+ .stderr
+ .take()
+ .unwrap()
+ .read_to_string(&mut diagnostic)
+ .unwrap();
+ panic!("host exited before binding: {diagnostic}");
+ }
+ assert!(Instant::now() < deadline, "host did not bind");
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ for (request, expected) in [("[\n", false), ("[\"version\"]\n[\"version\"]\n", false)] {
+ let mut client = UnixStream::connect(&socket).unwrap();
+ client
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .unwrap();
+ client.write_all(request.as_bytes()).unwrap();
+ let mut reply = Vec::new();
+ client.read_to_end(&mut reply).unwrap();
+ let envelope: serde_json::Value = serde_json::from_slice(&reply).unwrap();
+ assert_eq!(envelope["ok"], expected);
+ assert_eq!(reply.iter().filter(|byte| **byte == b'\n').count(), 1);
+ }
+ let identity = host_identity(&directory);
+ let mut expired = UnixStream::connect(&socket).unwrap();
+ expired
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .unwrap();
+ writeln!(
+ expired,
+ "{}",
+ serde_json::json!({
+ "identity": identity,
+ "args": ["session", "start"],
+ "directory": directory,
+ "agent_id": null,
+ "expires_ns": 0,
+ })
+ )
+ .unwrap();
+ let mut rejected = String::new();
+ expired.read_to_string(&mut rejected).unwrap();
+ let rejected: serde_json::Value = serde_json::from_str(&rejected).unwrap();
+ assert_eq!(rejected["error"]["code"], "TIMEOUT");
+ assert_eq!(
+ rejected["error"]["disposition"]["delivery"],
+ "not_delivered"
+ );
+ assert!(
+ !directory.join("sessions").exists(),
+ "expired request must not create a session"
+ );
+ for _ in 0..2 {
+ let mut client = UnixStream::connect(&socket).unwrap();
+ client
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .unwrap();
+ let request = serde_json::json!({
+ "identity": identity,
+ "args": ["version"],
+ "directory": directory,
+ "agent_id": null,
+ "expires_ns": future_deadline(),
+ });
+ writeln!(client, "{request}").unwrap();
+ let mut reply = String::new();
+ client.read_to_string(&mut reply).unwrap();
+ let reply: serde_json::Value = serde_json::from_str(&reply).unwrap();
+ assert_eq!(reply["ok"], true, "{reply}");
+ }
+ assert!(child.0.try_wait().unwrap().is_none());
+}
+
+#[test]
+fn experimental_cli_starts_and_reuses_its_host() {
+ use std::hash::{Hash, Hasher};
+ let directory = std::env::temp_dir().join(format!("ad-host-client-{}", std::process::id()));
+ let mut hash = std::collections::hash_map::DefaultHasher::new();
+ host_identity(&directory).hash(&mut hash);
+ let socket = std::env::temp_dir().join(format!(
+ "agent-desktop-host-{}/{:016x}.sock",
+ unsafe { libc::geteuid() },
+ hash.finish(),
+ ));
+ let invoke = || {
+ Command::new(env!("CARGO_BIN_EXE_agent-desktop"))
+ .arg("version")
+ .env("AGENT_DESKTOP_INTERNAL_HOST_CLIENT", "1")
+ .env_remove("AGENT_DESKTOP_INTERNAL_COMMAND_HOST")
+ .env_remove("AGENT_DESKTOP_SESSION")
+ .env("AGENT_DESKTOP_HOME", &directory)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap()
+ };
+ let first = invoke();
+ let concurrent = invoke();
+ let first = first.wait_with_output().unwrap();
+ let concurrent = concurrent.wait_with_output().unwrap();
+ let stream = UnixStream::connect(&socket).unwrap();
+ let mut pid: libc::pid_t = 0;
+ let mut size = std::mem::size_of_val(&pid) as libc::socklen_t;
+ assert_eq!(
+ unsafe {
+ libc::getsockopt(
+ stream.as_raw_fd(),
+ libc::SOL_LOCAL,
+ libc::LOCAL_PEERPID,
+ (&mut pid as *mut libc::pid_t).cast(),
+ &mut size,
+ )
+ },
+ 0
+ );
+ drop(stream);
+ let second = invoke().wait_with_output().unwrap();
+ let reused = UnixStream::connect(&socket).unwrap();
+ let mut second_pid: libc::pid_t = 0;
+ let lookup = unsafe {
+ libc::getsockopt(
+ reused.as_raw_fd(),
+ libc::SOL_LOCAL,
+ libc::LOCAL_PEERPID,
+ (&mut second_pid as *mut libc::pid_t).cast(),
+ &mut size,
+ )
+ };
+ drop(reused);
+ assert!(pid > 0);
+ unsafe { libc::kill(pid, libc::SIGTERM) };
+ assert_eq!(lookup, 0);
+ assert_eq!(
+ second_pid, pid,
+ "separate invocations must reuse the native owner"
+ );
+ for result in [first, concurrent, second] {
+ let reply: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap();
+ assert!(result.status.success(), "{reply}");
+ assert_eq!(reply["ok"], true);
+ assert_eq!(reply["command"], "version");
+ }
+}
+
+#[test]
+fn unread_reply_exits_without_shutdown_flush_or_next_dispatch() {
+ let (sender, mut receiver) = UnixStream::pair().unwrap();
+ let size: libc::c_int = 4096;
+ assert_eq!(
+ unsafe {
+ libc::setsockopt(
+ sender.as_raw_fd(),
+ libc::SOL_SOCKET,
+ libc::SO_SNDBUF,
+ (&size as *const libc::c_int).cast(),
+ std::mem::size_of_val(&size) as libc::socklen_t,
+ )
+ },
+ 0
+ );
+ let output: OwnedFd = sender.into();
+ let mut child = Command::new(env!("CARGO_BIN_EXE_agent-desktop"))
+ .env("AGENT_DESKTOP_INTERNAL_COMMAND_HOST", "1")
+ .env_remove("AGENT_DESKTOP_SESSION")
+ .env(
+ "AGENT_DESKTOP_HOME",
+ std::env::temp_dir().join(format!("ad-host-output-{}", std::process::id())),
+ )
+ .stdin(Stdio::piped())
+ .stdout(Stdio::from(output))
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap();
+ child
+ .stdin
+ .as_mut()
+ .unwrap()
+ .write_all(b"[\"skills\",\"get\",\"desktop\",\"--full\"]\n[\"version\"]\n")
+ .unwrap();
+ let deadline = Instant::now() + Duration::from_secs(20);
+ let status = loop {
+ if let Some(status) = child.try_wait().unwrap() {
+ break status;
+ }
+ if Instant::now() >= deadline {
+ child.kill().unwrap();
+ child.wait().unwrap();
+ panic!("host failed to exit while its output remained unread");
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ };
+ let mut diagnostics = String::new();
+ child
+ .stderr
+ .take()
+ .unwrap()
+ .read_to_string(&mut diagnostics)
+ .unwrap();
+ assert_eq!(status.code(), Some(1), "{diagnostics}");
+ assert!(diagnostics.contains("timed out"), "{diagnostics}");
+ let mut bytes = Vec::new();
+ receiver.read_to_end(&mut bytes).unwrap();
+ assert!(bytes.starts_with(b"{\"version\":"));
+ assert!(
+ !bytes.contains(&b'\n'),
+ "must not finish or dispatch the next reply"
+ );
+}
diff --git a/src/tests/conformance.rs b/src/tests/conformance.rs
index 15af1404b..ee4b27452 100644
--- a/src/tests/conformance.rs
+++ b/src/tests/conformance.rs
@@ -168,6 +168,7 @@ fn entry(bounds: Rect) -> RefEntry {
process_instance: Some("contract-process".into()),
},
identity: RefEntryIdentity {
+ retained_object: None,
role: "button".into(),
name: Some("OK".into()),
value: None,
diff --git a/tests/fixture-app/AgentDeskFixture.swift b/tests/fixture-app/AgentDeskFixture.swift
index ef9ed302f..2ee61c880 100644
--- a/tests/fixture-app/AgentDeskFixture.swift
+++ b/tests/fixture-app/AgentDeskFixture.swift
@@ -334,7 +334,13 @@ struct ContentView: View {
struct AgentDeskFixtureApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
- WindowGroup("AgentDesk Fixture") { ContentView() }
+ WindowGroup("AgentDesk Fixture") {
+ if ProcessInfo.processInfo.environment["AGENT_DESKTOP_FIXTURE_REF_CHURN"] == "1" {
+ RefChurnView()
+ } else {
+ ContentView()
+ }
+ }
.commands {
// Custom top menu so the harness can verify the app menu bar is
// enumerable via `snapshot --surface menubar`. (SwiftUI
diff --git a/tests/fixture-app/RefChurnView.swift b/tests/fixture-app/RefChurnView.swift
new file mode 100644
index 000000000..bb5260e14
--- /dev/null
+++ b/tests/fixture-app/RefChurnView.swift
@@ -0,0 +1,38 @@
+import SwiftUI
+
+struct RefChurnView: View {
+ @State private var filtered = false
+ @State private var alpha = "Alpha"
+ @State private var beta = "Beta"
+ @State private var stable = "Stable value"
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Button(filtered ? "Restore rows" : "Filter rows") {
+ filtered.toggle()
+ }
+ .accessibilityIdentifier("filter-rows")
+
+ VStack(alignment: .leading, spacing: 8) {
+ if !filtered {
+ TextField("", text: $alpha)
+ .accessibilityIdentifier("shared-title")
+ }
+ TextField("", text: $beta)
+ .accessibilityIdentifier("shared-title")
+ }
+ .frame(width: 300, height: 80, alignment: .topLeading)
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel("Changing collection")
+
+ TextField("Stable editor", text: $stable)
+ .accessibilityIdentifier("stable-editor")
+ .accessibilityLabel("Stable editor")
+ Text("Alpha stored: \(alpha)")
+ Text("Beta stored: \(beta)")
+ Text("Stable stored: \(stable)")
+ }
+ .padding(24)
+ .frame(width: 380, height: 300)
+ }
+}
diff --git a/tests/real-apps/README.md b/tests/real-apps/README.md
new file mode 100644
index 000000000..ec0c85a76
--- /dev/null
+++ b/tests/real-apps/README.md
@@ -0,0 +1,165 @@
+# Numbers model-facing reliability evaluation
+
+Use the public Agent Desktop CLI directly. The model must read the original JSON
+and select refs itself. Do not insert Python/jq tree extraction, a custom ref
+picker, raw AX mutations, or AppleScript into the evaluated interaction workflow.
+
+Follow [the native reliability plan](../../docs/plans/2026-09-19-native-reliability-evaluation-plan.md).
+The current trajectory and required outcomes are frozen in [acceptance v1](acceptance-v1.md).
+The earlier provisional numeric ratings are withdrawn; no measured overall score
+has been established.
+Numbers is the target. Fixture tests provide deterministic regressions, not proof
+of Numbers task completion.
+
+## Ownership and evidence
+
+Use an immutable release binary, an isolated absolute `AGENT_DESKTOP_HOME`, and
+an owned document named `AD Reliability.numbers`. Record binary/diff hashes,
+macOS/Numbers versions, seed contents, permissions and process/window identity.
+Never activate the app or touch another document. Preserve original command
+output; shell `tee` is acceptable, filtering responses for the model is not.
+
+Setup and independent verification are separate from task execution. Prepare
+Sheet 1 / Eval Grid with B2=`seed-target`, C2=`neighbor-guard`, B3=17, C3=25,
+eight rows and five columns. For the duplicate-table case, prepare Eval Other /
+Eval Grid with B2=`other-sheet-guard`. Native document scripting may prepare
+these seeds without activation, but cannot count as a completed CLI task.
+Wait for window readiness after asynchronous setup.
+
+## Model tasks
+
+1. Discover the grid through `list-windows`, `snapshot --window-id ... --skeleton
+ -i --compact`, and `snapshot --root ...`. Choose refs from those outputs.
+2. Select B2, discover the editor, replace its contents, and commit semantically.
+ Independently verify the exact cell and unchanged neighbor.
+3. Read the original cell ref after entering edit mode. Record automatic
+ recovery, stale refusal, or incorrect targeting separately.
+4. Switch sheets by ref. Compare `get --property states`, `get --property value`,
+ and `is --property checked` on the same ref with the actual active sheet.
+5. Change Number of rows from eight to nine and back using the original ref.
+ Compare CLI reads with independently queried document dimensions.
+6. Enter a formula, save, close, and reopen through supported semantic commands.
+ If an earlier step is blocked, report the dependent task uncompleted. Do not
+ fill or save through scripting and count it as Agent Desktop success.
+
+Retain every attempt, expected/actual effect, original output, latency and
+headless evidence. Distinguish task failure, safe refusal, native limitations,
+environmental interference and not-run cases. A later success does not erase a
+failure. Endpoint pointer equality alone is insufficient side-effect evidence.
+
+## Independent raw AX diagnosis
+
+`ax_probe.swift` is a diagnostic helper, not the model's driver. It reads native
+attributes/actions/settable flags through ApplicationServices without Agent
+Desktop internals. It requires an exact owned window title and process ID.
+
+Compile with `swiftc ax_probe.swift -o /tmp/ad-ax-probe`. Examples:
+
+```
+/tmp/ad-ax-probe PID 'AD Reliability.numbers' inspect 'seed-target'
+/tmp/ad-ax-probe PID 'AD Reliability.numbers' inspect editor
+```
+
+Reserve `press`, `select`, and `set` for separate raw AX trials on equivalent
+clean starting states. Never use them to rescue the CLI workflow or blindly
+repeat an uncertain action. Native success alone is not proof of effect.
+
+## Repeat sheet transitions without response rewriting
+
+Read `find --window-id ... --role radiobutton` yourself and choose the two
+sheet refs from its original response. With the owned document and correct
+state namespace, run:
+
+```
+bash tests/real-apps/numbers-sheets.sh /absolute/candidate w-123 @snapshot:e1 @snapshot:e2 5
+```
+
+Use actual qualified refs, not the placeholders above. Start with Eval Other
+active so the first click is a transition. The script reuses the same refs for
+ten transitions, prints and saves unchanged JSON, captures every transition,
+and waits for both selected and unselected values. Any command failure stops
+the run; a failed click gets a diagnostic screenshot but is never retried.
+It performs no setup, response parsing, app activation or physical input.
+
+Completion is not a passing score: inspect every `get`/`is` pair and screenshot,
+and independently verify active sheet and unchanged guard cells. Reset and
+rediscover refs between acceptance batches. Retain failed attempts. The runner
+does not verify continuous foreground/pointer stability or document persistence.
+Its failure-stop check is `python3 tests/real-apps/numbers_sheets_test.py`.
+
+## Parameterized replacement differential
+
+`replace_contract_fixture.m` and `replace_range_probe.swift` are separate raw AX
+diagnostics, not an Agent Desktop acceptance driver. Compile with:
+
+```
+clang -framework AppKit tests/real-apps/replace_contract_fixture.m -o /tmp/ad-replace-fixture
+swiftc -module-cache-path /tmp/ad-swift-cache tests/real-apps/replace_range_probe.swift -o /tmp/ad-replace-probe
+```
+
+Run `/tmp/ad-replace-fixture` for the custom receiver or add `--standard` for
+plain NSTextView. `--standard-focused` additionally assigns the text view as
+the window's internal first responder and logs input-context state without
+activating the app or making the window key. These modes create an owned
+background window and print their PID.
+In a separate process, use the printed PID:
+
+```
+/tmp/ad-replace-probe PID 'AD Reliability Parameter Contract' seed-target replacement-token
+```
+
+The probe requires the exact owned window and one AXTextArea with the expected
+seed value, checks advertised support, and refuses a foreground target. It
+dispatches once and exits 1 when AX fails or readback differs from the requested
+replacement. It does not retry, commit or prove continuous headless operation.
+Close only the printed fixture PID with `kill -TERM PID` after the test. A
+successful custom receiver proves parameter transport; it does not prove that
+AppKit's default receiver or Numbers can perform the operation in the background.
+
+This protocol does not claim that the planned repeated acceptance gate has run.
+
+## Nested scroll regression
+
+Compile `nested_scroll_fixture.m` with `clang -framework AppKit` and launch the
+resulting executable directly. It creates only an owned background window named
+AD Reliability Nested Scroll. Discover that window and the Clipped target ref
+through the public CLI. Capture a window screenshot before and after `scroll-to`
+on the discovered ref. Before, the button is outside its scroll viewport but
+inside its window; after, the button must actually be visible. Merely returning
+`verified: true` or reading window-relative offscreen state is not a valid oracle.
+The old implementation incorrectly returned a verified skipped step without
+moving anything. Record original command output and inspect both screenshots.
+Close only the fixture's printed PID with `kill -TERM PID` after the trial.
+
+## Additional Xcode coverage
+
+The second-app probe uses only `/tmp/ad-native-eval/AD Reliability.swift` in
+background Xcode. Discover Source Editor through skeleton/root, replace its
+value, insert text on the same ref, and verify screenshots plus exact disk
+contents. Closing by the original Close ref and reopening as separate setup
+checks persistence; do not count setup as CLI task completion. Preserve rejected
+old-window refs and native menu failures alongside successful editing.
+
+The raw AX helper can inspect controls by exact title or description and invoke
+`press` or `show-menu` on an owned AXMenuButton for separate diagnostic trials.
+It records foreground endpoints, not continuous monitoring. An uncertain native
+return never authorizes a fallback action or automatic replay.
+
+See [the Xcode evidence ledger](../../docs/solutions/runtime-errors/2026-09-19-xcode-headless-evaluation.md)
+for successful persistence, menu failures, and the stale-window classification gap.
+
+## Observe headless side effects during a trial
+
+Compile `headless_probe.swift` with `swiftc`, then run
+`headless-probe PID 60` in a separate terminal/process. Start evaluated commands
+only after its original JSON reports `event: ready`. It observes workspace
+activation notifications, session-wide input counters and pointer samples until
+the bounded duration expires. It performs no actions and records no key contents.
+`headless-probe --self-test` verifies counter arithmetic including rollover.
+
+Inspect its final JSON alongside action outputs. A target activation invalidates
+the headless claim. Other app activations and input increments are environmental
+activity with unknown attribution, not proof of either agent input or clean input
+isolation. Pointer sampling can miss a move-and-return between samples. Unknown
+foreground (`-1`), missing pointer samples or an exited target cannot pass a clean
+monitoring gate. This observer improves evidence but is not an automatic score.
diff --git a/tests/real-apps/acceptance-v1.md b/tests/real-apps/acceptance-v1.md
new file mode 100644
index 000000000..c5d45a9a5
--- /dev/null
+++ b/tests/real-apps/acceptance-v1.md
@@ -0,0 +1,106 @@
+# Native reliability acceptance v1
+
+Frozen task contract: 2026-09-20. Overall measured score: not established.
+User scope update: stop Numbers testing. N1-N8 below remain historical evidence,
+excluded from active qualification by explicit user instruction. Continue X1-X8,
+S1-S5, D1 and the negative cases; do not silently drop any of those requirements.
+The user-facing provisional baseline is 8/10. It is not a measured pass rate.
+Previous 6, 7.5 and 8 ratings were provisional judgments, not acceptance results.
+Do not promote historical probes into new-candidate acceptance passes.
+
+## Candidate and execution rules
+
+Starting candidate: `/tmp/ad-native-eval/window-context-candidate`, SHA-256
+`2a4e3e248893e44432494c8b7d2a6d027ff8a76cc3058c52f029592eecaa6500`.
+Branch: `codex/fix-chromium-ax-activation`. All work remains local.
+Each changed candidate gets a new immutable binary/hash and separate results.
+
+Use raw public CLI responses with model-selected qualified refs. Setup scripting
+and raw AX diagnostics stay separate. Only owned disposable documents/windows
+may be edited. The user-opened Xcode project is authorized for reversible
+navigation, filtering, drilling and scrolling; do not edit its source or build/run
+it. No focus stealing, physical input or clipboard-based insertion.
+Observe target activation throughout each action/settling interval, inspect
+same-window screenshots, and use independent document/file oracles.
+
+For each attempted task record: candidate hash, seed hash, app/OS versions,
+process/window/session identities, exact commands and raw responses, expected
+and actual effect, screenshot paths, independent readback, elapsed time, and
+headless evidence. Outcomes: pass, task_failed, unsupported, blocked_dependency,
+contaminated, not_run. No inferred pass from native success or exit zero alone.
+Failed mutations are never blindly retried. A rerun cannot erase an attempt.
+
+## Required task outcomes
+
+Numbers seed: Sheet 1 / Eval Grid, eight rows/five columns; B2=seed-target,
+C2=neighbor-guard, B3=17, C3=25. Eval Other / Eval Grid has B2=other-sheet-guard.
+Each text token includes the recorded batch/run number. Restore seed only between
+independent trials and record setup separately.
+
+| ID | Task | Required independent outcome |
+|---|---|---|
+| N1 | Cold-start list window, skeleton, drill to table/cell | Exact owned document, Sheet 1 and Eval Grid found; returned refs resolve |
+| N2 | Select B2 using a snapshot ref | Raw selected-cell row/column and table identify B2; C2 unchanged |
+| N3 | Enter edit mode, then reuse original cell ref | Same logical cell recovered; duplicate-table control is never chosen |
+| N4 | Replace B2 with a unique token; replace B3 with 19; commit semantically | Document model reads exact token and 19; C2 and C3 unchanged |
+| N5 | Set D3 to =B3+C3 and commit | Stored formula references B3/C3; calculated result is 44 after N4 |
+| N6 | Switch Sheet 1 → Eval Other → Sheet 1 with saved refs | Active sheet agrees with get/is; both same-named table guards unchanged |
+| N7 | Change row count 8 → 9 → 8 using original control ref | Document counts match each change; guard cells preserved |
+| N8 | Save, close and reopen edited Numbers document | N4 token, numeric value and N5 formula/result persist; no unrelated document touched |
+| X1 | Discover owned Xcode source editor | Correct file and editor ref; no other file selected |
+| X2 | Replace owned source text and insert one comment using same ref | Exact requested file bytes and screenshot; comment appears once; guard retained |
+| X3 | Save, close, reopen; query old editor ref | Edited bytes persist; old window ref cannot mutate reopened or unrelated windows |
+| X4 | Open, inspect, select and dismiss owned editor-options menu | Intended menu/item effect, inventory/snapshot agreement and no target activation |
+| X5 | Skeleton then drill navigator, editor, inspector and debug columns | Each returned root resolves to the expected region; sibling refs survive unrelated drills |
+| X6 | Exact find within each column, including negative cross-column queries | Same identity/value as drill/get; no results leak from another region |
+| X7 | Re-drill one column while retaining old child and sibling refs | Old child fails safely; new child resolves; untouched sibling still resolves |
+| X8 | Expand/collapse navigator and inspector; filter/clear; editor scroll round trip | Same-ref state agreement, visible intended effects, restored UI and no headless-policy violations |
+| S1 | SF Symbols skeleton → scope; first-match find → get/root | Same element identity and states across commands; honest partial-tree markers |
+| S2 | Scroll down/up and reuse original scroll/control refs | Visible content/scroll value changes in intended direction; original refs resolve |
+| S3 | Select Math → All using outline ref | Exact category selected and expected symbol collection visible |
+| S4 | Scroll-to a discovered offscreen item | Intended item becomes visible; no substitute match or focus stealing |
+| S5 | Open and close Weight menu semantically | Correct menu surface and dismissal, continuously monitored without activation |
+| D1 | Drag between two owned native reorder/drop targets | Exact source/destination effect through supported headless semantics |
+
+D1 has no proven headless-capable target/mechanism yet. It stays unsupported or
+not_run until discovery supplies one; do not silently remove it or count refusal
+as completion. Numbers cases are excluded from active qualification by the user update above.
+Dependent failures stay visible instead of substituting pre-filled saved data.
+
+## Mandatory negative cases
+
+Retain saved refs while removing/replacing the target, introducing a lookalike,
+closing/reopening its window and switching session namespaces. Verify no wrong
+target or cross-session lookup. Exercise delayed readiness, failed native reads,
+uncertain mutation returns and unchanged post-state with deterministic scripted
+adapter tests. Assert dispatch count and delivery/retry classification.
+CLI, batch and FFI must retain the same resolution and action contracts.
+
+## Ordered trajectory and gates
+
+1. Baseline: execute each task once on the frozen candidate; publish all outcomes.
+ Existing probes are supporting evidence, not a completed frozen baseline.
+2. Execute S1-S5 and X1-X8 on one frozen candidate, preserving every failure.
+ Investigate only blockers demonstrated by these tasks or mandatory negatives.
+3. Establish a supported semantic mechanism for D1 without physical input or
+ activation. If none is demonstrated, retain the unmet requirement explicitly.
+4. Complete the cross-app tasks. Resolve supported-action and
+ state inconsistencies at their existing shared boundary. Keep native limits
+ visible and investigate them separately from core/adapter defects.
+5. Repeatability: thirty consecutive valid runs per supported task across three
+ independent reset batches of ten. Preserve all failed/contaminated attempts.
+ A new build starts a new series; do not pool revisions into a passing series.
+6. Final qualification: all required outcomes and negative cases pass, full
+ workspace/format/lint/native gates pass, performance is reviewed on the exact
+ candidate, and another review checks the evidence and blast radius. No push
+ or release without the applicable user authorization.
+
+Report per-task successes/attempts and unmet coverage separately. Unsupported,
+blocked and unrun tasks cannot earn completion credit. The plan's weighted score
+is uncomputed until its denominators and observations exist. Any wrong-target
+write, duplicate effect, false verification or prohibited input/focus effect
+fails qualification regardless of the aggregate. No 9/10 or 10/10 from code
+volume, fixture counts, a few successful probes, or an incomplete denominator.
+
+Historical Numbers trials are retained in their evidence documents. Do not resume
+them or introduce another backend under the active scope without user direction.
diff --git a/tests/real-apps/ax_probe.swift b/tests/real-apps/ax_probe.swift
new file mode 100644
index 000000000..ed3ea47c1
--- /dev/null
+++ b/tests/real-apps/ax_probe.swift
@@ -0,0 +1,136 @@
+import AppKit
+import ApplicationServices
+
+func read(_ element: AXUIElement, _ attribute: String) -> (Int32, CFTypeRef?) {
+ var value: CFTypeRef?
+ let error = AXUIElementCopyAttributeValue(element, attribute as CFString, &value)
+ return (error.rawValue, value)
+}
+func text(_ element: AXUIElement, _ attribute: String) -> String {
+ let (_, value) = read(element, attribute)
+ return value.map { String(describing: $0) } ?? ""
+}
+func children(_ element: AXUIElement) -> [AXUIElement] {
+ read(element, "AXChildren").1 as? [AXUIElement] ?? []
+}
+func describe(_ element: AXUIElement) -> [String: Any] {
+ var result: [String: Any] = [:]
+ for key in ["AXIdentifier", "AXDOMIdentifier", "AXRole", "AXSubrole", "AXTitle", "AXDescription", "AXValue", "AXSelected", "AXFocused", "AXHidden", "AXExpanded", "AXPosition", "AXSize", "AXRowIndexRange", "AXColumnIndexRange"] {
+ let (error, value) = read(element, key)
+ result[key] = ["error": error, "value": value.map { String(describing: $0) } ?? ""]
+ }
+ var attributes: CFArray?
+ result["attributeNamesError"] = AXUIElementCopyAttributeNames(element, &attributes).rawValue
+ result["attributeNames"] = attributes as? [String] ?? []
+ var parameterized: CFArray?
+ result["parameterizedNamesError"] = AXUIElementCopyParameterizedAttributeNames(element, &parameterized).rawValue
+ result["parameterizedNames"] = parameterized as? [String] ?? []
+ var writable: [String: Any] = [:]
+ for attribute in attributes as? [String] ?? [] {
+ var flag = DarwinBoolean(false)
+ let error = AXUIElementIsAttributeSettable(element, attribute as CFString, &flag)
+ writable[attribute] = ["error": error.rawValue, "settable": flag.boolValue]
+ }
+ result["advertisedAttributeSetters"] = writable
+ var actions: CFArray?
+ result["actionsError"] = AXUIElementCopyActionNames(element, &actions).rawValue
+ result["actions"] = actions as? [String] ?? []
+ result["children"] = children(element).map {
+ ["role": text($0, "AXRole"), "title": text($0, "AXTitle"), "description": text($0, "AXDescription")]
+ }
+ var settable: [String: Any] = [:]
+ for key in ["AXValue", "AXSelectedText", "AXFocused", "AXSelectedCells"] {
+ var value = DarwinBoolean(false)
+ let error = AXUIElementIsAttributeSettable(element, key as CFString, &value)
+ settable[key] = ["error": error.rawValue, "value": value.boolValue]
+ }
+ result["settable"] = settable
+ result["selectedCells"] = (read(element, "AXSelectedCells").1 as? [AXUIElement] ?? []).map {
+ ["title": text($0, "AXTitle"), "description": text($0, "AXDescription")]
+ }
+ return result
+}
+func walk(_ element: AXUIElement, _ depth: Int, _ visit: (AXUIElement, Int) -> Void) {
+ guard depth < 25 else { return }
+ visit(element, depth)
+ for child in children(element) { walk(child, depth + 1, visit) }
+}
+let args = CommandLine.arguments
+if args.count < 4 { fatalError("usage: ax_probe PID OWNED_WINDOW_TITLE inspect|press|show-menu|select|set TARGET [VALUE]") }
+guard let pid = Int32(args[1]), args[2].hasPrefix("AD Reliability") else {
+ fatalError("requires owned evaluation window")
+}
+let app = AXUIElementCreateApplication(pid)
+AXUIElementSetMessagingTimeout(app, 3)
+let windowRead = read(app, "AXWindows")
+let windows = windowRead.1 as? [AXUIElement] ?? []
+let matches = windows.filter { text($0, "AXTitle") == args[2] }
+guard matches.count == 1 else {
+ let failure: [String: Any] = ["error": "owned_window_missing_or_ambiguous", "AXWindowsError": windowRead.0, "windows": windows.map { text($0, "AXTitle") }]
+ FileHandle.standardOutput.write(try JSONSerialization.data(withJSONObject: failure, options: [.sortedKeys]))
+ exit(1)
+}
+let window = matches[0]
+var nodes: [AXUIElement] = []
+walk(window, 0) { node, _ in nodes.append(node) }
+var result: [String: Any] = ["frontmostBefore": NSWorkspace.shared.frontmostApplication?.processIdentifier ?? -1]
+let focusedRead = read(app, "AXFocusedUIElement")
+result["focusedElementError"] = focusedRead.0
+if let value = focusedRead.1, CFGetTypeID(value) == AXUIElementGetTypeID() {
+ let focused = unsafeBitCast(value, to: AXUIElement.self)
+ result["focusedElement"] = describe(focused)
+ var ancestry: [[String: String]] = []
+ var current = focused
+ for _ in 0..<8 {
+ ancestry.append(["role": text(current, "AXRole"), "title": text(current, "AXTitle")])
+ guard let parent = read(current, "AXParent").1,
+ CFGetTypeID(parent) == AXUIElementGetTypeID() else { break }
+ current = unsafeBitCast(parent, to: AXUIElement.self)
+ }
+ result["focusedAncestry"] = ancestry
+}
+if args[3] == "inspect" {
+ result["nodes"] = nodes.filter {
+ if args.count > 4 {
+ if args[4] == "editor" { return ["AXTextArea", "AXTextField"].contains(text($0, "AXRole")) && text($0, "AXFocused") == "1" }
+ return text($0, "AXTitle") == args[4] || text($0, "AXDescription") == args[4]
+ }
+ return ["AXCell", "AXTable", "AXTextArea"].contains(text($0, "AXRole"))
+ }.map(describe)
+} else {
+ guard args.count >= 5 else { fatalError("target required") }
+ let targets = nodes.filter {
+ if args[4] == "editor" { return ["AXTextArea", "AXTextField"].contains(text($0, "AXRole")) && text($0, "AXFocused") == "1" }
+ return ["AXCell", "AXMenuButton"].contains(text($0, "AXRole")) && (text($0, "AXTitle") == args[4] || text($0, "AXDescription") == args[4])
+ }
+ guard targets.count == 1 else { fatalError("target missing or ambiguous") }
+ let target = targets[0]
+ result["before"] = describe(target)
+ let start = Date()
+ if args[3] == "press" {
+ result["nativeError"] = AXUIElementPerformAction(target, "AXPress" as CFString).rawValue
+ } else if args[3] == "show-menu" {
+ result["nativeError"] = AXUIElementPerformAction(target, "AXShowMenu" as CFString).rawValue
+ } else if args[3] == "set" && args.count == 6 {
+ result["nativeError"] = AXUIElementSetAttributeValue(target, "AXValue" as CFString, args[5] as CFString).rawValue
+ } else if args[3] == "select" {
+ let tables = nodes.filter { text($0, "AXRole") == "AXTable" && text($0, "AXTitle").contains("Eval Grid") }
+ guard tables.count == 1 else { fatalError("table missing or ambiguous") }
+ result["nativeError"] = AXUIElementSetAttributeValue(tables[0], "AXSelectedCells" as CFString, [target] as CFArray).rawValue
+ } else { fatalError("unsupported operation") }
+ result["elapsedMs"] = Date().timeIntervalSince(start) * 1000
+ result["after"] = describe(target)
+}
+var menus: [[String: Any]] = []
+walk(window, 0) { node, depth in
+ if text(node, "AXRole") == "AXMenu" {
+ menus.append(["depthFromWindow": depth, "node": describe(node)])
+ }
+}
+result["menusObserved"] = menus
+result["frontmostAfter"] = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? -1
+let data = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys])
+FileHandle.standardOutput.write(data)
+if args.last == "--hold" {
+ RunLoop.main.run(until: Date().addingTimeInterval(15))
+}
diff --git a/tests/real-apps/headless_probe.swift b/tests/real-apps/headless_probe.swift
new file mode 100644
index 000000000..e624dda41
--- /dev/null
+++ b/tests/real-apps/headless_probe.swift
@@ -0,0 +1,76 @@
+import AppKit
+import CoreGraphics
+
+func emit(_ value: [String: Any]) throws {
+ FileHandle.standardOutput.write(try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]))
+ FileHandle.standardOutput.write(Data([10]))
+}
+
+func eventDelta(_ before: UInt32, _ after: UInt32) -> UInt32 {
+ after &- before
+}
+
+let args = CommandLine.arguments
+if args.count == 2 && args[1] == "--self-test" {
+ precondition(eventDelta(12, 12) == 0)
+ precondition(eventDelta(12, 15) == 3)
+ precondition(eventDelta(UInt32.max - 1, 1) == 3)
+ print("PASS: input counters preserve increments and UInt32 rollover")
+ exit(0)
+}
+guard args.count == 3, let target = Int32(args[1]), target > 0,
+ let duration = Double(args[2]), duration.isFinite, duration > 0, duration <= 300,
+ let application = NSRunningApplication(processIdentifier: target) else {
+ fputs("usage: headless_probe RUNNING_PID DURATION_SECONDS (0 < duration <= 300)\n", stderr)
+ exit(2)
+}
+
+let events: [(String, CGEventType)] = [
+ ("keyDown", .keyDown), ("keyUp", .keyUp), ("flagsChanged", .flagsChanged),
+ ("leftMouseDown", .leftMouseDown), ("leftMouseUp", .leftMouseUp),
+ ("rightMouseDown", .rightMouseDown), ("rightMouseUp", .rightMouseUp),
+ ("otherMouseDown", .otherMouseDown), ("otherMouseUp", .otherMouseUp),
+ ("mouseMoved", .mouseMoved), ("leftMouseDragged", .leftMouseDragged),
+ ("rightMouseDragged", .rightMouseDragged), ("otherMouseDragged", .otherMouseDragged),
+ ("scrollWheel", .scrollWheel)
+]
+func counters() -> [UInt32] {
+ events.map { CGEventSource.counterForEventType(.combinedSessionState, eventType: $0.1) }
+}
+
+let start = ProcessInfo.processInfo.systemUptime
+var activations: [[String: Any]] = []
+let center = NSWorkspace.shared.notificationCenter
+let observer = center.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { notice in
+ guard let activated = notice.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication else { return }
+ activations.append(["pid": activated.processIdentifier, "elapsedMs": (ProcessInfo.processInfo.systemUptime - start) * 1000])
+}
+let initialForeground = NSWorkspace.shared.frontmostApplication?.processIdentifier
+let initialCounters = counters()
+let initialPointer = CGEvent(source: nil)?.location
+var pointerChanged = false
+var pointerSamples = 0
+let timer = Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { _ in
+ if let position = CGEvent(source: nil)?.location, let initialPointer {
+ pointerChanged = pointerChanged || position != initialPointer
+ pointerSamples += 1
+ }
+}
+try emit(["event": "ready", "targetPid": target, "frontmostPid": initialForeground ?? -1,
+ "durationSeconds": duration, "pointerAvailable": initialPointer != nil])
+while ProcessInfo.processInfo.systemUptime - start < duration {
+ RunLoop.main.run(until: Date().addingTimeInterval(0.05))
+}
+timer.invalidate()
+center.removeObserver(observer)
+let finalCounters = counters()
+let deltas = Dictionary(uniqueKeysWithValues: events.indices.map {
+ (events[$0].0, eventDelta(initialCounters[$0], finalCounters[$0]))
+})
+try emit(["event": "complete", "targetPid": target, "targetStillRunning": !application.isTerminated,
+ "elapsedMs": (ProcessInfo.processInfo.systemUptime - start) * 1000,
+ "initialFrontmostPid": initialForeground ?? -1,
+ "finalFrontmostPid": NSWorkspace.shared.frontmostApplication?.processIdentifier ?? -1,
+ "activations": activations, "inputEventDeltas": deltas,
+ "pointerChanged": pointerChanged, "pointerSamples": pointerSamples,
+ "scope": "Session-wide counters cannot attribute events to the agent; pointer movement is sampled. No key contents are recorded."])
diff --git a/tests/real-apps/nested_scroll_fixture.m b/tests/real-apps/nested_scroll_fixture.m
new file mode 100644
index 000000000..0cbbdca60
--- /dev/null
+++ b/tests/real-apps/nested_scroll_fixture.m
@@ -0,0 +1,23 @@
+#import <AppKit/AppKit.h>
+int main(void) { @autoreleasepool {
+ NSApplication *app = NSApplication.sharedApplication;
+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];
+ NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(300,200,500,600) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO];
+ window.title = @"AD Reliability Nested Scroll";
+ NSScrollView *scroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(50,50,300,100)];
+ scroll.hasVerticalScroller = YES;
+ NSView *document = [[NSView alloc] initWithFrame:NSMakeRect(0,0,280,500)];
+ NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(20,220,200,30)];
+ button.title = @"Clipped target";
+ [document addSubview:button];
+ scroll.documentView = document;
+ [window.contentView addSubview:scroll];
+ NSButton *sibling = [[NSButton alloc] initWithFrame:NSMakeRect(250,500,200,30)];
+ sibling.title = @"Visible sibling";
+ [window.contentView addSubview:sibling];
+ [scroll.contentView scrollToPoint:NSMakePoint(0,0)];
+ [scroll reflectScrolledClipView:scroll.contentView];
+ [window orderBack:nil];
+ NSLog(@"READY pid=%d clip=%@ target=%@", getpid(), NSStringFromRect(scroll.contentView.bounds), NSStringFromRect(button.frame));
+ [app run];
+} }
diff --git a/tests/real-apps/numbers-sheets.sh b/tests/real-apps/numbers-sheets.sh
new file mode 100644
index 000000000..8c3e83899
--- /dev/null
+++ b/tests/real-apps/numbers-sheets.sh
@@ -0,0 +1,52 @@
+#!/bin/bash
+set -euo pipefail
+
+if [[ $# -lt 4 || $# -gt 5 ]]; then
+ echo "usage: numbers-sheets.sh BINARY WINDOW_ID SHEET_1_REF OTHER_SHEET_REF [CYCLES]" >&2
+ exit 2
+fi
+
+binary=$1
+window=$2
+first=$3
+second=$4
+cycles=${5:-5}
+[[ "$binary" = /* && -x "$binary" ]]
+[[ "${AGENT_DESKTOP_HOME:-}" = /* ]]
+[[ "$window" =~ ^w-[0-9]+$ ]]
+[[ "$first" =~ ^@s[a-z0-9]+:e[0-9]+$ ]]
+[[ "$second" =~ ^@s[a-z0-9]+:e[0-9]+$ && "$first" != "$second" ]]
+[[ "$cycles" =~ ^[1-9][0-9]*$ && "$cycles" -le 15 ]]
+
+output=$(mktemp -d /tmp/ad-numbers-sheets.XXXXXX)
+echo "Evidence: $output" >&2
+step=0
+
+run() {
+ step=$((step + 1))
+ "$binary" "$@" | tee "$output/$step-$1.json"
+}
+
+transition() {
+ local target=$1
+ local inactive=$2
+ local label=$3
+ if ! run click "$target"; then
+ run screenshot --window-id "$window" "$output/$label-failed.png" || true
+ return 1
+ fi
+ run screenshot --window-id "$window" "$output/$label.png"
+ run wait --element "$target" --predicate value --value true --timeout 5000
+ run wait --element "$inactive" --predicate value --value false --timeout 5000
+ run get "$target" --property states
+ run is "$target" --property checked
+ run get "$inactive" --property states
+ run is "$inactive" --property checked
+}
+
+run list-windows --app Numbers
+for ((cycle = 1; cycle <= cycles; cycle++)); do
+ transition "$first" "$second" "$cycle-sheet-1"
+ transition "$second" "$first" "$cycle-other"
+done
+echo "Commands completed. Review raw state pairs, screenshots and independent document oracle before scoring." >&2
diff --git a/tests/real-apps/numbers_sheets_test.py b/tests/real-apps/numbers_sheets_test.py
new file mode 100644
index 000000000..11def6713
--- /dev/null
+++ b/tests/real-apps/numbers_sheets_test.py
@@ -0,0 +1,38 @@
+"""Run with python3 tests/real-apps/numbers_sheets_test.py."""
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+
+
+def check_failure_stops_mutations():
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ fake = root / "fake-ad"
+ calls = root / "calls"
+ fake.write_text("""#!/bin/bash
+printf '%s\\n' "$*" >> "$CALLS"
+if [[ "$1" == click ]]; then
+ echo '{"ok":false,"error":{"disposition":{"retry":"unsafe"}}}'
+ exit 1
+fi
+echo '{"ok":true}'
+""")
+ fake.chmod(0o700)
+ result = subprocess.run(
+ ["bash", str(Path(__file__).with_name("numbers-sheets.sh")),
+ str(fake), "w-123", "@stest:e1", "@stest:e2", "2"],
+ env={**os.environ, "CALLS": str(calls), "AGENT_DESKTOP_HOME": str(root)},
+ capture_output=True, text=True,
+ )
+ commands = calls.read_text().splitlines()
+ assert result.returncode != 0
+ assert commands[0] == "list-windows --app Numbers"
+ assert commands[1] == "click @stest:e1"
+ assert len(commands) == 3
+ assert commands[2].startswith("screenshot --window-id w-123 ")
+ assert '"retry":"unsafe"' in result.stdout
+
+
+if __name__ == "__main__":
+ check_failure_stops_mutations()
diff --git a/tests/real-apps/replace_contract_fixture.m b/tests/real-apps/replace_contract_fixture.m
new file mode 100644
index 000000000..7974f7273
--- /dev/null
+++ b/tests/real-apps/replace_contract_fixture.m
@@ -0,0 +1,36 @@
+#import <AppKit/AppKit.h>
+#import <dlfcn.h>
+@interface ContractText : NSTextView
+@end
+@implementation ContractText
+- (BOOL)accessibilityReplaceRange:(NSRange)range withText:(NSString *)text {
+ NSLog(@"RECEIVED range=%@ text=%@", NSStringFromRange(range), text);
+ if (range.location > self.string.length || range.length > self.string.length - range.location) return NO;
+ [self.textStorage replaceCharactersInRange:range withString:text];
+ NSLog(@"RESULT %@", self.string);
+ return YES;
+}
+@end
+int main(int argc, const char *argv[]) { @autoreleasepool {
+ BOOL focused = argc == 2 && strcmp(argv[1], "--standard-focused") == 0;
+ BOOL standard = focused || (argc == 2 && strcmp(argv[1], "--standard") == 0);
+ if (argc > 1 && !standard) return 2;
+ for (const char **p = (const char *[]){"NSAccessibilityReplacementRangeKey", "NSAccessibilityReplacementTextKey", "NSAccessibilityReplaceRangeWithTextParameterizedAttribute", NULL}; *p; p++) {
+ NSString **symbol = dlsym(RTLD_DEFAULT, *p);
+ NSLog(@"KEY %s = %@", *p, symbol ? *symbol : @"MISSING");
+ }
+ NSApplication *app = NSApplication.sharedApplication;
+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];
+ NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(200, 200, 400, 200) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO];
+ window.title = @"AD Reliability Parameter Contract";
+ NSTextView *text = [[(standard ? NSTextView.class : ContractText.class) alloc] initWithFrame:NSMakeRect(0,0,400,200)];
+ text.string = @"seed-target";
+ window.contentView = text;
+ [window orderBack:nil];
+ if (focused) {
+ BOOL accepted = [window makeFirstResponder:text];
+ NSLog(@"RESPONDER accepted=%d matches=%d active=%d key=%d currentContext=%@ editorContext=%@", accepted, window.firstResponder == text, app.active, window.keyWindow, NSTextInputContext.currentInputContext, text.inputContext);
+ }
+ NSLog(@"READY pid=%d", getpid());
+ [app run];
+} }
diff --git a/tests/real-apps/replace_range_probe.swift b/tests/real-apps/replace_range_probe.swift
new file mode 100644
index 000000000..fd775ebff
--- /dev/null
+++ b/tests/real-apps/replace_range_probe.swift
@@ -0,0 +1,35 @@
+import AppKit
+import ApplicationServices
+func read(_ node: AXUIElement, _ key: String) -> CFTypeRef? {
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(node, key as CFString, &value) == .success else { return nil }
+ return value
+}
+func children(_ node: AXUIElement) -> [AXUIElement] { read(node, "AXChildren") as? [AXUIElement] ?? [] }
+func collect(_ node: AXUIElement, depth: Int = 0) -> [AXUIElement] {
+ guard depth < 25 else { return [] }
+ return [node] + children(node).flatMap { collect($0, depth: depth + 1) }
+}
+let args = CommandLine.arguments
+precondition(args.count == 5)
+guard let pid = Int32(args[1]), args[2].hasPrefix("AD Reliability") else { fatalError("owned target required") }
+let app = AXUIElementCreateApplication(pid)
+AXUIElementSetMessagingTimeout(app, 3)
+let windows = (read(app, "AXWindows") as? [AXUIElement] ?? []).filter { read($0, "AXTitle") as? String == args[2] }
+precondition(windows.count == 1, "unique owned window required")
+let editors = collect(windows[0]).filter { read($0, "AXRole") as? String == "AXTextArea" && read($0, "AXValue") as? String == args[3] }
+precondition(editors.count == 1, "unique seeded editor required")
+let editor = editors[0]
+var names: CFArray?
+precondition(AXUIElementCopyParameterizedAttributeNames(editor, &names) == .success)
+precondition((names as? [String] ?? []).contains("AXReplaceRangeWithText"))
+precondition(NSWorkspace.shared.frontmostApplication?.processIdentifier != pid, "must be background")
+var range = CFRange(location: 0, length: args[3].utf16.count)
+guard let rangeValue = AXValueCreate(.cfRange, &range) else { fatalError("range allocation failed") }
+let parameter = ["AXReplacementRange": rangeValue, "AXReplacementText": args[4] as CFString] as CFDictionary
+var result: CFTypeRef?
+let frontBefore = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? -1
+let error = AXUIElementCopyParameterizedAttributeValue(editor, "AXReplaceRangeWithText" as CFString, parameter, &result)
+let after = read(editor, "AXValue") as? String
+print("nativeError=\(error.rawValue) result=\(String(describing: result)) before=\(args[3]) after=\(String(describing: after)) foregroundBefore=\(frontBefore) foregroundAfter=\(NSWorkspace.shared.frontmostApplication?.processIdentifier ?? -1)")
+exit(error == .success && after == args[4] ? 0 : 1)
diff --git a/tests/real-apps/retained-identity-probe.swift b/tests/real-apps/retained-identity-probe.swift
new file mode 100644
index 000000000..f91f663ea
--- /dev/null
+++ b/tests/real-apps/retained-identity-probe.swift
@@ -0,0 +1,74 @@
+import AppKit
+import ApplicationServices
+
+enum ProbeError: Error {
+ case invalidArguments
+ case nativeRead(String, Int32)
+ case incompleteTree
+ case nonUniqueTarget
+}
+
+func attribute(_ element: AXUIElement, _ name: String) throws -> CFTypeRef? {
+ var result: CFTypeRef?
+ let error = AXUIElementCopyAttributeValue(element, name as CFString, &result)
+ if error == .noValue || error == .attributeUnsupported { return nil }
+ guard error == .success else { throw ProbeError.nativeRead(name, error.rawValue) }
+ return result
+}
+
+func descendants(_ root: AXUIElement) throws -> [AXUIElement] {
+ var pending: [(AXUIElement, Int)] = [(root, 0)]
+ var result: [AXUIElement] = []
+ while let (node, depth) = pending.popLast() {
+ guard result.count < 1000, depth < 30 else { throw ProbeError.incompleteTree }
+ result.append(node)
+ let children = try attribute(node, "AXChildren") as? [AXUIElement] ?? []
+ pending.append(contentsOf: children.map { ($0, depth + 1) })
+ }
+ return result
+}
+
+guard CommandLine.arguments.count == 2,
+ let pid = Int32(CommandLine.arguments[1]) else { throw ProbeError.invalidArguments }
+let app = AXUIElementCreateApplication(pid)
+AXUIElementSetMessagingTimeout(app, 1)
+let windows = try attribute(app, "AXWindows") as? [AXUIElement] ?? []
+guard windows.count == 1, let window = windows.first else { throw ProbeError.nonUniqueTarget }
+let initial = try descendants(window)
+let matches = try initial.filter {
+ try attribute($0, "AXIdentifier") as? String == "shared-title"
+ && attribute($0, "AXValue") as? String == "Alpha"
+}
+guard matches.count == 1, let retained = matches.first else { throw ProbeError.nonUniqueTarget }
+let stableMatches = try initial.filter {
+ try attribute($0, "AXIdentifier") as? String == "stable-editor"
+}
+guard stableMatches.count == 1, let stable = stableMatches.first else {
+ throw ProbeError.nonUniqueTarget
+}
+print("ready: retained Alpha; enter a stage label to inspect current membership")
+fflush(stdout)
+while let stage = readLine() {
+ if stage == "quit" { break }
+ let live = try descendants(window)
+ let equal = live.filter { CFEqual(retained, $0) }
+ var fields: [String] = []
+ for node in live where try attribute(node, "AXIdentifier") as? String == "shared-title" {
+ let value = try attribute(node, "AXValue") as? String ?? "<absent>"
+ fields.append("\(value):retained=\(CFEqual(retained, node))")
+ }
+ var value: CFTypeRef?
+ let error = AXUIElementCopyAttributeValue(retained, "AXValue" as CFString, &value)
+ print("stage=\(stage) membership=\(equal.count) retainedError=\(error.rawValue) retainedValue=\(String(describing: value)) fields=\(fields)")
+ let stableMembership = live.filter { CFEqual(stable, $0) }.count
+ let stableValue = try attribute(stable, "AXValue") as? String
+ print("stableMembership=\(stableMembership) stableValue=\(String(describing: stableValue))")
+ if ["initial", "filtered", "restored", "edited", "cleared"].contains(stage) {
+ precondition(equal.count == (stage == "initial" ? 1 : 0))
+ precondition(stableMembership == 1)
+ precondition(stableValue == (stage == "edited" ? "retained-control" : "Stable value"))
+ precondition(!fields.contains("Beta:retained=true"))
+ print("stage assertions passed")
+ }
+ fflush(stdout)
+}
diff --git a/tests/real-apps/selection_delivery_fixture.swift b/tests/real-apps/selection_delivery_fixture.swift
new file mode 100644
index 000000000..7981878ab
--- /dev/null
+++ b/tests/real-apps/selection_delivery_fixture.swift
@@ -0,0 +1,42 @@
+import AppKit
+
+final class SilentRow: NSView {
+ override func isAccessibilityElement() -> Bool { true }
+ override func accessibilityRole() -> NSAccessibility.Role? { .row }
+ override func accessibilityLabel() -> String? { "Silent selection row" }
+ override func isAccessibilitySelected() -> Bool { false }
+ override func setAccessibilitySelected(_ value: Bool) {
+ NSLog("MUTATION direct-selection %@", value.description)
+ }
+ override func isAccessibilitySelectorAllowed(_ selector: Selector) -> Bool {
+ selector == #selector(setAccessibilitySelected(_:))
+ || super.isAccessibilitySelectorAllowed(selector)
+ }
+}
+
+final class SelectionTable: NSView {
+ override func isAccessibilityElement() -> Bool { true }
+ override func accessibilityRole() -> NSAccessibility.Role? { .table }
+ override func accessibilityLabel() -> String? { "Selection delivery table" }
+ override func accessibilitySelectedRows() -> [Any]? { [] }
+ override func setAccessibilitySelectedRows(_ rows: [Any]?) {
+ NSLog("MUTATION container-selection %ld", rows?.count ?? 0)
+ }
+ override func isAccessibilitySelectorAllowed(_ selector: Selector) -> Bool {
+ selector == #selector(setAccessibilitySelectedRows(_:))
+ || super.isAccessibilitySelectorAllowed(selector)
+ }
+}
+
+let app = NSApplication.shared
+app.setActivationPolicy(.accessory)
+let window = NSWindow(contentRect: NSRect(x: 300, y: 200, width: 400, height: 240),
+ styleMask: [.titled], backing: .buffered, defer: false)
+window.title = "AD Reliability Selection Delivery"
+let table = SelectionTable(frame: NSRect(x: 20, y: 20, width: 360, height: 200))
+let row = SilentRow(frame: NSRect(x: 0, y: 0, width: 300, height: 60))
+table.addSubview(row)
+window.contentView?.addSubview(table)
+window.orderBack(nil)
+NSLog("READY pid=%d", ProcessInfo.processInfo.processIdentifier)
+app.run()