Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat(macos): re-identify refs through the element's own accessibility address (#441)
Lahfirb4926b567055
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d721f35e8..7067eb216 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,10 +6,7 @@* Remove the macOS command host. Every CLI call runs in its own process, as on Windows and Linux. The npm install and every CLI call stop any command host an earlier version left running. After an install that skips npm scripts, or a manual install, run `agent-desktop version` once.* Refs from snapshots taken before this release return `STALE_REF`. Take a new snapshot.--### Known Limitations--* On macOS, a ref to a row in a list whose rows share an accessibility identifier can act on another row after the list changes. Take a new snapshot after the list changes.+* On macOS a ref follows its own element. A ref to a row that was removed returns `STALE_REF` instead of acting on the row that moved into its place, and identical controls can each be used by ref.## [1.0.2](https://github.com/vercel-labs/agent-desktop/compare/v1.0.1...v1.0.2) (2026-10-30)diff --git a/crates/macos/src/lib.rs b/crates/macos/src/lib.rsindex 481469dba..c13a12aaf 100644--- a/crates/macos/src/lib.rs+++ b/crates/macos/src/lib.rs@@ -13,4 +13,3 @@ pub use system::cocoa_runtime::ensure_cocoa_multithreaded;pub use system::permissions::permission_guide::entry_from_env as permission_guide_from_env;pub use system::permissions::permission_helper::entry_from_env as permission_prompt_helper_from_env;pub use system::process::legacy_host::stop_legacy_command_hosts;-pub use tree::resolve::retained::RetainedRefSession;diff --git a/crates/macos/src/tree/query/traversal.rs b/crates/macos/src/tree/query/traversal.rsindex 6987c140d..02f74d1e5 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 mut read = read_node(+ let read = read_node(&element,super::node_read_context::NodeReadContext {tree: &self.context,@@ -161,9 +161,6 @@ impl LocatorTraversal {if !subtree_complete {self.arena.mark_incomplete();}- if let Some(token) = crate::tree::resolve::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/resolve/mod.rs b/crates/macos/src/tree/resolve/mod.rsindex 9cf4e8beb..b795b9271 100644--- a/crates/macos/src/tree/resolve/mod.rs+++ b/crates/macos/src/tree/resolve/mod.rs@@ -48,7 +48,6 @@ pub(crate) fn resolve_locator_anchor_with_deadline(#[cfg(target_os = "macos")]fn verify_process_instance(entry: &RefEntry) -> Result<(), AdapterError> {- super::resolve::retained::validate(entry.identity.retained_object.as_deref())?;let Some(instance) = entry.process.process_instance.as_deref() else {return Err(AdapterError::stale_ref_because("Saved target has no process instance identity",@@ -72,6 +71,9 @@ fn resolve_once(entry: &RefEntry, deadline: Instant) -> Result<NativeHandle, Adalet started = Instant::now();crate::tree::locator_deadline::remaining(deadline)?;let mut read_context = ResolveReadContext::new(deadline);+ if let Some(result) = token_resolution(entry, deadline, &mut read_context, started) {+ return result;+ }if can_use_path_fast_path(entry) {let roots = match candidate_roots(entry, &mut read_context) {Ok(roots) => roots,@@ -142,6 +144,9 @@ fn resolve_locator_anchor_once(let started = Instant::now();crate::tree::locator_deadline::remaining(deadline)?;let mut read_context = ResolveReadContext::new(deadline);+ if let Some(result) = token_resolution(entry, deadline, &mut read_context, started) {+ return result;+ }if !can_use_locator_anchor_path(entry) {return finish_resolution(Err(AdapterError::element_not_found("locator anchor")),@@ -173,6 +178,35 @@ fn resolve_locator_anchor_once()}+/// The token answer a resolution pass shares: `Some` when the saved ref carries+/// a retained object, whether it resolved or was refused, and `None` when the+/// entry has no token and the path and search passes must decide.+#[cfg(target_os = "macos")]+fn token_resolution(+ entry: &RefEntry,+ deadline: Instant,+ context: &mut ResolveReadContext,+ started: Instant,+) -> Option<Result<NativeHandle, AdapterError>> {+ match super::resolve::retained_resolve::resolve_saved_token(entry, deadline) {+ Ok(Some(handle)) => Some(finish_resolution(+ Ok(handle),+ context,+ started,+ "remote_token",+ true,+ )),+ Ok(None) => None,+ Err(error) => Some(finish_resolution(+ Err(error),+ context,+ started,+ "remote_token",+ true,+ )),+ }+}+#[cfg(target_os = "macos")]fn finish_resolution<T>(result: Result<T, AdapterError>,@@ -304,7 +338,7 @@ pub(super) mod resolve_roots;pub(super) mod resolve_search;pub(super) mod resolve_source_app;pub(crate) mod retained;-pub(super) mod retained_store;+pub(super) mod retained_resolve;#[cfg(test)]#[path = "resolve_tests.rs"]mod tests;diff --git a/crates/macos/src/tree/resolve/resolve_search.rs b/crates/macos/src/tree/resolve/resolve_search.rsindex bb5da0e2e..018bdb49b 100644--- a/crates/macos/src/tree/resolve/resolve_search.rs+++ b/crates/macos/src/tree/resolve/resolve_search.rs@@ -323,6 +323,9 @@ pub(in crate::tree) fn native_identifier_reused_by_different_role(.any(|identifier| identifier == expected)}+/// Whether bounds alone may stand in for an element whose identity is unknown.+/// A ref that recorded a token never qualifies: only that token may match it,+/// which `has_meaningful_identity` already enforces.fn provisional_geometry_candidate(entry: &RefEntry) -> bool {entry.geometry.bounds_hash.is_some()&& !agent_desktop_core::refs::ref_identity::has_meaningful_identity(entry)@@ -380,3 +383,7 @@ fn mark_incomplete(context: &mut CollectContext<'_>, error: AdapterError) {*context.incomplete = Some(error);}}++#[cfg(all(test, target_os = "macos"))]+#[path = "resolve_search_tests.rs"]+mod tests;diff --git a/crates/macos/src/tree/resolve/resolve_search_tests.rs b/crates/macos/src/tree/resolve/resolve_search_tests.rsnew file mode 100644index 000000000..7a4c20818--- /dev/null+++ b/crates/macos/src/tree/resolve/resolve_search_tests.rs@@ -0,0 +1,51 @@+use super::provisional_geometry_candidate;+use agent_desktop_core::{+ ProcessId, RefCapabilities, RefEntry, RefEntryIdentity, RefGeometry, RefProcess, RefScope,+ RefSource, SnapshotSurface,+};++fn bounds_only_entry(retained_object: Option<&str>) -> RefEntry {+ RefEntry {+ process: RefProcess {+ pid: ProcessId::new(7),+ process_instance: Some("test-instance".into()),+ },+ identity: RefEntryIdentity {+ retained_object: retained_object.map(String::from),+ role: "cell".into(),+ name: None,+ value: None,+ description: None,+ native_id: None,+ },+ geometry: RefGeometry {+ bounds_space: None,+ bounds: None,+ bounds_hash: Some(42),+ },+ capabilities: RefCapabilities {+ states: vec![],+ available_actions: vec![],+ },+ source: RefSource {+ source_app: None,+ source_window_id: Some("w-10".into()),+ source_window_title: None,+ source_window_bounds_hash: None,+ source_surface: SnapshotSurface::Window,+ },+ scope: RefScope {+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::smallvec![0, 1],+ },+ }+}++#[test]+fn bounds_stand_in_for_an_identityless_ref_but_never_replace_a_token() {+ assert!(provisional_geometry_candidate(&bounds_only_entry(None)));+ assert!(!provisional_geometry_candidate(&bounds_only_entry(Some(+ "axtok1:0000000000000000"+ ))));+}diff --git a/crates/macos/src/tree/resolve/retained.rs b/crates/macos/src/tree/resolve/retained.rsindex cb0a56b72..7018dd6da 100644--- a/crates/macos/src/tree/resolve/retained.rs+++ b/crates/macos/src/tree/resolve/retained.rs@@ -1,156 +1,171 @@-use super::retained_store::RetainedStore;use crate::tree::AXElement;use agent_desktop_core::{- AdapterError, DeliverySemantics, ErrorCode, IdentifierEvidence, IdentityMatch, RefEntry,+ AdapterError, DeliverySemantics, ErrorCode, IdentifierEvidence, IdentityMatch, LocatorEvidence,+ RefEntry,};-use std::cell::RefCell;-use std::marker::PhantomData;-use std::rc::Rc;-use std::sync::atomic::{AtomicU64, Ordering};+use core_foundation::{+ base::TCFType,+ data::{CFData, CFDataRef},+};+use std::ffi::{CStr, c_void};+use std::sync::OnceLock;++const TOKEN_PREFIX: &str = "axtok1:";+const RTLD_DEFAULT: *mut c_void = -2_isize as *mut c_void;+const RTLD_LAZY: i32 = 0x1;+const APPLICATION_SERVICES: &CStr =+ c"/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices";-static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);+type TokenCreate = unsafe extern "C" fn(accessibility_sys::AXUIElementRef) -> CFDataRef;+type TokenResolve = unsafe extern "C" fn(CFDataRef) -> accessibility_sys::AXUIElementRef;-thread_local! {- static STORE: RefCell<Option<RetainedStore>> = const { RefCell::new(None) };+/// What a saved remote token says about the element it names in this process.+pub(crate) enum TokenLookup {+ NotAToken,+ Unavailable,+ Dead,+ Live(AXElement),}-/// Owns retained AX identity on the calling thread until dropped.-pub struct RetainedRefSession {- _owner_thread: PhantomData<Rc<()>>,+struct Symbols {+ create: TokenCreate,+ resolve: TokenResolve,}-impl RetainedRefSession {- pub fn capture_count(&self) -> usize {- STORE.with(|slot| {- slot.borrow()- .as_ref()- .map_or(0, RetainedStore::capture_count)- })+/// Saves the app's own token for `element` as `axtok1:<hex>`, or `None` when the+/// private symbols are missing or the app yields no token for it.+pub(crate) fn capture(element: &AXElement) -> Result<Option<String>, AdapterError> {+ if element.0.is_null() {+ return Err(AdapterError::stale_ref_because(+ "Cannot take a native object token from a null element",+ ));}-- pub fn retain(&self, live: &std::collections::HashSet<String>) {- STORE.with(|slot| {- if let Some(store) = slot.borrow_mut().as_mut() {- store.retain(live);- }- });+ let Some(symbols) = symbols() else {+ return Ok(None);+ };+ let data = unsafe { (symbols.create)(element.0) };+ if data.is_null() {+ return Ok(None);}+ let data = unsafe { CFData::wrap_under_create_rule(data) };+ Ok(Some(format!("{TOKEN_PREFIX}{}", encode_hex(data.bytes()))))+}- 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::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,- })- })+/// Resolves a saved token to the element it names, or says why it could not.+pub(crate) fn resolve_token(token: &str) -> Result<TokenLookup, AdapterError> {+ let Some(hex) = token.strip_prefix(TOKEN_PREFIX) else {+ return Ok(TokenLookup::NotAToken);+ };+ let Some(symbols) = symbols() else {+ return Ok(TokenLookup::Unavailable);+ };+ let Some(bytes) = decode_hex(hex) else {+ return Ok(TokenLookup::Dead);+ };+ let data = CFData::from_buffer(&bytes);+ let element = unsafe { (symbols.resolve)(data.as_concrete_TypeRef()) };+ if element.is_null() {+ return Ok(TokenLookup::Dead);}+ Ok(TokenLookup::Live(AXElement(element)))}-impl Drop for RetainedRefSession {- fn drop(&mut self) {- STORE.with(|slot| {- slot.borrow_mut().take();- });+pub(crate) fn evidence(element: &AXElement, identifiers: IdentifierEvidence) -> IdentifierEvidence {+ match capture(element) {+ Ok(Some(token)) => identifiers.with_retained_object(token),+ _ => identifiers,}}-#[cfg(target_os = "macos")]-pub(in crate::tree) fn element_hash(element: &AXElement) -> u64 {- if element.0.is_null() {- return 0;+/// Refuses a saved ref that carries a token this build cannot resolve at all.+pub(crate) fn validate(token: Option<&str>) -> Result<(), AdapterError> {+ match token {+ Some(token) if !token.starts_with(TOKEN_PREFIX) => Err(unsupported_token()),+ _ => Ok(()),}- unsafe { core_foundation::base::CFHash(element.0.cast()) as u64 }}-#[cfg(not(target_os = "macos"))]-pub(in crate::tree) fn element_hash(_element: &AXElement) -> u64 {- 0+/// Compares the token a candidate carries in `evidence` with the entry's token.+/// The candidate's own token is already in the evidence its read produced.+pub(crate) fn candidate_match(+ _element: &AXElement,+ entry: &RefEntry,+ evidence: &LocatorEvidence,+) -> Result<IdentityMatch, AdapterError> {+ let Some(token) = entry.identity.retained_object.as_deref() else {+ return Ok(super::resolve_search::match_native_or_text_identity(+ entry, evidence,+ ));+ };+ validate(Some(token))?;+ Ok(match evidence.identifiers.retained_object() {+ Some(actual) if actual == token => IdentityMatch::Match,+ Some(_) => IdentityMatch::NoMatch,+ None => super::resolve_search::match_native_or_text_identity(entry, evidence),+ })}-pub(crate) fn capture(element: &AXElement) -> Result<Option<String>, AdapterError> {- STORE.with(|slot| {- slot.borrow_mut()- .as_mut()- .map(|store| store.capture(element))- .transpose()- })+fn unsupported_token() -> AdapterError {+ AdapterError::new(+ ErrorCode::StaleRef,+ "The saved ref carries a native identity this build cannot resolve",+ )+ .with_suggestion("Run 'snapshot' to refresh, then retry with the updated ref.")+ .with_disposition(DeliverySemantics::not_delivered())}-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,+fn symbols() -> Option<&'static Symbols> {+ static SYMBOLS: OnceLock<Option<Symbols>> = OnceLock::new();+ SYMBOLS.get_or_init(load_symbols).as_ref()+}++fn load_symbols() -> Option<Symbols> {+ lookup_symbols(RTLD_DEFAULT).or_else(|| {+ let handle = unsafe { dlopen(APPLICATION_SERVICES.as_ptr(), RTLD_LAZY) };+ if handle.is_null() {+ None+ } else {+ lookup_symbols(handle)}})}-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()))- }+fn lookup_symbols(handle: *mut c_void) -> Option<Symbols> {+ let create = symbol(handle, c"_AXUIElementRemoteTokenCreate")?;+ let resolve = symbol(handle, c"_AXUIElementCreateWithRemoteToken")?;+ Some(Symbols {+ create: unsafe { std::mem::transmute::<*mut c_void, TokenCreate>(create) },+ resolve: unsafe { std::mem::transmute::<*mut c_void, TokenResolve>(resolve) },+ })}-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)- }))+fn symbol(handle: *mut c_void, name: &CStr) -> Option<*mut c_void> {+ let symbol = unsafe { dlsym(handle, name.as_ptr()) };+ (!symbol.is_null()).then_some(symbol)}-#[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- });+fn encode_hex(bytes: &[u8]) -> String {+ use std::fmt::Write;+ bytes.iter().fold(String::new(), |mut hex, byte| {+ let _ = write!(hex, "{byte:02x}");+ hex+ })+}++fn decode_hex(hex: &str) -> Option<Vec<u8>> {+ if hex.is_empty() || !hex.len().is_multiple_of(2) {+ return None;+ }+ let mut bytes = Vec::with_capacity(hex.len() / 2);+ for pair in hex.as_bytes().chunks_exact(2) {+ bytes.push(u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()?);}- Ok(super::resolve_search::match_native_or_text_identity(- entry, evidence,- ))+ Some(bytes)+}++unsafe extern "C" {+ fn dlsym(handle: *mut c_void, symbol: *const std::ffi::c_char) -> *mut c_void;+ fn dlopen(path: *const std::ffi::c_char, mode: i32) -> *mut c_void;}#[cfg(all(test, target_os = "macos"))]diff --git a/crates/macos/src/tree/resolve/retained_resolve.rs b/crates/macos/src/tree/resolve/retained_resolve.rsnew file mode 100644index 000000000..3037272a6--- /dev/null+++ b/crates/macos/src/tree/resolve/retained_resolve.rs@@ -0,0 +1,170 @@+use agent_desktop_core::{AdapterError, NativeHandle, RefEntry};++#[cfg(target_os = "macos")]+use super::resolve_classify::identity_summary_for_message;+#[cfg(target_os = "macos")]+use super::retained::{TokenLookup, resolve_token};+#[cfg(target_os = "macos")]+use crate::tree::AXElement;++/// Why a saved retained object no longer designates the element it was captured from.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(in crate::tree) enum RetainedMismatch {+ Dead,+ Pid,+ Role,+ NativeId,+}++impl RetainedMismatch {+ pub(in crate::tree) fn reason(self) -> &'static str {+ match self {+ Self::Dead => "dead",+ Self::Pid => "pid",+ Self::Role => "role",+ Self::NativeId => "native_identifier",+ }+ }+}++/// The attributes a token's element reports, read once so the accept decision+/// can be checked without a live accessibility connection.+pub(in crate::tree) struct RetainedFacts<'a> {+ pub(in crate::tree) pid: i32,+ pub(in crate::tree) role: Option<&'a str>,+ pub(in crate::tree) subrole: Option<&'a str>,+ pub(in crate::tree) native_id: Option<&'a str>,+}++/// Resolves a saved token to its element without a tree search, or reports why+/// the token can no longer stand for that element.+#[cfg(target_os = "macos")]+pub(in crate::tree) fn resolve_saved_token(+ entry: &RefEntry,+ deadline: std::time::Instant,+) -> Result<Option<NativeHandle>, AdapterError> {+ let Some(token) = entry.identity.retained_object.as_deref() else {+ return Ok(None);+ };+ match resolve_token(token)? {+ TokenLookup::NotAToken => Ok(None),+ TokenLookup::Unavailable => Err(stale_token_error(entry, RetainedMismatch::Dead)),+ TokenLookup::Dead => Err(stale_token_error(entry, RetainedMismatch::Dead)),+ TokenLookup::Live(element) => {+ verify_token_element(entry, &element, deadline)?;+ Ok(Some(element.into_native_handle()))+ }+ }+}++#[cfg(target_os = "macos")]+fn verify_token_element(+ entry: &RefEntry,+ element: &AXElement,+ deadline: std::time::Instant,+) -> Result<(), AdapterError> {+ let pid = crate::tree::properties::ax_ipc::pid(element, deadline)+ .map_err(|error| token_read_error(entry, error))?;+ let read = |attribute| {+ super::resolve_ax_read::read_string(element, attribute, deadline)+ .map_err(|error| destroyed_as_stale(entry, error))+ };+ let role = read("AXRole")?;+ let subrole = read("AXSubrole")?;+ let native_id = match entry+ .identity+ .native_id+ .as_ref()+ .and_then(|identifier| native_identifier_attribute(identifier.kind))+ {+ Some(attribute) => read(attribute)?,+ None => None,+ };+ let facts = RetainedFacts {+ pid,+ role: role.as_deref(),+ subrole: subrole.as_deref(),+ native_id: native_id.as_deref(),+ };+ if let Some(mismatch) = token_mismatch(entry, &facts) {+ return Err(stale_token_error(entry, mismatch));+ }+ Ok(())+}++#[cfg(target_os = "macos")]+fn token_read_error(entry: &RefEntry, ax_error: i32) -> AdapterError {+ if ax_error == accessibility_sys::kAXErrorInvalidUIElement {+ stale_token_error(entry, RetainedMismatch::Dead)+ } else {+ crate::tree::surface_read::map_error("AXPid", ax_error)+ }+}++#[cfg(target_os = "macos")]+fn destroyed_as_stale(entry: &RefEntry, error: AdapterError) -> AdapterError {+ if error.code == agent_desktop_core::ErrorCode::ElementNotFound {+ stale_token_error(entry, RetainedMismatch::Dead)+ } else {+ error+ }+}++/// Accepts a token's element only when its pid, snapshot role and recorded+/// native identifier all still agree with the saved ref.+pub(in crate::tree) fn token_mismatch(+ entry: &RefEntry,+ facts: &RetainedFacts<'_>,+) -> Option<RetainedMismatch> {+ let expected_pid = crate::system::process::process_identity::to_pid_t(entry.process.pid).ok();+ if expected_pid != Some(facts.pid) {+ return Some(RetainedMismatch::Pid);+ }+ let actual_role = facts+ .role+ .map(|role| crate::tree::roles::ax_role_and_subrole_to_str(role, facts.subrole));+ if actual_role != Some(entry.identity.role.as_str()) {+ return Some(RetainedMismatch::Role);+ }+ if let Some(recorded) = recorded_native_id(entry) {+ if facts.native_id != Some(recorded) {+ return Some(RetainedMismatch::NativeId);+ }+ }+ None+}++fn recorded_native_id(entry: &RefEntry) -> Option<&str> {+ let identifier = entry.identity.native_id.as_ref()?;+ native_identifier_attribute(identifier.kind)?;+ (!identifier.value.trim().is_empty()).then_some(identifier.value.as_str())+}++/// The accessibility attribute that reports one recorded identifier kind, or+/// `None` for a kind macOS cannot read back for comparison.+pub(in crate::tree) fn native_identifier_attribute(+ kind: agent_desktop_core::IdentifierKind,+) -> Option<&'static str> {+ match kind {+ agent_desktop_core::IdentifierKind::AxIdentifier => Some("AXIdentifier"),+ agent_desktop_core::IdentifierKind::AxDomIdentifier => Some("AXDOMIdentifier"),+ _ => None,+ }+}++#[cfg(target_os = "macos")]+fn stale_token_error(entry: &RefEntry, mismatch: RetainedMismatch) -> AdapterError {+ AdapterError::stale_ref_because(format!(+ "The saved element no longer exists or no longer matches: {}",+ identity_summary_for_message(entry)+ ))+ .with_details(serde_json::json!({+ "kind": "retained_object_stale",+ "reason": mismatch.reason(),+ "pid": entry.process.pid,+ }))+}++#[cfg(all(test, target_os = "macos"))]+#[path = "retained_resolve_tests.rs"]+mod tests;diff --git a/crates/macos/src/tree/resolve/retained_resolve_tests.rs b/crates/macos/src/tree/resolve/retained_resolve_tests.rsnew file mode 100644index 000000000..79c4f16b2--- /dev/null+++ b/crates/macos/src/tree/resolve/retained_resolve_tests.rs@@ -0,0 +1,146 @@+use super::{+ RetainedFacts, RetainedMismatch, native_identifier_attribute, resolve_saved_token,+ token_mismatch,+};+use agent_desktop_core::{+ ElementIdentifier, IdentifierKind, ProcessId, RefCapabilities, RefEntry, RefEntryIdentity,+ RefGeometry, RefProcess, RefScope, RefSource, SnapshotSurface,+};++fn entry(role: &str) -> RefEntry {+ RefEntry {+ process: RefProcess {+ pid: ProcessId::new(7),+ process_instance: Some("test-instance".into()),+ },+ identity: RefEntryIdentity {+ retained_object: None,+ role: role.into(),+ name: Some("Investors".into()),+ value: None,+ description: None,+ native_id: None,+ },+ geometry: RefGeometry {+ bounds_space: None,+ bounds: None,+ bounds_hash: None,+ },+ capabilities: RefCapabilities {+ states: vec![],+ available_actions: vec![],+ },+ source: RefSource {+ source_app: None,+ source_window_id: Some("w-10".into()),+ source_window_title: None,+ source_window_bounds_hash: None,+ source_surface: SnapshotSurface::Window,+ },+ scope: RefScope {+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::smallvec![0, 1],+ },+ }+}++fn facts<'a>(+ pid: i32,+ role: Option<&'a str>,+ subrole: Option<&'a str>,+ native_id: Option<&'a str>,+) -> RetainedFacts<'a> {+ RetainedFacts {+ pid,+ role,+ subrole,+ native_id,+ }+}++#[test]+fn token_mismatch_accepts_only_the_saved_element() {+ let stored = entry("button");++ assert_eq!(+ token_mismatch(&stored, &facts(7, Some("AXButton"), None, None)),+ None+ );+ assert_eq!(+ token_mismatch(+ &entry("treeitem"),+ &facts(7, Some("AXRow"), Some("AXOutlineRow"), None)+ ),+ None+ );+ assert_eq!(+ token_mismatch(&stored, &facts(8, Some("AXButton"), None, None)),+ Some(RetainedMismatch::Pid)+ );+ for role in [Some("AXCell"), None, Some("AXRoleThatDoesNotExist")] {+ assert_eq!(+ token_mismatch(&stored, &facts(7, role, None, None)),+ Some(RetainedMismatch::Role)+ );+ }++ let mut identified = entry("button");+ identified.identity.native_id = Some(ElementIdentifier {+ kind: IdentifierKind::AxDomIdentifier,+ value: "compose".into(),+ });+ assert_eq!(+ native_identifier_attribute(IdentifierKind::AxDomIdentifier),+ Some("AXDOMIdentifier")+ );+ assert_eq!(+ token_mismatch(+ &identified,+ &facts(7, Some("AXButton"), None, Some("compose"))+ ),+ None+ );+ assert_eq!(+ token_mismatch(+ &identified,+ &facts(7, Some("AXButton"), None, Some("other"))+ ),+ Some(RetainedMismatch::NativeId)+ );+ assert_eq!(+ token_mismatch(&identified, &facts(7, Some("AXButton"), None, None)),+ Some(RetainedMismatch::NativeId)+ );++ assert_eq!(+ native_identifier_attribute(IdentifierKind::AutomationId),+ None+ );+ let mut unreadable = entry("button");+ unreadable.identity.native_id = Some(ElementIdentifier {+ kind: IdentifierKind::AutomationId,+ value: "save-button".into(),+ });+ assert_eq!(+ token_mismatch(&unreadable, &facts(7, Some("AXButton"), None, None)),+ None+ );+ let mut blank = entry("button");+ blank.identity.native_id = Some(ElementIdentifier {+ kind: IdentifierKind::AxIdentifier,+ value: " ".into(),+ });+ assert_eq!(+ token_mismatch(&blank, &facts(7, Some("AXButton"), None, None)),+ None+ );+}++#[test]+fn a_ref_without_a_token_keeps_the_attribute_path() {+ let stored = entry("button");+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);++ assert!(resolve_saved_token(&stored, deadline).unwrap().is_none());+}diff --git a/crates/macos/src/tree/resolve/retained_store.rs b/crates/macos/src/tree/resolve/retained_store.rsdeleted file mode 100644index 5295f9587..000000000--- a/crates/macos/src/tree/resolve/retained_store.rs+++ /dev/null@@ -1,128 +0,0 @@-use crate::tree::AXElement;-use crate::tree::resolve::retained::element_hash;-use agent_desktop_core::AdapterError;-use std::collections::{HashMap, HashSet};--const MAX_OBJECTS: usize = 65_536;--pub(in crate::tree) 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(in crate::tree) fn new(generation: String) -> Self {- Self {- generation,- buckets: HashMap::new(),- count: 0,- tokens: HashSet::new(),- }- }-- pub(in crate::tree) 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(in crate::tree) fn capture(&mut self, element: &AXElement) -> Result<String, AdapterError> {- if element.0.is_null() {- return Err(AdapterError::stale_ref_because(- "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(in crate::tree) fn contains_token(&self, token: &str) -> bool {- self.tokens.contains(token)- }-- pub(in crate::tree) fn capture_count(&self) -> usize {- self.count- }-- pub(in crate::tree) 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/resolve/retained_tests.rs b/crates/macos/src/tree/resolve/retained_tests.rsindex 628db89da..91acca5ed 100644--- a/crates/macos/src/tree/resolve/retained_tests.rs+++ b/crates/macos/src/tree/resolve/retained_tests.rs@@ -1,18 +1,14 @@use super::*;-use agent_desktop_core::{LocatorField, LocatorRefEvidence};+use agent_desktop_core::{LocatorField, LocatorRefEvidence, SnapshotSurface};-fn app(pid: i32) -> AXElement {- AXElement(unsafe { accessibility_sys::AXUIElementCreateApplication(pid) })-}--fn entry(token: Option<String>) -> RefEntry {+fn entry(token: Option<&str>) -> 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,+ retained_object: token.map(str::to_owned),role: "button".into(),name: Some("Target".into()),value: None,@@ -33,7 +29,7 @@ fn entry(token: Option<String>) -> RefEntry {source_window_id: None,source_window_title: None,source_window_bounds_hash: None,- source_surface: agent_desktop_core::SnapshotSurface::Window,+ source_surface: SnapshotSurface::Window,},scope: agent_desktop_core::RefScope {root_ref: None,@@ -43,13 +39,15 @@ fn entry(token: Option<String>) -> RefEntry {}}-fn text_evidence(name: &str) -> agent_desktop_core::LocatorEvidence {- agent_desktop_core::LocatorEvidence {+fn candidate(token: Option<&str>, name: &str) -> LocatorEvidence {+ LocatorEvidence {role: LocatorField::Known("button".into()),name: LocatorField::Known(name.into()),description: LocatorField::Absent,value: LocatorField::Absent,- identifiers: IdentifierEvidence::absent(),+ identifiers: token.map_or_else(IdentifierEvidence::absent, |token| {+ IdentifierEvidence::absent().with_retained_object(token.into())+ }),states: LocatorField::Absent,ref_evidence: LocatorRefEvidence {window_bounds: LocatorField::Absent,@@ -61,100 +59,27 @@ fn text_evidence(name: &str) -> agent_desktop_core::LocatorEvidence {}#[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());-}+fn a_candidate_matches_only_its_own_token() {+ let element = AXElement(std::ptr::null_mut());+ let saved = entry(Some("axtok1:00ff"));+ let match_of = |saved: &RefEntry, token: Option<&str>| {+ candidate_match(&element, saved, &candidate(token, "Target"))+ };-#[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+ match_of(&saved, Some("axtok1:00ff")).unwrap(),+ IdentityMatch::Match);-}--#[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"+ match_of(&saved, Some("axtok1:00fe")).unwrap(),+ IdentityMatch::NoMatch);+ assert_eq!(match_of(&saved, None).unwrap(), IdentityMatch::Unknown);+ assert_eq!(match_of(&entry(None), None).unwrap(), IdentityMatch::Match);assert_eq!(- error.suggestion.as_deref(),- Some("Take a fresh snapshot in the active session")+ match_of(&entry(Some("host:1")), Some("axtok1:00ff"))+ .unwrap_err()+ .code,+ ErrorCode::StaleRef);- 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/surface_read.rs b/crates/macos/src/tree/surface_read.rsindex 6ef70eb7a..bd5d17886 100644--- a/crates/macos/src/tree/surface_read.rs+++ b/crates/macos/src/tree/surface_read.rs@@ -130,7 +130,7 @@ fn finish<T>(result.map_err(|error| map_error(attribute, error))}-fn map_error(attribute: &str, error: i32) -> AdapterError {+pub(crate) fn map_error(attribute: &str, error: i32) -> AdapterError {use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorCannotComplete, kAXErrorInvalidUIElement,};@@ -152,6 +152,7 @@ fn map_error(attribute: &str, error: i32) -> AdapterError {"attribute": attribute,"ax_error": error,"kind": "surface_read",+ "retryable": error == kAXErrorCannotComplete,})).with_suggestion("Retry after the application finishes updating its accessibility surfaces")}@@ -183,6 +184,12 @@ mod tests {);}+ #[test]+ fn a_busy_read_is_retryable_while_a_terminal_one_is_not() {+ assert!(map_error("AXRole", kAXErrorCannotComplete).is_transient_incomplete_read());+ assert!(!map_error("AXRole", kAXErrorAPIDisabled).is_transient_incomplete_read());+ }+#[test]fn expired_deadline_fails_without_native_reads() {let error = ensure_before_deadline(Instant::now()).expect_err("expired deadline");diff --git a/crates/macos/tests/retained_fixture.rs b/crates/macos/tests/retained_fixture.rsindex 076e70465..bb70d91f3 100644--- a/crates/macos/tests/retained_fixture.rs+++ b/crates/macos/tests/retained_fixture.rs@@ -4,7 +4,7 @@ use agent_desktop_core::{Deadline, IdentityPredicate, LocatorMaterialization, LocatorQuery, LocatorResolveRequest,LocatorSelection, ObservationOps, ObservationRoot, RefEntry, WindowFilter, resolve_query,};-use agent_desktop_macos::{MacOSAdapter, RetainedRefSession};+use agent_desktop_macos::MacOSAdapter;use std::io::{BufRead, Write};fn capture(@@ -70,7 +70,6 @@ fn read(#[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(@@ -115,7 +114,6 @@ fn retained_xcode_identity() {#[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(@@ -161,9 +159,4 @@ fn retained_fixture_identity() {stages,["initial", "filtered", "restored", "edited", "cleared"]);- drop(owner);- assert_eq!(- read(&adapter, &stable),- Err(agent_desktop_core::ErrorCode::StaleRef)- );}diff --git a/probes/macos/FINDINGS.md b/probes/macos/FINDINGS.mdnew file mode 100644index 000000000..92dc7f1f8--- /dev/null+++ b/probes/macos/FINDINGS.md@@ -0,0 +1,37 @@+# macOS platform findings++Evidence ledger for macOS accessibility behavior that the adapter relies on. Each row maps one experiment to what was observed. The probe sources for the M1 rows are in `ax-remote-token/` (`tok.c`, `scan.c`, `bench.c`, `unapproved.m`, `cover.c`, `web.c` with `rows.html`); build each with `clang -framework ApplicationServices <file>.c`.++## How to read a row++| column | meaning |+| --- | --- |+| `id` | stable row id (`M<area>-<n>`) |+| `probe` | the probe and step that produced the row |+| `scope` | `api-contract` holds for any app that exposes accessibility; `app` is specific to the measured app |+| `observed` | the measured values the conclusion rests on |+| `conclusion` | what the row establishes |++## Environment++macOS 26.4 (arm64) in a lume VM, logged-in GUI session, accessibility granted to the SSH context. Apps: the E2E fixture app (`tests/fixture-app`, SwiftUI, ref-churn view) and Finder (AppKit, list view of a folder of plain files).++## M1: durable cross-process element tokens++| id | probe | scope | observed | conclusion |+| --- | --- | --- | --- | --- |+| M1-1 | `probe.c` symbol lookup via `dlsym` | api-contract | `_AXUIElementRemoteTokenCreate` and `_AXUIElementCreateWithRemoteToken` resolve in ApplicationServices; `_AXUIElementCopyRemoteToken` and `AXUIElementCreateWithRemoteToken` do not exist | The private pair exists on macOS 26.4. It is private API: look it up at runtime and fall back when absent. |+| M1-2 | `tok.c dump`, then `tok.c resolve` in a new process, fixture rows sharing identifier `shared-title` | api-contract | Alpha token `f802…6f636f6335…` and Beta token `…36…` each resolve in a new process to the same role, identifier and value (`Alpha`, `Beta`) | A token created in one process resolves to the same element in another. Format: pid, a 4-byte tag, a per-app element id (20 bytes; Finder list rows use a 48-byte form). |+| M1-3 | fixture: filter out the Alpha row, resolve both saved tokens | api-contract | Alpha token: `kAXErrorInvalidUIElement` (-25202). Beta token: still Beta. | A removed element's token dies. It does not land on the row that shifted into its place, which is the wrong-row case that attribute matching cannot rule out. |+| M1-4 | fixture: restore rows (a new, identical Alpha), compare tokens | api-contract | new Alpha token `…44…` differs from the old `…35…`; the old token still fails with -25202 | Tokens are not reused for an identical replacement, so a dead token never resurrects onto a look-alike. |+| M1-5 | fixture: restart the app, resolve a saved token | api-contract | -25204 (cannot complete) | Tokens die with the process; the process-generation check stays as a second guard. |+| M1-6 | fixture: three unrelated list re-renders, resolve the `stable-editor` token | app | still resolves to `stable-editor` | Tokens survive re-renders of unrelated parts of a SwiftUI view. |+| M1-7 | Finder list view: `scan.c dump` (253 elements, 55 rows), add 3 files so rows re-sort and shift, `scan.c check` | app | same=252, dead=0, changed=1 (the "8 items" status text became "11 items") | Tokens keep resolving through list re-sorting and row shifts in a dense AppKit list. `scan.c` compares role and label only, so this row does not by itself prove the element behind each token is the original object; M1-3 and M1-4 do that for the fixture. |+| M1-8 | Finder: delete `delta.txt`, `scan.c check` | app | same=243, dead=9 (the deleted row's elements), changed=1 | Deleting a row kills that row's tokens, and no saved token resolved to an element with a different role or label. |+| M1-9 | Finder: rename `golf.txt` to `golf2.txt`, `scan.c check` | app | the renamed row's token resolves to the same element showing `golf2.txt` | A token follows its element through a text change; identity is the object, not its label. |+| M1-10 | `bench.c` in Finder: walk to `hotel.txt`, then resolve its token 50 times | app | tree walk 53.2 ms over 206 elements; token reconstruction plus one role read: min 0.024 ms, avg 0.028 ms | Reconstructing an element from a token is far cheaper than a tree walk. This measures the token call and one read, not the full guarded resolver, which adds process, window and role checks. |+| M1-11 | `unapproved.m`: an approved SSH context creates a token for the fixture's `stable-editor` field; an ad hoc signed app launched through LaunchServices (so TCC charges the app) receives the token, creates the element, reads its value, sets it to `poisoned-by-unapproved` and presses it | api-contract | unapproved app: `AXIsProcessTrusted=0`, element created, read -25211, set -25211, press -25211 (`kAXErrorAPIDisabled`); the field still reads `Stable value` afterwards | A token is an address, not a capability: every use still requires the caller's own Accessibility permission. Storing tokens in the session refmap grants nothing an unapproved app could not already guess, and adds no shared process that could lend permissions. |+| M1-12 | `cover.c`: walk every element of an app (children and windows), create each element's token, recreate the element from it and compare with `CFEqual` | api-contract | Finder: 685 elements, 685 tokens, 685 equal. Safari on a Wikipedia article: 417 / 417 / 417. Chrome 148 with the same article: 9906 / 9906 / 9906. Token sizes 12 to 44 bytes | Every element exposed through accessibility has a token, across AppKit, WebKit and Chromium content, and every token reconstructs the identical element. |+| M1-13 | `web.c` + `rows.html` in Chrome: capture tokens for four identical `Delete` buttons, then the page removes one row, edits another row's text, and finally re-renders the whole list with `innerHTML` | app | t0 all live; after removing Beta: Beta dead, the other three live; after the text edit: unchanged; after the full re-render: all four dead | In Chromium web content, identical twins each keep their own token, a removed node's token dies without landing on a neighbor, a text change keeps the token, and replaced DOM nodes get new elements, so refs to them become stale. |++Not yet measured: non-reuse across providers other than the fixture and Chrome web content, Electron apps, apps that rebuild their accessibility tree on every refresh, and behavior across macOS major versions. A token that dies more often only makes a ref return `STALE_REF`; it never resolves to another element.diff --git a/probes/macos/ax-remote-token/bench.c b/probes/macos/ax-remote-token/bench.cnew file mode 100644index 000000000..384ac86c0--- /dev/null+++ b/probes/macos/ax-remote-token/bench.c@@ -0,0 +1,20 @@+#include <ApplicationServices/ApplicationServices.h>+#include <stdio.h>+#include <string.h>+#include <stdlib.h>+#include <mach/mach_time.h>+extern CFDataRef _AXUIElementRemoteTokenCreate(AXUIElementRef);+extern AXUIElementRef _AXUIElementCreateWithRemoteToken(CFDataRef);+static double ms(uint64_t a,uint64_t b){ mach_timebase_info_data_t t; mach_timebase_info(&t); return (double)(b-a)*t.numer/t.denom/1e6; }+static void str(AXUIElementRef e, CFStringRef a, char *out, size_t n){ out[0]=0; CFTypeRef v=NULL; if(AXUIElementCopyAttributeValue(e,a,&v)==kAXErrorSuccess && v){ if(CFGetTypeID(v)==CFStringGetTypeID()) CFStringGetCString(v,out,n,kCFStringEncodingUTF8); CFRelease(v);} }+static AXUIElementRef found=NULL; static int visited=0;+static void find(AXUIElementRef e,const char*want,int d){ if(found||d>60) return; visited++; char v[300]; str(e,kAXValueAttribute,v,300); if(!strcmp(v,want)){CFRetain(e); found=e; return;} CFArrayRef k=NULL; if(AXUIElementCopyAttributeValue(e,kAXChildrenAttribute,(CFTypeRef*)&k)==kAXErrorSuccess&&k){ for(CFIndex i=0;i<CFArrayGetCount(k)&&!found;i++) find((AXUIElementRef)CFArrayGetValueAtIndex(k,i),want,d+1); CFRelease(k);} }+int main(int argc,char**argv){+ pid_t pid=atoi(argv[1]); AXUIElementRef app=AXUIElementCreateApplication(pid);+ uint64_t a=mach_absolute_time(); find(app,argv[2],0); uint64_t b=mach_absolute_time();+ if(!found){printf("target not found\n");return 1;}+ printf("tree walk to '%s': %.1f ms, %d elements visited\n",argv[2],ms(a,b),visited);+ CFDataRef tok=_AXUIElementRemoteTokenCreate(found);+ double best=1e9,total=0; for(int i=0;i<50;i++){ uint64_t c=mach_absolute_time(); AXUIElementRef e=_AXUIElementCreateWithRemoteToken(tok); CFTypeRef r=NULL; AXUIElementCopyAttributeValue(e,kAXRoleAttribute,&r); if(r)CFRelease(r); CFRelease(e); double t=ms(c,mach_absolute_time()); total+=t; if(t<best)best=t; }+ printf("token resolve + role read: min %.3f ms, avg %.3f ms (50 runs)\n",best,total/50);+ return 0; }diff --git a/probes/macos/ax-remote-token/cover.c b/probes/macos/ax-remote-token/cover.cnew file mode 100644index 000000000..e2e99c7fa--- /dev/null+++ b/probes/macos/ax-remote-token/cover.c@@ -0,0 +1,20 @@+#include <ApplicationServices/ApplicationServices.h>+#include <stdio.h>+#include <string.h>+#include <stdlib.h>+extern CFDataRef _AXUIElementRemoteTokenCreate(AXUIElementRef);+extern AXUIElementRef _AXUIElementCreateWithRemoteToken(CFDataRef);+static int total=0, withtok=0, roundtrip=0, mismatch=0, lens[256];+static void walk(AXUIElementRef e,int depth){+ if(depth>80||total>20000) return; total++;+ CFDataRef t=_AXUIElementRemoteTokenCreate(e);+ if(t){ withtok++; CFIndex n=CFDataGetLength(t); if(n<256) lens[n]++; AXUIElementRef b=_AXUIElementCreateWithRemoteToken(t); if(b){ if(CFEqual(b,e)) roundtrip++; else mismatch++; CFRelease(b);} else mismatch++; CFRelease(t); }+ CFArrayRef k=NULL; if(AXUIElementCopyAttributeValue(e,kAXChildrenAttribute,(CFTypeRef*)&k)==kAXErrorSuccess&&k){ for(CFIndex i=0;i<CFArrayGetCount(k);i++) walk((AXUIElementRef)CFArrayGetValueAtIndex(k,i),depth+1); CFRelease(k);} }+int main(int argc,char**argv){+ AXUIElementRef app=AXUIElementCreateApplication(atoi(argv[1]));+ AXUIElementSetAttributeValue(app,CFSTR("AXEnhancedUserInterface"),kCFBooleanTrue);+ AXUIElementSetAttributeValue(app,CFSTR("AXManualAccessibility"),kCFBooleanTrue);+ walk(app,0);+ CFArrayRef w=NULL; if(AXUIElementCopyAttributeValue(app,kAXWindowsAttribute,(CFTypeRef*)&w)==kAXErrorSuccess&&w){ printf("windows=%ld ",CFArrayGetCount(w)); for(CFIndex i=0;i<CFArrayGetCount(w);i++) walk((AXUIElementRef)CFArrayGetValueAtIndex(w,i),1); CFRelease(w);} else printf("windows=none ");+ printf("elements=%d with_token=%d (%.1f%%) roundtrip_equal=%d mismatch=%d token_sizes:",total,withtok,total?100.0*withtok/total:0,roundtrip,mismatch);+ for(int i=0;i<256;i++) if(lens[i]) printf(" %dB=%d",i,lens[i]); printf("\n"); return 0; }diff --git a/probes/macos/ax-remote-token/rows.html b/probes/macos/ax-remote-token/rows.htmlnew file mode 100644index 000000000..6db459156--- /dev/null+++ b/probes/macos/ax-remote-token/rows.html@@ -0,0 +1,9 @@+<!doctype html><html><body><h1>POC rows</h1><ul id="list"></ul><p id="status">phase0</p>+<script>+const list=document.getElementById('list'),status=document.getElementById('status');+function render(){list.innerHTML='';['Alpha','Beta','Gamma','Delta'].forEach(n=>{const li=document.createElement('li');li.id='row-'+n;li.innerHTML='<span>'+n+'</span> <button>Delete</button>';list.appendChild(li);});}+render();+setTimeout(()=>{document.getElementById('row-Beta').remove();status.textContent='phase1 removed Beta';},6000);+setTimeout(()=>{document.querySelector('#row-Gamma span').textContent='Gamma edited';status.textContent='phase2 edited Gamma';},12000);+setTimeout(()=>{render();status.textContent='phase3 re-rendered all';},18000);+</script></body></html>diff --git a/probes/macos/ax-remote-token/scan.c b/probes/macos/ax-remote-token/scan.cnew file mode 100644index 000000000..9973fb41b--- /dev/null+++ b/probes/macos/ax-remote-token/scan.c@@ -0,0 +1,18 @@+#include <ApplicationServices/ApplicationServices.h>+#include <stdio.h>+#include <string.h>+#include <stdlib.h>+extern CFDataRef _AXUIElementRemoteTokenCreate(AXUIElementRef);+extern AXUIElementRef _AXUIElementCreateWithRemoteToken(CFDataRef);+static void str(AXUIElementRef e, CFStringRef a, char *out, size_t n){ out[0]=0; CFTypeRef v=NULL; if(AXUIElementCopyAttributeValue(e,a,&v)==kAXErrorSuccess && v){ if(CFGetTypeID(v)==CFStringGetTypeID()) CFStringGetCString(v,out,n,kCFStringEncodingUTF8); CFRelease(v);} }+static void label(AXUIElementRef e, char *out, size_t n){ char t[200],v[200],d[200]; str(e,kAXTitleAttribute,t,200); str(e,kAXValueAttribute,v,200); str(e,kAXDescriptionAttribute,d,200); snprintf(out,n,"%s/%s/%s",t,v,d); for(char*p=out;*p;p++) if(*p=='|'||*p=='\n') *p=' '; }+static int count=0;+static void walk(AXUIElementRef e,int depth,int max){+ if(depth>max||count>4000) return; char role[64]; str(e,kAXRoleAttribute,role,64);+ if(!strcmp(role,"AXRow")||!strcmp(role,"AXCell")||!strcmp(role,"AXStaticText")||!strcmp(role,"AXButton")||!strcmp(role,"AXTextField")){+ char l[600]; label(e,l,600); CFDataRef t=_AXUIElementRemoteTokenCreate(e); printf("%s|%s|",role,l); if(t){const UInt8*b=CFDataGetBytePtr(t); for(CFIndex i=0;i<CFDataGetLength(t);i++) printf("%02x",b[i]); CFRelease(t);} printf("\n"); count++; }+ CFArrayRef kids=NULL; if(AXUIElementCopyAttributeValue(e,kAXChildrenAttribute,(CFTypeRef*)&kids)==kAXErrorSuccess&&kids){ for(CFIndex i=0;i<CFArrayGetCount(kids);i++) walk((AXUIElementRef)CFArrayGetValueAtIndex(kids,i),depth+1,max); CFRelease(kids);} }+int main(int argc,char**argv){+ if(!strcmp(argv[1],"dump")){ walk(AXUIElementCreateApplication(atoi(argv[2])),0,60); return 0; }+ if(!strcmp(argv[1],"check")){ FILE*f=fopen(argv[2],"r"); char line[2000]; int same=0,dead=0,changed=0; while(fgets(line,sizeof line,f)){ char*role=strtok(line,"|"); char*lab=strtok(NULL,"|"); char*tok=strtok(NULL,"|\n"); if(!tok||!lab) continue; size_t n=strlen(tok)/2; UInt8*buf=malloc(n); for(size_t i=0;i<n;i++) sscanf(tok+2*i,"%2hhx",&buf[i]); CFDataRef d=CFDataCreate(NULL,buf,n); AXUIElementRef e=_AXUIElementCreateWithRemoteToken(d); CFTypeRef v=NULL; AXError err=e?AXUIElementCopyAttributeValue(e,kAXRoleAttribute,&v):-1; if(v)CFRelease(v); if(err!=kAXErrorSuccess){dead++; continue;} char r2[64],l2[600]; str(e,kAXRoleAttribute,r2,64); label(e,l2,600); if(strcmp(r2,role)||strcmp(l2,lab)){changed++; printf("CHANGED %s [%s] -> %s [%s]\n",role,lab,r2,l2);} else same++; free(buf);} printf("same=%d dead=%d changed=%d\n",same,dead,changed); return 0; }+ return 2; }diff --git a/probes/macos/ax-remote-token/tok.c b/probes/macos/ax-remote-token/tok.cnew file mode 100644index 000000000..9b5b524c9--- /dev/null+++ b/probes/macos/ax-remote-token/tok.c@@ -0,0 +1,22 @@+#include <ApplicationServices/ApplicationServices.h>+#include <stdio.h>+#include <string.h>+#include <stdlib.h>+extern CFDataRef _AXUIElementRemoteTokenCreate(AXUIElementRef);+extern AXUIElementRef _AXUIElementCreateWithRemoteToken(CFDataRef);+static void str(AXUIElementRef e, CFStringRef a, char *out, size_t n){ out[0]=0; CFTypeRef v=NULL; if(AXUIElementCopyAttributeValue(e,a,&v)==kAXErrorSuccess && v){ if(CFGetTypeID(v)==CFStringGetTypeID()) CFStringGetCString(v,out,n,kCFStringEncodingUTF8); CFRelease(v);} }+static void hex(CFDataRef d){ const UInt8*b=CFDataGetBytePtr(d); for(CFIndex i=0;i<CFDataGetLength(d);i++) printf("%02x",b[i]); }+static void walk(AXUIElementRef e, const char *want, int depth){+ if(depth>40) return;+ char id[256]; str(e,kAXIdentifierAttribute,id,sizeof id);+ if((want[0]=='*' || strcmp(id,want)==0) && id[0]){ char role[64],val[256]; str(e,kAXRoleAttribute,role,sizeof role); str(e,kAXValueAttribute,val,sizeof val); CFDataRef t=_AXUIElementRemoteTokenCreate(e); printf("%s|%s|%s|",id,role,val); if(t){hex(t); CFRelease(t);} else printf("NOTOKEN"); printf("\n"); }+ CFArrayRef kids=NULL; if(AXUIElementCopyAttributeValue(e,kAXChildrenAttribute,(CFTypeRef*)&kids)==kAXErrorSuccess && kids){ for(CFIndex i=0;i<CFArrayGetCount(kids);i++) walk((AXUIElementRef)CFArrayGetValueAtIndex(kids,i),want,depth+1); CFRelease(kids);} }+static AXUIElementRef find(AXUIElementRef e, const char *want, int depth){+ if(depth>40) return NULL; char id[256]; str(e,kAXIdentifierAttribute,id,sizeof id); if(strcmp(id,want)==0){CFRetain(e); return e;}+ CFArrayRef kids=NULL; AXUIElementRef r=NULL; if(AXUIElementCopyAttributeValue(e,kAXChildrenAttribute,(CFTypeRef*)&kids)==kAXErrorSuccess && kids){ for(CFIndex i=0;i<CFArrayGetCount(kids)&&!r;i++) r=find((AXUIElementRef)CFArrayGetValueAtIndex(kids,i),want,depth+1); CFRelease(kids);} return r; }+int main(int argc,char**argv){+ if(argc<3){fprintf(stderr,"usage\n");return 2;}+ if(!strcmp(argv[1],"dump")){ AXUIElementRef app=AXUIElementCreateApplication(atoi(argv[2])); walk(app,argc>3?argv[3]:"*",0); return 0; }+ if(!strcmp(argv[1],"press")){ AXUIElementRef app=AXUIElementCreateApplication(atoi(argv[2])); AXUIElementRef b=find(app,argv[3],0); if(!b){printf("press: not found\n");return 1;} printf("press: %d\n",AXUIElementPerformAction(b,kAXPressAction)); return 0; }+ if(!strcmp(argv[1],"resolve")){ size_t n=strlen(argv[2])/2; UInt8*buf=malloc(n); for(size_t i=0;i<n;i++) sscanf(argv[2]+2*i,"%2hhx",&buf[i]); CFDataRef d=CFDataCreate(NULL,buf,n); AXUIElementRef e=_AXUIElementCreateWithRemoteToken(d); if(!e){printf("resolve: NULL element\n");return 1;} char role[64],id[256],val[256]; CFTypeRef v=NULL; AXError err=AXUIElementCopyAttributeValue(e,kAXRoleAttribute,&v); if(v)CFRelease(v); str(e,kAXRoleAttribute,role,sizeof role); str(e,kAXIdentifierAttribute,id,sizeof id); str(e,kAXValueAttribute,val,sizeof val); pid_t p=0; AXUIElementGetPid(e,&p); printf("resolve: err=%d pid=%d role=%s id=%s value=%s\n",err,p,role,id,val); return 0; }+ return 2; }diff --git a/probes/macos/ax-remote-token/unapproved.m b/probes/macos/ax-remote-token/unapproved.mnew file mode 100644index 000000000..ef67baa14--- /dev/null+++ b/probes/macos/ax-remote-token/unapproved.m@@ -0,0 +1,27 @@+#import <Cocoa/Cocoa.h>+#import <ApplicationServices/ApplicationServices.h>+extern AXUIElementRef _AXUIElementCreateWithRemoteToken(CFDataRef);+@interface R : NSObject <NSApplicationDelegate> @end+@implementation R+- (void)applicationDidFinishLaunching:(NSNotification *)n {+ NSArray *a = NSProcessInfo.processInfo.arguments;+ NSString *hex = a.count > 1 ? a[1] : @""; NSString *out = a.count > 2 ? a[2] : @"/tmp/poc-unapproved.txt";+ NSMutableData *d = [NSMutableData data];+ for (NSUInteger i = 0; i + 1 < hex.length; i += 2) { unsigned b; sscanf([[hex substringWithRange:NSMakeRange(i,2)] UTF8String], "%2x", &b); uint8_t c = b; [d appendBytes:&c length:1]; }+ NSMutableString *r = [NSMutableString string];+ [r appendFormat:@"AXIsProcessTrusted=%d\n", AXIsProcessTrusted()];+ AXUIElementRef e = _AXUIElementCreateWithRemoteToken((__bridge CFDataRef)d);+ [r appendFormat:@"element_created=%d\n", e != NULL];+ if (e) {+ CFTypeRef v = NULL; AXError err = AXUIElementCopyAttributeValue(e, kAXValueAttribute, &v);+ [r appendFormat:@"read_value_err=%d value=%@\n", err, err == 0 ? (__bridge id)v : @"-"];+ AXError s = AXUIElementSetAttributeValue(e, kAXValueAttribute, CFSTR("poisoned-by-unapproved"));+ [r appendFormat:@"set_value_err=%d\n", s];+ AXError p = AXUIElementPerformAction(e, kAXPressAction);+ [r appendFormat:@"press_err=%d\n", p];+ }+ [r writeToFile:out atomically:YES encoding:NSUTF8StringEncoding error:nil];+ [NSApp terminate:nil];+}+@end+int main(void){ @autoreleasepool { NSApplication *app=[NSApplication sharedApplication]; R *d=[R new]; app.delegate=d; [app run]; } return 0; }diff --git a/probes/macos/ax-remote-token/web.c b/probes/macos/ax-remote-token/web.cnew file mode 100644index 000000000..4b7448c30--- /dev/null+++ b/probes/macos/ax-remote-token/web.c@@ -0,0 +1,15 @@+#include <ApplicationServices/ApplicationServices.h>+#include <stdio.h>+#include <string.h>+#include <stdlib.h>+extern CFDataRef _AXUIElementRemoteTokenCreate(AXUIElementRef);+extern AXUIElementRef _AXUIElementCreateWithRemoteToken(CFDataRef);+static void str(AXUIElementRef e, CFStringRef a, char *o, size_t n){ o[0]=0; CFTypeRef v=NULL; if(AXUIElementCopyAttributeValue(e,a,&v)==kAXErrorSuccess&&v){ if(CFGetTypeID(v)==CFStringGetTypeID()) CFStringGetCString(v,o,n,kCFStringEncodingUTF8); CFRelease(v);} }+static CFDataRef toks[64]; static char labels[64][64]; static int nt=0; static AXUIElementRef lastText=NULL;+static void walk(AXUIElementRef e,int d){ if(d>60) return; char role[64],title[128],val[128]; str(e,kAXRoleAttribute,role,64); str(e,kAXTitleAttribute,title,128); str(e,kAXValueAttribute,val,128);+ if(!strcmp(role,"AXStaticText") && (!strcmp(val,"Alpha")||!strcmp(val,"Beta")||!strcmp(val,"Gamma")||!strcmp(val,"Delta"))) { lastText=e; }+ if(!strcmp(role,"AXButton") && strstr(title,"Delete") && lastText && nt<64){ char lab[64]; str(lastText,kAXValueAttribute,lab,64); snprintf(labels[nt],64,"Delete(%s)",lab); toks[nt++]=_AXUIElementRemoteTokenCreate(e); }+ CFArrayRef k=NULL; if(AXUIElementCopyAttributeValue(e,kAXChildrenAttribute,(CFTypeRef*)&k)==kAXErrorSuccess&&k){ for(CFIndex i=0;i<CFArrayGetCount(k);i++) walk((AXUIElementRef)CFArrayGetValueAtIndex(k,i),d+1); CFRelease(k);} }+static void check(const char*phase){ printf("%s:",phase); for(int i=0;i<nt;i++){ AXUIElementRef e=_AXUIElementCreateWithRemoteToken(toks[i]); char t[128]=""; CFTypeRef v=NULL; AXError err=e?AXUIElementCopyAttributeValue(e,kAXRoleAttribute,&v):-1; if(v)CFRelease(v); if(e) str(e,kAXTitleAttribute,t,128); printf(" %s=%s",labels[i],err==0?"live":"DEAD"); if(e)CFRelease(e);} printf("\n"); fflush(stdout); }+int main(int argc,char**argv){ AXUIElementRef app=AXUIElementCreateApplication(atoi(argv[1])); CFArrayRef w=NULL; AXUIElementCopyAttributeValue(app,kAXWindowsAttribute,(CFTypeRef*)&w); if(w){ for(CFIndex i=0;i<CFArrayGetCount(w);i++) walk((AXUIElementRef)CFArrayGetValueAtIndex(w,i),0);} printf("captured %d Delete buttons\n",nt);+ check("t0 captured"); sleep(7); check("t1 after Beta removed"); sleep(6); check("t2 after Gamma text edit"); sleep(6); check("t3 after full re-render"); return 0; }diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.mdindex c1ae3b4f8..eb732c5fc 100644--- a/skills/agent-desktop-macos/SKILL.md+++ b/skills/agent-desktop-macos/SKILL.md@@ -49,7 +49,7 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,**Identity.** `launch` accepts a display name (`"System Settings"`) or a bundle ID (`com.apple.systempreferences`). Other commands take the display name through `--app`. Window IDs such as `w-4521` stay valid for the life of the window. Find them with `list-windows`.-**Repeated collections.** A ref to a row in a list whose rows share an accessibility identifier can act on another row after the list changes. Take a new snapshot after the list changes.+**Refs follow their element.** A ref stores the element's own accessibility address. If the element is removed or the app restarts, the ref returns `STALE_REF`; it never lands on a look-alike. Identical controls, such as several `Delete` buttons, each keep their own ref.**Keys.** The primary modifier is `cmd`: `press cmd+c`, `press cmd+s`. Quit shortcuts such as `cmd+q`, `cmd+shift+q`, `cmd+alt+esc`, `ctrl+cmd+q` and `cmd+shift+delete` return `POLICY_DENIED` unless you pass `--force`. To quit an app, use `close-app`. Punctuation keys work in combos, as the symbol (`,` `.` `/` `;` `'` `[` `]` `\` `-` `=` `` ` ``) or by name (`comma`, `period`, `slash`, `semicolon`, `quote`, `leftbracket`, `rightbracket`, `backslash`, `minus`, `equal`, `grave`). Each one is sent with the key that types it in the active keyboard layout, so `press cmd+,` opens Settings on ANSI and JIS keyboards alike.diff --git a/tests/e2e/scenarios/error_contract.sh b/tests/e2e/scenarios/error_contract.shindex 0ae12876e..c394a21ed 100644--- a/tests/e2e/scenarios/error_contract.sh+++ b/tests/e2e/scenarios/error_contract.sh@@ -23,7 +23,7 @@ error_contract_suite() {skipmsg "APP_NOT_FOUND carries the list-apps recovery hint: $DUPLICATE_PID_DEFECT"elseassert "APP_NOT_FOUND carries the list-apps recovery hint" \- "$(case "$(json_field "$RUN_JSON" error.suggestion)" in *list-apps*) echo 1 ;; *) echo 0 ;; esac)" \+ "$(json_field "$RUN_JSON" error.suggestion | grep -q list-apps && echo 1 || echo 0)" \"suggestion=$(json_field "$RUN_JSON" error.suggestion)"assert_error_envelope "unknown app is APP_NOT_FOUND" APP_NOT_FOUND 1 not_delivered \snapshot --app NoSuchApp12345 -idiff --git a/tests/e2e/scenarios/ref_churn.sh b/tests/e2e/scenarios/ref_churn.shindex f861f4515..0a2d089da 100644--- a/tests/e2e/scenarios/ref_churn.sh+++ b/tests/e2e/scenarios/ref_churn.sh@@ -9,10 +9,26 @@ require_target_by_id alpha textfield shared-titlerequire_target_by_id stable textfield stable-editoract_target "$filter" click >/dev/null 2>&1"$bin" wait --text "Restore rows" --app "$app" --timeout 5000 >/dev/null 2>&1-duplicate_identifier_note="known limitation: a removed row's ref can resolve to the surviving row that shares shared-title"-skipmsg "removed row is refused without delivery: $duplicate_identifier_note"-skipmsg "batch also refuses the removed row without delivery: $duplicate_identifier_note"-skipmsg "surviving row kept its value: $duplicate_identifier_note"+output="$("$bin" set-value "$(target_ref "$alpha")" poisoned 2>/dev/null)"+ok="$(json_field "$output" ok)"+code="$(json_field "$output" error.code)"+delivery="$(json_field "$output" error.disposition.delivery)"+assert "removed row is refused without delivery" \+ "$([ "$ok" = "False" ] && [ "$code" = "STALE_REF" ] && [ "$delivery" = "not_delivered" ] && echo 1 || echo 0)" \+ "ok=$ok code=$code delivery=$delivery"+batch_payload="$(python3 - "$(target_ref "$alpha")" <<'BATCH_PY'+import json, sys+print(json.dumps([{"command": "set-value", "args": {"ref_id": sys.argv[1], "value": "poisoned"}}]))+BATCH_PY+)"+batch_output="$("$bin" batch "$batch_payload" 2>/dev/null)"+assert "batch also refuses the removed row without delivery" \+ "$([ "$(json_field "$batch_output" data.results.0.error.code)" = "STALE_REF" ] && [ "$(json_field "$batch_output" data.results.0.error.disposition.delivery)" = "not_delivered" ] && echo 1 || echo 0)" \+ "code=$(json_field "$batch_output" data.results.0.error.code)"+beta_seen="$("$bin" wait --text "Beta stored: Beta" --app "$app" --timeout 3000 2>/dev/null)"+assert "surviving row kept its value" \+ "$([ "$(json_field "$beta_seen" data.found)" = "True" ] && echo 1 || echo 0)" \+ "found=$(json_field "$beta_seen" data.found)"stable_write="$("$bin" set-value "$(target_ref "$stable")" stable-ok 2>/dev/null)"stable_seen="$(wait_target "$stable" value 3000 --value stable-ok 2>/dev/null)"assert "unchanged editor remains editable through its ref" \