Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
fix: return observed trees and stop demanding renderer activation from shallow walks (#117)
Lahfir32175e44c553
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6193948a4..feee51c1c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -286,7 +286,7 @@ Every command produces a response envelope:```json{- "version": "2.1",+ "version": "2.2","ok": true,"command": "snapshot","data": {@@ -302,7 +302,7 @@ Error responses:```json{- "version": "2.1",+ "version": "2.2","ok": false,"command": "click","error": {@@ -339,6 +339,7 @@ The `error` object may also carry optional `details` and `recovery` objects. Ver- Static text and non-actionable groups/containers do NOT get refs (they remain in tree for context)- Refs are deterministic within a snapshot but NOT stable across snapshots if UI changed- Snapshot refs are stored by snapshot ID under `~/.agent-desktop/snapshots/{snapshot_id}/refmap.json`, with a `latest_snapshot_id` pointer for commands that omit `--snapshot`+- Retention keeps the newest 128 snapshots per namespace and evicts down to 96, so the sort-and-stat pass is amortised instead of running on every save. Refs are invalidated by the next UI change, so retention only has to cover one interaction's drill-downs. Per R7/KTD5 of the session-first trace plan, a `snapshot_id` referenced by an *older* trace event may therefore no longer resolve to a full tree; `ArtifactsMode::Full` is the recorded mitigation because it copies each refmap into `<session>/trace/refmaps/`- `~/.agent-desktop/last_refmap.json` is written only as a latest-snapshot inspection artifact; command code must use `RefStore`- Action commands use strict re-identification from platform-neutral `RefEntry` evidence: pid, role, path/source surface, role-conditional stable text identity, and bounds hash. Mutable control values are volatile and must not be treated as stable text identity. Return `STALE_REF` on mismatch and `AMBIGUOUS_TARGET` when multiple plausible live candidates remain.- Progressive traversal: `--skeleton` clamps depth to 3, annotates truncated containers with `children_count`. Named/described containers at boundary receive refs as drill-down targetsdiff --git a/CONCEPTS.md b/CONCEPTS.mdindex 28512a08b..c2cd4a70a 100644--- a/CONCEPTS.md+++ b/CONCEPTS.md@@ -19,6 +19,11 @@ A scoped UI layer that can be observed separately from the whole window, such as### Drill-downA snapshot operation that starts from an existing ref to observe that element's subtree instead of re-reading the entire window.+### Partial Observation+A snapshot that ran out of its allotted time before finishing the tree and returns what it did observe rather than discarding the walk.++Completeness is reported on the observation as a whole and on each node whose descendants were cut, so a reader can walk from the root to the boundary. A depth clamp knows how many children it skipped and says so; budget exhaustion cannot afford that count and marks the node without one. Only a full snapshot may be partial — a drill-down replaces refs inside an existing map, so it requires a complete observation and fails rather than destroying descendants it cannot re-allocate.+## Refs And Identity### Ref@@ -78,13 +83,23 @@ The refusal is enforced where the close happens, so CLI, FFI, and any future con### ActionabilityThe pre-dispatch judgement that a resolved element is safe to act on, based on native evidence such as visibility, stability, enabled state, supported action, policy, and editability.+### Delivery Semantics+What a failed or uncertain action says about whether input actually reached the application, and therefore whether repeating it is safe.++The distinction that matters is not success versus failure but delivered versus not: an action that never reached the target can be retried freely, while one that may have landed cannot be repeated without risking a duplicate. Verification is a third axis — an action can be known-delivered yet unverified, meaning the input was posted but its effect was not confirmed. Errors carry this alongside the recovery hint so a caller never has to infer retry safety from an error code.++### Interaction Lease+Machine-wide exclusivity over desktop input, held by one process at a time so concurrent callers cannot interleave synthetic input into each other's actions.++The lease covers dispatch only, never the waiting that precedes it: waiting for an element to become actionable can run long, and holding exclusivity across it would serialize every caller on the machine. Anything resolved while waiting was therefore observed without exclusivity and is re-resolved once the lease is held. That second resolution is the correctness boundary, not redundant work.+### Capability VocabularyThe platform-neutral set of supported action names that core uses to compare command intent with native adapter evidence.Each adapter maps native primitives into this shared vocabulary before core evaluates actionability. New commands should extend the central vocabulary first, then reuse it from actionability, ref allocation, predicates, FFI tests, and platform adapters.### Interaction Policy-The side-effect contract attached to an action request, controlling whether the command may steal focus, move the cursor, or use physical input. Ref commands expose exactly two modes: **headless** (the default — accessibility-only, no cursor, fails closed when the semantic path is unavailable) and **headed** (opt-in via the global `--headed` flag — authorizes the action's declared focus and cursor preconditions).+The side-effect contract attached to an action request, controlling whether the command may steal focus, move the cursor, or use physical input. The CLI exposes two: **headless** (the default — accessibility-only, no cursor, fails closed when the semantic path is unavailable) and **headed** (opt-in via the global `--headed` flag — authorizes the action's declared focus and cursor preconditions). A third, **focus fallback**, sits between them: it permits focus but not cursor movement. It is not reachable from the CLI flag — it is the base policy of an explicit key press, and language bindings may select it directly.Core owns those preconditions through `HeadedRequirement`: `FocusedWindow` for keyboard or focus-sensitive work, and `FocusedWindowAndCursor` for pointer delivery. For ref actions, core focuses the exact source window before dispatch and resolves a verified target point for pointer work; the platform adapter owns the OS-specific focus primitive and delivery mechanism. Raw coordinate input has no ref identity, so it never infers or focuses a window. On macOS, headed `click`, `right-click`, `type`, `clear`, and `scroll` are physical-first; double/triple-click, hover, and drag are physical-only; expand/collapse and the remaining semantic actions stay semantic after the core focus precondition.diff --git a/crates/core/src/commands/find_tests.rs b/crates/core/src/commands/find_tests.rsindex 4d488bc45..fbaef50a0 100644--- a/crates/core/src/commands/find_tests.rs+++ b/crates/core/src/commands/find_tests.rs@@ -15,6 +15,7 @@ fn node(name: Option<&str>, value: Option<&str>, description: Option<&str>) -> A},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}}@@ -102,6 +103,7 @@ fn default_limit_caps_materialized_matches() {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: (0..60).map(|i| node(Some(&format!("Button {i}")), None, None)).collect(),@@ -149,6 +151,7 @@ fn count_matches_does_not_build_result_json() {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![node(Some("Save"), None, None),node(Some("Cancel"), None, None),diff --git a/crates/core/src/commands/helpers_ref_action_wait_tests.rs b/crates/core/src/commands/helpers_ref_action_wait_tests.rsindex 3a66b0b07..417179f8e 100644--- a/crates/core/src/commands/helpers_ref_action_wait_tests.rs+++ b/crates/core/src/commands/helpers_ref_action_wait_tests.rs@@ -61,6 +61,7 @@ impl ObservationOps for ScopedWaitAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],},)@@ -109,6 +110,7 @@ impl ObservationOps for ScopedWaitAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],})}@@ -202,6 +204,7 @@ impl ObservationOps for MultiWindowAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}).into_iter()@@ -217,6 +220,7 @@ impl ObservationOps for MultiWindowAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children,},)@@ -279,6 +283,7 @@ impl ObservationOps for MultiWindowAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}]} else {@@ -293,6 +298,7 @@ impl ObservationOps for MultiWindowAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children,})}diff --git a/crates/core/src/commands/is_check.rs b/crates/core/src/commands/is_check.rsindex 1aaf2dee3..914d5d896 100644--- a/crates/core/src/commands/is_check.rs+++ b/crates/core/src/commands/is_check.rs@@ -45,41 +45,38 @@ pub fn execute(.clone().unwrap_or_else(|| state_from_ref_entry(&entry));let states_from_live = live_state.is_some();- let live_bounds = optional_live_read(adapter.get_element_bounds(&handle, deadline))?;- let visibility = VisibilityEvidence {- bounds: live_bounds.or(entry.geometry.bounds),- states: state.states.clone(),- bounds_from_live: live_bounds.is_some(),- states_from_live,- };- let applicable = match args.property {- IsProperty::Visible => visibility.applicable(),- IsProperty::Enabled | IsProperty::Focused => true,- IsProperty::Checked => {+ let (applicable, result) = match args.property {+ IsProperty::Visible => {+ let live_bounds = optional_live_read(adapter.get_element_bounds(&handle, deadline))?;+ let visibility = VisibilityEvidence {+ bounds: live_bounds.or(entry.geometry.bounds),+ states: state.states.clone(),+ bounds_from_live: live_bounds.is_some(),+ states_from_live,+ };+ (visibility.applicable(), visibility.result())+ }+ IsProperty::Enabled => (true, !state::has_state(&state.states, DISABLED)),+ IsProperty::Focused => (true, state::has_state(&state.states, FOCUSED)),+ IsProperty::Checked => (crate::roles::is_toggleable_role(&entry.identity.role)|| state::has_state(&state.states, CHECKED)|| crate::capability::contains_any(&entry.capabilities.available_actions,crate::capability::CHECKED_APPLICABILITY,- )- }- IsProperty::Expanded => {+ ),+ state::has_state(&state.states, CHECKED),+ ),+ IsProperty::Expanded => (crate::roles::is_expandable_role(&entry.identity.role)|| state::has_state(&state.states, EXPANDED)|| crate::capability::contains_any(&entry.capabilities.available_actions,crate::capability::EXPANDED_APPLICABILITY,- )- }- };-- let result = match args.property {- IsProperty::Visible => visibility.result(),- IsProperty::Enabled => !state::has_state(&state.states, DISABLED),- IsProperty::Checked => state::has_state(&state.states, CHECKED),- IsProperty::Focused => state::has_state(&state.states, FOCUSED),- IsProperty::Expanded => state::has_state(&state.states, EXPANDED),+ ),+ state::has_state(&state.states, EXPANDED),+ ),};Ok(diff --git a/crates/core/src/commands/query_tests.rs b/crates/core/src/commands/query_tests.rsindex dd347f180..13681376d 100644--- a/crates/core/src/commands/query_tests.rs+++ b/crates/core/src/commands/query_tests.rs@@ -12,6 +12,7 @@ fn node(role: &str, name: Option<&str>, value: Option<&str>) -> AccessibilityNod},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/commands/right_click_tests.rs b/crates/core/src/commands/right_click_tests.rsindex a666c05ca..937cc8058 100644--- a/crates/core/src/commands/right_click_tests.rs+++ b/crates/core/src/commands/right_click_tests.rs@@ -70,6 +70,7 @@ impl ObservationOps for ProbeFailingAdapter {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: Vec::new(),})}diff --git a/crates/core/src/commands/snapshot.rs b/crates/core/src/commands/snapshot.rsindex 69e9e3d31..7ac0cc176 100644--- a/crates/core/src/commands/snapshot.rs+++ b/crates/core/src/commands/snapshot.rs@@ -163,8 +163,13 @@ pub(crate) fn format_snapshot_fields(},"ref_count": ref_count,"snapshot_id": result.snapshot_id,+ "complete": result.complete,"tree": tree});+ if !result.complete {+ body["truncated"] = json!(true);+ body["nodes_observed"] = json!(result.nodes_observed);+ }if let Some(ms) = elapsed_ms {body["elapsed_ms"] = json!(ms);}diff --git a/crates/core/src/commands/snapshot_tests.rs b/crates/core/src/commands/snapshot_tests.rsindex 280288dce..6a3d30b52 100644--- a/crates/core/src/commands/snapshot_tests.rs+++ b/crates/core/src/commands/snapshot_tests.rs@@ -44,6 +44,7 @@ impl ObservationOps for WaitSnapshotAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![AccessibilityNode {ref_id: None,@@ -54,6 +55,7 @@ impl ObservationOps for WaitSnapshotAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],},AccessibilityNode {@@ -73,6 +75,7 @@ impl ObservationOps for WaitSnapshotAdapter {..Default::default()},children_count: None,+ subtree_truncated: false,children: vec![],},],@@ -114,6 +117,7 @@ impl ObservationOps for WaitSnapshotAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![AccessibilityNode {ref_id: None,role: "button".into(),@@ -123,6 +127,7 @@ impl ObservationOps for WaitSnapshotAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}],})diff --git a/crates/core/src/commands/wait_scenario_tests.rs b/crates/core/src/commands/wait_scenario_tests.rsindex 066c0b45c..34117f15b 100644--- a/crates/core/src/commands/wait_scenario_tests.rs+++ b/crates/core/src/commands/wait_scenario_tests.rs@@ -22,6 +22,7 @@ impl ObservationOps for TextlessTreeAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],},)@@ -61,6 +62,7 @@ impl ObservationOps for TextlessTreeAdapter {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],})}diff --git a/crates/core/src/commands/wait_selector_tests.rs b/crates/core/src/commands/wait_selector_tests.rsindex 5aa3a3bf8..57fc08cb3 100644--- a/crates/core/src/commands/wait_selector_tests.rs+++ b/crates/core/src/commands/wait_selector_tests.rs@@ -16,6 +16,7 @@ fn window_node(children: Vec<AccessibilityNode>) -> AccessibilityNode {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children,}}@@ -30,6 +31,7 @@ fn button_node(label: &str) -> AccessibilityNode {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/commands/wait_text_match.rs b/crates/core/src/commands/wait_text_match.rsindex bbfbde218..dfd272fcd 100644--- a/crates/core/src/commands/wait_text_match.rs+++ b/crates/core/src/commands/wait_text_match.rs@@ -54,6 +54,7 @@ mod tests {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children,}}diff --git a/crates/core/src/live_locator/observed_tree.rs b/crates/core/src/live_locator/observed_tree.rsindex 8fba46437..4604523f4 100644--- a/crates/core/src/live_locator/observed_tree.rs+++ b/crates/core/src/live_locator/observed_tree.rs@@ -74,6 +74,26 @@ impl ObservedTree {self.project(self.roots[0] as usize)}+ /// Projects whatever was observed and reports its completeness, rather than+ /// discarding an entire walk because the budget expired before the last+ /// node. Callers that need an all-or-nothing tree keep using+ /// `into_accessibility_tree`. The observation layer already annotates each+ /// truncated container with `children_count`, so a partial tree stays+ /// honest about its own boundaries.+ pub fn into_accessibility_tree_partial(+ self,+ ) -> Result<(AccessibilityNode, bool, usize), AdapterError> {+ if self.roots.len() != 1 {+ return Err(AdapterError::internal(+ "accessibility projection requires exactly one root",+ ));+ }+ let complete = self.structurally_complete;+ let nodes_observed = self.nodes.len();+ let tree = self.project(self.roots[0] as usize)?;+ Ok((tree, complete, nodes_observed))+ }+fn append(&mut self, subtree: ObservedSubtree, path: RefPath) -> Result<u32, AdapterError> {let index = u32::try_from(self.nodes.len()).map_err(|_| AdapterError::internal("observed tree exceeds u32"))?;@@ -152,6 +172,7 @@ impl ObservedTree {bounds: node.evidence.ref_evidence.bounds.known().copied(),},children_count: node.children_count,+ subtree_truncated: !node.completeness.subtree_complete,children,})}diff --git a/crates/core/src/live_locator/observed_tree_tests.rs b/crates/core/src/live_locator/observed_tree_tests.rsindex edbd1083a..7b2dd0b7e 100644--- a/crates/core/src/live_locator/observed_tree_tests.rs+++ b/crates/core/src/live_locator/observed_tree_tests.rs@@ -152,3 +152,64 @@ fn identifier_evidence_preserves_preference_without_platform_names() {assert_eq!(identifiers.preferred_value(), Some("automation-id"));assert!(identifiers.is_complete());}++#[test]+fn partial_projection_returns_the_observed_subtree_instead_of_discarding_it() {+ let incomplete =+ ObservedSubtree::new(evidence("button", Some("Save")), Vec::new(), false, None);+ let tree = ObservedTree::from_roots(+ vec![subtree("window", "Fixture", vec![incomplete])],+ source(),+ Default::default(),+ true,+ )+ .unwrap();+ let observed = tree.node_count();++ assert!(tree.clone().into_accessibility_tree().is_err());++ let (projected, complete, nodes_observed) = tree.into_accessibility_tree_partial().unwrap();++ assert!(!complete);+ assert_eq!(nodes_observed, observed);+ assert_eq!(projected.role, "window");+ assert_eq!(projected.children.len(), 1);+ assert_eq!(projected.children[0].identity.name.as_deref(), Some("Save"));++ assert!(+ projected.children[0].subtree_truncated,+ "the node whose descendants were cut must carry a boundary marker"+ );+ assert!(+ projected.subtree_truncated,+ "truncation must propagate to ancestors so a caller can walk to the cut"+ );+}++#[test]+fn partial_projection_reports_completeness_when_the_walk_finished() {+ let tree = ObservedTree::from_roots(+ vec![subtree(+ "window",+ "Fixture",+ vec![subtree("button", "Save", Vec::new())],+ )],+ source(),+ Default::default(),+ true,+ )+ .unwrap();++ let strict = tree.clone().into_accessibility_tree().unwrap();+ let (projected, complete, nodes_observed) = tree.into_accessibility_tree_partial().unwrap();++ assert!(complete);+ assert_eq!(nodes_observed, 2);+ assert!(+ !projected.subtree_truncated && !projected.children[0].subtree_truncated,+ "a complete walk must not mark any node truncated"+ );+ assert_eq!(projected.role, strict.role);+ assert_eq!(projected.identity.name, strict.identity.name);+ assert_eq!(projected.children.len(), strict.children.len());+}diff --git a/crates/core/src/locator_tests.rs b/crates/core/src/locator_tests.rsindex 3446c9bc1..35ddf8788 100644--- a/crates/core/src/locator_tests.rs+++ b/crates/core/src/locator_tests.rs@@ -20,6 +20,7 @@ fn node(..Default::default()},children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/node.rs b/crates/core/src/node.rsindex ea88124fd..3619aad71 100644--- a/crates/core/src/node.rs+++ b/crates/core/src/node.rs@@ -20,6 +20,13 @@ pub struct AccessibilityNode {#[serde(skip_serializing_if = "Option::is_none", default)]pub children_count: Option<u32>,+ /// Set when this node's descendants were cut short. Skeleton mode also+ /// carries `children_count`; budget or deadline exhaustion cannot afford+ /// the child-count read that would produce one, so the flag is the only+ /// honest marker available on that path.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub subtree_truncated: bool,+#[serde(skip_serializing_if = "Vec::is_empty", default)]pub children: Vec<AccessibilityNode>,}diff --git a/crates/core/src/node_tests.rs b/crates/core/src/node_tests.rsindex d3b8a8659..443805536 100644--- a/crates/core/src/node_tests.rs+++ b/crates/core/src/node_tests.rs@@ -28,6 +28,7 @@ fn test_children_count_omitted_when_none() {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],};let json = serde_json::to_string(&node).unwrap();@@ -45,6 +46,7 @@ fn test_children_count_present_when_set() {},presentation: Default::default(),children_count: Some(47),+ subtree_truncated: false,children: vec![],};let json = serde_json::to_string(&node).unwrap();@@ -150,6 +152,7 @@ fn accessibility_node_bounds_none_omitted_from_json() {},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],};let json = serde_json::to_string(&node).unwrap();@@ -169,6 +172,7 @@ fn accessibility_node_hint_none_omitted_from_json() {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],};let json = serde_json::to_string(&node).unwrap();diff --git a/crates/core/src/output.rs b/crates/core/src/output.rsindex d579160ad..9890ffb7d 100644--- a/crates/core/src/output.rs+++ b/crates/core/src/output.rs@@ -4,7 +4,7 @@ use serde_json::Value;use crate::recovery_hint::RecoveryHint;use crate::{AppError, DeliverySemantics, ErrorCode, RetryDisposition};-pub const ENVELOPE_VERSION: &str = "2.1";+pub const ENVELOPE_VERSION: &str = "2.2";/// Structured output envelope used by the CLI and future programmatic transports.#[derive(Debug, Serialize)]diff --git a/crates/core/src/output_tests.rs b/crates/core/src/output_tests.rsindex 79f883db2..71d22c283 100644--- a/crates/core/src/output_tests.rs+++ b/crates/core/src/output_tests.rs@@ -117,7 +117,11 @@ fn ok_response_json_shape_has_version_ok_command_data_and_no_error_field() {let map: serde_json::Map<String, serde_json::Value> =serde_json::from_value(serde_json::to_value(&resp).expect("serializable")).expect("map");- assert_eq!(map["version"].as_str(), Some("2.1"), "version must be 2.1");+ assert_eq!(+ map["version"].as_str(),+ Some(super::ENVELOPE_VERSION),+ "version must track ENVELOPE_VERSION"+ );assert_eq!(map["ok"].as_bool(), Some(true), "ok must be true");assert_eq!(map["command"].as_str(),@@ -139,7 +143,11 @@ fn err_response_json_shape_has_version_ok_command_error_and_no_data_field() {let map: serde_json::Map<String, serde_json::Value> =serde_json::from_value(serde_json::to_value(&resp).expect("serializable")).expect("map");- assert_eq!(map["version"].as_str(), Some("2.1"), "version must be 2.1");+ assert_eq!(+ map["version"].as_str(),+ Some(super::ENVELOPE_VERSION),+ "version must track ENVELOPE_VERSION"+ );assert_eq!(map["ok"].as_bool(), Some(false), "ok must be false");assert_eq!(map["command"].as_str(), Some("click"), "command must match");assert!(diff --git a/crates/core/src/ref_action_poll.rs b/crates/core/src/ref_action_poll.rsindex 3be977ca6..00857f336 100644--- a/crates/core/src/ref_action_poll.rs+++ b/crates/core/src/ref_action_poll.rs@@ -16,6 +16,13 @@ use crate::{const STABILITY_POLL_INTERVAL: Duration = Duration::from_millis(16);+/// Waits until the target looks actionable and returns only counters. The+/// resolved handle is deliberately not handed to dispatch: this loop runs+/// *before* the interaction lease is taken, because the lease is a+/// cross-process lock and holding it for the whole wait budget would serialize+/// every agent-desktop process on the machine. Anything resolved here was+/// therefore observed without exclusivity, so dispatch re-resolves under the+/// lease. The second resolve is the correctness boundary, not redundant work.pub(crate) fn execute_poll_loop(context: RefActionWaitContext<'_>,request: &ActionRequest,diff --git a/crates/core/src/ref_alloc_tests.rs b/crates/core/src/ref_alloc_tests.rsindex 937efc488..c67fb549a 100644--- a/crates/core/src/ref_alloc_tests.rs+++ b/crates/core/src/ref_alloc_tests.rs@@ -19,6 +19,7 @@ fn node(role: &str, name: Option<&str>) -> AccessibilityNode {..Default::default()},children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/refs_store.rs b/crates/core/src/refs_store.rsindex bec98f29f..db3dbf908 100644--- a/crates/core/src/refs_store.rs+++ b/crates/core/src/refs_store.rs@@ -8,7 +8,13 @@ use std::io::ErrorKind;use std::path::{Path, PathBuf};const LATEST_SNAPSHOT_FILE: &str = "latest_snapshot_id";-const MAX_SAVED_SNAPSHOTS: usize = 512;++/// Refs are invalidated by the next UI change, so retention only has to cover+/// the handful of snapshots an agent drills through within one interaction.+/// Pruning to a low-water mark keeps the sort-and-stat pass off the common+/// save, which otherwise paid it on every snapshot once the cap was reached.+const MAX_SAVED_SNAPSHOTS: usize = 128;+pub(crate) const PRUNE_LOW_WATER: usize = 96;pub(crate) const STALE_TMP_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(60);#[derive(Debug, Clone)]diff --git a/crates/core/src/refs_store_prune.rs b/crates/core/src/refs_store_prune.rsindex 015456867..bb383b93a 100644--- a/crates/core/src/refs_store_prune.rs+++ b/crates/core/src/refs_store_prune.rs@@ -1,4 +1,4 @@-use super::{MAX_SAVED_SNAPSHOTS, RefStore, STALE_TMP_MAX_AGE};+use super::{MAX_SAVED_SNAPSHOTS, PRUNE_LOW_WATER, RefStore, STALE_TMP_MAX_AGE};use crate::AppError;use crate::refs::validate_snapshot_id;@@ -6,27 +6,76 @@ impl RefStore {/// Removes orphaned `*.tmp` files left behind when a process died between/// the temp write and the atomic rename. Runs under the store write lock;/// the age threshold keeps any in-flight write from another process safe.+ #[cfg(test)]pub(crate) fn remove_tmp_files_older_than(&self, max_age: std::time::Duration) {+ let latest = self.latest_snapshot_id().ok().flatten().unwrap_or_default();+ self.remove_reachable_tmp_files(&latest, &self.snapshots_dir(), max_age);+ }++ /// Sweeps only the directories this save can have written. Snapshot ids are+ /// allocated once, so a directory is never rewritten and an orphan left in+ /// an older one is not reachable from here; those are collected by the+ /// exhaustive sweep that runs with eviction. Doing the exhaustive sweep on+ /// every save cost a `read_dir` per retained snapshot and dominated the+ /// save itself once the store reached its cap.+ fn remove_reachable_tmp_files(+ &self,+ latest_id: &str,+ snapshots_dir: &std::path::Path,+ max_age: std::time::Duration,+ ) {remove_stale_files_in_dir(&self.base_dir, max_age, is_orphaned_tmp_file);- let snapshots_dir = self.snapshots_dir();- remove_stale_files_in_dir(&snapshots_dir, max_age, is_orphaned_tmp_file);- let Ok(entries) = std::fs::read_dir(snapshots_dir) else {+ remove_stale_files_in_dir(snapshots_dir, max_age, is_orphaned_tmp_file);+ if latest_id.is_empty() {+ return;+ }+ remove_stale_files_in_dir(+ &snapshots_dir.join(latest_id),+ max_age,+ is_orphaned_tmp_file,+ );+ }++ /// Drops only the refmaps the trace already holds a copy of, leaving every+ /// other artifact in place. Being in `ArtifactsMode::Full` is not on its own+ /// proof that a copy exists: the artifact budget and a serialisation failure+ /// both skip a copy and report success, so a session that recorded more+ /// refmaps than the budget allows keeps snapshots whose only copy is here.+ /// Each directory is therefore removed only against its own duplicate, and+ /// the latest-snapshot pointer survives unless the snapshot it names is gone.+ pub fn discard_duplicated_ref_scaffolding(&self) {+ let snapshots = self.snapshots_dir();+ let duplicates = crate::trace_artifacts::refmap_artifact_dir(&self.trace_dir());+ let Ok(entries) = std::fs::read_dir(&snapshots) else {return;};for entry in entries.flatten() {- if entry.file_type().is_ok_and(|kind| kind.is_dir()) {- remove_stale_files_in_dir(&entry.path(), max_age, is_orphaned_tmp_file);+ if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {+ continue;}+ let id = entry.file_name().to_string_lossy().to_string();+ if validate_snapshot_id(&id).is_err() {+ continue;+ }+ if duplicates.join(format!("{id}.json")).is_file() {+ let _ = std::fs::remove_dir_all(entry.path());+ }+ }+ let pointer = self.base_dir.join(super::LATEST_SNAPSHOT_FILE);+ if let Ok(Some(latest)) = self.latest_snapshot_id()+ && !snapshots.join(&latest).is_dir()+ {+ let _ = std::fs::remove_file(pointer);}}pub(super) fn prune_old_snapshots_unlocked(&self, latest_id: &str) -> Result<(), AppError> {- self.remove_tmp_files_older_than(STALE_TMP_MAX_AGE);let dir = self.snapshots_dir();+ self.remove_reachable_tmp_files(latest_id, &dir, STALE_TMP_MAX_AGE);let Ok(entries) = std::fs::read_dir(&dir) else {return Ok(());};- let mut snapshots = Vec::new();+ let mut retained = Vec::new();for entry in entries.flatten() {let Ok(file_type) = entry.file_type() else {continue;@@ -38,18 +87,27 @@ impl RefStore {if validate_snapshot_id(&id).is_err() {continue;}- let modified = entry- .metadata()- .and_then(|metadata| metadata.modified())- .unwrap_or(std::time::SystemTime::UNIX_EPOCH);- snapshots.push((modified, id, entry.path()));+ retained.push((id, entry.path()));}- if snapshots.len() <= MAX_SAVED_SNAPSHOTS {+ if retained.len() <= MAX_SAVED_SNAPSHOTS {return Ok(());}- snapshots.sort_by_key(|(modified, id, _)| (*modified, id.clone()));- let mut remove_count = snapshots.len() - MAX_SAVED_SNAPSHOTS;- for (_, id, path) in snapshots {+ for (_, path) in &retained {+ remove_stale_files_in_dir(path, STALE_TMP_MAX_AGE, is_orphaned_tmp_file);+ }+ let mut dated: Vec<_> = retained+ .into_iter()+ .map(|(id, path)| {+ let modified = path+ .metadata()+ .and_then(|metadata| metadata.modified())+ .unwrap_or(std::time::SystemTime::UNIX_EPOCH);+ (modified, id, path)+ })+ .collect();+ dated.sort_by(|left, right| (left.0, &left.1).cmp(&(right.0, &right.1)));+ let mut remove_count = dated.len().saturating_sub(PRUNE_LOW_WATER);+ for (_, id, path) in dated {if remove_count == 0 {break;}diff --git a/crates/core/src/refs_store_pruning_tests.rs b/crates/core/src/refs_store_pruning_tests.rsindex e04c0a803..d59455496 100644--- a/crates/core/src/refs_store_pruning_tests.rs+++ b/crates/core/src/refs_store_pruning_tests.rs@@ -86,3 +86,61 @@ fn prune_never_removes_trace_segments() {assert!(segment.is_file());assert!(trace_dir.is_dir());}++#[test]+fn eviction_sweeps_orphans_left_in_snapshots_this_process_never_touched() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();++ let survivor = store.save_new_snapshot(&map_with("Survivor")).unwrap();+ let orphan = store+ .snapshots_dir()+ .join(&survivor)+ .join("refmap.json.abandoned.tmp");+ std::fs::write(&orphan, b"orphan").unwrap();+ let aged = std::time::SystemTime::now() - (STALE_TMP_MAX_AGE * 2);+ std::fs::File::options()+ .write(true)+ .open(&orphan)+ .unwrap()+ .set_modified(aged)+ .unwrap();++ for i in 0..=MAX_SAVED_SNAPSHOTS {+ store+ .save_new_snapshot(&map_with(&format!("Fill {i}")))+ .unwrap();+ }++ assert!(+ !orphan.exists(),+ "snapshot ids are one-shot, so an orphan in a directory this process never rewrites \+ is only reachable by the exhaustive sweep that runs with eviction"+ );+}++#[test]+fn eviction_drops_to_the_low_water_mark_rather_than_the_cap() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();++ for i in 0..=MAX_SAVED_SNAPSHOTS {+ store+ .save_new_snapshot(&map_with(&format!("Snapshot {i}")))+ .unwrap();+ }++ let retained = std::fs::read_dir(store.snapshots_dir())+ .unwrap()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))+ .count();++ assert_eq!(+ retained,+ PRUNE_LOW_WATER,+ "eviction goes below the cap so the sort-and-stat pass is amortised across the next \+ {} saves instead of running on every one",+ MAX_SAVED_SNAPSHOTS - PRUNE_LOW_WATER+ );+}diff --git a/crates/core/src/renderer_accessibility.rs b/crates/core/src/renderer_accessibility.rsindex 26da9243a..deea11212 100644--- a/crates/core/src/renderer_accessibility.rs+++ b/crates/core/src/renderer_accessibility.rs@@ -3,12 +3,23 @@ use crate::{live_locator::{ObservationRequest, ObservationRoot, ObservedTree},};+/// A renderer that has not published its accessibility tree yet is discovered+/// by walking the tree and failing, so every retry here costs a full+/// observation. Polling that at a fixed short interval spends the whole budget+/// re-walking a tree that is not ready — on a large renderer it burns dozens of+/// complete walks and returns nothing. The wait backs off instead, so a+/// renderer that activates quickly is still caught quickly while one that never+/// activates is retried a handful of times rather than continuously.+const INITIAL_ACTIVATION_RETRY: std::time::Duration = std::time::Duration::from_millis(25);+const MAX_ACTIVATION_RETRY: std::time::Duration = std::time::Duration::from_millis(400);+pub(crate) fn observe_tree(adapter: &dyn PlatformAdapter,root: ObservationRoot<'_>,request: &ObservationRequest,) -> Result<ObservedTree, AppError> {let mut activated = false;+ let mut retry_delay = INITIAL_ACTIVATION_RETRY;loop {match adapter.observe_tree(root, request) {Ok(tree) => return Ok(tree),@@ -23,7 +34,8 @@ pub(crate) fn observe_tree(if remaining.is_zero() {return Err(request.deadline.timeout_error().into());}- std::thread::sleep(remaining.min(std::time::Duration::from_millis(25)));+ std::thread::sleep(remaining.min(retry_delay));+ retry_delay = retry_delay.saturating_mul(2).min(MAX_ACTIVATION_RETRY);}Err(error) => return Err(AppError::Adapter(error)),}diff --git a/crates/core/src/renderer_accessibility_tests.rs b/crates/core/src/renderer_accessibility_tests.rsindex a1b577a22..4cf24a050 100644--- a/crates/core/src/renderer_accessibility_tests.rs+++ b/crates/core/src/renderer_accessibility_tests.rs@@ -42,6 +42,7 @@ impl ObservationOps for RendererAdapter {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: Vec::new(),},)@@ -100,3 +101,72 @@ fn activation_lease_is_dropped_before_observation_retry() {assert_eq!(adapter.activations.load(Ordering::SeqCst), 1);assert!(!held.load(Ordering::SeqCst));}++struct NeverActivatesAdapter {+ lease_held: Arc<AtomicBool>,+ observations: AtomicU32,+}++impl ObservationOps for NeverActivatesAdapter {+ fn observe_tree(+ &self,+ _root: ObservationRoot<'_>,+ _request: &ObservationRequest,+ ) -> Result<ObservedTree, crate::AdapterError> {+ self.observations.fetch_add(1, Ordering::SeqCst);+ Err(crate::AdapterError::renderer_accessibility_activation_required("activation required"))+ }+}++impl ActionOps for NeverActivatesAdapter {}+impl InputOps for NeverActivatesAdapter {}++impl SystemOps for NeverActivatesAdapter {+ fn acquire_interaction_lease(+ &self,+ deadline: crate::Deadline,+ ) -> Result<crate::InteractionLease, crate::AdapterError> {+ self.lease_held.store(true, Ordering::SeqCst);+ crate::InteractionLease::guarded(deadline, LeaseFlag(Arc::clone(&self.lease_held)))+ }++ fn activate_renderer_accessibility(+ &self,+ _process: crate::ProcessIdentity,+ _lease: &crate::InteractionLease,+ ) -> Result<(), crate::AdapterError> {+ Ok(())+ }+}++#[test]+fn a_renderer_that_never_activates_is_not_re_walked_continuously() {+ let held = Arc::new(AtomicBool::new(false));+ let adapter = NeverActivatesAdapter {+ lease_held: Arc::clone(&held),+ observations: AtomicU32::new(0),+ };+ let window = crate::WindowInfo {+ id: "w-1".into(),+ title: "Renderer".into(),+ app: "Renderer".into(),+ pid: crate::ProcessId::new(42),+ process_instance: Some("instance-1".into()),+ bounds: None,+ state: Default::default(),+ };+ let deadline = crate::Deadline::after(3_000).unwrap();+ let request = ObservationRequest::snapshot(&crate::TreeOptions::default(), deadline)+ .validate()+ .unwrap();++ observe_tree(&adapter, ObservationRoot::Window(&window), &request)+ .expect_err("a renderer that never activates must still fail at the deadline");++ let attempts = adapter.observations.load(Ordering::SeqCst);+ assert!(+ attempts <= 16,+ "each retry costs a full tree walk; a 3s budget polled without backoff would spend \+ over a hundred of them, got {attempts}"+ );+}diff --git a/crates/core/src/search_text_tests.rs b/crates/core/src/search_text_tests.rsindex a2cfd36e0..af07ea8eb 100644--- a/crates/core/src/search_text_tests.rs+++ b/crates/core/src/search_text_tests.rs@@ -13,6 +13,7 @@ fn node(name: Option<&str>, value: Option<&str>, description: Option<&str>) -> A},presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rsindex 76b577b24..185f6a3e3 100644--- a/crates/core/src/session/mod.rs+++ b/crates/core/src/session/mod.rs@@ -205,6 +205,11 @@ pub fn end_session(session_id: &str) -> Result<SessionManifest, AppError> {if manifest.ended_at.is_none() {manifest.ended_at = Some(now_millis());write_manifest(&manifest)?;+ if manifest.artifacts == ArtifactsMode::Full+ && let Ok(store) = crate::refs_store::RefStore::for_session(Some(&id))+ {+ store.discard_duplicated_ref_scaffolding();+ }}Ok(manifest)}diff --git a/crates/core/src/session/session_tests.rs b/crates/core/src/session/session_tests.rsindex c9af41316..6b7772666 100644--- a/crates/core/src/session/session_tests.rs+++ b/crates/core/src/session/session_tests.rs@@ -290,3 +290,102 @@ fn legacy_pointer_symlink_does_not_activate_a_session() {assert!(resolve_active_session(None, None).unwrap().is_none());}++fn seed_session_refs(id: &str) -> (std::path::PathBuf, String) {+ let store = crate::refs_store::RefStore::for_session(Some(id)).unwrap();+ let snapshot_id = store+ .save_new_snapshot(&crate::RefMap::new())+ .expect("session snapshot");+ let dir = session_dir(id).unwrap();+ let refmaps = dir.join("trace").join("refmaps");+ std::fs::create_dir_all(&refmaps).unwrap();+ std::fs::write(refmaps.join(format!("{snapshot_id}.json")), b"{}").unwrap();+ std::fs::write(+ dir.join("trace").join("42-1.jsonl"),+ b"{\"event\":\"command.start\"}\n",+ )+ .unwrap();+ assert!(dir.join("snapshots").is_dir());+ (dir, snapshot_id)+}++#[test]+fn ending_a_full_artifacts_session_drops_scaffolding_but_keeps_the_recording() {+ let _guard = HomeGuard::new();+ let manifest = start_session(StartSessionOptions {+ name: Some("sealed-full".into()),+ trace: SessionTraceMode::On,+ artifacts: crate::session::manifest::ArtifactsMode::Full,+ })+ .unwrap();+ let (dir, snapshot_id) = seed_session_refs(&manifest.id);++ end_session(&manifest.id).unwrap();++ assert!(!dir.join("snapshots").join(&snapshot_id).exists());+ assert!(!dir.join("latest_snapshot_id").exists());+ assert!(dir.join("trace").join("42-1.jsonl").is_file());+ assert!(dir.join("session.json").is_file());+}++#[test]+fn a_refmap_the_trace_never_copied_survives_ending_a_full_session() {+ let _guard = HomeGuard::new();+ let manifest = start_session(StartSessionOptions {+ name: Some("sealed-partial".into()),+ trace: SessionTraceMode::On,+ artifacts: crate::session::manifest::ArtifactsMode::Full,+ })+ .unwrap();++ let store = crate::refs_store::RefStore::for_session(Some(&manifest.id)).unwrap();+ let copied = store.save_new_snapshot(&crate::RefMap::new()).unwrap();+ let skipped = store.save_new_snapshot(&crate::RefMap::new()).unwrap();+ let dir = session_dir(&manifest.id).unwrap();++ let refmaps = dir.join("trace").join("refmaps");+ std::fs::create_dir_all(&refmaps).unwrap();+ std::fs::write(refmaps.join(format!("{copied}.json")), b"{}").unwrap();++ end_session(&manifest.id).unwrap();++ let snapshots = dir.join("snapshots");+ assert!(+ !snapshots.join(&copied).exists(),+ "a refmap the trace already holds is redundant here"+ );+ assert!(+ snapshots.join(&skipped).is_dir(),+ "deleting a refmap the trace never copied severs snapshot resolution for anyone \+ reading that trace afterwards, permanently"+ );+}++#[test]+fn ending_a_default_session_keeps_refmaps_because_nothing_else_copies_them() {+ let _guard = HomeGuard::new();+ let manifest = start_session(StartSessionOptions {+ name: Some("sealed-events".into()),+ ..Default::default()+ })+ .unwrap();+ assert_eq!(+ manifest.artifacts,+ crate::session::manifest::ArtifactsMode::Events+ );+ let (dir, _snapshot_id) = seed_session_refs(&manifest.id);++ end_session(&manifest.id).unwrap();++ assert!(+ dir.join("snapshots").is_dir(),+ "Events mode never copies refmaps into trace/, so discarding them would sever snapshot_id resolution for trace readers"+ );+ assert!(+ read_manifest(&manifest.id)+ .unwrap()+ .unwrap()+ .ended_at+ .is_some()+ );+}diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rsindex 6221d6743..ded5a5ad2 100644--- a/crates/core/src/snapshot.rs+++ b/crates/core/src/snapshot.rs@@ -19,6 +19,8 @@ pub struct SnapshotResult {pub refmap: RefMap,pub window: WindowInfo,pub snapshot_id: Option<String>,+ pub complete: bool,+ pub nodes_observed: usize,}impl SnapshotResult {@@ -37,12 +39,12 @@ pub fn build() -> Result<SnapshotResult, AppError> {let window = resolve_window(adapter, app_name, window_id, deadline)?;let observation_options = opts.with_ref_identity_bounds();- let raw_tree = crate::renderer_accessibility::observe_tree(+ let (raw_tree, complete, nodes_observed) = crate::renderer_accessibility::observe_tree(adapter,ObservationRoot::Window(&window),&ObservationRequest::snapshot(&observation_options, deadline).validate()?,)?- .into_accessibility_tree()?;+ .into_accessibility_tree_partial()?;let mut refmap = RefMap::new();let config = RefAllocConfig {@@ -74,6 +76,8 @@ pub fn build(refmap,window,snapshot_id: None,+ complete,+ nodes_observed,})}diff --git a/crates/core/src/snapshot_ref.rs b/crates/core/src/snapshot_ref.rsindex 73e448f37..ad764b619 100644--- a/crates/core/src/snapshot_ref.rs+++ b/crates/core/src/snapshot_ref.rs@@ -58,6 +58,7 @@ pub fn run_from_ref_with_context(&ObservationRequest::snapshot(&observation_options, deadline).validate()?,)?.into_accessibility_tree()?;+ let nodes_observed = count_nodes(&raw_tree);let source_app = entry.source.source_app.as_deref();let source_window_id = entry.source.source_window_id.as_deref();@@ -121,9 +122,18 @@ pub fn run_from_ref_with_context(refmap,window,snapshot_id: Some(active_snapshot_id),+ complete: true,+ nodes_observed,})}+/// A drill-down replaces refs inside an existing snapshot, so it must observe+/// its whole subtree or leave the stored map untouched. Partial projection is+/// only safe for a full snapshot, which writes a fresh map and destroys nothing.+fn count_nodes(node: &crate::AccessibilityNode) -> usize {+ 1 + node.children.iter().map(count_nodes).sum::<usize>()+}+#[cfg(test)]#[path = "snapshot_ref_tests.rs"]mod tests;diff --git a/crates/core/src/snapshot_ref_alloc_tests.rs b/crates/core/src/snapshot_ref_alloc_tests.rsindex 7252436da..6ac06649d 100644--- a/crates/core/src/snapshot_ref_alloc_tests.rs+++ b/crates/core/src/snapshot_ref_alloc_tests.rs@@ -9,6 +9,7 @@ fn node(role: &str) -> AccessibilityNode {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/snapshot_ref_tests.rs b/crates/core/src/snapshot_ref_tests.rsindex f5894c1f1..9d1e8501e 100644--- a/crates/core/src/snapshot_ref_tests.rs+++ b/crates/core/src/snapshot_ref_tests.rs@@ -26,6 +26,7 @@ fn node(role: &str) -> AccessibilityNode {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/snapshot_tests.rs b/crates/core/src/snapshot_tests.rsindex 177be6442..299550222 100644--- a/crates/core/src/snapshot_tests.rs+++ b/crates/core/src/snapshot_tests.rs@@ -8,6 +8,7 @@ fn node(role: &str) -> AccessibilityNode {identity: Default::default(),presentation: Default::default(),children_count: None,+ subtree_truncated: false,children: vec![],}}diff --git a/crates/core/src/trace_artifacts.rs b/crates/core/src/trace_artifacts.rsindex 44c4592b4..d00e49e6e 100644--- a/crates/core/src/trace_artifacts.rs+++ b/crates/core/src/trace_artifacts.rs@@ -43,6 +43,10 @@ fn screens_dir(trace_dir: &Path) -> PathBuf {trace_dir.join("screens")}+pub(crate) fn refmap_artifact_dir(trace_dir: &Path) -> PathBuf {+ refmaps_dir(trace_dir)+}+fn refmaps_dir(trace_dir: &Path) -> PathBuf {trace_dir.join("refmaps")}diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.hindex 39b4e4220..b969d4656 100644--- a/crates/ffi/include/agent_desktop.h+++ b/crates/ffi/include/agent_desktop.h@@ -1420,7 +1420,7 @@ AdResult ad_execute_by_ref_timeout(const struct AdAdapter *adapter,* to disk, and writes the JSON envelope into `*out`.** The JSON shape matches `agent-desktop snapshot`:- * `{"version":"2.1","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.+ * `{"version":"2.2","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.** **`*out` ownership and error behaviour:*** - On success (`AD_RESULT_OK`): `*out` is a heap-allocated JSON string with `"ok":true`.diff --git a/crates/ffi/src/commands/snapshot.rs b/crates/ffi/src/commands/snapshot.rsindex fe88be93e..6a0b590bb 100644--- a/crates/ffi/src/commands/snapshot.rs+++ b/crates/ffi/src/commands/snapshot.rs@@ -15,7 +15,7 @@ use std::ptr;/// to disk, and writes the JSON envelope into `*out`.////// The JSON shape matches `agent-desktop snapshot`:-/// `{"version":"2.1","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.+/// `{"version":"2.2","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.////// **`*out` ownership and error behaviour:**/// - On success (`AD_RESULT_OK`): `*out` is a heap-allocated JSON string with `"ok":true`.diff --git a/crates/ffi/src/tree/flatten.rs b/crates/ffi/src/tree/flatten.rsindex 33751d627..f221bf637 100644--- a/crates/ffi/src/tree/flatten.rs+++ b/crates/ffi/src/tree/flatten.rs@@ -153,6 +153,7 @@ mod tests {presentation: agent_desktop_core::NodePresentation::default(),children: vec![],children_count: None,+ subtree_truncated: false,}}diff --git a/crates/ffi/src/tree/free.rs b/crates/ffi/src/tree/free.rsindex 56ebad09a..9779a18b7 100644--- a/crates/ffi/src/tree/free.rs+++ b/crates/ffi/src/tree/free.rs@@ -159,6 +159,7 @@ mod tests {presentation: agent_desktop_core::NodePresentation::default(),children: vec![],children_count: None,+ subtree_truncated: false,};let mut tree = crate::tree::flatten::flatten_tree(&root).unwrap();tree.count = u32::MAX;diff --git a/crates/macos/src/system/window_bridge.rs b/crates/macos/src/system/window_bridge.rsindex 14ad76da7..3f6d63db9 100644--- a/crates/macos/src/system/window_bridge.rs+++ b/crates/macos/src/system/window_bridge.rs@@ -51,17 +51,25 @@ unsafe extern "C" {) -> *mut std::ffi::c_void;}+/// `kAXErrorIllegalArgument` is the bridge rejecting the element outright, not+/// a busy window that might answer later. Treating it as retryable made callers+/// spin the full resolve budget on a call that can never succeed, and made a+/// window that simply has no CGWindowID look like an unresolved candidate+/// rather than a settled non-match.#[cfg(target_os = "macos")]fn classify(error: i32) -> Result<bool, AdapterError> {use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorAttributeUnsupported, kAXErrorCannotComplete,- kAXErrorInvalidUIElement, kAXErrorNoValue, kAXErrorSuccess,+ kAXErrorIllegalArgument, kAXErrorInvalidUIElement, kAXErrorNoValue, kAXErrorSuccess,};if error == kAXErrorSuccess {return Ok(true);}- if error == kAXErrorAttributeUnsupported || error == kAXErrorNoValue {+ if error == kAXErrorAttributeUnsupported+ || error == kAXErrorNoValue+ || error == kAXErrorIllegalArgument+ {return Ok(false);}if error == kAXErrorAPIDisabled {@@ -142,6 +150,14 @@ mod tests {}}+ #[test]+ fn illegal_argument_is_a_settled_absence_not_a_retryable_failure() {+ assert!(+ !classify(accessibility_sys::kAXErrorIllegalArgument).unwrap(),+ "a window the bridge rejects outright has no CGWindowID; retrying cannot change that"+ );+ }+#[test]fn unavailable_symbol_is_machine_distinguishable() {assert!(is_unavailable(&bridge_unavailable()));diff --git a/crates/macos/src/tree/query/child_read.rs b/crates/macos/src/tree/query/child_read.rsindex 70bd276e1..329b5c0b1 100644--- a/crates/macos/src/tree/query/child_read.rs+++ b/crates/macos/src/tree/query/child_read.rs@@ -87,6 +87,8 @@ mod imp {max_elements: usize,deadline: std::time::Instant,) -> ChildRead {+ let count_deadline =+ super::super::child_read_budget::boundary_count_deadline(max_elements, deadline);let mut status = ChildReadStatus::default();if prepare(element, deadline, &mut status).is_err() {return ChildRead {@@ -99,7 +101,7 @@ mod imp {};}status.attempts += 1;- let count = match child_count(element, attribute, deadline) {+ let count = match child_count(element, attribute, count_deadline) {Ok(count) => count,Err(error) if is_absent_error(error) => {return ChildRead::unavailable(status);diff --git a/crates/macos/src/tree/query/child_read_budget.rs b/crates/macos/src/tree/query/child_read_budget.rsnew file mode 100644index 000000000..c98ffaeb9--- /dev/null+++ b/crates/macos/src/tree/query/child_read_budget.rs@@ -0,0 +1,52 @@+/// A boundary node is read for its child count alone, purely to annotate how+/// much was left unobserved. On a renderer that materialises children lazily+/// that count is not cheap — asking for it can cost more than the traversal it+/// was describing, and a single one could consume an entire snapshot budget.+/// The count is therefore best-effort: it gets a small slice, and a boundary+/// that cannot afford one is still reported as truncated, just without a number.+const BOUNDARY_COUNT_BUDGET: std::time::Duration = std::time::Duration::from_millis(25);++pub(super) fn boundary_count_deadline(+ max_elements: usize,+ deadline: std::time::Instant,+) -> std::time::Instant {+ if max_elements == 0 {+ deadline.min(std::time::Instant::now() + BOUNDARY_COUNT_BUDGET)+ } else {+ deadline+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::{Duration, Instant};++ #[test]+ fn a_boundary_count_gets_only_a_slice_of_a_long_deadline() {+ let far = Instant::now() + Duration::from_secs(3);++ let bounded = boundary_count_deadline(0, far);++ assert!(+ bounded < far,+ "a boundary node is read for its count alone; letting one lazy renderer container \+ spend the whole snapshot budget on it is what this bound exists to prevent"+ );+ assert!(bounded <= Instant::now() + Duration::from_millis(60));+ }++ #[test]+ fn a_real_child_read_keeps_the_callers_deadline() {+ let far = Instant::now() + Duration::from_secs(3);++ assert_eq!(boundary_count_deadline(128, far), far);+ }++ #[test]+ fn the_bound_never_extends_a_deadline_that_is_already_shorter() {+ let near = Instant::now() + Duration::from_millis(5);++ assert_eq!(boundary_count_deadline(0, near), near);+ }+}diff --git a/crates/macos/src/tree/query/mod.rs b/crates/macos/src/tree/query/mod.rsindex 2de8260ec..4580b635a 100644--- a/crates/macos/src/tree/query/mod.rs+++ b/crates/macos/src/tree/query/mod.rs@@ -1,6 +1,7 @@mod arena;mod child_page;pub(crate) mod child_read;+pub(crate) mod child_read_budget;pub(crate) mod child_read_plan;mod child_read_status;mod child_read_telemetry;@@ -29,6 +30,21 @@ struct ResolvedRoot {activation_eligible: bool,}+/// Whether the walk ran out of tree before it ran out of depth budget, which is+/// what makes an absent renderer surface a conclusion rather than a guess. A+/// depth-clamped observation stops above the web content by design, so its+/// empty result says nothing about whether the renderer is activated — treating+/// it as evidence made every shallow snapshot of a Chromium application demand+/// an activation it did not need, then re-walk the tree until the deadline+/// expired. Reaching the cap is inconclusive either way: the tree may have+/// ended exactly there or been cut, and nothing observed can distinguish them.+fn observation_reached_tree_end(+ stats: &agent_desktop_core::LocatorStats,+ request: &ObservationRequest,+) -> bool {+ stats.traversal.max_logical_depth < request.max_logical_depth+}+pub(crate) fn observe_tree(root: ObservationRoot<'_>,request: &ObservationRequest,@@ -39,7 +55,8 @@ pub(crate) fn observe_tree(let (tree, renderer_ready, stats) =traversal::LocatorTraversal::new(&request, resolved.context, deadline).build(resolved.element, resolved.source)?;- if resolved.activation_eligible && tree.is_complete() && !renderer_ready {+ let looked_deep_enough = observation_reached_tree_end(&stats, &request);+ if resolved.activation_eligible && tree.is_complete() && !renderer_ready && looked_deep_enough {if let Some(instance) = resolved.process_instance.as_deref() {if crate::tree::renderer_probe::activation_supported(resolved.pid, instance, deadline)?{@@ -176,6 +193,44 @@ mod tests {RefProcess, RefScope, RefSource,};+ fn request_with_depth(max_depth: u8) -> ObservationRequest {+ ObservationRequest::snapshot(+ &agent_desktop_core::TreeOptions {+ max_depth,+ ..Default::default()+ },+ agent_desktop_core::Deadline::after(1_000).expect("deadline"),+ )+ }++ fn stats_reaching(max_logical_depth: u8) -> agent_desktop_core::LocatorStats {+ let mut stats = agent_desktop_core::LocatorStats::default();+ stats.traversal.max_logical_depth = max_logical_depth;+ stats+ }++ #[test]+ fn a_walk_that_ended_before_the_cap_can_conclude_the_renderer_is_absent() {+ assert!(observation_reached_tree_end(+ &stats_reaching(4),+ &request_with_depth(10)+ ));+ }++ #[test]+ fn a_walk_that_reached_the_cap_cannot_conclude_anything_about_the_renderer() {+ assert!(+ !observation_reached_tree_end(&stats_reaching(3), &request_with_depth(3)),+ "at the cap the tree may have ended there or been cut, and the observation \+ cannot tell which; demanding activation on that basis re-walked Chromium \+ trees until the deadline expired"+ );+ assert!(!observation_reached_tree_end(+ &stats_reaching(10),+ &request_with_depth(10)+ ));+ }+#[test]fn null_element_root_is_a_structured_stale_ref() {let pid = i32::try_from(std::process::id()).expect("test pid fits macOS pid_t");diff --git a/docs/json-output.md b/docs/json-output.mdindex 3f3598903..7eafa7194 100644--- a/docs/json-output.md+++ b/docs/json-output.md@@ -4,7 +4,7 @@ Every command returns structured JSON:```json{- "version": "2.1",+ "version": "2.2","ok": true,"command": "click","data": { "action": "click" }@@ -15,7 +15,7 @@ Errors include machine-readable codes and recovery hints:```json{- "version": "2.1",+ "version": "2.2","ok": false,"command": "click","error": {diff --git a/docs/phases.md b/docs/phases.mdindex ee30cf43a..d655b3cac 100644--- a/docs/phases.md+++ b/docs/phases.md@@ -116,7 +116,7 @@ Phase 1 is the load-bearing phase. It establishes the shared command path, trait| P1-O2 | Platform adapter trait | Trait compiles with mock adapter; macOS adapter satisfies all trait methods || P1-O3 | Ref-based interaction | `click @s8f3k2p9:e3` successfully invokes AXPress on the resolved element || P1-O4 | Context efficiency | Typical Finder snapshot < 500 tokens (measured via tiktoken) |-| P1-O5 | Typed JSON contract | Output envelope carries `version: "2.1"`. **Partial**: dedicated standalone JSON-Schema files were never delivered — deferred to later quality gates. |+| P1-O5 | Typed JSON contract | Output envelope carries `version: "2.2"`. **Partial**: dedicated standalone JSON-Schema files were never delivered — deferred to later quality gates. || P1-O6 | Permission detection | Permission report covers Accessibility, Screen Recording, and Automation with recovery suggestions || P1-O7 | Command extensibility | Adding a new command follows the current shared path: `commands/{name}.rs` + `commands/mod.rs` + `src/cli_args/` + `src/cli/mod.rs` + `src/dispatch/mod.rs` + `src/command_policy/mod.rs` || P1-O8 | 58 shipped command names (54 operational) | All commands pass integration tests; `key-down` / `key-up` / `mouse-down` / `mouse-up` fail closed pending daemon-owned held input |@@ -169,7 +169,7 @@ agent-desktop/│ │ ├── trace.rs / trace_read/ # JSONL reliability trace, segment merge, HTML viewer│ │ ├── error_code.rs # ErrorCode enum│ │ ├── adapter_error.rs / app_error.rs # AdapterError, AppError-│ │ ├── output.rs # ENVELOPE_VERSION ("2.1") + envelope builders+│ │ ├── output.rs # ENVELOPE_VERSION ("2.2") + envelope builders│ │ ├── notification.rs # NotificationInfo, NotificationFilter, NotificationIdentity│ │ └── commands/ # one file per command (direct match, no Command trait)│ ├── macos/ # agent-desktop-macos (Phase 1, shipped)@@ -459,12 +459,12 @@ The `wait` command has been extended with notification, menu, event-diff, and se### JSON Output Contract-All commands produce a response envelope with `version: "2.1"`. Standalone schema files are still deferred; the current contract is enforced by Rust serde types, CLI conformance tests, and documented examples.+All commands produce a response envelope with `version: "2.2"`. Standalone schema files are still deferred; the current contract is enforced by Rust serde types, CLI conformance tests, and documented examples.Success:```json{- "version": "2.1",+ "version": "2.2","ok": true,"command": "snapshot","data": {@@ -479,7 +479,7 @@ Success:Error:```json{- "version": "2.1",+ "version": "2.2","ok": false,"command": "click","error": {diff --git a/docs/solutions/best-practices/abort-state-guidance-multi-step-physical-input.md b/docs/solutions/best-practices/abort-state-guidance-multi-step-physical-input.mdindex 76afdea8a..12008010b 100644--- a/docs/solutions/best-practices/abort-state-guidance-multi-step-physical-input.md+++ b/docs/solutions/best-practices/abort-state-guidance-multi-step-physical-input.md@@ -24,10 +24,12 @@ pre-dispatch failure: the system may still believe the button is down.## Guidance`crates/macos/src/input/mouse_drag.rs` owns a `DragReleaseGuard` for the whole-sequence. It arms only after mouse-down is posted, retains the destination-release until that post succeeds, and uses `Drop` to post a dragged and up-event at the origin when the sequence aborts. The happy path disarms only-after the destination up event has been posted.+sequence. It arms immediately before mouse-down is posted, so the guard is+already live when the first committed event goes out, then records delivery+once that post returns. It retains the destination release until the post+succeeds, and uses `Drop` to post a dragged and up event at the origin when+the sequence aborts. The happy path disarms only after the destination up+event has been posted.The guard also tracks delivery. Public errors are enriched from that state, socallers can distinguish a pre-delivery failure from an interrupted physicaldiff --git a/docs/solutions/best-practices/real-app-tests-are-the-platform-adapter-gate.md b/docs/solutions/best-practices/real-app-tests-are-the-platform-adapter-gate.mdindex 220a102b5..0749cd9d7 100644--- a/docs/solutions/best-practices/real-app-tests-are-the-platform-adapter-gate.md+++ b/docs/solutions/best-practices/real-app-tests-are-the-platform-adapter-gate.md@@ -62,3 +62,4 @@ deletion without treating a mock as a platform oracle.- [Build desktop actions as an observe-resolve-preflight-dispatch contract](playwright-grade-desktop-reliability-2026-06-02.md)- [Guard OS-reordered resources with an identity fingerprint](identity-fingerprint-against-os-reorder-2026-04-16.md)+- [Never ship platform code that CI cannot execute](never-ship-platform-code-that-ci-cannot-execute.md) — the complementary gate. This doc covers permissioned native verification of the macOS adapter against real applications; that one covers running platform-conditional core code on real Windows and Linux runners.diff --git a/docs/solutions/documentation-gaps/hover-drag-skip-the-actionability-battery.md b/docs/solutions/documentation-gaps/hover-drag-skip-the-actionability-battery.mdindex c4ddac793..daf403729 100644--- a/docs/solutions/documentation-gaps/hover-drag-skip-the-actionability-battery.md+++ b/docs/solutions/documentation-gaps/hover-drag-skip-the-actionability-battery.md@@ -26,11 +26,20 @@ path evolves.Follow the code path, not a command-family generalization:-`hover` and `drag` enter `pointer_action::resolve_point_with_deadline`. For a-ref target it retries strict resolution within the command deadline and reads-live bounds and state. It scrolls a non-visible target into view once, verifies-valid bounds, requires a stable bounds hash across attempts, and then performs-the `receives_events` hit-test before physical input.+`hover` and `drag` resolve their point in two phases, mirroring the pre-lease+and leased split that ref actions use. `pointer_action::wait_for_point_with_deadline`+runs first, without exclusivity: for a ref target it retries strict resolution+within the command deadline, reads live bounds and state, scrolls a non-visible+target into view once, verifies valid bounds, and requires a stable bounds hash+across attempts. `pointer_action::resolve_point_under_lease` then re-resolves+once the interaction lease is held and performs the `receives_events` hit-test+before physical input.++Two different hit-tests exist and should not be conflated. The shared+actionability battery runs a multi-candidate-point check for actions whose+`Action::requires_hit_test()` is true — which now includes the click family,+not only hover and drag. The pointer pipeline runs its own single-point check+on the resolved coordinate. Hover and drag use the latter.An occluded, invalid, or permanently non-visible target returns a structuredterminal error. Only transient resolution and stability conditions consume thediff --git a/docs/solutions/logic-errors/progressive-snapshot-review-contract-2026-04-16.md b/docs/solutions/logic-errors/progressive-snapshot-review-contract-2026-04-16.mdindex 3e4fae451..0b22bc37e 100644--- a/docs/solutions/logic-errors/progressive-snapshot-review-contract-2026-04-16.md+++ b/docs/solutions/logic-errors/progressive-snapshot-review-contract-2026-04-16.md@@ -41,6 +41,16 @@ makes old refs appear valid after their evidence has changed.observation policy: it clamps depth to three and leaves `children_count` ontruncated nodes. Named structural anchors can receive drill-down refs, butinert containers do not become actionable merely because they were visible.+- Truncation has two paths and they carry different markers. A depth clamp+ knows how many children it skipped, so it leaves `children_count`. Budget or+ deadline exhaustion cannot afford the child-count read that would produce+ one, so every node whose descendants were cut carries `subtree_truncated`,+ which propagates to its ancestors and lets a reader walk from the root to+ the cut. A full snapshot that exhausts its budget returns the subtree it did+ observe with `complete: false` and `truncated: true` in `data`, rather than+ discarding the walk. A drill-down never does this: `--root` replaces refs+ inside an existing map, so it still requires a complete observation and+ errors instead of destructively merging a partial one.- Derive the response window from the root entry's process identity with`window_lookup::find_window_for_process`; never synthesize a plausiblewindow response.@@ -57,7 +67,13 @@ ensuring no stale descendants survive a re-drill.- Test full-snapshot replacement and rooted-subtree replacement separately.- Test qualified and bare ref parsing, including mismatched snapshot IDs.- Assert every truncation path exposes a boundary marker instead of silently- dropping descendants.+ dropping descendants. Depth clamping and budget exhaustion are separate+ paths; a test that only covers the clamp will not notice the other losing+ its marker.+- Assert a drill-down refuses to replace refs from an incomplete observation.+ A full snapshot may return a partial tree because it writes a fresh map and+ destroys nothing; a rooted replacement deletes descendants it may then be+ unable to re-allocate.- Keep ref allocation in `crates/core/src/ref_alloc.rs`; full snapshots anddrill-downs must not grow separate allocators.diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.mdindex ead574602..f359426cb 100644--- a/skills/agent-desktop/SKILL.md+++ b/skills/agent-desktop/SKILL.md@@ -102,8 +102,8 @@ Use **progressive skeleton traversal** as the default approach. It reduces tokenEvery command returns a JSON envelope on stdout:-**Success:** `{ "version": "2.1", "ok": true, "command": "snapshot", "data": { ... } }`-**Error:** `{ "version": "2.1", "ok": false, "command": "click", "error": { "code": "STALE_REF", "message": "...", "suggestion": "..." } }`+**Success:** `{ "version": "2.2", "ok": true, "command": "snapshot", "data": { ... } }`+**Error:** `{ "version": "2.2", "ok": false, "command": "click", "error": { "code": "STALE_REF", "message": "...", "suggestion": "..." } }`The `error` object may also carry an optional `details` object (e.g. the actionability report on an actionability failure, candidate summaries on `AMBIGUOUS_TARGET`, or the last observed state on a `wait` `TIMEOUT`). Parse errors leniently — `details` and future fields are additive, so do not reject responses with unknown keys.diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.mdindex 7ace05bdc..e20da3eca 100644--- a/skills/agent-desktop/references/commands-observation.md+++ b/skills/agent-desktop/references/commands-observation.md@@ -37,7 +37,7 @@ agent-desktop snapshot --root @e12 --snapshot <snapshot_id> -i**Output structure:**```json{- "version": "2.1",+ "version": "2.2","ok": true,"command": "snapshot","data": {diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex b7a3ef68a..526b72cfc 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -326,7 +326,7 @@ Each entry may include `"session": "id"` beside `command` and `args`. If omitted**Per-entry failure shape:**```json{- "version": "2.1",+ "version": "2.2","ok": false,"command": "click","error": {