Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat!: verify stateful ref actions against fresh platform state
Lahfir9bc91bc0ab53
diff --git a/.github/workflows/inspector.yml b/.github/workflows/inspector.ymlnew file mode 100644index 000000000..ee3eea774--- /dev/null+++ b/.github/workflows/inspector.yml@@ -0,0 +1,24 @@+name: Inspector and visual viewer++on:+ push:+ branches: [main, master]+ pull_request:+ workflow_dispatch:++permissions: {}++jobs:+ test:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1+ - name: Check Node runtime+ run: node -e 'if (Number(process.versions.node.split(".")[0]) < 22) throw new Error("Node 22 or newer required")'+ - name: Inspector contract and lifecycle tests+ run: npm --prefix tools/inspector test+ - name: Embedded visual viewer tests+ run: node --test src/visual_debug/viewer_filter.test.jsdiff --git a/CONCEPTS.md b/CONCEPTS.mdindex 4c8c81b1f..75441db02 100644--- a/CONCEPTS.md+++ b/CONCEPTS.md@@ -10,6 +10,11 @@ A structured representation of an application's user interface exposed by the op### SnapshotAn observation of an accessibility tree at a point in time, persisted with the element refs allocated from that observation.+### Visual Debug Artifact+A standalone, opt-in visualization that pairs a snapshot's returned nodes or a click's pre-dispatch target with window screenshots, using labeled bounds and role-group filters for human inspection.++Its filters change only the visualization, not the recorded command result or the desktop. Before/after images are separate observations, not a recording or proof of action delivery.+### Snapshot IDA compact identifier for one persisted snapshot. Lookup is confined to the selected session namespace, so an ID created in a session is not a cross-session handle.diff --git a/Cargo.lock b/Cargo.lockindex 8bd60f273..6d02e0e73 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -19,6 +19,7 @@ dependencies = ["agent-desktop-linux","agent-desktop-macos","agent-desktop-windows",+ "base64","clap","serde","serde_json",diff --git a/crates/core/src/action.rs b/crates/core/src/action.rsindex 93b7284b9..324530e1e 100644--- a/crates/core/src/action.rs+++ b/crates/core/src/action.rs@@ -80,6 +80,18 @@ impl Action {}}+ pub(crate) fn writes_element_value(&self) -> bool {+ matches!(self, Self::SetValue(_) | Self::Clear | Self::TypeText(_))+ }++ pub(crate) fn requires_state_readback(&self) -> bool {+ self.writes_element_value()+ || matches!(+ self,+ Self::Check | Self::Uncheck | Self::Toggle | Self::Expand | Self::Collapse+ )+ }+pub fn requires_cursor_policy(&self) -> bool {matches!(self, Self::Hover | Self::Drag(_))}@@ -130,6 +142,7 @@ impl Action {| Self::Clear| Self::Hover| Self::Drag(_)+ | Self::Scroll(_, _))}diff --git a/crates/core/src/action_result.rs b/crates/core/src/action_result.rsindex bd0416f9d..f4043bd68 100644--- a/crates/core/src/action_result.rs+++ b/crates/core/src/action_result.rs@@ -1,6 +1,6 @@use crate::{- Action, AdapterError, DeliverySemantics, ErrorCode, action_step::ActionStep,- action_step_outcome::ActionStepOutcome, element_state::ElementState,+ Action, DeliverySemantics, action_step::ActionStep, action_step_outcome::ActionStepOutcome,+ element_state::ElementState,};use serde::{Deserialize, Deserializer, Serialize};@@ -26,27 +26,23 @@ pub struct ActionResult {}impl ActionResult {- pub fn from_execution(- action: &Action,- steps: Vec<ActionStep>,- post_state: Option<ElementState>,- ) -> Result<Self, AdapterError> {+ pub fn from_execution(action: &Action, steps: Vec<ActionStep>) -> Self {let label = action.name();let (delivered, verified) = delivery_summary(&steps);if !delivered {- return Ok(Self::satisfied_without_delivery(label).with_steps(steps));- }- if let Some(state) = post_state.as_ref() {- verify_post_state(action, state)?;+ return Self::satisfied_without_delivery(label).with_steps(steps);}let mut result = Self::delivered_unverified(label).with_steps(steps);if verified {result = result.with_verified_delivery();+ if action.writes_element_value() {+ result = result.with_details(serde_json::json!({+ "verification_scope": "element_value",+ "application_commit": "not_verified",+ }));+ }}- if let Some(state) = post_state {- result = result.with_state(state);- }- Ok(result)+ result}pub fn satisfied_without_delivery(action: impl Into<String>) -> Self {@@ -93,6 +89,13 @@ impl ActionResult {self}+ pub(crate) fn with_unverified_delivery(mut self) -> Self {+ if self.disposition == DeliverySemantics::delivered_verified() {+ self.disposition = DeliverySemantics::delivered_unverified();+ }+ self+ }+pub const fn disposition(&self) -> DeliverySemantics {self.disposition}@@ -112,23 +115,6 @@ fn delivery_summary(steps: &[ActionStep]) -> (bool, bool) {(delivered, verification.unwrap_or(false))}-fn verify_post_state(action: &Action, state: &ElementState) -> Result<(), AdapterError> {- if matches!(action, Action::Clear)- && state- .value- .as_deref()- .is_some_and(|value| !value.is_empty())- {- return Err(AdapterError::new(- ErrorCode::ActionFailed,- "Clear reported success but element value is still non-empty",- )- .with_suggestion("Retry 'clear', or use 'press cmd+a' then 'press delete'.")- .with_disposition(DeliverySemantics::delivered_unverified()));- }- Ok(())-}-const fn default_action_disposition() -> DeliverySemantics {DeliverySemantics::delivered_unverified()}diff --git a/crates/core/src/action_result_tests.rs b/crates/core/src/action_result_tests.rsindex 272a76785..abc61fb09 100644--- a/crates/core/src/action_result_tests.rs+++ b/crates/core/src/action_result_tests.rs@@ -22,7 +22,7 @@ fn execution_result(verifications: &[Option<bool>]) -> ActionResult {}}).collect();- ActionResult::from_execution(&Action::Click, steps, None).expect("execution result")+ ActionResult::from_execution(&Action::Click, steps)}#[test]@@ -62,6 +62,19 @@ fn verified_action_uses_verified_delivery() {);}+#[test]+fn unavailable_verification_preserves_no_delivery_and_demotes_verified_delivery() {+ let satisfied = ActionResult::satisfied_without_delivery("clear").with_unverified_delivery();+ assert_eq!(satisfied.disposition(), DeliverySemantics::not_delivered());+ let delivered = ActionResult::delivered_unverified("set-value")+ .with_verified_delivery()+ .with_unverified_delivery();+ assert_eq!(+ delivered.disposition(),+ DeliverySemantics::delivered_unverified()+ );+}+#[test]fn legacy_json_defaults_to_delivered_unverified() {let result: ActionResult = serde_json::from_value(serde_json::json!({@@ -112,8 +125,7 @@ fn successful_action_deserializes_satisfied_without_delivery() {#[test]fn execution_without_succeeded_steps_is_satisfied_without_delivery() {let steps = vec![ActionStep::skipped("AlreadyInState").with_verified(true)];- let result = ActionResult::from_execution(&Action::Check, steps, Some(state(Some("1"))))- .expect("no-op result");+ let result = ActionResult::from_execution(&Action::Check, steps);assert_eq!(result.disposition(), DeliverySemantics::not_delivered());assert_eq!(result.steps.len(), 1);@@ -143,12 +155,8 @@ fn execution_derives_disposition_from_succeeded_step_evidence() {fn execution_attaches_post_state_without_changing_serialization() {let steps = vec![ActionStep::succeeded("AXValue").with_verified(false)];let post_state = state(Some("done"));- let actual = ActionResult::from_execution(- &Action::SetValue("done".into()),- steps.clone(),- Some(post_state.clone()),- )- .expect("result");+ let actual = ActionResult::from_execution(&Action::SetValue("done".into()), steps.clone())+ .with_state(post_state.clone());let expected = ActionResult::delivered_unverified("set-value").with_steps(steps).with_state(post_state);@@ -160,31 +168,16 @@ fn execution_attaches_post_state_without_changing_serialization() {}#[test]-fn clear_postcondition_preserves_exact_error_contract() {- for post_state in [state(Some("")), state(None)] {- ActionResult::from_execution(- &Action::Clear,- vec![ActionStep::succeeded("AXValue").with_verified(true)],- Some(post_state),- )- .expect("clear result");- }-- let error = ActionResult::from_execution(- &Action::Clear,+fn verified_text_value_does_not_claim_application_commit() {+ let result = ActionResult::from_execution(+ &Action::SetValue("8".into()),vec![ActionStep::succeeded("AXValue").with_verified(true)],- Some(state(Some("still here"))),- )- .expect_err("non-empty clear must fail");-- assert_eq!(error.code, ErrorCode::ActionFailed);- assert_eq!(- error.message,- "Clear reported success but element value is still non-empty");assert_eq!(- error.suggestion.as_deref(),- Some("Retry 'clear', or use 'press cmd+a' then 'press delete'.")+ result.disposition(),+ DeliverySemantics::delivered_verified());- assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ let details = result.details.unwrap();+ assert_eq!(details["verification_scope"], "element_value");+ assert_eq!(details["application_commit"], "not_verified");}diff --git a/crates/core/src/action_tests.rs b/crates/core/src/action_tests.rsindex bbc6dc61b..e9a252c71 100644--- a/crates/core/src/action_tests.rs+++ b/crates/core/src/action_tests.rs@@ -230,6 +230,7 @@ fn requires_scroll_into_view_covers_all_actions() {Action::Clear,Action::Hover,Action::Drag(dummy_drag()),+ Action::Scroll(Direction::Down, 1),];for action in scroll_into_view {assert!(@@ -240,7 +241,6 @@ fn requires_scroll_into_view_covers_all_actions() {}let not_scroll_into_view: &[Action] = &[- Action::Scroll(Direction::Down, 1),Action::ScrollTo,Action::SetFocus,Action::PressKey(dummy_key()),diff --git a/crates/core/src/actionability/evaluate.rs b/crates/core/src/actionability/evaluate.rsindex 0d84addb8..393c3af73 100644--- a/crates/core/src/actionability/evaluate.rs+++ b/crates/core/src/actionability/evaluate.rs@@ -160,6 +160,12 @@ fn finish(let code = report.terminal_code().unwrap_or(ErrorCode::ActionFailed);let suggestion = if code == ErrorCode::ActionFailed {"Wait for the target to become actionable, refresh the snapshot, or use an explicit physical/focus command if intended."+ } else if evidence.state.role == "cell"+ && report.checks.iter().any(|check| {+ check.check == "editable" && check.status == super::status::ActionabilityStatus::Fail+ })+ {+ "This cell is not directly editable. Activate the cell, take a fresh snapshot, then target the text editor it exposes. --headed alone does not enter cell editing."} else {"Waiting will not help: this element cannot satisfy the action as targeted. Target an element that advertises the action (check available_actions in a fresh snapshot) or adjust the interaction policy (e.g. pass --headed)."};diff --git a/crates/core/src/actionability/live.rs b/crates/core/src/actionability/live.rsindex fc46afedb..67f204236 100644--- a/crates/core/src/actionability/live.rs+++ b/crates/core/src/actionability/live.rs@@ -52,7 +52,8 @@ pub(crate) fn check_live_with_stability(target.adapter.get_live_element(target.handle, target.deadline),- )?;+ )+ .map_err(crate::ref_action::mark_pre_dispatch_resolution_failure)?;check_with_stability(stability,&evidence,@@ -60,6 +61,7 @@ pub(crate) fn check_live_with_stability(Some((target.handle, target.adapter)),target.deadline,)+ .map_err(crate::ref_action::mark_pre_dispatch_resolution_failure)}fn observe(diff --git a/crates/core/src/actionability_live_failure_tests.rs b/crates/core/src/actionability_live_failure_tests.rsindex 079d488f4..7a7c5b99f 100644--- a/crates/core/src/actionability_live_failure_tests.rs+++ b/crates/core/src/actionability_live_failure_tests.rs@@ -60,4 +60,46 @@ fn live_read_errors_are_not_silently_downgraded_to_snapshot_data() {.unwrap_err();assert_eq!(err.code, ErrorCode::PermDenied);+ assert_eq!(err.disposition, crate::DeliverySemantics::not_delivered());+}++#[test]+fn transient_live_read_failure_reports_no_delivery() {+ struct FailedRead(crate::DeliverySemantics);+ impl ObservationOps for FailedRead {+ fn get_live_element(+ &self,+ _: &NativeHandle,+ _: crate::Deadline,+ ) -> Result<LiveElement, AdapterError> {+ Err(+ AdapterError::new(ErrorCode::AppUnresponsive, "incomplete live evidence")+ .with_disposition(self.0),+ )+ }+ }+ impl ActionOps for FailedRead {}+ impl InputOps for FailedRead {}+ impl SystemOps for FailedRead {}++ for (reported, expected) in [+ (+ crate::DeliverySemantics::unknown(),+ crate::DeliverySemantics::not_delivered(),+ ),+ (+ crate::DeliverySemantics::uncertain(),+ crate::DeliverySemantics::uncertain(),+ ),+ ] {+ let error = check_live(+ &entry(),+ &NativeHandle::null(),+ &FailedRead(reported),+ &ActionRequest::headless(Action::Click),+ )+ .unwrap_err();+ assert_eq!(error.code, ErrorCode::AppUnresponsive);+ assert_eq!(error.disposition, expected);+ }}diff --git a/crates/core/src/actionability_tests.rs b/crates/core/src/actionability_tests.rsindex e6e1035bc..58db4b807 100644--- a/crates/core/src/actionability_tests.rs+++ b/crates/core/src/actionability_tests.rs@@ -231,6 +231,17 @@ fn text_input_requires_editable_target() {assert!(err.message.contains("editable"));}+#[test]+fn cell_text_input_explains_how_to_target_the_editor() {+ let mut cell = entry();+ cell.identity.role = "cell".into();+ for action in [Action::TypeText("x".into()), Action::SetValue("x".into())] {+ let error = check(&cell, &ActionRequest::headless(action)).unwrap_err();+ assert!(error.suggestion.unwrap().contains("target the text editor"));+ assert_eq!(error.disposition, crate::DeliverySemantics::not_delivered());+ }+}+#[test]fn cursor_movement_requires_physical_policy() {let err = check(&entry(), &ActionRequest::headless(Action::Hover)).unwrap_err();diff --git a/crates/core/src/adapter/mod.rs b/crates/core/src/adapter/mod.rsindex ad93295ed..ac3d2ad75 100644--- a/crates/core/src/adapter/mod.rs+++ b/crates/core/src/adapter/mod.rs@@ -13,7 +13,7 @@ pub(crate) use system::SystemOps;#[cfg(test)]pub(crate) use test_support::{complete_live_observation, exact_window_focus, guarded_interaction_lease, live_identity,- observed_tree,+ observed_tree, recorded_action_state,};pub(crate) use crate::live_element::LiveElement;diff --git a/crates/core/src/adapter/observation.rs b/crates/core/src/adapter/observation.rsindex 1ea1783ac..7fd844f9e 100644--- a/crates/core/src/adapter/observation.rs+++ b/crates/core/src/adapter/observation.rs@@ -117,6 +117,15 @@ pub trait ObservationOps: Send + Sync {Err(AdapterError::not_supported("get_live_value"))}+ /// Selected text offsets in UTF-16 code units, or unavailable evidence.+ fn get_text_selection(+ &self,+ _handle: &NativeHandle,+ _deadline: Deadline,+ ) -> Result<Option<std::ops::Range<usize>>, AdapterError> {+ Err(AdapterError::not_supported("get_text_selection"))+ }+fn get_live_state(&self,_handle: &NativeHandle,diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rsindex 8552ddad6..59a14a17b 100644--- a/crates/core/src/adapter/system.rs+++ b/crates/core/src/adapter/system.rs@@ -156,6 +156,14 @@ pub trait SystemOps: Send + Sync {Err(AdapterError::not_supported("screenshot"))}+ fn screenshot_window_frame(+ &self,+ _window: &WindowInfo,+ _deadline: Deadline,+ ) -> Result<ImageBuffer, AdapterError> {+ Err(AdapterError::not_supported("screenshot_window_frame"))+ }+fn list_displays(&self, _deadline: Deadline) -> Result<Vec<DisplayInfo>, AdapterError> {Err(AdapterError::not_supported("list_displays"))}diff --git a/crates/core/src/adapter/test_support.rs b/crates/core/src/adapter/test_support.rsindex 464666de6..67bc7da32 100644--- a/crates/core/src/adapter/test_support.rs+++ b/crates/core/src/adapter/test_support.rs@@ -1,24 +1,41 @@macro_rules! complete_live_observation {($role:expr, $name:expr, [$($action:expr),* $(,)?]) => {+ $crate::adapter::complete_live_observation!(+ @impl $role,+ $name,+ [$($action),*],+ _adapter => $crate::ElementState {+ role: $role.into(),+ states: Vec::new(),+ value: None,+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ }+ );+ };+ ($role:expr, $name:expr, [$($action:expr),* $(,)?], $adapter:ident => $state:expr) => {+ $crate::adapter::complete_live_observation!(+ @impl $role,+ $name,+ [$($action),*],+ $adapter => $state+ );+ };+ (@impl $role:expr, $name:expr, [$($action:expr),* $(,)?], $adapter:ident => $state:expr) => {fn get_live_element(&self,_handle: &$crate::adapter::NativeHandle,_deadline: $crate::Deadline,) -> Result<$crate::LiveElement, $crate::AdapterError> {+ let $adapter = self;Ok($crate::LiveElement {identity: $crate::LiveIdentity {name: $crate::LocatorField::Known($name.into()),description: $crate::LocatorField::Absent,identifiers: $crate::IdentifierEvidence::absent(),},- state: $crate::ElementState {- role: $role.into(),- states: Vec::new(),- value: None,- enabled: Some(true),- hidden: Some(false),- offscreen: Some(false),- },+ state: $state,states_complete: true,bounds: Some($crate::Rect {x: 1.0,@@ -35,14 +52,8 @@ macro_rules! complete_live_observation {_handle: &$crate::adapter::NativeHandle,_deadline: $crate::Deadline,) -> Result<Option<$crate::ElementState>, $crate::AdapterError> {- Ok(Some($crate::ElementState {- role: $role.into(),- states: Vec::new(),- value: None,- enabled: Some(true),- hidden: Some(false),- offscreen: Some(false),- }))+ let $adapter = self;+ Ok(Some($state))}fn get_element_bounds(@@ -122,6 +133,39 @@ pub(crate) fn live_identity(name: &str) -> crate::LiveIdentity {}}+pub(crate) fn recorded_action_state(requests: &[crate::ActionRequest]) -> crate::ElementState {+ let mut value = String::new();+ let mut checked = false;+ let mut expanded = false;+ for request in requests {+ match &request.action {+ crate::Action::Clear => value.clear(),+ crate::Action::SetValue(next) | crate::Action::TypeText(next) => value.clone_from(next),+ crate::Action::Check => checked = true,+ crate::Action::Uncheck => checked = false,+ crate::Action::Toggle => checked = !checked,+ crate::Action::Expand => expanded = true,+ crate::Action::Collapse => expanded = false,+ _ => {}+ }+ }+ let mut states = Vec::new();+ if checked {+ states.push(crate::state::CHECKED.into());+ }+ if expanded {+ states.push(crate::state::EXPANDED.into());+ }+ crate::ElementState {+ role: "textfield".into(),+ states,+ value: Some(value),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ }+}+pub(crate) fn observed_tree(root: &crate::live_locator::ObservationRoot<'_>,node: crate::AccessibilityNode,diff --git a/crates/core/src/commands/execute_by_ref_tests.rs b/crates/core/src/commands/execute_by_ref_tests.rsindex 45773daf1..415b4dbed 100644--- a/crates/core/src/commands/execute_by_ref_tests.rs+++ b/crates/core/src/commands/execute_by_ref_tests.rs@@ -139,7 +139,20 @@ impl ObservationOps for PolicyCaptureAdapter {crate::capability::CLICK,crate::capability::PRESS_KEY,crate::capability::SET_VALUE- ]+ ],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: adapter.captured.lock().unwrap().as_ref().and_then(|request| {+ match &request.action {+ Action::SetValue(value) => Some(value.clone()),+ _ => None,+ }+ }),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ });}diff --git a/crates/core/src/commands/find_live.rs b/crates/core/src/commands/find_live.rsindex 1b518be8a..b22efaa12 100644--- a/crates/core/src/commands/find_live.rs+++ b/crates/core/src/commands/find_live.rs@@ -162,7 +162,7 @@ fn format_response(let matches = resolution.matches.into_iter()- .map(|found| serde_json::to_value(found.data))+ .map(|found| format_match(found.data, found.entry.geometry.bounds)).collect::<Result<Vec<_>, _>>()?;if args.selection.first || args.selection.last || args.selection.nth.is_some() {let mut response = single_match_response(matches.into_iter().next(), query, roles_present);@@ -180,6 +180,18 @@ fn format_response(Ok(response)}+fn format_match(+ data: crate::live_locator::LocatorMatchData,+ bounds: Option<crate::Rect>,+) -> Result<Value, serde_json::Error> {+ let needs_geometry = data.ref_id.is_none();+ let mut value = serde_json::to_value(data)?;+ if needs_geometry && let Some(bounds) = bounds {+ value["bounds"] = serde_json::to_value(bounds)?;+ }+ Ok(value)+}+fn attach_snapshot_id(response: &mut Value, snapshot_id: Option<&str>) {if let (Some(object), Some(snapshot_id)) = (response.as_object_mut(), snapshot_id) {object.insert("snapshot_id".into(), json!(snapshot_id));@@ -243,6 +255,30 @@ mod tests {}}+ #[test]+ fn context_matches_expose_geometry_without_inventing_action_refs() {+ let data = crate::live_locator::LocatorMatchData {+ ref_id: None,+ role: "group".into(),+ name: "(unnamed group)".into(),+ value: None,+ states: Vec::new(),+ interactive: false,+ path: vec!["list".into()],+ };+ let bounds = crate::Rect {+ x: 10.0,+ y: 20.0,+ width: 100.0,+ height: 30.0,+ };+ let response = format_match(data.clone(), Some(bounds)).unwrap();++ assert_eq!(response["bounds"], json!(bounds));+ assert!(response["ref_id"].is_null());+ assert!(format_match(data, None).unwrap().get("bounds").is_none());+ }+#[test]fn zero_limit_requests_all_matches() {let request = resolve_request(&args(Some(0)), crate::Deadline::standard().unwrap());diff --git a/crates/core/src/commands/helpers_ref_action_dispatch_tests.rs b/crates/core/src/commands/helpers_ref_action_dispatch_tests.rsindex 32c170443..ccf790767 100644--- a/crates/core/src/commands/helpers_ref_action_dispatch_tests.rs+++ b/crates/core/src/commands/helpers_ref_action_dispatch_tests.rs@@ -27,7 +27,26 @@ impl ObservationOps for RecordingAdapter {crate::adapter::complete_live_observation!("textfield","OK",- [crate::capability::CLICK, crate::capability::TYPE_TEXT]+ [crate::capability::CLICK, crate::capability::TYPE_TEXT],+ adapter => ElementState {+ role: "textfield".into(),+ states: vec!["focused".into()],+ value: Some(+ adapter+ .request+ .lock()+ .unwrap()+ .as_ref()+ .and_then(|request| match &request.action {+ Action::TypeText(text) => Some(text.clone()),+ _ => None,+ })+ .unwrap_or_default(),+ ),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ });}diff --git a/crates/core/src/commands/ref_policy_tests.rs b/crates/core/src/commands/ref_policy_tests.rsindex f4c58c714..1e01d1893 100644--- a/crates/core/src/commands/ref_policy_tests.rs+++ b/crates/core/src/commands/ref_policy_tests.rs@@ -79,8 +79,22 @@ impl ObservationOps for RecordingAdapter {crate::capability::SCROLL,crate::capability::SCROLL_TO,crate::capability::TYPE_TEXT,- ]+ ],+ adapter => crate::adapter::recorded_action_state(&adapter.requests.lock().unwrap()));++ fn get_text_selection(+ &self,+ _handle: &NativeHandle,+ _deadline: crate::Deadline,+ ) -> Result<Option<std::ops::Range<usize>>, AdapterError> {+ let len = crate::adapter::recorded_action_state(&self.requests.lock().unwrap())+ .value+ .unwrap_or_default()+ .encode_utf16()+ .count();+ Ok(Some(0..len))+ }}impl ActionOps for RecordingAdapter {diff --git a/crates/core/src/commands/set_value_tests.rs b/crates/core/src/commands/set_value_tests.rsindex 46075c38a..6d740a1b2 100644--- a/crates/core/src/commands/set_value_tests.rs+++ b/crates/core/src/commands/set_value_tests.rs@@ -6,15 +6,18 @@ use crate::{adapter::NativeHandle, commands::stale_retry_test_support::StaleRetryCounter, refs::RefEntry,refs_test_support::HomeGuard,};+use std::sync::Mutex;struct StaleThenOkAdapter {retry: StaleRetryCounter,+ value: Mutex<String>,}impl StaleThenOkAdapter {fn new(fail_until: u32) -> Self {Self {retry: StaleRetryCounter::new(fail_until),+ value: Mutex::new(String::new()),}}}@@ -31,7 +34,15 @@ impl ObservationOps for StaleThenOkAdapter {crate::adapter::complete_live_observation!("textfield","Target",- [crate::capability::SET_VALUE]+ [crate::capability::SET_VALUE],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: Some(adapter.value.lock().unwrap().clone()),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ });}@@ -39,9 +50,12 @@ impl ActionOps for StaleThenOkAdapter {fn execute_action(&self,_handle: &NativeHandle,- _request: ActionRequest,+ request: ActionRequest,_lease: &crate::InteractionLease,) -> Result<ActionResult, AdapterError> {+ if let crate::Action::SetValue(value) = request.action {+ *self.value.lock().unwrap() = value;+ }Ok(ActionResult::delivered_unverified("set_value"))}}diff --git a/crates/core/src/commands/type_text_tests.rs b/crates/core/src/commands/type_text_tests.rsindex 2dd8751c2..e17c02ec2 100644--- a/crates/core/src/commands/type_text_tests.rs+++ b/crates/core/src/commands/type_text_tests.rs@@ -6,15 +6,18 @@ use crate::{adapter::NativeHandle, commands::stale_retry_test_support::StaleRetryCounter, refs::RefEntry,refs_test_support::HomeGuard,};+use std::sync::Mutex;struct StaleThenOkAdapter {retry: StaleRetryCounter,+ value: Mutex<String>,}impl StaleThenOkAdapter {fn new(fail_until: u32) -> Self {Self {retry: StaleRetryCounter::new(fail_until),+ value: Mutex::new(String::new()),}}}@@ -31,7 +34,15 @@ impl ObservationOps for StaleThenOkAdapter {crate::adapter::complete_live_observation!("textfield","Target",- [crate::capability::TYPE_TEXT]+ [crate::capability::TYPE_TEXT],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: Some(adapter.value.lock().unwrap().clone()),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ });}@@ -39,9 +50,12 @@ impl ActionOps for StaleThenOkAdapter {fn execute_action(&self,_handle: &NativeHandle,- _request: ActionRequest,+ request: ActionRequest,_lease: &crate::InteractionLease,) -> Result<ActionResult, AdapterError> {+ if let crate::Action::TypeText(text) = request.action {+ self.value.lock().unwrap().push_str(&text);+ }Ok(ActionResult::delivered_unverified("type_text"))}}diff --git a/crates/core/src/cursor_overlay/control.rs b/crates/core/src/cursor_overlay/control.rsindex 65529ec7b..d11902ba9 100644--- a/crates/core/src/cursor_overlay/control.rs+++ b/crates/core/src/cursor_overlay/control.rs@@ -163,6 +163,16 @@ impl CursorOverlayControl {})}+ pub fn expects_acknowledgement(&self) -> bool {+ self.is_hide()+ || self.is_show()+ || self.is_disable()+ || self.is_travel()+ || self+ .instruction()+ .is_some_and(|instruction| instruction.phase() == CursorPhase::Effect)+ }+pub const fn is_hide(&self) -> bool {matches!(self, Self::Hide { .. })}diff --git a/crates/core/src/cursor_overlay/tests.rs b/crates/core/src/cursor_overlay/tests.rsindex 3387f14af..6fcef48d0 100644--- a/crates/core/src/cursor_overlay/tests.rs+++ b/crates/core/src/cursor_overlay/tests.rs@@ -150,6 +150,7 @@ fn drag_phase_is_serialized_and_requires_acknowledgement() {let control = CursorOverlayControl::present("run-1".into(), instruction);assert!(control.is_travel());+ assert!(control.expects_acknowledgement());assert_eq!(serde_json::to_value(control).expect("control serializes")["instruction"]["phase"],"drag"@@ -166,6 +167,10 @@ fn control_protocol_carries_the_session_lifecycle() {assert!(enable.is_enable());assert_eq!(disable.session_id(), "run-1");assert!(disable.is_disable());+ assert!(disable.expects_acknowledgement());+ assert!(!enable.expects_acknowledgement());+ assert!(CursorOverlayControl::show("run-1".into()).expects_acknowledgement());+ assert!(CursorOverlayControl::hide("run-1".into()).expects_acknowledgement());}#[test]diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex 3dd3610b9..54a3c4e22 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -70,6 +70,7 @@ pub mod output;pub mod permission_report;pub mod permission_state;mod point;+mod post_action;mod private_file;mod private_file_parent;mod process_id;@@ -143,6 +144,7 @@ pub mod trace_sanitize;mod trace_state;pub mod tree_options;mod ui_event;+mod value_matches;mod wait_budget;pub mod window_filter;mod window_focus;@@ -236,6 +238,7 @@ pub use output::{ErrorPayload, Response};pub use permission_report::PermissionReport;pub use permission_state::PermissionState;pub use point::Point;+pub use post_action::execute_verified_action;pub use process_id::ProcessId;pub use process_identity::ProcessIdentity;pub use recovery_hint::RecoveryHint;@@ -268,6 +271,7 @@ pub use surface_signal::SurfaceSignal;pub use trace_sanitize::sanitize_trace_value;pub use tree_options::TreeOptions;pub use ui_event::UiEvent;+pub use value_matches::value_matches;pub use wait_budget::{MAX_WAIT_TIMEOUT_MS, wait_timeout_duration};pub use window_filter::WindowFilter;pub use window_info::WindowInfo;diff --git a/crates/core/src/output.rs b/crates/core/src/output.rsindex b0760e002..a2dc3c9e4 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.3";+pub const ENVELOPE_VERSION: &str = "2.4";/// Structured output envelope used by the CLI and future programmatic transports.#[derive(Debug, Serialize)]diff --git a/crates/core/src/post_action.rs b/crates/core/src/post_action.rsnew file mode 100644index 000000000..4a2effc9b--- /dev/null+++ b/crates/core/src/post_action.rs@@ -0,0 +1,213 @@+use crate::{+ Action, ActionRequest, ActionResult, AdapterError, DeliverySemantics, ErrorCode,+ InteractionLease, LiveElement, NativeHandle, PlatformAdapter,+};++/// Executes once, then verifies stateful actions from fresh platform observations.+pub fn execute_verified_action(+ adapter: &dyn PlatformAdapter,+ handle: &NativeHandle,+ request: ActionRequest,+ lease: &InteractionLease,+) -> Result<ActionResult, AdapterError> {+ let action = request.action.clone();+ if !action.requires_state_readback() {+ return adapter.execute_action(handle, request, lease);+ }+ let deadline = lease.deadline();+ let before = matches!(action, Action::TypeText(_) | Action::Toggle)+ .then(|| adapter.get_live_element(handle, deadline).ok())+ .flatten();+ let expected_text = match (&action, &before) {+ (Action::TypeText(text), Some(before)) => before.state.value.as_deref().and_then(|value| {+ let selection_is_preserved = !request.policy.is_headed()+ || crate::state::has_state(&before.state.states, crate::state::FOCUSED);+ let selection = selection_is_preserved+ .then(|| adapter.get_text_selection(handle, deadline).ok().flatten())+ .flatten();+ expected_insertion(value, text, selection)+ }),+ _ => None,+ };+ let execution = adapter.execute_action(handle, request, lease);+ if execution+ .as_ref()+ .is_err_and(|error| error.disposition == DeliverySemantics::not_delivered())+ {+ return execution;+ }+ let mut observed = adapter.get_live_element(handle, deadline);+ let settle = std::time::Duration::from_millis(50);+ let settle_deadline = deadline.capped(std::time::Duration::from_millis(400));+ while execution.is_ok()+ && observed.as_ref().is_ok_and(|observed| {+ matches_postcondition(&action, before.as_ref(), expected_text.as_deref(), observed)+ == Some(false)+ })+ && settle_deadline.remaining() > settle+ {+ std::thread::sleep(settle);+ observed = adapter.get_live_element(handle, deadline);+ }+ let mut result = match execution {+ Ok(result) => result,+ Err(mut error) => {+ if let Ok(observed) = observed {+ let details = error.details.get_or_insert_with(|| serde_json::json!({}));+ if let Some(details) = details.as_object_mut() {+ details.insert("post_state".into(), serde_json::json!(observed.state));+ if let Some(satisfied) = matches_postcondition(+ &action,+ before.as_ref(),+ expected_text.as_deref(),+ &observed,+ ) {+ details.insert("postcondition_satisfied".into(), satisfied.into());+ }+ }+ }+ return Err(error);+ }+ };+ let observed = observed.map_err(|error| verification_error(&result, None, error))?;+ let verified = matches_postcondition(+ &action,+ before.as_ref(),+ expected_text.as_deref(),+ &observed,+ );+ if verified.is_none() {+ let reason = if secure_value_is_redacted(&action, &observed) {+ "secure_field"+ } else {+ "insufficient_evidence"+ };+ result.post_state = Some(observed.state);+ result = result.with_unverified_delivery();+ let details = result.details.get_or_insert_with(|| serde_json::json!({}));+ if let Some(details) = details.as_object_mut() {+ details.insert("verification_scope".into(), "unavailable".into());+ details.insert("verification_reason".into(), reason.into());+ details.insert("application_commit".into(), "not_verified".into());+ }+ return Ok(result);+ }+ if verified == Some(false) {+ return Err(verification_error(+ &result,+ Some(&observed),+ AdapterError::new(+ ErrorCode::ActionFailed,+ "Post-action state does not match the requested change",+ ),+ ));+ }+ result.post_state = Some(observed.state);+ result = result.with_verified_delivery();+ let details = result.details.get_or_insert_with(|| serde_json::json!({}));+ if let Some(details) = details.as_object_mut() {+ details.insert("verification_scope".into(), "element_state".into());+ if action.writes_element_value() {+ details.insert("verification_scope".into(), "element_value".into());+ details.insert("application_commit".into(), "not_verified".into());+ }+ }+ Ok(result)+}++fn secure_value_is_redacted(action: &Action, observed: &LiveElement) -> bool {+ action.writes_element_value()+ && observed.state.value.is_none()+ && crate::state::has_state(&observed.state.states, crate::state::SECURE)+}++fn matches_postcondition(+ action: &Action,+ before: Option<&LiveElement>,+ expected_text: Option<&str>,+ observed: &LiveElement,+) -> Option<bool> {+ let state = &observed.state;+ match action {+ Action::SetValue(expected) => state+ .value+ .as_deref()+ .map(|value| crate::value_matches(&state.role, expected, Some(value))),+ Action::Clear => state.value.as_deref().map(str::is_empty),+ Action::TypeText(_) => expected_text+ .zip(state.value.as_deref())+ .map(|(expected, value)| expected == value),+ Action::Check | Action::Uncheck => {+ checked(observed).map(|value| value == matches!(action, Action::Check))+ }+ Action::Toggle => before+ .and_then(checked)+ .zip(checked(observed))+ .map(|(before, after)| before != after),+ Action::Expand | Action::Collapse => observed.states_complete.then(|| {+ crate::state::has_state(&state.states, crate::state::EXPANDED)+ == matches!(action, Action::Expand)+ }),+ _ => None,+ }+}++fn checked(element: &LiveElement) -> Option<bool> {+ if !element.states_complete+ || crate::state::has_state(&element.state.states, crate::state::INDETERMINATE)+ {+ return None;+ }+ Some(crate::state::has_state(+ &element.state.states,+ crate::state::CHECKED,+ ))+}++fn expected_insertion(+ before: &str,+ text: &str,+ selection: Option<std::ops::Range<usize>>,+) -> Option<String> {+ let range = selection.or_else(|| before.is_empty().then_some(0..0))?;+ let mut value: Vec<u16> = before.encode_utf16().collect();+ value.get(range.clone())?;+ String::from_utf16(&value[..range.start]).ok()?;+ String::from_utf16(&value[range.end..]).ok()?;+ value.splice(range, text.encode_utf16());+ String::from_utf16(&value).ok()+}++fn verification_error(+ result: &ActionResult,+ observed: Option<&LiveElement>,+ mut error: AdapterError,+) -> AdapterError {+ let disposition = if result.disposition() == DeliverySemantics::not_delivered() {+ DeliverySemantics::not_delivered()+ } else {+ DeliverySemantics::delivered_unverified()+ };+ let mut details = match error.details.take() {+ Some(serde_json::Value::Object(details)) => details,+ Some(cause) => serde_json::Map::from_iter([("cause".into(), cause)]),+ None => serde_json::Map::new(),+ };+ details.insert("kind".into(), "post_action_verification".into());+ details.insert("after_action".into(), serde_json::json!(result));+ if let Some(observed) = observed {+ details.insert("post_state".into(), serde_json::json!(observed.state));+ }+ if error.suggestion.is_none() {+ error.suggestion = Some(+ "Inspect the returned state before deciding whether another action is needed.".into(),+ );+ }+ error+ .with_disposition(disposition)+ .with_details(details.into())+}++#[cfg(test)]+#[path = "post_action_tests.rs"]+mod tests;diff --git a/crates/core/src/post_action_budget_tests.rs b/crates/core/src/post_action_budget_tests.rsnew file mode 100644index 000000000..e0b4988ea--- /dev/null+++ b/crates/core/src/post_action_budget_tests.rs@@ -0,0 +1,39 @@+use super::*;++#[test]+fn settling_reuses_caller_deadline_without_repeating_delivery() {+ let adapter = adapter(element(Some("old"), &[]), element(Some("new"), &[]));+ adapter+ .settling+ .lock()+ .unwrap()+ .extend([element(Some("old"), &[]), element(Some("partial"), &[])]);+ let deadline = Deadline::after(1000).unwrap();+ let result = execute_verified_action(+ &adapter,+ &NativeHandle::null(),+ ActionRequest::headless(Action::SetValue("new".into())),+ &InteractionLease::guarded(deadline, ()).unwrap(),+ )+ .unwrap();+ assert_eq!(+ result.disposition(),+ DeliverySemantics::delivered_verified()+ );+ assert_eq!(*adapter.reads.lock().unwrap(), vec![deadline; 3]);+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+}++#[test]+fn no_settle_read_is_started_without_remaining_budget() {+ let adapter = adapter(element(Some("old"), &[]), element(Some("old"), &[]));+ let error = execute_verified_action(+ &adapter,+ &NativeHandle::null(),+ ActionRequest::headless(Action::Clear),+ &InteractionLease::guarded(Deadline::after(40).unwrap(), ()).unwrap(),+ )+ .unwrap_err();+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ assert_eq!(adapter.reads.lock().unwrap().len(), 1);+}diff --git a/crates/core/src/post_action_focus_tests.rs b/crates/core/src/post_action_focus_tests.rsnew file mode 100644index 000000000..914a532fd--- /dev/null+++ b/crates/core/src/post_action_focus_tests.rs@@ -0,0 +1,49 @@+use super::*;++fn type_after_focus(headed: bool, already_focused: bool) -> Result<ActionResult, AdapterError> {+ let states = if already_focused {+ vec!["focused"]+ } else {+ vec![]+ };+ let mut adapter = adapter(+ element(Some("before"), &states),+ element(Some("inserted"), &["focused"]),+ );+ adapter.selection = Some(0..0);+ let action = Action::TypeText("inserted".into());+ let request = if headed {+ ActionRequest::headed(action)+ } else {+ ActionRequest::headless(action)+ };+ execute_verified_action(+ &adapter,+ &NativeHandle::null(),+ request,+ &InteractionLease::guarded(Deadline::after(1000).unwrap(), ()).unwrap(),+ )+}++#[test]+fn headed_typing_does_not_treat_a_pre_focus_selection_as_delivery_evidence() {+ let result = type_after_focus(true, false).unwrap();+ assert_eq!(+ result.disposition(),+ DeliverySemantics::delivered_unverified()+ );+ assert_eq!(+ result.post_state.unwrap().value.as_deref(),+ Some("inserted")+ );+ assert_eq!(result.details.unwrap()["verification_scope"], "unavailable");+}++#[test]+fn focused_and_headless_typing_still_reject_contradictory_insertions() {+ for (headed, focused) in [(true, true), (false, false)] {+ let error = type_after_focus(headed, focused).unwrap_err();+ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ }+}diff --git a/crates/core/src/post_action_tests.rs b/crates/core/src/post_action_tests.rsnew file mode 100644index 000000000..efe3e00d3--- /dev/null+++ b/crates/core/src/post_action_tests.rs@@ -0,0 +1,345 @@+use super::*;+use crate::{ActionOps, Deadline, InputOps, ObservationOps, SystemOps};+use std::sync::atomic::{AtomicUsize, Ordering};++struct Adapter {+ before: Result<LiveElement, AdapterError>,+ after: Result<LiveElement, AdapterError>,+ selection: Option<std::ops::Range<usize>>,+ execution: Result<ActionResult, AdapterError>,+ calls: AtomicUsize,+ reads: std::sync::Mutex<Vec<Deadline>>,+ settling: std::sync::Mutex<std::collections::VecDeque<LiveElement>>,+}++impl ObservationOps for Adapter {+ fn get_live_element(+ &self,+ _: &NativeHandle,+ deadline: Deadline,+ ) -> Result<LiveElement, AdapterError> {+ self.reads.lock().unwrap().push(deadline);+ if self.calls.load(Ordering::SeqCst) == 0 {+ self.before.clone()+ } else {+ self.settling+ .lock()+ .unwrap()+ .pop_front()+ .map(Ok)+ .unwrap_or_else(|| self.after.clone())+ }+ }++ fn get_text_selection(+ &self,+ _: &NativeHandle,+ _: Deadline,+ ) -> Result<Option<std::ops::Range<usize>>, AdapterError> {+ Ok(self.selection.clone())+ }+}++impl ActionOps for Adapter {+ fn execute_action(+ &self,+ _: &NativeHandle,+ _: ActionRequest,+ _: &InteractionLease,+ ) -> Result<ActionResult, AdapterError> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ self.execution.clone()+ }+}++impl InputOps for Adapter {}+impl SystemOps for Adapter {}++fn element(value: Option<&str>, states: &[&str]) -> LiveElement {+ LiveElement {+ identity: crate::adapter::live_identity("field"),+ state: crate::ElementState {+ role: "textfield".into(),+ states: states.iter().map(|s| s.to_string()).collect(),+ value: value.map(str::to_string),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ },+ states_complete: true,+ bounds: None,+ available_actions: vec![],+ }+}++fn adapter(before: LiveElement, after: LiveElement) -> Adapter {+ Adapter {+ before: Ok(before),+ after: Ok(after),+ selection: None,+ execution: Ok(ActionResult::delivered_unverified("test")),+ calls: AtomicUsize::new(0),+ reads: Default::default(),+ settling: Default::default(),+ }+}++fn execute(adapter: &Adapter, action: Action) -> Result<ActionResult, AdapterError> {+ execute_verified_action(+ adapter,+ &NativeHandle::null(),+ ActionRequest::headless(action),+ &InteractionLease::guarded(Deadline::after(1000).unwrap(), ()).unwrap(),+ )+}++#[test]+fn adapter_success_cannot_override_contradictory_fresh_state() {+ for (action, before, after) in [+ (+ Action::TypeText("new".into()),+ element(Some(""), &[]),+ element(Some(""), &[]),+ ),+ (+ Action::SetValue("new".into()),+ element(Some("old"), &[]),+ element(Some("partial"), &[]),+ ),+ (+ Action::Clear,+ element(Some("old"), &[]),+ element(Some("old"), &[]),+ ),+ (Action::Check, element(None, &[]), element(None, &[])),+ (+ Action::Uncheck,+ element(None, &["checked"]),+ element(None, &["checked"]),+ ),+ (+ Action::Toggle,+ element(None, &["checked"]),+ element(None, &["checked"]),+ ),+ (Action::Expand, element(None, &[]), element(None, &[])),+ (+ Action::Collapse,+ element(None, &["expanded"]),+ element(None, &["expanded"]),+ ),+ ] {+ let adapter = adapter(before, after);+ let error = execute(&adapter, action).unwrap_err();+ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ assert!(error.details.unwrap()["post_state"].is_object());+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+ }+}++#[test]+fn text_selection_replacement_is_verified_and_returns_the_actual_value() {+ let mut adapter = adapter(element(Some("a😀b"), &[]), element(Some("aXb"), &[]));+ adapter.selection = Some(1..3);+ let result = execute(&adapter, Action::TypeText("X".into())).unwrap();+ assert_eq!(+ result.disposition(),+ DeliverySemantics::delivered_verified()+ );+ assert_eq!(result.post_state.unwrap().value.as_deref(), Some("aXb"));+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+ assert!(expected_insertion("😀", "X", Some(1..1)).is_none());+ assert!(expected_insertion("a", "X", Some(0..3)).is_none());+ assert!(expected_insertion("contains X", "X", None).is_none());+}++#[test]+fn absent_or_incomplete_evidence_cannot_be_verified() {+ let mut incomplete = element(None, &[]);+ incomplete.states_complete = false;+ for (action, after) in [+ (Action::SetValue("new".into()), element(None, &[])),+ (Action::Uncheck, incomplete),+ ] {+ let adapter = adapter(element(Some(""), &[]), after);+ let result = execute(&adapter, action).unwrap();+ assert_eq!(+ result.disposition(),+ DeliverySemantics::delivered_unverified()+ );+ assert_eq!(result.details.unwrap()["verification_scope"], "unavailable");+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+ }+}++#[test]+fn native_errors_keep_postcondition_evidence_without_repeating_delivery() {+ for (action, value, satisfied) in [+ (Action::TypeText("requested".into()), "partial", false),+ (Action::SetValue("requested".into()), "requested", true),+ ] {+ let mut adapter = adapter(element(Some(""), &[]), element(Some(value), &[]));+ adapter.execution = Err(AdapterError::timeout("native delivery")+ .with_disposition(DeliverySemantics::uncertain()));+ let error = execute(&adapter, action).unwrap_err();+ assert_eq!(error.code, ErrorCode::Timeout);+ assert_eq!(error.disposition, DeliverySemantics::uncertain());+ let details = error.details.unwrap();+ assert_eq!(details["post_state"]["value"], value);+ assert_eq!(details["postcondition_satisfied"], satisfied);+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+ }+}++#[test]+fn post_read_errors_preserve_cause_codes_details_and_recovery_hints() {+ for code in [+ ErrorCode::StaleRef,+ ErrorCode::AppUnresponsive,+ ErrorCode::Timeout,+ ErrorCode::PermDenied,+ ] {+ let mut adapter = adapter(element(Some("old"), &[]), element(None, &[]));+ adapter.after = Err(AdapterError::new(code.clone(), "readback failed")+ .with_platform_detail("native cause")+ .with_details(serde_json::json!({"cause_evidence": "kept"}))+ .with_suggestion("original recovery"));+ let error = execute(&adapter, Action::Clear).unwrap_err();+ assert_eq!(error.code, code);+ assert_eq!(error.platform_detail.as_deref(), Some("native cause"));+ assert_eq!(error.suggestion.as_deref(), Some("original recovery"));+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ let details = error.details.unwrap();+ assert_eq!(details["cause_evidence"], "kept");+ assert_eq!(details["kind"], "post_action_verification");+ assert!(details.get("post_state").is_none());+ }+}++#[test]+fn secure_text_writes_succeed_without_claiming_value_verification() {+ for action in [+ Action::SetValue("private".into()),+ Action::Clear,+ Action::TypeText("private".into()),+ ] {+ let expected_reads = if matches!(action, Action::TypeText(_)) {+ 2+ } else {+ 1+ };+ let mut adapter = adapter(element(None, &["secure"]), element(None, &["secure"]));+ adapter.execution = Ok(ActionResult::delivered_unverified("test").with_verified_delivery());+ let result = execute(&adapter, action).expect("redacted readback is not a failed write");+ assert_eq!(+ result.disposition(),+ DeliverySemantics::delivered_unverified()+ );+ assert_eq!(result.post_state.as_ref().unwrap().value, None);+ assert_eq!(+ result.details.as_ref().unwrap()["verification_reason"],+ "secure_field"+ );+ assert_eq!(+ result.details.as_ref().unwrap()["verification_scope"],+ "unavailable"+ );+ assert!(!serde_json::to_string(&result).unwrap().contains("private"));+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+ assert_eq!(adapter.reads.lock().unwrap().len(), expected_reads);+ }+}++#[test]+fn secure_field_redaction_does_not_hide_delivery_errors() {+ let mut adapter = adapter(element(None, &["secure"]), element(None, &["secure"]));+ adapter.execution =+ Err(AdapterError::timeout("write").with_disposition(DeliverySemantics::uncertain()));+ let error = execute(&adapter, Action::SetValue("private".into())).unwrap_err();+ assert_eq!(error.code, ErrorCode::Timeout);+ assert_eq!(error.disposition, DeliverySemantics::uncertain());+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+}++#[test]+fn missing_selection_does_not_turn_delivered_text_into_a_failure() {+ let adapter = adapter(element(Some("old"), &[]), element(Some("oldnew"), &[]));+ let result = execute(&adapter, Action::TypeText("new".into())).unwrap();+ assert_eq!(+ result.disposition(),+ DeliverySemantics::delivered_unverified()+ );+ assert_eq!(+ result.details.unwrap()["verification_reason"],+ "insufficient_evidence"+ );+ assert_eq!(adapter.reads.lock().unwrap().len(), 2);+}++#[test]+fn satisfied_actions_and_pre_delivery_errors_do_not_claim_delivery() {+ let mut adapter = adapter(element(Some(""), &[]), element(Some(""), &[]));+ adapter.execution = Ok(ActionResult::satisfied_without_delivery("clear"));+ assert_eq!(+ execute(&adapter, Action::Clear).unwrap().disposition(),+ DeliverySemantics::not_delivered()+ );+ adapter.execution = Err(AdapterError::timeout("before delivery")+ .with_disposition(DeliverySemantics::not_delivered()));+ adapter.reads.lock().unwrap().clear();+ let error = execute(&adapter, Action::Clear).unwrap_err();+ assert_eq!(error.message, "before delivery");+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());+ assert_eq!(adapter.reads.lock().unwrap().len(), 0);+}++#[test]+fn numeric_coercion_is_verified_by_live_readback() {+ let mut observed = element(Some("1.0"), &[]);+ observed.state.role = "slider".into();+ let adapter = adapter(element(Some("0"), &[]), observed);+ assert_eq!(+ execute(&adapter, Action::SetValue("1".into()))+ .unwrap()+ .disposition(),+ DeliverySemantics::delivered_verified()+ );+}++#[test]+fn missing_before_evidence_does_not_block_or_repeat_headed_or_headless_delivery() {+ for request in [+ ActionRequest::headless(Action::TypeText("new".into())),+ ActionRequest::headed(Action::TypeText("new".into())),+ ] {+ let mut adapter = adapter(element(Some(""), &[]), element(Some("new"), &[]));+ adapter.before = Err(AdapterError::timeout("before read"));+ let result = execute_verified_action(+ &adapter,+ &NativeHandle::null(),+ request,+ &InteractionLease::guarded(Deadline::after(1000).unwrap(), ()).unwrap(),+ )+ .unwrap();+ assert_eq!(+ result.disposition(),+ DeliverySemantics::delivered_unverified()+ );+ assert_eq!(adapter.calls.load(Ordering::SeqCst), 1);+ assert_eq!(adapter.reads.lock().unwrap().len(), 2);+ }+}++#[test]+fn clicks_do_not_read_a_target_that_navigation_can_destroy() {+ let adapter = adapter(element(None, &[]), element(None, &[]));+ execute(&adapter, Action::Click).unwrap();+ assert_eq!(adapter.reads.lock().unwrap().len(), 0);+}++#[path = "post_action_focus_tests.rs"]+mod focus_tests;++#[path = "post_action_budget_tests.rs"]+mod budget_tests;diff --git a/crates/core/src/ref_action.rs b/crates/core/src/ref_action.rsindex cd855e992..9d90b61b9 100644--- a/crates/core/src/ref_action.rs+++ b/crates/core/src/ref_action.rs@@ -1,3 +1,4 @@+use crate::ref_action_wait_support::{after_scroll, trace_scroll_error};use crate::{AdapterError, AppError,action_request::ActionRequest,@@ -90,9 +91,10 @@ pub(crate) fn dispatch_resolved(handle = target.adapter.resolve_element_strict(target.entry, target.deadline)- .map_err(mark_pre_dispatch_resolution_failure)?;+ .map_err(after_scroll)?;let scrolled_target = ResolvedRefAction::new(target, &handle);- stable_preflight(&scrolled_target, &request)?+ stable_preflight(&scrolled_target, &request)+ .map_err(|error| after_scroll(into_adapter_error(error)))?}};if matches!(@@ -113,9 +115,8 @@ pub(crate) fn dispatch_resolved(let raises_surface = request.action.may_raise_surface();let presentation_action = request.action.clone();presentation::before_dispatch(&final_target, &preflight, lease);- let dispatch_result = final_target- .adapter- .execute_action(final_target.handle, request, lease);+ let dispatch_result =+ crate::execute_verified_action(final_target.adapter, final_target.handle, request, lease);presentation::after_dispatch(final_target.adapter,final_target.context,@@ -225,18 +226,24 @@ fn stable_preflight(target: &ResolvedRefAction<'_>,request: &ActionRequest,) -> Result<ActionabilityPreflight, AppError> {- let permissive = check_actionability_with_trace(+ match check_actionability_with_trace(target,request,actionability::StabilityExpectation::permissive(target.entry.geometry.bounds_hash),- )?;- if !actionability::requires_stability(&request.action)- || matches!(- permissive.pointer_delivery,- actionability::PointerDelivery::Semantic- )- {- return Ok(permissive);+ ) {+ Ok(preflight)+ if !actionability::requires_stability(&request.action)+ || matches!(+ preflight.pointer_delivery,+ actionability::PointerDelivery::Semantic+ ) =>+ {+ return Ok(preflight);+ }+ Ok(_) => {}+ Err(AppError::Adapter(error))+ if crate::ref_action_wait_evidence::only_stability_pending(&error) => {}+ Err(error) => return Err(error),}let started = std::time::Instant::now();let mut sampler = actionability::stability_sampler::StabilitySampler::new();@@ -261,16 +268,6 @@ fn stable_preflight(}}-fn trace_scroll_error(target: &RefActionContext<'_>, error: &AdapterError) {- let _ = target.context.trace_lazy("ref.scroll_into_view.error", || {- serde_json::json!({- "ref": target.ref_id,- "code": error.code.as_str(),- "message": error.message,- })- });-}-#[cfg(test)]pub(crate) fn execute_resolved(target: ResolvedRefAction<'_>,diff --git a/crates/core/src/ref_action_cursor_overlay_tests.rs b/crates/core/src/ref_action_cursor_overlay_tests.rsindex 437234ce7..b15599e09 100644--- a/crates/core/src/ref_action_cursor_overlay_tests.rs+++ b/crates/core/src/ref_action_cursor_overlay_tests.rs@@ -8,6 +8,7 @@ use std::sync::Mutex;struct CursorAdapter {presented: Mutex<Vec<CursorOverlayControl>>,events: Mutex<Vec<CursorEvent>>,+ value: Mutex<Option<String>>,fail_presentation: bool,}@@ -23,6 +24,7 @@ impl CursorAdapter {Self {presented: Mutex::new(Vec::new()),events: Mutex::new(Vec::new()),+ value: Mutex::new(None),fail_presentation,}}@@ -40,7 +42,15 @@ impl ObservationOps for CursorAdapter {crate::adapter::complete_live_observation!("textfield","Run",- [capability::CLICK, capability::SET_VALUE]+ [capability::CLICK, capability::SET_VALUE],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: adapter.value.lock().unwrap().clone(),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ });}@@ -57,6 +67,9 @@ impl ActionOps for CursorAdapter {Some(&crate::Point { x: 11.0, y: 11.0 }));}+ if let Action::SetValue(value) = &request.action {+ *self.value.lock().unwrap() = Some(value.clone());+ }self.events.lock().unwrap().push(CursorEvent::Dispatch);Ok(ActionResult::delivered_unverified("click"))}diff --git a/crates/core/src/ref_action_exactly_once_tests.rs b/crates/core/src/ref_action_exactly_once_tests.rsindex 0edbd4d35..703658c13 100644--- a/crates/core/src/ref_action_exactly_once_tests.rs+++ b/crates/core/src/ref_action_exactly_once_tests.rs@@ -93,7 +93,7 @@ impl ObservationOps for DispatchGuardAdapter {states: Vec::new(),value: None,enabled: Some(true),- hidden: Some(false),+ hidden: Some(self.mode == "hidden_after_scroll"),offscreen: Some(self.mode == "offscreen_slow"),},states_complete: true,@@ -231,6 +231,19 @@ fn execute(adapter: &DispatchGuardAdapter, timeout_ms: u64) -> Result<ActionResu)}+#[test]+fn failed_preflight_after_scroll_cannot_authorize_an_automatic_retry() {+ let adapter = DispatchGuardAdapter::new("hidden_after_scroll", 0);+ let error = execute(&adapter, 500).unwrap_err();+ assert_eq!(error.disposition, crate::DeliverySemantics::uncertain());+ assert_eq!(+ error.details.unwrap()["preparatory_scroll"],+ "may_have_changed_view"+ );+ assert_eq!(adapter.scroll_calls.load(Ordering::SeqCst), 1);+ assert_eq!(adapter.dispatch_calls.load(Ordering::SeqCst), 0);+}+#[test]fn dispatch_failure_is_returned_without_repeating_the_action() {let adapter = DispatchGuardAdapter::new("dispatch_error", 0);diff --git a/crates/core/src/ref_action_focus_order_tests.rs b/crates/core/src/ref_action_focus_order_tests.rsnew file mode 100644index 000000000..ab5689d25--- /dev/null+++ b/crates/core/src/ref_action_focus_order_tests.rs@@ -0,0 +1,175 @@+use crate::{+ Action, ActionOps, ActionRequest, ActionResult, AdapterError, Deadline, ElementState, InputOps,+ InteractionLease, LiveElement, NativeHandle, ObservationOps, RefEntry, SystemOps, WindowInfo,+};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};++struct FocusAdapter {+ focused: AtomicBool,+ dispatched: AtomicUsize,+ persistent_occlusion: bool,+ enabled: bool,+}++fn bounds() -> crate::Rect {+ crate::Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ }+}++impl FocusAdapter {+ fn live_bounds(&self) -> crate::Rect {+ crate::Rect {+ x: if self.focused.load(Ordering::SeqCst) {+ 100.0+ } else {+ 1.0+ },+ ..bounds()+ }+ }+}++impl ObservationOps for FocusAdapter {+ fn resolve_element_strict(+ &self,+ _: &RefEntry,+ _: Deadline,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_live_element(&self, _: &NativeHandle, _: Deadline) -> Result<LiveElement, AdapterError> {+ Ok(LiveElement {+ identity: crate::adapter::live_identity("Run"),+ state: ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ enabled: Some(self.enabled),+ hidden: Some(false),+ offscreen: Some(false),+ },+ states_complete: true,+ bounds: Some(self.live_bounds()),+ available_actions: vec![crate::capability::CLICK.into()],+ })+ }++ fn get_element_bounds(+ &self,+ _: &NativeHandle,+ _: Deadline,+ ) -> Result<Option<crate::Rect>, AdapterError> {+ Ok(Some(self.live_bounds()))+ }++ fn hit_test(+ &self,+ _: &NativeHandle,+ _: crate::Point,+ _: Deadline,+ ) -> Result<crate::HitTestResult, AdapterError> {+ Ok(+ if self.focused.load(Ordering::SeqCst) && !self.persistent_occlusion {+ crate::HitTestResult::ReachesTarget+ } else {+ crate::HitTestResult::InterceptedBy {+ role: Some("window".into()),+ name: None,+ bounds: None,+ }+ },+ )+ }+}++impl ActionOps for FocusAdapter {+ fn execute_action(+ &self,+ _: &NativeHandle,+ request: ActionRequest,+ _: &InteractionLease,+ ) -> Result<ActionResult, AdapterError> {+ if request.policy.is_headed() {+ assert!(self.focused.load(Ordering::SeqCst));+ assert_eq!(request.verified_point().map(|point| point.x), Some(110.0));+ }+ self.dispatched.fetch_add(1, Ordering::SeqCst);+ Ok(ActionResult::delivered_unverified("click"))+ }+}+impl InputOps for FocusAdapter {}+impl SystemOps for FocusAdapter {+ crate::adapter::guarded_interaction_lease!();++ fn resolve_window_strict(+ &self,+ window: &WindowInfo,+ _: Deadline,+ ) -> Result<WindowInfo, AdapterError> {+ Ok(window.clone())+ }+ fn focus_window(&self, _: &WindowInfo, _: &InteractionLease) -> Result<(), AdapterError> {+ self.focused.store(true, Ordering::SeqCst);+ Ok(())+ }+}++fn execute(adapter: &FocusAdapter, headed: bool) -> Result<ActionResult, AdapterError> {+ let entry: RefEntry = serde_json::from_value(serde_json::json!({+ "pid": 1, "process_instance": "test-instance", "role": "button", "name": "Run",+ "source_window_id": "w-test", "source_surface": "window", "path": [0],+ "bounds": bounds(), "bounds_hash": bounds().bounds_hash(), "available_actions": ["Click"], "states": []+ })).unwrap();+ let request = if headed {+ ActionRequest::headed(Action::Click)+ } else {+ ActionRequest::headless(Action::Click)+ };+ crate::ref_action::execute_entry(adapter, &entry, request.with_timeout_ms(Some(150)))+}++fn adapter(persistent_occlusion: bool, enabled: bool) -> FocusAdapter {+ FocusAdapter {+ focused: AtomicBool::new(false),+ dispatched: AtomicUsize::new(0),+ persistent_occlusion,+ enabled,+ }+}++#[test]+fn headed_background_target_is_focused_before_final_hit_test_and_dispatch() {+ let adapter = adapter(false, true);+ execute(&adapter, true).unwrap();+ assert!(adapter.focused.load(Ordering::SeqCst));+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1);+}++#[test]+fn headed_target_still_occluded_after_focus_never_receives_input() {+ let adapter = adapter(true, true);+ execute(&adapter, true).unwrap_err();+ assert!(adapter.focused.load(Ordering::SeqCst));+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0);+}++#[test]+fn disabled_target_does_not_trigger_early_focus() {+ let adapter = adapter(false, false);+ execute(&adapter, true).unwrap_err();+ assert!(!adapter.focused.load(Ordering::SeqCst));+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0);+}++#[test]+fn headless_semantic_action_never_raises_the_window() {+ let adapter = adapter(false, true);+ execute(&adapter, false).unwrap();+ assert!(!adapter.focused.load(Ordering::SeqCst));+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1);+}diff --git a/crates/core/src/ref_action_poll.rs b/crates/core/src/ref_action_poll.rsindex ce5aca265..b6e5efeac 100644--- a/crates/core/src/ref_action_poll.rs+++ b/crates/core/src/ref_action_poll.rs@@ -49,7 +49,9 @@ pub(crate) fn execute_poll_loop(state.preflight_attempts = state.preflight_attempts.saturating_add(1);if let Err(error) = preflight_resolved(&target, request, state.stability()) {let error = into_adapter_error(error);- if !should_scroll_after_preflight(request, &error) {+ let focus_pending = request.headed_requirement().requires_focus()+ && failed_check(&error, "receives_events");+ if !focus_pending && !should_scroll_after_preflight(request, &error) {handle_actionability_failure(&mut state, error, deadline)?;continue;}diff --git a/crates/core/src/ref_action_wait.rs b/crates/core/src/ref_action_wait.rsindex b74e36a69..d937fefe4 100644--- a/crates/core/src/ref_action_wait.rs+++ b/crates/core/src/ref_action_wait.rs@@ -140,3 +140,7 @@ mod success_tests;#[cfg(test)]#[path = "ref_action_exactly_once_tests.rs"]mod exactly_once_tests;++#[cfg(test)]+#[path = "ref_action_focus_order_tests.rs"]+mod focus_order_tests;diff --git a/crates/core/src/ref_action_wait_evidence.rs b/crates/core/src/ref_action_wait_evidence.rsindex 7ef23e897..ff3f1264e 100644--- a/crates/core/src/ref_action_wait_evidence.rs+++ b/crates/core/src/ref_action_wait_evidence.rs@@ -18,6 +18,22 @@ pub(crate) fn failed_check(error: &AdapterError, check_name: &str) -> bool {})}+pub(crate) fn only_stability_pending(error: &AdapterError) -> bool {+ error+ .details+ .as_ref()+ .and_then(|details| details.get("checks"))+ .and_then(serde_json::Value::as_array)+ .is_some_and(|checks| {+ checks+ .iter()+ .any(|check| check["check"] == "stable" && check["status"] != "pass")+ && checks+ .iter()+ .all(|check| check["check"] == "stable" || check["status"] == "pass")+ })+}+pub(crate) fn observed_bounds_hash(error: &AdapterError) -> Option<u64> {error.detailsdiff --git a/crates/core/src/ref_action_wait_support.rs b/crates/core/src/ref_action_wait_support.rsindex 0b36940ae..4864a1b54 100644--- a/crates/core/src/ref_action_wait_support.rs+++ b/crates/core/src/ref_action_wait_support.rs@@ -108,6 +108,30 @@ pub(crate) fn trace_resolve_error(context: &CommandContext, ref_id: &str, err: &});}+pub(crate) fn after_scroll(mut error: AdapterError) -> AdapterError {+ if matches!(+ error.disposition,+ crate::DeliverySemantics::NotDelivered | crate::DeliverySemantics::Unknown+ ) {+ error.disposition = crate::DeliverySemantics::uncertain();+ }+ let details = error.details.get_or_insert_with(|| json!({}));+ if let Some(details) = details.as_object_mut() {+ details.insert("preparatory_scroll".into(), "may_have_changed_view".into());+ }+ error+}++pub(crate) fn trace_scroll_error(+ target: &crate::ref_action_context::RefActionContext<'_>,+ error: &AdapterError,+) {+ let _ = target.context.trace_lazy(+ "ref.scroll_into_view.error",+ || json!({"ref": target.ref_id, "code": error.code.as_str(), "message": error.message}),+ );+}+pub(crate) fn trace_resolve_ok(context: &CommandContext, ref_id: &str) {let _ = context.trace_lazy("ref.resolve.ok", || json!({ "ref": ref_id }));}diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rsindex d2471eca6..c46b8842f 100644--- a/crates/core/src/refs.rs+++ b/crates/core/src/refs.rs@@ -85,8 +85,23 @@ impl RefMap {}pub fn remove_by_root_ref(&mut self, root: &str) {- self.inner- .retain(|_, entry| entry.scope.root_ref.as_deref() != Some(root));+ let root_entry = self.inner.get(root).cloned();+ self.inner.retain(|ref_id, entry| {+ if ref_id == root {+ return true;+ }+ let owned = entry.scope.root_ref.as_deref() == Some(root);+ let descendant = root_entry.as_ref().is_some_and(|parent| {+ entry.process == parent.process+ && entry.source == parent.source+ && (parent.scope.root_ref.is_none() || parent.scope.path_is_absolute)+ && (entry.scope.root_ref.is_none() || entry.scope.path_is_absolute)+ && entry.scope.path.starts_with(&parent.scope.path)+ && (entry.scope.path.len() > parent.scope.path.len()+ || entry.scope.root_ref.is_some())+ });+ !owned && !descendant+ });}pub fn validate(&self) -> Result<(), AppError> {diff --git a/crates/core/src/refs_store.rs b/crates/core/src/refs_store.rsindex ab7bb06eb..9ef4162f1 100644--- a/crates/core/src/refs_store.rs+++ b/crates/core/src/refs_store.rs@@ -88,6 +88,18 @@ impl RefStore {}}+ pub fn load_ref(+ &self,+ ref_id: &str,+ snapshot_id: Option<&str>,+ ) -> Result<crate::RefEntry, AppError> {+ let (snapshot_id, local_ref) = crate::ref_token::resolve_ref_target(ref_id, snapshot_id)?;+ self.load_snapshot(&snapshot_id)?+ .get(&local_ref)+ .cloned()+ .ok_or_else(|| AppError::stale_ref(ref_id))+ }+pub fn load_latest(&self) -> Result<RefMap, AppError> {if let Some(id) = self.read_latest_snapshot_id()? {return self.load_snapshot_from_base(&self.base_dir, &id);diff --git a/crates/core/src/refs_store_tests.rs b/crates/core/src/refs_store_tests.rsindex 53a72c772..c7421e8d3 100644--- a/crates/core/src/refs_store_tests.rs+++ b/crates/core/src/refs_store_tests.rs@@ -75,6 +75,45 @@ fn snapshot_roundtrip_updates_latest_pointer() {assert_eq!(store.load(None).unwrap().len(), 1);}+#[test]+fn load_ref_uses_qualified_identity_and_never_crosses_sessions() {+ let _guard = HomeGuard::new();+ let store = RefStore::for_session(Some("debug-session")).unwrap();+ let snapshot = store.save_new_snapshot(&map_with("Target")).unwrap();+ let qualified = format!("@{snapshot}:e1");+ assert_eq!(store.load_ref(&qualified, None).unwrap(), entry("Target"));+ assert_eq!(+ store.load_ref("@e1", Some(&snapshot)).unwrap(),+ entry("Target")+ );+ assert_eq!(+ store.load_ref("@e1", None).unwrap_err().code(),+ "INVALID_ARGS"+ );+ assert_eq!(+ store+ .load_ref(&qualified, Some("sother"))+ .unwrap_err()+ .code(),+ "INVALID_ARGS"+ );+ assert_eq!(+ store+ .load_ref(&format!("@{snapshot}:e2"), None)+ .unwrap_err()+ .code(),+ "STALE_REF"+ );+ assert_eq!(+ RefStore::new()+ .unwrap()+ .load_ref(&qualified, None)+ .unwrap_err()+ .code(),+ "SNAPSHOT_NOT_FOUND"+ );+}+fn save_snapshot_after_contention(store: &RefStore, name: &str) -> String {let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);loop {diff --git a/crates/core/src/refs_tests.rs b/crates/core/src/refs_tests.rsindex 835a0278a..36aeb8256 100644--- a/crates/core/src/refs_tests.rs+++ b/crates/core/src/refs_tests.rs@@ -178,6 +178,36 @@ fn test_root_ref_serde_roundtrip() {assert_eq!(back.scope.root_ref.as_deref(), Some("@e5"));}+#[test]+fn drill_replaces_full_snapshot_and_nested_descendants_only() {+ let mut map = RefMap::new();+ let mut allocate = |path: &[usize], owner: Option<&str>| {+ let mut value = entry("button", Some("Target"));+ value.scope.path = path.iter().copied().collect();+ value.scope.root_ref = owner.map(str::to_string);+ value.scope.path_is_absolute = owner.is_some();+ map.allocate(value)+ };+ let root = allocate(&[0], None);+ let full_child = allocate(&[0, 0], None);+ let drilled_child = allocate(&[0, 0], Some(&root));+ let nested_child = allocate(&[0, 0, 0], Some(&drilled_child));+ let sibling = allocate(&[1], None);+ let mut other_window = map.get(&full_child).unwrap().clone();+ other_window.source.source_window_id = Some("w-2".into());+ let other_window = map.allocate(other_window);+ map.remove_by_root_ref(&root);+ assert!(map.get(&root).is_some());+ assert!(map.get(&sibling).is_some());+ assert!(map.get(&other_window).is_some());+ for removed in [full_child, drilled_child, nested_child] {+ assert!(+ map.get(&removed).is_none(),+ "obsolete ref {removed} survived"+ );+ }+}+#[test]fn test_serialize_with_size_check_rejects_oversized() {let mut map = RefMap::new();@@ -204,7 +234,9 @@ fn test_serialize_with_size_check_accepts_normal() {}let result = map.serialize_with_size_check();- assert!(result.is_ok(), "normal-sized refmap should serialize");+ let value: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();+ assert_eq!(value["inner"]["@e1"]["role"], "button");+ assert_eq!(value["inner"]["@e1"]["name"], "OK");}#[test]diff --git a/crates/core/src/value_matches.rs b/crates/core/src/value_matches.rsnew file mode 100644index 000000000..2c4d2bd28--- /dev/null+++ b/crates/core/src/value_matches.rs@@ -0,0 +1,51 @@+/// Compares text exactly and numeric controls with an absolute readback tolerance.+pub fn value_matches(role: &str, expected: &str, observed: Option<&str>) -> bool {+ let Some(observed) = observed else {+ return false;+ };+ if expected == observed {+ return true;+ }+ if !matches!(role, "slider" | "incrementor" | "scrollbar" | "handle") {+ return false;+ }+ if let (Ok(expected), Ok(observed)) = (expected.parse::<i128>(), observed.parse::<i128>()) {+ return expected == observed;+ }+ match (expected.parse::<f64>(), observed.parse::<f64>()) {+ (Ok(expected), Ok(observed)) => {+ expected.is_finite()+ && observed.is_finite()+ && expected.abs().max(observed.abs()) < 9_007_199_254_740_992.0+ && (expected - observed).abs() <= 1e-6+ }+ _ => false,+ }+}++#[cfg(test)]+mod tests {+ use super::value_matches;++ #[test]+ fn numeric_readback_tolerance_does_not_hide_different_text_or_integer_targets() {+ for (role, expected, observed, matches) in [+ ("textfield", "001", "1", false),+ ("slider", "50", "50.00", true),+ ("slider", "50", "50.0000004", true),+ ("incrementor", "1000000000", "1000000001", false),+ ("incrementor", "1000000000", "1000000001.0", false),+ ("incrementor", "9007199254740993", "9007199254740992", false),+ (+ "incrementor",+ "9007199254740993",+ "9007199254740992.0",+ false,+ ),+ ("slider", "1", "inf", false),+ ] {+ assert_eq!(value_matches(role, expected, Some(observed)), matches);+ }+ assert!(!value_matches("slider", "1", None));+ }+}diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.hindex 68299e1e3..57d298741 100644--- a/crates/ffi/include/agent_desktop.h+++ b/crates/ffi/include/agent_desktop.h@@ -1425,7 +1425,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.3","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.+ * `{"version":"2.4","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/actions/execute.rs b/crates/ffi/src/actions/execute.rsindex 2730e8993..4aaafe6cd 100644--- a/crates/ffi/src/actions/execute.rs+++ b/crates/ffi/src/actions/execute.rs@@ -101,10 +101,12 @@ pub unsafe extern "C" fn ad_execute_action_with_policy(error::set_last_error(&error);return error::last_error_code();}- match adapter- .inner- .execute_action(native_handle.as_ref(), request, &lease)- {+ match agent_desktop_core::execute_verified_action(+ adapter.inner.as_ref(),+ native_handle.as_ref(),+ request,+ &lease,+ ) {Ok(result) => {*out = action_result_to_c(&result);AdResult::Okdiff --git a/crates/ffi/src/commands/snapshot.rs b/crates/ffi/src/commands/snapshot.rsindex d090ad743..1d8acc816 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.3","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.+/// `{"version":"2.4","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/macos/src/actions/activation_effect.rs b/crates/macos/src/actions/activation_effect.rsindex 445fff980..fdff1c1a8 100644--- a/crates/macos/src/actions/activation_effect.rs+++ b/crates/macos/src/actions/activation_effect.rs@@ -10,7 +10,6 @@ mod imp {/// The readback for `perform`, which has no written attribute to re-read.#[derive(Default)]pub(crate) struct FocusState {- window_title: Option<String>,focused_element: Option<AXElement>,}@@ -20,62 +19,98 @@ mod imp {/// identity the framework defines.impl PartialEq for FocusState {fn eq(&self, other: &Self) -> bool {- self.window_title == other.window_title- && match (&self.focused_element, &other.focused_element) {- (None, None) => true,- (Some(mine), Some(theirs)) => crate::tree::same_element(mine, theirs),- _ => false,- }+ match (&self.focused_element, &other.focused_element) {+ (None, None) => true,+ (Some(mine), Some(theirs)) => crate::tree::same_element(mine, theirs),+ _ => false,+ }}}- pub(crate) fn focus_state(element: &AXElement, deadline: Deadline) -> FocusState {- let Some(app) = crate::system::app_ops::pid_from_element(element, deadline)- .map(crate::tree::element_for_pid)- else {- return FocusState::default();- };- FocusState {- window_title: read_element(&app, "AXFocusedWindow", deadline).and_then(|window| {- crate::tree::attributes::copy_string_attr_result(&window, "AXTitle", deadline)- .ok()- .flatten()- }),- focused_element: read_element(&app, "AXFocusedUIElement", deadline),- }+ pub(crate) fn focus_state(element: &AXElement, deadline: Deadline) -> Option<FocusState> {+ let app = crate::system::app_ops::pid_from_element(element, deadline)+ .map(crate::tree::element_for_pid)?;+ Some(FocusState {+ focused_element: crate::tree::attributes::copy_element_attr_result(+ &app,+ "AXFocusedUIElement",+ deadline,+ )+ .ok()?,+ })}pub(crate) fn changed_now(- before: &FocusState,+ before: &Option<FocusState>,element: &AXElement,deadline: Deadline,) -> bool {- focus_state(element, deadline) != *before+ let after = focus_state(element, deadline);+ let target_focused = after+ .as_ref()+ .and_then(|state| state.focused_element.as_ref())+ .is_some_and(|focused| crate::tree::same_element(focused, element));+ observed_change(before, &after, target_focused)}pub(crate) fn settled_change(- before: &FocusState,+ before: &Option<FocusState>,element: &AXElement,deadline: Deadline,) -> bool {- let started = std::time::Instant::now();- loop {- if focus_state(element, deadline) != *before {+ if before.is_none() {+ return false;+ }+ let deadline = deadline.capped(std::time::Duration::from_millis(SETTLE_BUDGET_MS));+ while !deadline.is_expired() {+ if changed_now(before, element, deadline) {return true;}- if started.elapsed() >= std::time::Duration::from_millis(SETTLE_BUDGET_MS)- || deadline.is_expired()- {- return false;- }- std::thread::sleep(std::time::Duration::from_millis(SETTLE_POLL_MS));+ std::thread::sleep(+ deadline+ .remaining()+ .min(std::time::Duration::from_millis(SETTLE_POLL_MS)),+ );}+ false+ }++ fn observed_change(+ before: &Option<FocusState>,+ after: &Option<FocusState>,+ target_focused: bool,+ ) -> bool {+ target_focused && matches!((before, after), (Some(before), Some(after)) if before != after)}- fn read_element(app: &AXElement, attr: &str, deadline: Deadline) -> Option<AXElement> {- crate::tree::attributes::copy_element_attr_result(app, attr, deadline)- .ok()- .flatten()+ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn focus_changes_must_correlate_with_the_target() {+ let before = Some(FocusState {+ focused_element: Some(crate::tree::element_for_pid(1)),+ });+ let after = Some(FocusState {+ focused_element: Some(crate::tree::element_for_pid(2)),+ });+ assert!(!observed_change(&before, &after, false));+ assert!(observed_change(&before, &after, true));+ assert!(!observed_change(&after, &after, true));+ }++ #[test]+ fn missing_observation_cannot_verify_an_action() {+ let before = Some(FocusState::default());+ let after = Some(FocusState::default());+ assert!(!observed_change(&before, &None, true));+ assert!(!observed_change(&None, &after, true));+ assert!(!observed_change(&None, &None, true));+ assert!(!observed_change(&before, &before, true));+ assert!(!observed_change(&before, &after, false));+ assert!(!observed_change(&before, &after, true));+ }}}diff --git a/crates/macos/src/actions/ax_helpers.rs b/crates/macos/src/actions/ax_helpers.rsindex a0efc9f65..c5371a6d7 100644--- a/crates/macos/src/actions/ax_helpers.rs+++ b/crates/macos/src/actions/ax_helpers.rs@@ -1,5 +1,7 @@use agent_desktop_core::{AdapterError, ErrorCode};+pub(crate) use super::ax_perform::{advertises_action, perform_observed_action};+#[cfg(target_os = "macos")]mod imp {use super::*;@@ -18,64 +20,15 @@ mod imp {name: &str,deadline: agent_desktop_core::Deadline,) -> Result<bool, AdapterError> {+ if advertises_action(el, name, deadline) == Some(false) {+ return Ok(false);+ }let action = CFString::new(name);run_mutation(el, name, ax_mutation::PERFORM_API, deadline, |deadline| {crate::tree::ax_ipc::perform_action(el, action.as_concrete_TypeRef(), deadline)})}- /// Decides delivery from what the application did, not what it claimed.- /// Unadvertised actions are never performed, because a responder can answer- /// `kAXErrorSuccess` to an action it never published and never ran. Only an- /// uninformative code needs the settle poll to decide delivery at all; a- /// reported success is already delivered, so observing it merely upgrades- /// the report to verified and must not cost the caller a wait.- pub(crate) fn perform_observed_action(- el: &AXElement,- name: &str,- deadline: agent_desktop_core::Deadline,- ) -> Result<crate::actions::chain_delivery::DeliveryOutcome, AdapterError> {- use crate::actions::activation_effect;- use crate::actions::chain_delivery::DeliveryOutcome;- use ax_mutation::PerformSignal;-- if !advertises_action(el, name, deadline) {- return Ok(DeliveryOutcome::NotDelivered);- }- let before = activation_effect::focus_state(el, deadline);- let action = CFString::new(name);- let error =- crate::tree::ax_ipc::perform_action(el, action.as_concrete_TypeRef(), deadline)?;- match ax_mutation::classify_perform(name, error)? {- PerformSignal::ReportedUnsupported => Ok(DeliveryOutcome::NotDelivered),- PerformSignal::ReportedDelivered => Ok(DeliveryOutcome::from_delivery(- true,- activation_effect::changed_now(&before, el, deadline),- )),- PerformSignal::Uninformative => Ok(DeliveryOutcome::from_delivery(- activation_effect::settled_change(&before, el, deadline),- true,- )),- }- }-- fn advertises_action(- el: &AXElement,- name: &str,- deadline: agent_desktop_core::Deadline,- ) -> bool {- let mut usage = crate::tree::observation_usage::ObservationUsage::with_defaults();- let read = crate::tree::capabilities::copy_action_names_with_status(- el,- std::time::Instant::now() + deadline.remaining(),- &mut usage,- );- match read.value {- Some(actions) => actions.iter().any(|action| action == name),- None => true,- }- }-pub(crate) fn set_ax_bool_or_err(el: &AXElement,attr: &str,@@ -386,6 +339,6 @@ mod imp {}pub(crate) use imp::{- ax_focus_or_err, element_role, is_attr_settable, perform_observed_action, set_ax_bool_or_err,- set_ax_string_or_err, set_ax_value_coerced, try_ax_action_or_err,+ ax_focus_or_err, element_role, is_attr_settable, set_ax_bool_or_err, set_ax_string_or_err,+ set_ax_value_coerced, try_ax_action_or_err,};diff --git a/crates/macos/src/actions/ax_mutation.rs b/crates/macos/src/actions/ax_mutation.rsindex 344b3ccf6..3b729a508 100644--- a/crates/macos/src/actions/ax_mutation.rs+++ b/crates/macos/src/actions/ax_mutation.rs@@ -17,19 +17,37 @@ pub(crate) fn classify_result(}fn classify(operation: &str, api: &str, error: i32) -> Result<bool, AdapterError> {- signal_or_error(operation, api, error).map(|signal| signal == PerformSignal::ReportedDelivered)+ let signal = signal_or_error(operation, api, error)?;+ if signal == PerformSignal::Uninformative && api == PERFORM_API {+ return settle_uninformative_perform(operation, error, false)+ .map(|outcome| outcome.was_delivered());+ }+ Ok(signal == PerformSignal::ReportedDelivered)}fn signal_or_error(operation: &str, api: &str, error: i32) -> Result<PerformSignal, AdapterError> {if error == kAXErrorSuccess {return Ok(PerformSignal::ReportedDelivered);}- if error == kAXErrorActionUnsupported- || error == kAXErrorNotImplemented- || error == kAXErrorFailure- {+ if error == kAXErrorActionUnsupported || error == kAXErrorNotImplemented {return Ok(PerformSignal::ReportedUnsupported);}+ if error == kAXErrorFailure {+ return Err(crate::actions::DeliveryTracker::uncertain(+ AdapterError::new(+ ErrorCode::ActionFailed,+ format!("{operation} returned kAXErrorFailure; mutation outcome is uncertain"),+ )+ .with_details(serde_json::json!({+ "ax_error": error,+ "operation": operation,+ }))+ .with_platform_detail(format!("{api}({operation}) returned {error}"))+ .with_suggestion(+ "Inspect the target state with a fresh snapshot before deciding whether to retry.",+ ),+ ));+ }if error == kAXErrorAttributeUnsupported || error == kAXErrorNoValue {return Ok(PerformSignal::Uninformative);}@@ -99,11 +117,30 @@ pub(crate) fn classify_perform(operation: &str, error: i32) -> Result<PerformSigsignal_or_error(operation, PERFORM_API, error)}+pub(crate) fn settle_uninformative_perform(+ operation: &str,+ error: i32,+ observed_effect: bool,+) -> Result<crate::actions::chain_delivery::DeliveryOutcome, AdapterError> {+ if observed_effect {+ return Ok(crate::actions::chain_delivery::DeliveryOutcome::DeliveredVerified);+ }+ Err(AdapterError::new(+ ErrorCode::ActionFailed,+ format!("{operation} did not establish a verifiable effect; mutation outcome is uncertain"),+ )+ .with_disposition(DeliverySemantics::uncertain())+ .with_details(serde_json::json!({ "ax_error": error, "operation": operation }))+ .with_suggestion(+ "Inspect the target state with a fresh snapshot before deciding whether to retry.",+ ))+}+#[cfg(test)]mod tests {use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorActionUnsupported, kAXErrorAttributeUnsupported,- kAXErrorCannotComplete, kAXErrorInvalidUIElement, kAXErrorSuccess,+ kAXErrorCannotComplete, kAXErrorFailure, kAXErrorInvalidUIElement, kAXErrorSuccess,};use agent_desktop_core::{DeliveryDisposition, ErrorCode, RetryDisposition};@@ -115,6 +152,39 @@ mod tests {assert!(result.unwrap());}+ #[test]+ fn uninformative_perform_without_observed_effect_stops_fallback() {+ let error =+ super::settle_uninformative_perform("AXOpen", kAXErrorAttributeUnsupported, false)+ .expect_err("missing or unchanged observations do not prove non-delivery");+ assert_eq!(+ error.disposition.delivery(),+ DeliveryDisposition::DeliveryUncertain+ );+ assert_eq!(error.disposition.retry(), RetryDisposition::Unsafe);+ assert_eq!(+ super::settle_uninformative_perform("AXOpen", kAXErrorAttributeUnsupported, true)+ .unwrap(),+ crate::actions::chain_delivery::DeliveryOutcome::DeliveredVerified,+ );+ }++ #[test]+ fn raw_perform_cannot_fall_through_on_an_uninformative_return_code() {+ for code in [+ kAXErrorAttributeUnsupported,+ accessibility_sys::kAXErrorNoValue,+ ] {+ let error = classify("AXConfirm", super::PERFORM_API, code).unwrap_err();+ assert_eq!(error.disposition.retry(), RetryDisposition::Unsafe);+ assert_eq!(+ error.disposition.delivery(),+ DeliveryDisposition::DeliveryUncertain+ );+ assert!(!classify("AXValue", "AXUIElementSetAttributeValue", code).unwrap());+ }+ }+#[test]fn unsupported_action_remains_safe_non_delivery() {let result = classify("AXPress", "perform", kAXErrorActionUnsupported);@@ -139,16 +209,37 @@ mod tests {);}- /// `tree::action_list` reads `kAXErrorFailure` as "this element implements- /// no such action". A perform must not read the same code as a failure, or- /// an element the reader called action-less becomes an error when acted on.#[test]- fn perform_and_capability_reads_agree_on_the_appkit_absence_code() {+ fn capability_read_absence_does_not_prove_perform_non_delivery() {+ let error = super::classify_perform("AXScrollToVisible", kAXErrorFailure)+ .expect_err("generic failure does not prove an action was unsupported");+ assert_eq!(error.code, ErrorCode::ActionFailed);assert_eq!(- super::classify_perform("AXScrollToVisible", accessibility_sys::kAXErrorFailure)- .unwrap(),- super::PerformSignal::ReportedUnsupported+ error.disposition.delivery(),+ DeliveryDisposition::DeliveryUncertain);+ assert_eq!(error.disposition.retry(), RetryDisposition::Unsafe);+ }++ #[test]+ fn generic_failure_cannot_authorize_a_second_mutation() {+ for (operation, api) in [+ ("AXPress", super::PERFORM_API),+ ("AXValue", "AXUIElementSetAttributeValue"),+ ] {+ let error = classify(operation, api, kAXErrorFailure).unwrap_err();+ assert_eq!(+ error.disposition,+ agent_desktop_core::DeliverySemantics::uncertain()+ );+ assert_eq!(error.disposition.retry(), RetryDisposition::Unsafe);+ assert!(+ error+ .suggestion+ .unwrap()+ .contains("Inspect the target state")+ );+ }}#[test]diff --git a/crates/macos/src/actions/ax_perform.rs b/crates/macos/src/actions/ax_perform.rsnew file mode 100644index 000000000..43097f89d--- /dev/null+++ b/crates/macos/src/actions/ax_perform.rs@@ -0,0 +1,98 @@+use agent_desktop_core::AdapterError;++#[cfg(target_os = "macos")]+mod imp {+ use super::*;+ use crate::actions::ax_mutation;+ use crate::tree::AXElement;+ use core_foundation::{base::TCFType, string::CFString};++ /// Decides delivery from what the application did, not what it claimed.+ /// Unadvertised actions are never performed, because a responder can answer+ /// `kAXErrorSuccess` to an action it never published and never ran. Only an+ /// uninformative code needs the settle poll to decide delivery at all; a+ /// reported success is already delivered, so observing it merely upgrades+ /// the report to verified and must not cost the caller a wait.+ pub(crate) fn perform_observed_action(+ el: &AXElement,+ name: &str,+ deadline: agent_desktop_core::Deadline,+ ) -> Result<crate::actions::chain_delivery::DeliveryOutcome, AdapterError> {+ use crate::actions::activation_effect;+ use crate::actions::chain_delivery::DeliveryOutcome;+ use ax_mutation::PerformSignal;++ if advertises_action(el, name, deadline) == Some(false) {+ return Ok(DeliveryOutcome::NotDelivered);+ }+ let before = activation_effect::focus_state(el, deadline);+ let action = CFString::new(name);+ let error =+ crate::tree::ax_ipc::perform_action(el, action.as_concrete_TypeRef(), deadline)?;+ let signal = match ax_mutation::classify_perform(name, error) {+ Ok(signal) => signal,+ Err(failure)+ if failure.disposition == agent_desktop_core::DeliverySemantics::uncertain() =>+ {+ return ax_mutation::settle_uninformative_perform(+ name,+ error,+ activation_effect::settled_change(&before, el, deadline),+ )+ .map_err(|_| failure);+ }+ Err(failure) => return Err(failure),+ };+ match signal {+ PerformSignal::ReportedUnsupported => Ok(DeliveryOutcome::NotDelivered),+ PerformSignal::ReportedDelivered => Ok(DeliveryOutcome::from_delivery(+ true,+ activation_effect::changed_now(&before, el, deadline),+ )),+ PerformSignal::Uninformative => ax_mutation::settle_uninformative_perform(+ name,+ error,+ activation_effect::settled_change(&before, el, deadline),+ ),+ }+ }++ pub(crate) fn advertises_action(+ el: &AXElement,+ name: &str,+ deadline: agent_desktop_core::Deadline,+ ) -> Option<bool> {+ let mut usage = crate::tree::observation_usage::ObservationUsage::with_defaults();+ let read = crate::tree::capabilities::copy_action_names_with_status(+ el,+ std::time::Instant::now() + deadline.remaining(),+ &mut usage,+ );+ read.value+ .map(|actions| actions.iter().any(|action| action == name))+ }+}++#[cfg(not(target_os = "macos"))]+mod imp {+ use super::*;+ use crate::tree::AXElement;++ pub fn advertises_action(+ _el: &AXElement,+ _name: &str,+ _deadline: agent_desktop_core::Deadline,+ ) -> Option<bool> {+ None+ }++ pub fn perform_observed_action(+ _el: &AXElement,+ _name: &str,+ _deadline: agent_desktop_core::Deadline,+ ) -> Result<crate::actions::chain_delivery::DeliveryOutcome, AdapterError> {+ Ok(crate::actions::chain_delivery::DeliveryOutcome::NotDelivered)+ }+}++pub(crate) use imp::{advertises_action, perform_observed_action};diff --git a/crates/macos/src/actions/chain.rs b/crates/macos/src/actions/chain.rsindex 4c0df0fb2..d0c5090f0 100644--- a/crates/macos/src/actions/chain.rs+++ b/crates/macos/src/actions/chain.rs@@ -31,18 +31,16 @@ mod imp {crate::tree::attributes::set_messaging_timeout(el, ctx.deadline)?;for (i, step) in def.steps.iter().enumerate() {- ctx.ensure_budget()?;+ ctx.ensure_budget()+ .map_err(|error| after_steps(&steps, error))?;if !step_allowed(step, policy) {continue;}let label = step_label(step);- let outcome = execute_step(el, step, ctx, policy)?;- if record_step_outcome(- &mut steps,- step,- outcome,- def.continue_after_unverified_delivery,- ) {+ let outcome =+ execute_step(el, step, ctx, policy).map_err(|error| after_steps(&steps, error))?;+ let continue_unverified = def.continue_after_unverified_delivery;+ if record_step_outcome(&mut steps, step, outcome, continue_unverified) {tracing::debug!("chain: [{}/{}] {} -> success", i + 1, total, label);return Ok(steps);}@@ -50,11 +48,20 @@ mod imp {}tracing::debug!("chain: all {total} steps exhausted");- Err(- AdapterError::new(ErrorCode::ActionFailed, "All chain steps exhausted")- .with_disposition(exhaustion_disposition(&steps))- .with_suggestion(def.suggestion),- )+ Err(exhaustion_error(&steps, def.suggestion))+ }++ pub(crate) fn exhaustion_error(steps: &[ActionStep], suggestion: &str) -> AdapterError {+ AdapterError::new(ErrorCode::ActionFailed, "All chain steps exhausted")+ .with_disposition(exhaustion_disposition(steps))+ .with_suggestion(suggestion)+ }++ pub(crate) fn after_steps(steps: &[ActionStep], error: AdapterError) -> AdapterError {+ let delivered = exhaustion_disposition(steps)+ == agent_desktop_core::DeliverySemantics::delivered_unverified();+ crate::actions::DeliveryTracker::from_delivered_units(usize::from(delivered))+ .annotate(error)}pub(crate) fn exhaustion_disposition(@@ -132,7 +139,8 @@ mod imp {#[cfg(all(test, target_os = "macos"))]pub(crate) use imp::{- build_step, exhaustion_disposition, record_step_outcome, step_allowed, step_mechanism,+ after_steps, build_step, exhaustion_disposition, exhaustion_error, record_step_outcome,+ step_allowed, step_mechanism,};#[cfg(test)]diff --git a/crates/macos/src/actions/chain_defs.rs b/crates/macos/src/actions/chain_defs.rsindex 3256ac03d..2ce6dc92d 100644--- a/crates/macos/src/actions/chain_defs.rs+++ b/crates/macos/src/actions/chain_defs.rs@@ -104,7 +104,7 @@ mod imp {ChainStep::IncrementToDynamic,],suggestion: "Target an element with a settable value or native increment/decrement actions.",- continue_after_unverified_delivery: true,+ continue_after_unverified_delivery: false,};pub(crate) static CLEAR_CHAIN: ChainDef = ChainDef {@@ -113,7 +113,7 @@ mod imp {ChainStep::SetDynamic { attr: "AXValue" },],suggestion: "Target an editable control or allow the verified keyboard fallback.",- continue_after_unverified_delivery: true,+ continue_after_unverified_delivery: false,};pub(crate) static SEMANTIC_CLICK_CHAIN: ChainDef = ChainDef {diff --git a/crates/macos/src/actions/chain_disclosure_steps.rs b/crates/macos/src/actions/chain_disclosure_steps.rsindex d8347ddde..7828daa38 100644--- a/crates/macos/src/actions/chain_disclosure_steps.rs+++ b/crates/macos/src/actions/chain_disclosure_steps.rs@@ -106,7 +106,12 @@ mod imp {expanded: bool,) -> Result<DeliveryOutcome, AdapterError> {if last_state == Some(!expanded) {- Ok(DeliveryOutcome::NotDelivered)+ Err(AdapterError::new(+ agent_desktop_core::ErrorCode::ActionFailed,+ "Disclosure action completed but the requested expanded state was not observed",+ )+ .with_disposition(agent_desktop_core::DeliverySemantics::delivered_unverified())+ .with_suggestion("Inspect the expanded state before deciding whether to retry."))} else {Ok(DeliveryOutcome::DeliveredUnverified)}@@ -150,8 +155,10 @@ mod imp {#[test]fn unobserved_delivery_preserves_honest_unknown_state() {assert_eq!(- unobserved_delivery(Some(false), true).expect("known opposite state"),- DeliveryOutcome::NotDelivered+ unobserved_delivery(Some(false), true)+ .expect_err("known opposite state")+ .disposition,+ agent_desktop_core::DeliverySemantics::delivered_unverified());assert_eq!(unobserved_delivery(None, true).expect("unreadable state after delivery"),diff --git a/crates/macos/src/actions/chain_tests.rs b/crates/macos/src/actions/chain_tests.rsindex 3326ee0bd..4f2925e88 100644--- a/crates/macos/src/actions/chain_tests.rs+++ b/crates/macos/src/actions/chain_tests.rs@@ -216,8 +216,14 @@ fn exhaustion_after_unverified_delivery_reports_delivered_unverified() {true,));+ let error = super::exhaustion_error(&steps, "Inspect the current state");+ assert_eq!(error.code, agent_desktop_core::ErrorCode::ActionFailed);assert_eq!(- exhaustion_disposition(&steps),+ error.suggestion.as_deref(),+ Some("Inspect the current state")+ );+ assert_eq!(+ error.disposition,agent_desktop_core::DeliverySemantics::delivered_unverified());}@@ -242,6 +248,52 @@ fn exhaustion_without_any_delivery_reports_not_delivered() {);}+#[test]+fn value_writes_stop_fallback_without_claiming_verification() {+ for definition in [+ &crate::actions::chain_defs::SET_VALUE_CHAIN,+ &crate::actions::chain_defs::CLEAR_CHAIN,+ ] {+ for step in definition.steps {+ let mut steps = Vec::new();+ assert!(record_step_outcome(+ &mut steps,+ step,+ DeliveryOutcome::DeliveredUnverified,+ definition.continue_after_unverified_delivery+ ));+ assert_eq!(steps[0].verified(), Some(false));+ assert!(!record_step_outcome(+ &mut Vec::new(),+ step,+ DeliveryOutcome::NotDelivered,+ definition.continue_after_unverified_delivery+ ));+ }+ }+}++#[test]+fn later_step_failure_retains_earlier_delivery() {+ use agent_desktop_core::{AdapterError, DeliverySemantics};+ let steps = [build_step(+ &ChainStep::SetDynamic { attr: "AXValue" },+ DeliveryOutcome::DeliveredUnverified,+ )];+ let error = AdapterError::timeout("later step failed")+ .with_disposition(DeliverySemantics::not_delivered());+ assert_eq!(+ super::after_steps(&steps, error).disposition,+ DeliverySemantics::delivered_unverified()+ );+ let uncertain = AdapterError::timeout("later step uncertain")+ .with_disposition(DeliverySemantics::uncertain());+ assert_eq!(+ super::after_steps(&steps, uncertain).disposition,+ DeliverySemantics::uncertain()+ );+}+#[test]fn headed_menubar_click_uses_only_semantic_press_and_keeps_other_clicks_physical() {let menu = crate::actions::chain_defs::click_chain(Some("AXMenuBarItem"));diff --git a/crates/macos/src/actions/chain_value_write.rs b/crates/macos/src/actions/chain_value_write.rsindex 2b7bbe9a3..dfc936174 100644--- a/crates/macos/src/actions/chain_value_write.rs+++ b/crates/macos/src/actions/chain_value_write.rs@@ -21,10 +21,14 @@ mod imp {if error.disposition != agent_desktop_core::DeliverySemantics::uncertain() {return Err(error);}- let recovery = Deadline::detached_after(500)?;- let observed = crate::tree::copy_value_typed(element, recovery);- let verified =- chain_verify::dynamic_write_had_effect(attribute, None, value, observed.as_deref());+ let observed = crate::tree::copy_value_typed(element, deadline);+ let role = ax_helpers::element_role(element, deadline).ok().flatten();+ let verified = chain_verify::dynamic_write_had_effect(+ attribute,+ role.as_deref(),+ value,+ observed.as_deref(),+ );return if verified {Ok(DeliveryOutcome::DeliveredVerified)} else {@@ -36,7 +40,6 @@ mod imp {prepare(element, deadline).map_err(|error| delivery.annotate(error))?;let role = ax_helpers::element_role(element, deadline).map_err(|error| delivery.annotate(error))?;- prepare(element, deadline).map_err(|error| delivery.annotate(error))?;let observed = crate::tree::copy_value_typed(element, deadline);Ok(DeliveryOutcome::from_delivery(true,@@ -56,17 +59,18 @@ mod imp {) -> Result<DeliveryOutcome, AdapterError> {const MAX_INCREMENT_STEPS: usize = 1_024;- let Some(target) = finite_target(target) else {+ let requested = target;+ let Some(target) = finite_target(requested) else {return Ok(DeliveryOutcome::NotDelivered);};- let Some(mut current) = read_number(element, deadline)? else {+ let Some((mut current, mut current_text)) = read_number(element, deadline)? else {return Ok(DeliveryOutcome::NotDelivered);};let start = current;let mut delivered = false;let mut delivery = crate::actions::DeliveryTracker::default();for _ in 0..MAX_INCREMENT_STEPS {- if (current - target).abs() < 0.5 {+ if increment_target_reached(¤t_text, requested) {return Ok(if delivered {DeliveryOutcome::DeliveredVerified} else {@@ -74,32 +78,37 @@ mod imp {});}if deadline.is_expired() {- return Err(chain_verify::increment_deadline_error(+ return Err(delivery.annotate(chain_verify::increment_deadline_error(start, current, target,- ));+ )));}- let action = if current < target {- "AXIncrement"- } else {- "AXDecrement"+ let Some(action) = increment_action(¤t_text, requested) else {+ return Ok(DeliveryOutcome::from_delivery(delivered, false));};prepare(element, deadline).map_err(|error| delivery.annotate(error))?;- let delivered_step = match ax_helpers::try_ax_action_or_err(element, action, deadline) {- Ok(delivered) => delivered,- Err(error) if delivered => return Err(delivery.annotate(error)),- Err(error) => return Err(error),- };+ let delivered_step = ax_helpers::try_ax_action_or_err(element, action, deadline)+ .map_err(|error| delivery.annotate(error))?;if !delivered_step {break;}delivered = true;delivery.mark_delivered();match read_number(element, deadline).map_err(|error| delivery.annotate(error))? {- Some(next) if (next - current).abs() >= f64::EPSILON => current = next,+ Some((next, text)) => {+ let progressed = increment_progressed(¤t_text, &text, requested);+ current = next;+ current_text = text;+ if !progressed {+ return Err(delivery.annotate(AdapterError::new(+ agent_desktop_core::ErrorCode::ActionFailed,+ "Native increments stopped progressing toward the requested value",+ ).with_suggestion("Read the current value; choose a target supported by the control's native step size.")));+ }+ }_ => break,}}- if (current - target).abs() < 0.5 {+ if increment_target_reached(¤t_text, requested) {return Ok(DeliveryOutcome::DeliveredVerified);}if (current - start).abs() >= f64::EPSILON {@@ -131,36 +140,59 @@ mod imp {))}+ pub(crate) fn increment_action(current: &str, target: &str) -> Option<&'static str> {+ let ordering =+ if let (Ok(current), Ok(target)) = (current.parse::<i128>(), target.parse::<i128>()) {+ current.cmp(&target)+ } else {+ let (current, target) = (finite_target(current)?, finite_target(target)?);+ if current.abs().max(target.abs()) >= 9_007_199_254_740_992.0 {+ return None;+ }+ current.partial_cmp(&target)?+ };+ match ordering {+ std::cmp::Ordering::Less => Some("AXIncrement"),+ std::cmp::Ordering::Greater => Some("AXDecrement"),+ std::cmp::Ordering::Equal => None,+ }+ }++ pub(crate) fn increment_progressed(before: &str, after: &str, target: &str) -> bool {+ let direction = increment_action(before, target);+ increment_target_reached(after, target)+ || (direction.is_some()+ && increment_action(before, after) == direction+ && increment_action(after, target) == direction)+ }++ pub(crate) fn increment_target_reached(current: &str, target: &str) -> bool {+ agent_desktop_core::value_matches("incrementor", target, Some(current))+ }+pub(crate) fn finite_target(target: &str) -> Option<f64> {target.parse::<f64>().ok().filter(|value| value.is_finite())}- fn read_number(element: &AXElement, deadline: Deadline) -> Result<Option<f64>, AdapterError> {+ fn read_number(+ element: &AXElement,+ deadline: Deadline,+ ) -> Result<Option<(f64, String)>, AdapterError> {prepare(element, deadline)?;Ok(crate::tree::copy_value_typed(element, deadline)- .and_then(|value| value.parse::<f64>().ok()))+ .and_then(|value| finite_target(&value).map(|number| (number, value))))}fn prepare(element: &AXElement, deadline: Deadline) -> Result<(), AdapterError> {crate::tree::attributes::set_messaging_timeout(element, deadline)}-- #[cfg(test)]- pub(crate) fn verification_failure_after_write(error: AdapterError) -> AdapterError {- let mut delivery = crate::actions::DeliveryTracker::default();- delivery.mark_delivered();- delivery.annotate(error)- }}#[cfg(target_os = "macos")]pub(crate) use imp::{increment_to_value, set_bool_verified, set_dynamic_verified};#[cfg(all(test, target_os = "macos"))]-use imp::finite_target;--#[cfg(all(test, target_os = "macos"))]-use imp::verification_failure_after_write;+use imp::{finite_target, increment_action, increment_target_reached};#[cfg(test)]#[path = "chain_value_write_tests.rs"]diff --git a/crates/macos/src/actions/chain_value_write_tests.rs b/crates/macos/src/actions/chain_value_write_tests.rsindex 27bf43069..5a06365f8 100644--- a/crates/macos/src/actions/chain_value_write_tests.rs+++ b/crates/macos/src/actions/chain_value_write_tests.rs@@ -1,5 +1,28 @@use super::finite_target;+#[test]+fn increments_stop_at_overshoot_stalls_or_motion_away_from_target() {+ for (before, after, target, expected) in [+ ("5", "6", "5.5", false),+ ("6", "5", "5.5", false),+ ("5", "5", "6", false),+ ("5", "4", "6", false),+ ("4", "5", "6", true),+ ("5", "6", "6", true),+ (+ "9007199254740992",+ "9007199254740993",+ "9007199254740994",+ true,+ ),+ ] {+ assert_eq!(+ super::imp::increment_progressed(before, after, target),+ expected+ );+ }+}+#[test]fn finite_target_rejects_non_finite_numbers() {assert_eq!(finite_target("42.5"), Some(42.5));@@ -10,13 +33,37 @@ fn finite_target_rejects_non_finite_numbers() {}#[test]-fn verification_failure_after_first_write_is_unsafe_to_retry() {- let error = super::verification_failure_after_write(agent_desktop_core::AdapterError::timeout(- "verification fixture",- ));+fn increment_direction_never_guesses_from_rounded_large_fractions() {+ for (current, target, expected) in [+ ("0", "0.4", Some("AXIncrement")),+ ("1.4", "1", Some("AXDecrement")),+ ("9007199254740992", "9007199254740993", Some("AXIncrement")),+ ("9007199254740993", "9007199254740992", Some("AXDecrement")),+ ("9007199254740992", "9007199254740992.5", None),+ ("9007199254740992.5", "9007199254740992", None),+ ("-9007199254740992", "-9007199254740992.5", None),+ ("1e30", "1.000000000000000001e30", None),+ ("2", "2", None),+ ("NaN", "1", None),+ ] {+ assert_eq!(+ super::increment_action(current, target),+ expected,+ "{current} → {target}"+ );+ }+}- assert_eq!(- error.disposition,- agent_desktop_core::DeliverySemantics::delivered_unverified()- );+#[test]+fn increment_requires_the_requested_fractional_value() {+ assert!(!super::increment_target_reached("0", "0.4"));+ assert!(!super::increment_target_reached(+ "9007199254740992",+ "9007199254740993"+ ));+ assert!(!super::increment_target_reached("1", "1.4"));+ assert!(super::increment_target_reached(+ "0.30000000000000004",+ "0.3"+ ));}diff --git a/crates/macos/src/actions/chain_verify.rs b/crates/macos/src/actions/chain_verify.rsindex c8d8069e8..46ed458c8 100644--- a/crates/macos/src/actions/chain_verify.rs+++ b/crates/macos/src/actions/chain_verify.rs@@ -57,23 +57,7 @@ pub(crate) fn dynamic_write_had_effect(expected: &str,observed: Option<&str>,) -> bool {- if attr != "AXValue" || role == Some("AXSecureTextField") {- return true;- }- observed == Some(expected) || numbers_match(expected, observed)-}--fn numbers_match(expected: &str, observed: Option<&str>) -> bool {- match (- expected.parse::<f64>(),- observed.and_then(|o| o.parse::<f64>().ok()),- ) {- (Ok(a), Some(b)) => {- let tolerance = 1e-6_f64.max(a.abs().max(b.abs()) * 1e-9);- (a - b).abs() <= tolerance- }- _ => false,- }+ attr == "AXValue" && agent_desktop_core::value_matches(role.unwrap_or(""), expected, observed)}#[cfg(test)]@@ -132,27 +116,27 @@ mod tests {fn ax_value_write_requires_readback_match() {assert!(!dynamic_write_had_effect("AXValue",- Some("AXTextField"),+ Some("textfield"),"",Some("unchanged")));assert!(dynamic_write_had_effect("AXValue",- Some("AXTextField"),+ Some("textfield"),"",Some("")));}#[test]- fn non_value_and_secure_writes_trust_ax_success() {- assert!(dynamic_write_had_effect(+ fn missing_readback_never_verifies_a_write() {+ assert!(!dynamic_write_had_effect("AXSelected",Some("AXCheckBox"),"true",None));- assert!(dynamic_write_had_effect(+ assert!(!dynamic_write_had_effect("AXValue",Some("AXSecureTextField"),"secret",@@ -172,25 +156,25 @@ mod tests {fn numeric_value_write_matches_reformatted_readback() {assert!(dynamic_write_had_effect("AXValue",- Some("AXSlider"),+ Some("slider"),"50",Some("50.00")));assert!(dynamic_write_had_effect("AXValue",- Some("AXIncrementor"),+ Some("incrementor"),"3",Some("3")));assert!(dynamic_write_had_effect("AXValue",- Some("AXSlider"),+ Some("slider"),"50",Some("50.0000004")));assert!(!dynamic_write_had_effect("AXValue",- Some("AXSlider"),+ Some("slider"),"50",Some("12.00")));diff --git a/crates/macos/src/actions/delivery_tracker.rs b/crates/macos/src/actions/delivery_tracker.rsindex 711271769..a86cc4150 100644--- a/crates/macos/src/actions/delivery_tracker.rs+++ b/crates/macos/src/actions/delivery_tracker.rs@@ -71,4 +71,20 @@ mod tests {);}}++ #[test]+ fn later_non_delivery_cannot_erase_an_earlier_mutation() {+ let error = AdapterError::internal("second mutation rejected")+ .with_disposition(DeliverySemantics::not_delivered());+ assert_eq!(+ DeliveryTracker::from_delivered_units(1)+ .annotate(error.clone())+ .disposition,+ DeliverySemantics::delivered_unverified(),+ );+ assert_eq!(+ DeliveryTracker::default().annotate(error).disposition,+ DeliverySemantics::not_delivered(),+ );+ }}diff --git a/crates/macos/src/actions/dispatch.rs b/crates/macos/src/actions/dispatch.rsindex 9bc938650..69c47ec96 100644--- a/crates/macos/src/actions/dispatch.rs+++ b/crates/macos/src/actions/dispatch.rs@@ -1,6 +1,6 @@use agent_desktop_core::{Action, ActionResult, ActionStep, AdapterError, Deadline, ErrorCode, StepMechanism,- action_request::ActionRequest, action_step_outcome::ActionStepOutcome,+ action_request::ActionRequest,};#[cfg(target_os = "macos")]@@ -198,13 +198,7 @@ mod imp {}}- let post_state = if delivery_occurred(&steps) && !deadline.is_expired() {- crate::actions::post_state::read_post_state(el, action, deadline)- .map_err(after_delivery)?- } else {- None- };- ActionResult::from_execution(action, steps, post_state)+ Ok(ActionResult::from_execution(action, steps))}fn run_chain(@@ -236,16 +230,6 @@ mod imp {result => result,}}-- fn after_delivery(error: AdapterError) -> AdapterError {- error.with_disposition(agent_desktop_core::DeliverySemantics::delivered_unverified())- }-- fn delivery_occurred(steps: &[ActionStep]) -> bool {- steps- .iter()- .any(|step| matches!(step.outcome, ActionStepOutcome::Succeeded))- }}#[cfg(not(target_os = "macos"))]diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rsindex a1dd509d4..369541c06 100644--- a/crates/macos/src/actions/mod.rs+++ b/crates/macos/src/actions/mod.rs@@ -4,6 +4,7 @@ mod adapter;pub(crate) mod ax_helpers;#[cfg(target_os = "macos")]pub(crate) mod ax_mutation;+pub(crate) mod ax_perform;pub(crate) mod chain;mod chain_context;mod chain_def;diff --git a/crates/macos/src/actions/physical_keyboard.rs b/crates/macos/src/actions/physical_keyboard.rsindex 9ddc68910..017e7f44a 100644--- a/crates/macos/src/actions/physical_keyboard.rs+++ b/crates/macos/src/actions/physical_keyboard.rs@@ -19,8 +19,8 @@ pub(crate) fn press_sequence(deadline: Deadline,) -> Result<(), AdapterError> {let mut delivery = crate::actions::DeliveryTracker::default();- let identity =- prepare_target(element, policy, deadline).map_err(|error| delivery.annotate(error))?;+ let identity = prepare_target(element, policy, deadline, &mut delivery)+ .map_err(|error| delivery.annotate(error))?;let pid = identity.pid();for combo in combos {verify_delivery_target(element, identity, deadline)@@ -39,17 +39,21 @@ pub(crate) fn type_text(deadline: Deadline,) -> Result<(), AdapterError> {crate::input::keyboard::preflight_text(text, deadline)?;- let identity = prepare_target(element, policy, deadline)?;+ let mut delivery = crate::actions::DeliveryTracker::default();+ let identity = prepare_target(element, policy, deadline, &mut delivery)+ .map_err(|error| delivery.annotate(error))?;let pid = identity.pid();crate::input::keyboard::synthesize_text(text, pid, deadline, |deadline| {verify_delivery_target(element, identity, deadline)})+ .map_err(|error| delivery.annotate(error))}fn prepare_target(element: &AXElement,policy: InteractionPolicy,deadline: Deadline,+ delivery: &mut crate::actions::DeliveryTracker,) -> Result<crate::system::process_identity::ProcessIdentity, AdapterError> {if !policy.allow_focus_steal {return Err(AdapterError::policy_denied_for_policy(@@ -84,6 +88,7 @@ fn prepare_target().with_disposition(agent_desktop_core::DeliverySemantics::not_delivered()));}+ delivery.mark_delivered();wait_for_focused_element(element, pid, deadline)?;crate::system::focus::verify_app_focused(pid, deadline)?;verify_delivery_target(element, identity, deadline)?;diff --git a/crates/macos/src/actions/post_state.rs b/crates/macos/src/actions/post_state.rsindex 1b093c5ce..247e8c111 100644--- a/crates/macos/src/actions/post_state.rs+++ b/crates/macos/src/actions/post_state.rs@@ -1,45 +1,11 @@use agent_desktop_core::{- Action, AdapterError, Deadline, ElementState, ErrorCode, EvidenceRequirements, LiveElement,+ AdapterError, Deadline, ElementState, ErrorCode, EvidenceRequirements, LiveElement,LiveIdentity, LocatorField, Rect,};-use std::time::{Duration, Instant};+use std::time::Instant;use crate::tree::AXElement;-pub(crate) fn read_post_state(- element: &AXElement,- action: &Action,- deadline: Deadline,-) -> Result<Option<ElementState>, AdapterError> {- let delay = match action {- Action::TypeText(_) => Duration::from_millis(50),- Action::Toggle- | Action::Check- | Action::Uncheck- | Action::SetValue(_)- | Action::Clear- | Action::Expand- | Action::Collapse => Duration::ZERO,- Action::Click- | Action::DoubleClick- | Action::RightClick- | Action::TripleClick- | Action::SetFocus- | Action::Select(_)- | Action::Scroll(_, _)- | Action::ScrollTo- | Action::PressKey(_)- | Action::KeyDown(_)- | Action::KeyUp(_)- | Action::Hover- | Action::Drag(_) => return Ok(None),- };- if !delay.is_zero() && !pause_if_budget_allows(deadline, delay) {- return Ok(None);- }- read_element_state(element, deadline).map(Some)-}-pub(crate) fn read_element_state(element: &AXElement,deadline: Deadline,@@ -73,8 +39,13 @@ pub(crate) fn read_live_element(let state = element_state_from_attrs(element, attrs, role, window_bounds)?;Ok(LiveElement {identity,+ states_complete: !crate::tree::roles::is_toggleable_role(&state.role)+ || state+ .value+ .as_deref()+ .and_then(crate::tree::state_reader::parse_checked_value)+ .is_some(),state,- states_complete: true,bounds,available_actions,})@@ -232,15 +203,6 @@ fn normalized_role(ax_role: Option<&str>, ax_subrole: Option<&str>) -> String {.to_string()}-fn pause_if_budget_allows(deadline: Deadline, delay: Duration) -> bool {- let remaining = deadline.remaining();- if remaining <= delay {- return false;- }- std::thread::sleep(delay);- !deadline.is_expired()-}-fn deadline_instant(deadline: Deadline) -> Result<Instant, AdapterError> {let remaining = deadline.remaining();if remaining.is_zero() {diff --git a/crates/macos/src/actions/post_state_tests.rs b/crates/macos/src/actions/post_state_tests.rsindex f9d71207d..767971078 100644--- a/crates/macos/src/actions/post_state_tests.rs+++ b/crates/macos/src/actions/post_state_tests.rs@@ -60,24 +60,6 @@ fn element_state_from_attrs_omits_offscreen_without_window_bounds() {);}-#[test]-fn post_delay_is_skipped_when_it_would_exhaust_the_budget() {- let deadline = Deadline::after(1).unwrap();-- assert!(!pause_if_budget_allows(- deadline,- std::time::Duration::from_millis(50)- ));-}--#[test]-fn click_does_not_post_read_a_target_that_navigation_may_detach() {- let element = crate::tree::AXElement(std::ptr::null_mut());- let state = read_post_state(&element, &Action::Click, Deadline::after(1).unwrap()).unwrap();-- assert!(state.is_none());-}-#[test]fn post_state_uses_the_same_subrole_mapping_as_snapshot_observation() {assert_eq!(diff --git a/crates/macos/src/actions/scroll.rs b/crates/macos/src/actions/scroll.rsindex de39ff0da..efee995b6 100644--- a/crates/macos/src/actions/scroll.rs+++ b/crates/macos/src/actions/scroll.rs@@ -6,47 +6,6 @@ use crate::tree::AXElement;const MAX_SCROLL_AMOUNT: u32 = 1_000;-/// A responder can serve a page action while answering an uninformative code-/// for it, which leaves the return value unable to prove anything. The content-/// position is the observable that can, so the scroll is judged by whether the-/// first child actually moved.-fn paged_scroll_moved_content(- target: &AXElement,- direction: &Direction,- amount: u32,- deadline: Deadline,-) -> Result<bool, AdapterError> {- let Some(before) = first_child_origin(target, deadline)? else {- return Ok(false);- };- for _ in 0..amount.max(1) {- try_action(target, page_action(direction), deadline)?;- }- let Some(after) = first_child_origin(target, deadline)? else {- return Ok(false);- };- Ok((before.0 - after.0).abs() > f64::EPSILON || (before.1 - after.1).abs() > f64::EPSILON)-}--fn first_child_origin(- target: &AXElement,- deadline: Deadline,-) -> Result<Option<(f64, f64)>, AdapterError> {- let instant = crate::tree::locator_deadline::from_operation(deadline)?;- let Some(child) =- crate::tree::attributes::copy_ax_array_prefix_result(target, "AXChildren", 1, instant)- .ok()- .flatten()- .and_then(|children| children.into_iter().next())- else {- return Ok(None);- };- Ok(- crate::tree::element_bounds::read_bounds_with_deadline(&child, instant)?- .map(|bounds| (bounds.x, bounds.y)),- )-}-pub(crate) fn ax_scroll(element: &AXElement,direction: &Direction,@@ -61,7 +20,6 @@ pub(crate) fn ax_scroll(physical_wheel(target, direction, amount, deadline)?;return Ok((StepMechanism::PhysicalSynthetic, false));}- accept_optional_visibility_result(try_action(element, "AXScrollToVisible", deadline))?;let (bar_attribute, increment_action) = scroll_bar_action(direction);if let Some(bar) = crate::actions::scroll_read::element(target, bar_attribute, deadline)? {@@ -78,9 +36,6 @@ pub(crate) fn ax_scroll(if perform_repeated_action(target, page_action(direction), amount, deadline)? {return Ok((StepMechanism::SemanticApi, false));}- if paged_scroll_moved_content(target, direction, amount, deadline)? {- return Ok((StepMechanism::SemanticApi, true));- }Err(AdapterError::new(ErrorCode::ActionNotSupported,"Element advertises Scroll but no scroll mechanism moved its content",@@ -94,25 +49,6 @@ pub(crate) fn ax_scroll())}-fn accept_optional_visibility_result(- result: Result<bool, AdapterError>,-) -> Result<(), AdapterError> {- match result {- Ok(_) => Ok(()),- Err(error)- if matches!(- error.code,- ErrorCode::ActionFailed- | ErrorCode::ActionNotSupported- | ErrorCode::AppUnresponsive- ) =>- {- Ok(())- }- Err(error) => Err(error),- }-}-fn validate_amount(amount: u32) -> Result<(), AdapterError> {if amount == 0 || amount > MAX_SCROLL_AMOUNT {return Err(AdapterError::new(diff --git a/crates/macos/src/actions/scroll_into_view.rs b/crates/macos/src/actions/scroll_into_view.rsindex 96689972e..5a92c62d3 100644--- a/crates/macos/src/actions/scroll_into_view.rs+++ b/crates/macos/src/actions/scroll_into_view.rs@@ -24,11 +24,7 @@ mod imp {outcome @ (DeliveryOutcome::SatisfiedNoDelivery| DeliveryOutcome::DeliveredVerified) => Ok(outcome),DeliveryOutcome::NotDelivered => scroll_ancestor_until_visible(element, deadline),- DeliveryOutcome::DeliveredUnverified => Err(AdapterError::new(- ErrorCode::ActionFailed,- "AXScrollToVisible completed without verified visibility",- )- .with_disposition(DeliverySemantics::delivered_unverified())),+ DeliveryOutcome::DeliveredUnverified => Err(unverified_scroll_error()),}}@@ -36,21 +32,34 @@ mod imp {element: &AXElement,deadline: Deadline,) -> Result<DeliveryOutcome, AdapterError> {+ let mut delivery = crate::actions::DeliveryTracker::default();for attempt in 0..MAX_ANCESTOR_SCROLLS {- let Some(direction) = direction_to_window(element, deadline)? else {+ let Some(direction) =+ direction_to_window(element, deadline).map_err(|error| delivery.annotate(error))?+ else {return Ok(if attempt == 0 {DeliveryOutcome::SatisfiedNoDelivery} else {DeliveryOutcome::DeliveredVerified});};+ let parent = crate::actions::scroll_read::element(element, "AXParent", deadline)+ .map_err(|error| delivery.annotate(error))?+ .ok_or_else(|| {+ delivery.annotate(AdapterError::new(+ ErrorCode::ActionNotSupported,+ "Target has no ancestor to scroll",+ ))+ })?;crate::actions::scroll::ax_scroll(- element,+ &parent,&direction,1,InteractionPolicy::headless(),deadline,- )?;+ )+ .map_err(|error| delivery.annotate(error))?;+ delivery.mark_delivered();}Err(AdapterError::new(ErrorCode::ActionFailed,@@ -66,9 +75,9 @@ mod imp {let instant = crate::tree::locator_deadline::from_operation(deadline)?;let bounds = crate::tree::element_bounds::read_bounds_with_deadline(element, instant)?.ok_or_else(|| AdapterError::new(ErrorCode::ActionFailed, "Target has no bounds"))?;- let Some(window) = crate::tree::surface_read::element(element, "AXWindow", instant)? else {- return Ok(None);- };+ let window = require_window(crate::tree::surface_read::element(+ element, "AXWindow", instant,+ )?)?;let window_bounds = crate::tree::element_bounds::read_bounds_with_deadline(&window, instant,)?@@ -76,6 +85,15 @@ mod imp {Ok(direction_for_visibility(bounds, window_bounds))}+ pub(super) fn require_window(window: Option<AXElement>) -> Result<AXElement, AdapterError> {+ window.ok_or_else(|| {+ AdapterError::new(+ ErrorCode::ActionFailed,+ "Target window is unavailable; visibility cannot be verified",+ )+ })+ }+pub(crate) fn direction_for_visibility(target: Rect, viewport: Rect) -> Option<Direction> {if target.y < viewport.y {Some(Direction::Up)@@ -116,14 +134,7 @@ mod imp {)));}if Instant::now() >= local_end {- if !scroll_effect_observed(before, element_bounds(element, deadline)?) {- return Ok(DeliveryOutcome::NotDelivered);- }- return Err(AdapterError::new(- ErrorCode::ActionFailed,- "AXScrollToVisible completed but target visibility was not verified",- )- .with_disposition(DeliverySemantics::delivered_unverified()));+ return settled_scroll_outcome(before, element_bounds(element, deadline));}let pause = deadline.remaining_slice(Duration::from_millis(20))@@ -132,6 +143,16 @@ mod imp {}}+ pub(super) fn settled_scroll_outcome(+ before: Option<Rect>,+ after: Result<Option<Rect>, AdapterError>,+ ) -> Result<DeliveryOutcome, AdapterError> {+ if !scroll_effect_observed(before, after.map_err(after_delivery)?) {+ return Ok(DeliveryOutcome::NotDelivered);+ }+ Err(unverified_scroll_error())+ }+fn element_bounds(element: &AXElement,deadline: Deadline,@@ -150,6 +171,15 @@ mod imp {}}+ pub(super) fn unverified_scroll_error() -> AdapterError {+ AdapterError::new(+ ErrorCode::ActionFailed,+ "AXScrollToVisible completed but target visibility was not verified",+ )+ .with_disposition(DeliverySemantics::delivered_unverified())+ .with_suggestion("Inspect target visibility before deciding whether to scroll again.")+ }+fn visible_in_window(element: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {let instant = crate::tree::locator_deadline::from_operation(deadline)?;let Some(bounds) =@@ -217,3 +247,15 @@ pub(crate) use imp::{direction_for_visibility, intersects, rect_has_area, scroll#[cfg(all(test, target_os = "macos"))]#[path = "scroll_into_view_tests.rs"]mod tests;++#[cfg(all(test, target_os = "macos"))]+mod evidence_tests {+ #[test]+ fn missing_window_is_not_verified_visibility() {+ assert!(super::imp::require_window(None).is_err());+ assert_eq!(+ super::imp::unverified_scroll_error().disposition,+ agent_desktop_core::DeliverySemantics::delivered_unverified()+ );+ }+}diff --git a/crates/macos/src/actions/scroll_into_view_tests.rs b/crates/macos/src/actions/scroll_into_view_tests.rsindex 30cc470e8..9c8510c32 100644--- a/crates/macos/src/actions/scroll_into_view_tests.rs+++ b/crates/macos/src/actions/scroll_into_view_tests.rs@@ -46,6 +46,18 @@ fn offscreen_direction_uses_global_viewport_edges() {assert!(direction_for_visibility(rect(1500.0, 100.0, 73.0, 24.0), viewport).is_none());}+#[test]+fn final_scroll_read_timeout_does_not_claim_safe_non_delivery() {+ let error = agent_desktop_core::AdapterError::timeout("final bounds read")+ .with_disposition(agent_desktop_core::DeliverySemantics::not_delivered());+ let error = super::imp::settled_scroll_outcome(None, Err(error)).unwrap_err();+ assert_eq!(error.code, agent_desktop_core::ErrorCode::Timeout);+ assert_eq!(+ error.disposition,+ agent_desktop_core::DeliverySemantics::delivered_unverified()+ );+}+#[test]fn acknowledged_scroll_without_geometry_change_is_not_delivery() {let before = rect(2622.0, 1063.0, 177.0, 24.0);diff --git a/crates/macos/src/actions/scroll_tests.rs b/crates/macos/src/actions/scroll_tests.rsindex 51d23a5c8..9bcc07c0e 100644--- a/crates/macos/src/actions/scroll_tests.rs+++ b/crates/macos/src/actions/scroll_tests.rs@@ -4,37 +4,6 @@ use agent_desktop_core::{AdapterError, Direction, ErrorCode};use super::repeat_action;-#[test]-fn optional_visibility_pre_step_ignores_recoverable_ax_failures() {- for code in [- ErrorCode::ActionFailed,- ErrorCode::ActionNotSupported,- ErrorCode::AppUnresponsive,- ] {- let result =- super::accept_optional_visibility_result(Err(AdapterError::new(code.clone(), "ax")));- assert!(- result.is_ok(),- "{code:?} should not abort the real scroll path"- );- }-}--#[test]-fn optional_visibility_pre_step_preserves_terminal_failures() {- for code in [- ErrorCode::PermDenied,- ErrorCode::StaleRef,- ErrorCode::Timeout,- ErrorCode::Internal,- ] {- let error =- super::accept_optional_visibility_result(Err(AdapterError::new(code.clone(), "ax")))- .expect_err("terminal pre-step failure must remain visible");- assert_eq!(error.code, code);- }-}-#[test]fn horizontal_wheel_delta_matches_direction() {assert_eq!(super::scroll_wheel_delta(&Direction::Right, 2), (0, 2));diff --git a/crates/macos/src/actions/select_menu.rs b/crates/macos/src/actions/select_menu.rsindex 914bfd6aa..35e99b2de 100644--- a/crates/macos/src/actions/select_menu.rs+++ b/crates/macos/src/actions/select_menu.rs@@ -216,7 +216,8 @@ fn deliver_candidate(match select_attribute() {Ok(Some(verified)) => return Ok(verified),Ok(None) => None,- Err(error) => Some(error),+ Err(error) if error.disposition == DeliverySemantics::not_delivered() => Some(error),+ Err(error) => return Err(error),}} else {None@@ -246,10 +247,24 @@ fn select_candidate_attribute(if !crate::actions::ax_helpers::set_ax_bool_or_err(candidate, "AXSelected", true, deadline)? {return Ok(None);}- let instant = crate::tree::locator_deadline::from_operation(deadline)?;- Ok(Some(- crate::tree::surface_read::boolean(candidate, "AXSelected", instant)? == Some(true),- ))+ let instant =+ crate::tree::locator_deadline::from_operation(deadline).map_err(after_menu_delivery)?;+ let observed = crate::tree::surface_read::boolean(candidate, "AXSelected", instant)+ .map_err(after_menu_delivery)?;+ selected_readback(observed).map(Some)+}++fn selected_readback(observed: Option<bool>) -> Result<bool, AdapterError> {+ match observed {+ Some(false) => Err(AdapterError::new(+ ErrorCode::ActionFailed,+ "AXSelected write completed but the item remained unselected",+ )+ .with_disposition(DeliverySemantics::delivered_unverified())+ .with_suggestion("Inspect the selection before deciding whether to retry.")),+ Some(true) => Ok(true),+ None => Ok(false),+ }}fn press_candidate(candidate: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {@@ -301,58 +316,5 @@ fn prepare(element: &AXElement, deadline: Deadline) -> Result<(), AdapterError>}#[cfg(test)]-mod tests {- use super::*;- use std::cell::Cell;-- #[test]- fn select_traversal_limits_are_bounded() {- assert_eq!(MAX_SELECT_NODES, 2_048);- assert_eq!(MAX_SELECT_DEPTH, 8);- }-- #[test]- fn menu_items_are_pressed_without_setting_selected_first() {- let selected_calls = Cell::new(0);- let press_calls = Cell::new(0);-- let verified = deliver_candidate(- false,- || {- selected_calls.set(selected_calls.get() + 1);- Ok(Some(true))- },- || {- press_calls.set(press_calls.get() + 1);- Ok(true)- },- )- .expect("menu candidate delivery");-- assert!(!verified);- assert_eq!(selected_calls.get(), 0);- assert_eq!(press_calls.get(), 1);- }-- #[test]- fn collection_selection_falls_back_to_press_when_selected_write_fails() {- let press_calls = Cell::new(0);- let verified = deliver_candidate(- true,- || {- Err(AdapterError::new(- ErrorCode::ActionFailed,- "AXSelected is unavailable",- ))- },- || {- press_calls.set(press_calls.get() + 1);- Ok(true)- },- )- .expect("press fallback");-- assert!(!verified);- assert_eq!(press_calls.get(), 1);- }-}+#[path = "select_menu_tests.rs"]+mod tests;diff --git a/crates/macos/src/actions/select_menu_tests.rs b/crates/macos/src/actions/select_menu_tests.rsnew file mode 100644index 000000000..8af162557--- /dev/null+++ b/crates/macos/src/actions/select_menu_tests.rs@@ -0,0 +1,88 @@+use super::*;+use std::cell::Cell;++#[test]+fn select_traversal_limits_are_bounded() {+ assert_eq!(MAX_SELECT_NODES, 2_048);+ assert_eq!(MAX_SELECT_DEPTH, 8);+}++#[test]+fn menu_items_are_pressed_without_setting_selected_first() {+ let selected_calls = Cell::new(0);+ let press_calls = Cell::new(0);++ let verified = deliver_candidate(+ false,+ || {+ selected_calls.set(selected_calls.get() + 1);+ Ok(Some(true))+ },+ || {+ press_calls.set(press_calls.get() + 1);+ Ok(true)+ },+ )+ .expect("menu candidate delivery");++ assert!(!verified);+ assert_eq!(selected_calls.get(), 0);+ assert_eq!(press_calls.get(), 1);+}++#[test]+fn collection_selection_falls_back_to_press_when_selected_write_fails() {+ let press_calls = Cell::new(0);+ let verified = deliver_candidate(+ true,+ || {+ Err(+ AdapterError::new(ErrorCode::ActionFailed, "AXSelected is unavailable")+ .with_disposition(DeliverySemantics::not_delivered()),+ )+ },+ || {+ press_calls.set(press_calls.get() + 1);+ Ok(true)+ },+ )+ .expect("press fallback");++ assert!(!verified);+ assert_eq!(press_calls.get(), 1);+}++#[test]+fn uncertain_collection_selection_never_falls_back_to_press() {+ for disposition in [+ DeliverySemantics::uncertain(),+ DeliverySemantics::delivered_unverified(),+ ] {+ let presses = Cell::new(0);+ let result = deliver_candidate(+ true,+ || {+ Err(+ AdapterError::new(ErrorCode::ActionFailed, "write uncertainty")+ .with_disposition(disposition),+ )+ },+ || {+ presses.set(presses.get() + 1);+ Ok(true)+ },+ );+ assert_eq!(result.unwrap_err().disposition, disposition);+ assert_eq!(presses.get(), 0);+ }+}++#[test]+fn selected_readback_distinguishes_contradiction_from_missing_evidence() {+ assert_eq!(+ selected_readback(Some(false)).unwrap_err().disposition,+ DeliverySemantics::delivered_unverified()+ );+ assert!(selected_readback(Some(true)).unwrap());+ assert!(!selected_readback(None).unwrap());+}diff --git a/crates/macos/src/actions/toggle_state.rs b/crates/macos/src/actions/toggle_state.rsindex caa1b0cc7..4ad5a4f16 100644--- a/crates/macos/src/actions/toggle_state.rs+++ b/crates/macos/src/actions/toggle_state.rs@@ -9,7 +9,7 @@ use crate::{chain::{ChainContext, execute_chain},chain_defs,},- tree::AXElement,+ tree::{AXElement, state_reader::parse_checked_value},};const TOGGLE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(600);@@ -109,9 +109,7 @@ fn after_delivery(error: AdapterError) -> AdapterError {fn mark_last_verified(steps: &mut [ActionStep], verified: bool) {if let Some(step) = steps.last_mut() {- if verified || step.verified.is_none() {- step.verified = Some(verified);- }+ step.verified = Some(verified);}}@@ -119,15 +117,6 @@ fn checked_state(el: &AXElement, deadline: Deadline) -> Result<Option<bool>, AdaOk(read_value(el, deadline)?.and_then(|value| parse_checked_value(&value)))}-fn parse_checked_value(value: &str) -> Option<bool> {- match value.trim().to_ascii_lowercase().as_str() {- "1" | "true" | "yes" | "on" | "checked" => Some(true),- "0" | "false" | "no" | "off" | "unchecked" => Some(false),- "2" | "mixed" | "indeterminate" => None,- _ => None,- }-}-fn wait_for_checked_state(el: &AXElement,want_checked: bool,@@ -279,10 +268,10 @@ mod tests {}#[test]- fn absent_toggle_state_does_not_erase_existing_verification() {+ fn absent_toggle_state_does_not_inherit_click_verification() {let mut steps = vec![ActionStep::succeeded("verified_press").with_verified(true)];mark_last_verified(&mut steps, false);- assert_eq!(steps[0].verified(), Some(true));+ assert_eq!(steps[0].verified(), Some(false));}#[test]diff --git a/crates/macos/src/input/keyboard_event.rs b/crates/macos/src/input/keyboard_event.rsindex 2059146ea..e0296efc0 100644--- a/crates/macos/src/input/keyboard_event.rs+++ b/crates/macos/src/input/keyboard_event.rs@@ -83,6 +83,7 @@ fn post_pair(delivery: &mut crate::actions::DeliveryTracker,total: usize,) -> Result<(), AdapterError> {+ ensure_budget(deadline, total, *delivery)?;let (down, up) = events;let mut release = KeyReleaseGuard {event: Some(up),diff --git a/crates/macos/src/input/mouse_drag_state.rs b/crates/macos/src/input/mouse_drag_state.rsindex 000f165c2..8c3c6757f 100644--- a/crates/macos/src/input/mouse_drag_state.rs+++ b/crates/macos/src/input/mouse_drag_state.rs@@ -50,11 +50,11 @@ impl DragDeliveryState {details.insert("emergency_release_acknowledged".into(), false.into());}}- error- .with_details(details)- .with_suggestion(- "Inspect the source and destination before retrying; the emergency release was posted without an OS acknowledgement",- )+ error.with_details(details).with_suggestion(if self.armed {+ "Inspect the source and destination before retrying; the emergency release was posted without an OS acknowledgement"+ } else {+ "Inspect the source and destination before retrying; the normal release was posted without an OS acknowledgement"+ })}}@@ -92,4 +92,25 @@ mod tests {assert_eq!(details["delivered_events"], 4);assert_eq!(details["emergency_release_posted"], true);}++ #[test]+ fn timeout_after_normal_release_does_not_claim_emergency_cleanup() {+ let mut state = DragDeliveryState::default();+ state.arm();+ state.mark_down_posted();+ state.disarm();+ let error = state.enrich_error(AdapterError::timeout("after release"));+ assert!(!error.suggestion.unwrap().contains("emergency release"));+ assert!(+ error+ .details+ .unwrap()+ .get("emergency_release_posted")+ .is_none()+ );+ assert_eq!(+ error.disposition.retry(),+ agent_desktop_core::RetryDisposition::Unsafe+ );+ }}diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rsindex 37ca9eaf3..a96a95557 100644--- a/crates/macos/src/system/adapter.rs+++ b/crates/macos/src/system/adapter.rs@@ -1,9 +1,8 @@use agent_desktop_core::{ActionResult, AdapterError, Deadline, DismissAllNotificationsRequest,DismissNotificationRequest, ImageBuffer, InteractionLease, NotificationActionRequest,- NotificationFilter, NotificationInfo, ObservationOps, PermissionReport, ProcessIdentity,- ScreenshotTarget, SignalBaseline, SignalFilter, SnapshotSurface, SystemOps, WindowFilter,- WindowInfo, WindowOp,+ NotificationFilter, NotificationInfo, PermissionReport, ProcessIdentity, ScreenshotTarget,+ SignalBaseline, SignalFilter, SnapshotSurface, SystemOps, WindowInfo, WindowOp,};use crate::adapter::MacOSAdapter;@@ -150,13 +149,18 @@ impl SystemOps for MacOSAdapter {}}+ fn screenshot_window_frame(+ &self,+ window: &WindowInfo,+ deadline: Deadline,+ ) -> Result<ImageBuffer, AdapterError> {+ crate::system::screenshot::capture_window_frame(window, deadline)+ }+fn focused_window(&self, deadline: Deadline) -> Result<Option<WindowInfo>, AdapterError> {- let filter = WindowFilter {- focused_only: true,- app: None,- };- let windows = self.list_windows(&filter, deadline)?;- Ok(windows.into_iter().next())+ crate::system::window_inventory::focused_window_until(+ crate::tree::locator_deadline::from_operation(deadline)?,+ )}fn press_key_for_app(diff --git a/crates/macos/src/system/cursor_overlay/child.rs b/crates/macos/src/system/cursor_overlay/child.rsindex fb1c52e52..81a791c0b 100644--- a/crates/macos/src/system/cursor_overlay/child.rs+++ b/crates/macos/src/system/cursor_overlay/child.rs@@ -92,7 +92,7 @@ fn run() -> Result<(), AdapterError> {state.resting = false;}let outcome = handle(&control, &mut state);- if outcome.is_ok() && (control.is_hide() || control.is_travel()) {+ if outcome.is_ok() && control.expects_acknowledgement() {let _ = stream.write_all(&[1]);}if outcome.is_err() {diff --git a/crates/macos/src/system/cursor_overlay/spawn.rs b/crates/macos/src/system/cursor_overlay/spawn.rsindex 9d5c354fd..68342b4b4 100644--- a/crates/macos/src/system/cursor_overlay/spawn.rs+++ b/crates/macos/src/system/cursor_overlay/spawn.rs@@ -221,7 +221,7 @@ fn send_until(.with_platform_detail(error.to_string())})?;let travels = control.is_travel();- if !travels && !control.is_hide() && !control.is_disable() {+ if !control.expects_acknowledgement() {return Ok(true);}stream@@ -263,6 +263,22 @@ fn send_until(.with_platform_detail(error.to_string()),)}+ Err(error)+ if control.instruction().is_some_and(|instruction| {+ instruction.phase() == agent_desktop_core::CursorPhase::Effect+ }) =>+ {+ tracing::warn!(+ session = control.session_id(),+ agent = control.agent_id(),+ %error,+ "cursor overlay effect was not acknowledged; continuing without effect confirmation"+ );+ Err(+ AdapterError::internal("macOS cursor overlay did not confirm cursor effect")+ .with_platform_detail(error.to_string()),+ )+ }Err(error) => Err(AdapterError::internal("macOS cursor overlay did not acknowledge the control",)diff --git a/crates/macos/src/system/cursor_overlay/spawn_tests.rs b/crates/macos/src/system/cursor_overlay/spawn_tests.rsindex 6df490ab1..b7e000649 100644--- a/crates/macos/src/system/cursor_overlay/spawn_tests.rs+++ b/crates/macos/src/system/cursor_overlay/spawn_tests.rs@@ -11,6 +11,11 @@ fn drag_requires_acknowledgement_before_tracking_is_considered_ready() {check_acknowledgement(agent_desktop_core::CursorPhase::Drag, false);}+#[test]+fn effect_requires_acknowledgement_before_it_is_considered_delivered() {+ check_acknowledgement(agent_desktop_core::CursorPhase::Effect, false);+}+fn check_acknowledgement(phase: agent_desktop_core::CursorPhase, accepted: bool) {let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)diff --git a/crates/macos/src/system/focus.rs b/crates/macos/src/system/focus.rsindex 53a44eb2c..35f01f8d8 100644--- a/crates/macos/src/system/focus.rs+++ b/crates/macos/src/system/focus.rs@@ -8,12 +8,17 @@ const VERIFY_LIMIT: Duration = Duration::from_millis(500);#[cfg(target_os = "macos")]pub(crate) fn ensure_app_focused(pid: i32, deadline: Deadline) -> Result<(), AdapterError> {+ focus_app(pid, deadline).map(|_| ())+}++#[cfg(target_os = "macos")]+fn focus_app(pid: i32, deadline: Deadline) -> Result<bool, AdapterError> {use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};tracing::debug!("system: ensure app focused pid={pid}");let app = crate::tree::element_for_pid(pid);if read_frontmost(&app, deadline)? {- return Ok(());+ return Ok(false);}prepare(&app, deadline)?;let attribute = CFString::new("AXFrontmost");@@ -30,6 +35,7 @@ pub(crate) fn ensure_app_focused(pid: i32, deadline: Deadline) -> Result<(), Adadeadline,"application did not become frontmost",)+ .map(|()| true).map_err(after_delivery)}@@ -62,9 +68,11 @@ pub(crate) fn focus_window_impl(window.title);let pid = crate::system::process_identity::to_pid_t(window.pid)?;- ensure_app_focused(pid, deadline)?;let element = crate::system::window_resolve::window_element_for_info(window, deadline)?;- crate::system::window_ops::raise_window(&element, deadline)?;+ let focused = focus_app(pid, deadline)?;+ crate::system::window_ops::raise_window(&element, deadline).map_err(|error| {+ crate::actions::DeliveryTracker::from_delivered_units(usize::from(focused)).annotate(error)+ })?;verify_app_focused(pid, deadline).map_err(after_delivery)}@@ -187,7 +195,7 @@ pub(crate) fn finish_mutation(}#[cfg(target_os = "macos")]-fn map_ax_read_error(error: i32, operation: &str) -> AdapterError {+pub(crate) fn map_ax_read_error(error: i32, operation: &str) -> AdapterError {use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorCannotComplete, kAXErrorInvalidUIElement,};diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rsindex 54f01004a..066b9902e 100644--- a/crates/macos/src/system/key_dispatch.rs+++ b/crates/macos/src/system/key_dispatch.rs@@ -20,6 +20,16 @@ pub(crate) fn press_for_app_impl(combo: &KeyCombo,policy: agent_desktop_core::InteractionPolicy,deadline: Deadline,+) -> Result<ActionResult, AdapterError> {+ press_for_app(process, combo, policy, deadline)+ .map_err(|error| crate::actions::DeliveryTracker::default().annotate(error))+}++fn press_for_app(+ process: ProcessIdentity,+ combo: &KeyCombo,+ policy: agent_desktop_core::InteractionPolicy,+ deadline: Deadline,) -> Result<ActionResult, AdapterError> {tracing::debug!(pid = process.pid.get(),@@ -29,7 +39,6 @@ pub(crate) fn press_for_app_impl(let identity = crate::system::process_identity::require_core(&process)?;let pid = identity.pid();let app = crate::tree::element_for_pid(pid);- prepare(&app, deadline)?;if !combo.modifiers.is_empty() {match try_menu_bar_shortcut(&app, combo, deadline) {@@ -79,7 +88,9 @@ fn try_simple_key_action(let Some(focused) = focused_element(app, deadline)? else {return Ok(false);};- prepare(&focused, deadline)?;+ if crate::actions::ax_helpers::advertises_action(&focused, action, deadline) != Some(true) {+ return Ok(false);+ }crate::actions::ax_helpers::try_ax_action_or_err(&focused, action, deadline)}@@ -108,7 +119,6 @@ fn try_menu_bar_shortcut(.is_some_and(|value| value.to_uppercase() == target_char)&& read_menu_item_modifiers(&element, deadline)? == Some(target_modifiers){- prepare(&element, deadline)?;return crate::actions::ax_helpers::try_ax_action_or_err(&element, "AXPress", deadline);}if depth >= MAX_MENU_DEPTH {@@ -155,7 +165,6 @@ fn element_attribute(attribute: &str,deadline: Deadline,) -> Result<Option<AXElement>, AdapterError> {- prepare(element, deadline)?;let result = crate::tree::attributes::copy_element_attr_result(element, attribute, deadline);ensure_budget(deadline)?;result.map_err(|error| read_error(attribute, error))@@ -230,7 +239,6 @@ fn read_string(attribute: &str,deadline: Deadline,) -> Result<Option<String>, AdapterError> {- prepare(element, deadline)?;let result = crate::tree::attributes::copy_string_attr_result(element, attribute, deadline);ensure_budget(deadline)?;result.map_err(|error| read_error(attribute, error))@@ -243,7 +251,6 @@ fn read_menu_item_modifiers(use accessibility_sys::kAXErrorSuccess;use core_foundation::{base::TCFType, string::CFString};- prepare(element, deadline)?;let attribute = CFString::new("AXMenuItemCmdModifiers");let (error, value) = crate::tree::ax_ipc::copy_attribute_value(element,@@ -331,10 +338,6 @@ fn is_bounded_menu_incomplete(error: &AdapterError) -> bool {.is_some_and(|kind| matches!(kind, "node_limit" | "child_limit" | "depth_limit"))}-fn prepare(element: &AXElement, deadline: Deadline) -> Result<(), AdapterError> {- crate::tree::attributes::set_messaging_timeout(element, deadline)-}-fn ensure_budget(deadline: Deadline) -> Result<(), AdapterError> {if deadline.is_expired() {Err(deadline.timeout_error())diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rsindex 22003a7ca..4bffa007c 100644--- a/crates/macos/src/system/key_dispatch_tests.rs+++ b/crates/macos/src/system/key_dispatch_tests.rs@@ -1,5 +1,18 @@use super::*;+#[test]+fn process_preflight_failure_reports_no_key_delivery() {+ let error = press_for_app_impl(+ ProcessIdentity::new(u32::MAX, "invalid"),+ &combo(Vec::new()),+ agent_desktop_core::InteractionPolicy::default(),+ Deadline::standard().unwrap(),+ )+ .unwrap_err();+ assert_eq!(error.code, ErrorCode::InvalidArgs);+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());+}+#[test]fn key_dispatch_rejects_non_unique_display_names() {let error = match [10, 11].as_slice() {diff --git a/crates/macos/src/system/screenshot.rs b/crates/macos/src/system/screenshot.rsindex b9a84bb64..fb9c5259c 100644--- a/crates/macos/src/system/screenshot.rs+++ b/crates/macos/src/system/screenshot.rs@@ -93,6 +93,21 @@ mod imp {pub fn capture_window(window: &WindowInfo,deadline: Deadline,+ ) -> Result<ImageBuffer, AdapterError> {+ capture_window_options(window, deadline, false)+ }++ pub fn capture_window_frame(+ window: &WindowInfo,+ deadline: Deadline,+ ) -> Result<ImageBuffer, AdapterError> {+ capture_window_options(window, deadline, true)+ }++ fn capture_window_options(+ window: &WindowInfo,+ deadline: Deadline,+ omit_shadow: bool,) -> Result<ImageBuffer, AdapterError> {if window.process_instance.is_none() {return Err(AdapterError::new(@@ -108,7 +123,13 @@ mod imp {let window_id = parse_window_id(&verified.id)?;let scale = crate::system::display::scale_for_bounds(verified.bounds, deadline)?;ensure_budget(deadline)?;- let captured = capture(scale, deadline, |path| Ok(window_args(window_id, path)))?;+ let captured = capture(scale, deadline, |path| {+ let mut args = window_args(window_id, path);+ if omit_shadow {+ args.insert(0, OsString::from("-o"));+ }+ Ok(args)+ })?;crate::system::window_resolve::resolve_capture_window(&verified,deadline_instant(deadline)?,@@ -337,6 +358,10 @@ mod imp {}}+#[cfg(not(target_os = "macos"))]+pub(crate) use imp::capture_window as capture_window_frame;+#[cfg(target_os = "macos")]+pub(crate) use imp::capture_window_frame;pub(crate) use imp::{capture_display, capture_screen, capture_window};#[cfg(all(test, target_os = "macos"))]diff --git a/crates/macos/src/system/window_inventory.rs b/crates/macos/src/system/window_inventory.rsindex 611f78979..dd43f5b65 100644--- a/crates/macos/src/system/window_inventory.rs+++ b/crates/macos/src/system/window_inventory.rs@@ -69,6 +69,42 @@ pub(crate) fn list_windows_until(})}+#[cfg(target_os = "macos")]+pub(crate) fn focused_window_until(deadline: Instant) -> Result<Option<WindowInfo>, AdapterError> {+ let Some(pid) = focused_application_pid(deadline)? else {+ return Ok(None);+ };+ let records =+ cg_window::window_records_until(deadline, cg_window::WindowRecordScope::Pid(pid))?;+ let windows = windows_from_records_with_focus(+ records,+ true,+ |owner| crate::system::window_ax_state::read_until(owner, deadline),+ crate::system::process_identity::matches_instance,+ )?;+ if focused_application_pid(deadline)? != Some(pid) {+ return Err(AdapterError::app_unresponsive(+ "Foreground application changed during focus verification",+ ));+ }+ Ok(windows.into_iter().next())+}++#[cfg(target_os = "macos")]+fn focused_application_pid(deadline: Instant) -> Result<Option<i32>, AdapterError> {+ let system =+ crate::tree::AXElement(unsafe { accessibility_sys::AXUIElementCreateSystemWide() });+ crate::tree::surface_read::element(&system, "AXFocusedApplication", deadline)?+ .map(|app| crate::tree::ax_ipc::pid(&app, deadline))+ .transpose()+ .map_err(|error| crate::system::focus::map_ax_read_error(error, "read focused application"))+}++#[cfg(not(target_os = "macos"))]+pub(crate) fn focused_window_until(_deadline: Instant) -> Result<Option<WindowInfo>, AdapterError> {+ Err(AdapterError::not_supported("focused_window"))+}+fn require_running_app(pids: &rustc_hash::FxHashSet<i32>,app_filter: &str,diff --git a/crates/macos/src/system/window_ops.rs b/crates/macos/src/system/window_ops.rsindex ef2b8d9a0..fe502972f 100644--- a/crates/macos/src/system/window_ops.rs+++ b/crates/macos/src/system/window_ops.rs@@ -6,7 +6,11 @@ mod imp {use accessibility_sys::{kAXPositionAttribute, kAXSizeAttribute, kAXValueTypeCGPoint, kAXValueTypeCGSize,};- use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};+ use core_foundation::{+ base::{CFType, TCFType},+ boolean::CFBoolean,+ string::CFString,+ };use core_graphics::geometry::{CGPoint, CGSize};use std::ffi::c_void;@@ -44,7 +48,9 @@ mod imp {)?;let work_area = crate::system::display_work_area::for_window(current, deadline)?;set_position(el, work_area.x, work_area.y, deadline)?;- set_size(el, work_area.width, work_area.height, deadline)+ set_size(el, work_area.width, work_area.height, deadline).map_err(|error| {+ crate::actions::DeliveryTracker::from_delivered_units(1).annotate(error)+ })}fn set_size(@@ -62,13 +68,13 @@ mod imp {return Err(AdapterError::internal("Failed to create AXValue for size"));}let cf_attr = CFString::new(kAXSizeAttribute);+ let ax_value = unsafe { CFType::wrap_under_create_rule(ax_value as _) };let err = crate::tree::ax_ipc::set_attribute_value(el,cf_attr.as_concrete_TypeRef(),- ax_value as _,+ ax_value.as_CFTypeRef(),deadline,)?;- unsafe { core_foundation::base::CFRelease(ax_value as _) };finish(el, err, "resize window", deadline)?;crate::system::window_postcondition::wait_for_geometry(el,@@ -100,13 +106,13 @@ mod imp {));}let cf_attr = CFString::new(kAXPositionAttribute);+ let ax_value = unsafe { CFType::wrap_under_create_rule(ax_value as _) };let err = crate::tree::ax_ipc::set_attribute_value(el,cf_attr.as_concrete_TypeRef(),- ax_value as _,+ ax_value.as_CFTypeRef(),deadline,)?;- unsafe { core_foundation::base::CFRelease(ax_value as _) };finish(el, err, "move window", deadline)?;crate::system::window_postcondition::wait_for_geometry(el,@@ -225,10 +231,6 @@ mod imp {#[cfg(target_os = "macos")]mod raise {- use accessibility_sys::{- kAXErrorActionUnsupported, kAXErrorAttributeUnsupported, kAXErrorNotImplemented,- kAXErrorSuccess,- };use agent_desktop_core::{AdapterError, Deadline, DeliverySemantics};use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};@@ -240,37 +242,78 @@ mod raise {let raise = CFString::new("AXRaise");let raise_err =crate::tree::ax_ipc::perform_action(window, raise.as_concrete_TypeRef(), deadline)?;- if raise_err == kAXErrorSuccess {- return crate::system::focus::wait_until_main(window, deadline).map_err(after_delivery);+ let outcome = crate::actions::ax_mutation::classify_result(+ window,+ "AXRaise",+ crate::actions::ax_mutation::PERFORM_API,+ raise_err,+ );+ if !needs_main_fallback(outcome, || {+ crate::system::focus::wait_until_main(window, deadline)+ })? {+ return Ok(());}- if safe_to_fallback(raise_err) {- prepare(window, deadline)?;- let main_attr = CFString::new("AXMain");- let ax_err = crate::tree::ax_ipc::set_attribute_value(- window,- main_attr.as_concrete_TypeRef(),- CFBoolean::true_value().as_CFTypeRef(),- deadline,- )?;- crate::system::focus::finish_mutation(window, ax_err, "raise window", deadline)?;- return crate::system::focus::wait_until_main(window, deadline).map_err(after_delivery);+ prepare(window, deadline)?;+ let main_attr = CFString::new("AXMain");+ let ax_err = crate::tree::ax_ipc::set_attribute_value(+ window,+ main_attr.as_concrete_TypeRef(),+ CFBoolean::true_value().as_CFTypeRef(),+ deadline,+ )?;+ crate::system::focus::finish_mutation(window, ax_err, "raise window", deadline)?;+ crate::system::focus::wait_until_main(window, deadline).map_err(after_delivery)+ }++ fn needs_main_fallback(+ outcome: Result<bool, AdapterError>,+ verify: impl FnOnce() -> Result<(), AdapterError>,+ ) -> Result<bool, AdapterError> {+ match outcome {+ Ok(false) => Ok(true),+ Ok(true) => verify().map(|()| false).map_err(after_delivery),+ Err(error) if error.disposition == DeliverySemantics::uncertain() => {+ verify().map(|()| false).map_err(|_| error)+ }+ Err(error) => Err(error),}- crate::system::focus::finish_mutation(window, raise_err, "raise window", deadline)}fn prepare(window: &crate::tree::AXElement, deadline: Deadline) -> Result<(), AdapterError> {crate::tree::attributes::set_messaging_timeout(window, deadline)}- fn safe_to_fallback(error: i32) -> bool {- error == kAXErrorActionUnsupported- || error == kAXErrorAttributeUnsupported- || error == kAXErrorNotImplemented- }-fn after_delivery(error: AdapterError) -> AdapterError {error.with_disposition(DeliverySemantics::delivered_unverified())}++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn uncertain_raise_requires_main_window_evidence_and_never_falls_back() {+ let error = AdapterError::timeout("raise uncertain")+ .with_disposition(DeliverySemantics::uncertain());+ assert!(!needs_main_fallback(Err(error.clone()), || Ok(())).unwrap());+ let failure =+ needs_main_fallback(Err(error), || Err(AdapterError::timeout("readback")))+ .unwrap_err();+ assert_eq!(failure.message, "raise uncertain");+ assert_eq!(failure.disposition, DeliverySemantics::uncertain());+ }++ #[test]+ fn only_unsupported_raise_authorizes_the_main_attribute_fallback() {+ assert!(needs_main_fallback(Ok(false), || panic!("no read needed")).unwrap());+ assert!(!needs_main_fallback(Ok(true), || Ok(())).unwrap());+ let error = needs_main_fallback(Err(AdapterError::permission_denied()), || {+ panic!("no probe after permission denial")+ })+ .unwrap_err();+ assert_eq!(error.code, agent_desktop_core::ErrorCode::PermDenied);+ }+ }}#[cfg(target_os = "macos")]diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rsindex a7d89486a..c312512f3 100644--- a/crates/macos/src/tree/adapter.rs+++ b/crates/macos/src/tree/adapter.rs@@ -128,6 +128,22 @@ impl ObservationOps for MacOSAdapter {Err(AdapterError::not_supported("get_live_state"))}+ fn get_text_selection(+ &self,+ handle: &NativeHandle,+ deadline: Deadline,+ ) -> Result<Option<std::ops::Range<usize>>, AdapterError> {+ #[cfg(target_os = "macos")]+ {+ Ok(crate::tree::attributes::selected_text_range(+ ax_element(handle)?,+ deadline,+ ))+ }+ #[cfg(not(target_os = "macos"))]+ Ok(None)+ }+fn get_live_actions(&self,handle: &NativeHandle,diff --git a/crates/macos/src/tree/attributes.rs b/crates/macos/src/tree/attributes.rsindex 1904011ec..c4d452e1d 100644--- a/crates/macos/src/tree/attributes.rs+++ b/crates/macos/src/tree/attributes.rs@@ -124,6 +124,50 @@ mod imp {.ok_or(MALFORMED_AX_VALUE)}+ pub(crate) fn selected_text_range(+ element: &AXElement,+ deadline: agent_desktop_core::Deadline,+ ) -> Option<std::ops::Range<usize>> {+ use accessibility_sys::{+ AXValueGetTypeID, AXValueGetValue, kAXErrorSuccess, kAXValueTypeCFRange,+ };+ use core_foundation::{+ base::{CFType, TCFType},+ string::CFString,+ };+ use core_foundation_sys::base::CFRange;++ let attribute = CFString::new("AXSelectedTextRange");+ let (error, raw) = crate::tree::ax_ipc::copy_attribute_value(+ element,+ attribute.as_concrete_TypeRef(),+ deadline,+ );+ if raw.is_null() {+ return None;+ }+ let value = unsafe { CFType::wrap_under_create_rule(raw) };+ if error != kAXErrorSuccess || value.type_of() != unsafe { AXValueGetTypeID() } {+ return None;+ }+ let mut range = CFRange {+ location: 0,+ length: 0,+ };+ if !unsafe {+ AXValueGetValue(+ raw as _,+ kAXValueTypeCFRange,+ (&mut range as *mut CFRange).cast(),+ )+ } {+ return None;+ }+ let start = usize::try_from(range.location).ok()?;+ let length = usize::try_from(range.length).ok()?;+ Some(start..start.checked_add(length)?)+ }+fn ax_array_items(arr: CFArray<CFType>) -> Vec<AXElement> {arr.into_iter().filter_map(|item| ax_value::retained_ax_element(&item))@@ -198,3 +242,6 @@ pub(crate) use imp::{#[cfg(not(target_os = "macos"))]pub(crate) use imp::copy_ax_array_result;++#[cfg(target_os = "macos")]+pub(crate) use imp::selected_text_range;diff --git a/crates/macos/src/tree/node_attribute_fetch.rs b/crates/macos/src/tree/node_attribute_fetch.rsindex 531db293a..07de1dd8a 100644--- a/crates/macos/src/tree/node_attribute_fetch.rs+++ b/crates/macos/src/tree/node_attribute_fetch.rs@@ -82,7 +82,7 @@ mod imp {continue;}if let Some(error) = node_attribute_decode::slot_error(&item) {- status.record_slot_error(index, error);+ status.record_native_slot_error(index, error);continue;}match index {@@ -172,7 +172,7 @@ mod imp {Some(item) if node_attribute_decode::is_null(&item) => {}Some(item) => {if let Some(error) = node_attribute_decode::slot_error(&item) {- status.record_slot_error(VALUE, error);+ status.record_native_slot_error(VALUE, error);} else {match node_attribute_decode::text(VALUE, &item, usage) {Some(value) if value.complete => {diff --git a/crates/macos/src/tree/node_attribute_status.rs b/crates/macos/src/tree/node_attribute_status.rsindex ed0a73569..a2ffa18fd 100644--- a/crates/macos/src/tree/node_attribute_status.rs+++ b/crates/macos/src/tree/node_attribute_status.rs@@ -31,7 +31,7 @@ const ATTRIBUTE_COUNT: usize = 23;const ROLE_MASK: u32 = bit(ROLE) | bit(SUBROLE);const STATE_MASK: u32 =- bit(ROLE) | bit(VALUE) | range_mask(4, 12) | bit(POSITION) | bit(SIZE) | bit(READONLY_PROBE);+ ROLE_MASK | bit(VALUE) | range_mask(4, 12) | bit(POSITION) | bit(SIZE) | bit(READONLY_PROBE);const BOUNDS_MASK: u32 = bit(POSITION) | bit(SIZE);const SCROLLBAR_MASK: u32 = bit(VERTICAL_SCROLLBAR) | bit(HORIZONTAL_SCROLLBAR);const ALL_ATTRIBUTE_MASK: u32 = range_mask(0, ATTRIBUTE_COUNT - 1);@@ -51,6 +51,12 @@ impl NodeAttributeStatus {self.record_error(bit(index), error);}+ pub(crate) fn record_native_slot_error(&mut self, index: usize, error: i32) {+ if !crate::tree::ax_absence::is_absent_attribute_error(error) {+ self.record_slot_error(index, error);+ }+ }+pub(crate) fn record_batch_error(&mut self, error: i32) {self.record_error(ALL_ATTRIBUTE_MASK, error);}@@ -177,6 +183,48 @@ mod tests {assert_eq!(status.text_truncations, 1);}+ #[test]+ fn native_absence_slots_do_not_make_name_evidence_unknown() {+ for error in [+ kAXErrorAttributeUnsupported,+ kAXErrorNoValue,+ accessibility_sys::kAXErrorNotImplemented,+ accessibility_sys::kAXErrorFailure,+ ] {+ let mut status = NodeAttributeStatus::default();+ status.record_native_slot_error(DESCRIPTION, error);++ assert!(!status.field_unknown(DESCRIPTION));+ assert_eq!(status.native_read_failures, 0);+ }+ }++ #[test]+ fn native_transport_and_invalid_element_slots_remain_unknown() {+ for error in [+ kAXErrorCannotComplete,+ kAXErrorInvalidUIElement,+ kAXErrorAPIDisabled,+ ] {+ let mut status = NodeAttributeStatus::default();+ status.record_native_slot_error(DESCRIPTION, error);++ assert!(status.field_unknown(DESCRIPTION));+ assert_eq!(status.cannot_complete, error == kAXErrorCannotComplete);+ assert_eq!(status.invalid_element, error == kAXErrorInvalidUIElement);+ assert_eq!(status.api_disabled, error == kAXErrorAPIDisabled);+ }+ }++ #[test]+ fn malformed_batches_cannot_be_treated_as_absence() {+ let mut status = NodeAttributeStatus::default();+ status.record_batch_error(accessibility_sys::kAXErrorFailure);++ assert!(status.field_unknown(DESCRIPTION));+ assert_eq!(status.native_read_failures, 1);+ }+#[test]fn decode_failure_is_counted_as_an_unclassified_native_read_failure() {let mut status = NodeAttributeStatus::default();diff --git a/crates/macos/src/tree/query/evidence_fields.rs b/crates/macos/src/tree/query/evidence_fields.rsindex 6e6fa32c0..52351bbd7 100644--- a/crates/macos/src/tree/query/evidence_fields.rs+++ b/crates/macos/src/tree/query/evidence_fields.rs@@ -4,6 +4,21 @@ use crate::tree::node_attribute_status::{DESCRIPTION, LABEL, NodeAttributeStatus, PLACEHOLDER, TITLE, TITLE_ELEMENT, VALUE,};+pub(crate) fn role_field(+ role: Option<&str>,+ subrole: Option<&str>,+ status: &NodeAttributeStatus,+) -> LocatorField<String> {+ if status.role_unknown() {+ LocatorField::Unknown+ } else {+ super::node_evidence::option_field(+ role.map(|role| crate::tree::roles::ax_role_and_subrole_to_str(role, subrole).into()),+ false,+ )+ }+}+pub(crate) fn name_field(evidence: &NameEvidence,status: &NodeAttributeStatus,@@ -110,6 +125,29 @@ fn meaningful(value: Option<&str>) -> Option<&str> {mod tests {use super::*;+ #[test]+ fn failed_subrole_read_cannot_prove_a_canonical_role_or_state() {+ let mut status = NodeAttributeStatus::default();+ status.record_slot_error(+ crate::tree::node_attribute_status::SUBROLE,+ accessibility_sys::kAXErrorCannotComplete,+ );++ assert_eq!(+ role_field(Some("AXGroup"), None, &status),+ LocatorField::Unknown+ );+ assert!(status.states_unknown());+ assert_eq!(+ role_field(+ Some("AXGroup"),+ Some("AXApplicationDialog"),+ &NodeAttributeStatus::default()+ ),+ LocatorField::Known("dialog".into()),+ );+ }+#[test]fn transient_higher_priority_name_source_keeps_fallback_unknown() {let evidence = NameEvidence {diff --git a/crates/macos/src/tree/query/node_read.rs b/crates/macos/src/tree/query/node_read.rsindex bcdc50440..ef1147d9c 100644--- a/crates/macos/src/tree/query/node_read.rs+++ b/crates/macos/src/tree/query/node_read.rs@@ -182,11 +182,11 @@ pub(crate) fn read_node(&identifiers,&actions,);- let role_field = if attrs.role.is_some() {- LocatorField::Known(role)- } else {- option_field(None, read.status.role_unknown())- };+ let role_field = super::evidence_fields::role_field(+ attrs.role.as_deref(),+ attrs.subrole.as_deref(),+ &read.status,+ );let evidence = LocatorEvidence {role: role_field,name: name_field,diff --git a/crates/macos/src/tree/query/traversal.rs b/crates/macos/src/tree/query/traversal.rsindex b8fa9cfce..a3d6e54ee 100644--- a/crates/macos/src/tree/query/traversal.rs+++ b/crates/macos/src/tree/query/traversal.rs@@ -203,6 +203,7 @@ impl LocatorTraversal {);}None => {+ complete = false;retained_edge_certainty(&mut predecessors_complete, false);}}@@ -246,7 +247,33 @@ fn retained_edge_certainty(prefix_certain: &mut bool, retained: bool) -> bool {#[cfg(test)]mod tests {- use super::retained_edge_certainty;+ use super::*;++ #[test]+ fn omitted_child_cannot_leave_its_parent_subtree_complete() {+ let mut request = ObservationRequest::snapshot(+ &agent_desktop_core::TreeOptions::default(),+ agent_desktop_core::Deadline::after(1_000).unwrap(),+ );+ request.budget.max_nodes = 1;+ let mut traversal = LocatorTraversal::new(+ &request,+ crate::tree::TreeBuildContext::empty(false),+ Instant::now() + Duration::from_secs(1),+ );+ assert!(traversal.usage.claim_node());+ traversal.arena.add_handles(1);+ let mut read = ChildRead::empty(true);+ read.elements.push(AXElement(std::ptr::null_mut()));+ read.total_count = 1;++ let (children, complete) = traversal.visit_children(read, (1, 0)).unwrap();++ assert!(children.is_empty());+ assert!(!complete);+ assert!(!traversal.arena.structurally_complete);+ assert!(traversal.arena.finish().is_ok());+ }#[test]fn uncertain_source_prefix_marks_retained_edge_uncertain() {diff --git a/crates/macos/src/tree/state_reader.rs b/crates/macos/src/tree/state_reader.rsindex 48ebb5ccd..2471f4226 100644--- a/crates/macos/src/tree/state_reader.rs+++ b/crates/macos/src/tree/state_reader.rs@@ -75,12 +75,25 @@ fn is_expanded(attrs: &NodeAttrs) -> bool {.unwrap_or(false)}+pub(crate) fn parse_checked_value(value: &str) -> Option<bool> {+ match value.trim().to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" | "on" | "checked" => Some(true),+ "0" | "false" | "no" | "off" | "unchecked" => Some(false),+ _ => None,+ }+}+fn value_is_checked(value: Option<&str>) -> bool {- matches!(value, Some("1" | "true"))+ value.and_then(parse_checked_value) == Some(true)}fn value_is_indeterminate(value: Option<&str>) -> bool {- matches!(value, Some("2" | "mixed"))+ value.is_some_and(|value| {+ matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "2" | "mixed" | "indeterminate"+ )+ })}/// `None` when either rectangle is unknown. No macOS element publishesdiff --git a/crates/macos/src/tree/state_reader_tests.rs b/crates/macos/src/tree/state_reader_tests.rsindex dbe96dc6a..baaf6e85b 100644--- a/crates/macos/src/tree/state_reader_tests.rs+++ b/crates/macos/src/tree/state_reader_tests.rs@@ -37,6 +37,17 @@ fn mixed_checkbox_emits_indeterminate_not_checked() {assert!(!states.contains(&state::CHECKED.to_string()));}+#[test]+fn checked_value_spellings_match_action_readback() {+ for value in ["1", "true", "yes", "on", "checked", " ON "] {+ let mut attrs = sample_attrs();+ attrs.value = Some(value.into());+ let el = AXElement(std::ptr::null_mut());+ let states = states_from_element(&el, &attrs, "checkbox", &ctx_with(None, false));+ assert!(states.contains(&state::CHECKED.to_string()), "{value}");+ }+}+#[test]fn hidden_attr_emits_hidden_token() {let mut attrs = sample_attrs();diff --git a/docs/json-output.md b/docs/json-output.mdindex ca2b802c7..72d18a7a2 100644--- a/docs/json-output.md+++ b/docs/json-output.md@@ -4,7 +4,7 @@ Every command returns structured JSON:```json{- "version": "2.3",+ "version": "2.4","ok": true,"command": "click","data": { "action": "click" }@@ -15,7 +15,7 @@ Errors include machine-readable codes and recovery hints:```json{- "version": "2.3",+ "version": "2.4","ok": false,"command": "click","error": {@@ -41,6 +41,22 @@ recovery strategy from `recovery.strategy` only when `disposition.retry` is`safe`; command strings from older envelopes must not be executed blindly.The removed `retry_command` field has no compatibility alias.+## Version 2.4 migration++Stateful ref actions (`set-value`, `type`, `clear`, `check`, `uncheck`, `toggle`, `expand`, and `collapse`) now reject observed postcondition contradictions after one delivery attempt. Readback failures preserve the adapter's error code and carry `details.kind: "post_action_verification"`. Missing evidence alone remains a successful `delivered_unverified` result with `details.verification_scope: "unavailable"`; neither that result nor verified element state proves application-level persistence.++macOS mutation errors that do not prove non-delivery stop fallback chains with an unsafe retry disposition. This affects activation, selection, disclosure, scrolling, and window operations; an unchanged or unreadable state is not proof that a mutation was never delivered. Value-writing chains also stop after unverified delivery instead of applying a second mechanism. Failures after preparatory scrolling carry `details.preparatory_scroll` and do not authorize automatic retry.++Inspect `disposition.retry` before retrying or choosing an alternative action, regardless of `error.code`. An error may include `post_state` and `postcondition_satisfied` without erasing the original execution failure. The same verification rules apply to FFI ref actions; the C ABI is unchanged. The Rust `ActionResult::from_execution` constructor now takes only action and steps and returns an infallible result; live verification belongs to `execute_verified_action`.++## Headed action verification++- Headed ref interactions activate the exact source app/window before final pointer hit testing. Read-only readiness polling must not prevent a background target from reaching that focus phase; final hit testing remains mandatory before delivery.+- Focus and preparatory scrolling can change coordinates. Stability is verified against fresh live observations, not by requiring coordinates to remain equal to the original snapshot.+- On macOS, post-activation focus confirmation uses fresh system-wide `AXFocusedApplication` and exact-window evidence with process-generation checks. A cached `NSWorkspace` foreground snapshot is not sufficient in a process that just activated another app.+- Focusing an inactive text field can change its selection. A pre-focus range cannot establish the expected insertion into a nonempty field; such a result is explicitly unverified rather than falsely contradicted.+- A settle-loop pacing budget does not replace the caller's deadline for native reads. Tests assert deadline identity rather than arbitrary remaining-time thresholds.+## Error codes| Code | Meaning |diff --git a/docs/solutions/developer-experience/visual-debug-snapshot-and-click-artifacts.md b/docs/solutions/developer-experience/visual-debug-snapshot-and-click-artifacts.mdnew file mode 100644index 000000000..a6dd5790d--- /dev/null+++ b/docs/solutions/developer-experience/visual-debug-snapshot-and-click-artifacts.md@@ -0,0 +1,47 @@+---+title: Visual debug artifacts for snapshots and clicks+date: 2026-09-09+category: developer-experience+module: src/visual_debug+problem_type: developer_experience+component: tooling+severity: medium+applies_when:+ - "Demonstrating snapshot targets or investigating a click visually"+ - "Maintaining screenshot alignment and viewer filters"+tags: [visual-debug, skeleton, screenshots, role-filters, macos]+---++# Visual debug artifacts for snapshots and clicks++## Context++JSON is useful for agents but awkward for a visual demo. The opt-in HTML viewer shows captured window pixels with labeled element bounds. Its sidebar groups nodes by role instead of displaying one long list.++## Guidance++- Use `--debug --screenshot PATH.html` with window-surface `snapshot` or ref-based `click`. The destination must be new; screenshots and labels are sensitive.+- Keep role groups collapsed initially. Checkbox filters select roles without expanding their lists; multiple selections combine, and no selection shows all. Preserve original element numbers and refs when grouping.+- Capture the exact source window, not whichever window is focused. Use shadow-free window captures and check geometry before drawing bounds; macOS implements this in `crates/macos/src/system/screenshot.rs`.+- Keep before/after click images separate. The before target is resolved before dispatch, not necessarily at the final delivery point. Do not reuse its bounds on the after image or treat screenshots as proof of delivery.+- Preserve the original command result if late artifact capture or writing fails. Report a warning instead of encouraging a duplicate click. `src/visual_debug/mod.rs` owns this boundary.+- Escape app-controlled data before embedding it in HTML and render labels with `textContent`. Keep the viewer self-contained with no network requests.++## Why This Matters++The debug view must help explain an action without changing its meaning, capturing the wrong window, or making an uncertain result look verified.++## When to Apply++Use this when changing `src/visual_debug/` or the window-frame screenshot adapter. Rebuild the binary and generate a new artifact after viewer changes; existing HTML files are static.++## Examples++See [Visual debug usage](../../../skills/agent-desktop/references/commands-observation.md#visual-debug) for capture commands and viewer controls.++```bash+cargo test -p agent-desktop --bin agent-desktop visual_debug+node --test src/visual_debug/viewer_filter.test.js+```++Also check role-only filtering, combined roles, reset, group expansion, individual selection, and narrow-screen layout in a browser. Live TextEdit captures verified Retina alignment and a Bold click; a separate accessibility read confirmed the checked state.diff --git a/scripts/perf_ab_probe.py b/scripts/perf_ab_probe.pyindex 62c0d2f30..d4707eaab 100755--- a/scripts/perf_ab_probe.py+++ b/scripts/perf_ab_probe.py@@ -34,8 +34,10 @@ def env_for(binary):def run(binary, *args, timeout=90):start = time.monotonic()+ lease = os.environ.get("AGENT_DESKTOP_INTERACTION_LEASE_FD")proc = subprocess.run(- [binary, *args], capture_output=True, text=True, timeout=timeout, env=env_for(binary)+ [binary, *args], capture_output=True, text=True, timeout=timeout, env=env_for(binary),+ pass_fds=(int(lease),) if lease else (),)elapsed = (time.monotonic() - start) * 1000return elapsed, procdiff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.mdindex cfabaf992..850c90be2 100644--- a/skills/agent-desktop/SKILL.md+++ b/skills/agent-desktop/SKILL.md@@ -102,8 +102,8 @@ When you know the target's role or exact name, use `find --role ... --name ... -Every command returns a JSON envelope on stdout:-**Success:** `{ "version": "2.3", "ok": true, "command": "snapshot", "data": { ... } }`-**Error:** `{ "version": "2.3", "ok": false, "command": "click", "error": { "code": "STALE_REF", "message": "...", "suggestion": "..." } }`+**Success:** `{ "version": "2.4", "ok": true, "command": "snapshot", "data": { ... } }`+**Error:** `{ "version": "2.4", "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.@@ -118,7 +118,7 @@ Exit codes: `0` success, `1` structured error, `2` argument error.| `PERM_DENIED` | Accessibility or Screen Recording permission not granted | Grant the named permission in System Settings || `ELEMENT_NOT_FOUND` | Ref cannot be resolved against the live UI | Re-run snapshot, use fresh ref || `APP_NOT_FOUND` | App not running | Launch it first |-| `ACTION_FAILED` | AX action rejected | Try an explicit alternative command |+| `ACTION_FAILED` | Action rejected or its observed result contradicted the request | Inspect `disposition.retry`, `details.post_state`, and `details.after_action`; do not repeat or substitute an action after uncertain or unverified delivery || `ACTION_NOT_SUPPORTED` | Element can't do this | Use different command || `STALE_REF` | Ref could not be re-identified in the live UI | Use the `snapshot_id` returned with this ref; if the UI changed or the target disappeared, re-run `snapshot` / `snapshot --skeleton` to get fresh refs || `AMBIGUOUS_TARGET` | Multiple elements matched the old ref identity | Re-run snapshot and choose a more specific ref |@@ -134,6 +134,8 @@ Exit codes: `0` success, `1` structured error, `2` argument error.`TIMEOUT` errors carry a `details` object whose `kind` field selects the schema. `kind: "wait_timeout"` includes `predicate`, `timeout_ms`, and `last_observed` or `last_error`, plus `ref`/`title`/`text_chars` depending on the wait mode. `kind: "chain_deadline"` includes `value_before`, `value_at_timeout`, `target`, and `mutated` (increment waits) or `wanted_expanded`/`observed_expanded` (disclosure waits). `mutated: true` — or an unknown `observed_expanded` state — means re-read the element before retrying; `mutated: false` means the state did not change and retrying directly is safe.+`details.kind: "post_action_verification"` means execution was followed by a contradictory or failed state read. The original read error code is preserved, so even `STALE_REF` or `TIMEOUT` can follow delivery. Inspect `post_state`, `after_action`, and `disposition.retry` before any retry or alternative action. Missing evidence alone is reported as successful `delivered_unverified` with `details.verification_scope: "unavailable"`, not as proof that the change failed.+## Command Quick Reference (59 names, 55 operational)### Observation@@ -151,6 +153,8 @@ agent-desktop is @e1 --snapshot <snapshot_id> --property enabled # Check eleagent-desktop list-surfaces --app "App" # Available surfaces```+For a visual demo on macOS, add `--debug --screenshot /tmp/visual.html` to `snapshot` or `click`. The local HTML viewer has ref highlights and collapsible role groups with checkbox filters. Choose a new file; see [Visual debug](references/commands-observation.md#visual-debug).+### Interaction```agent-desktop click @e5 --snapshot <snapshot_id> # Headless semantic clickdiff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex 39c1fc2f5..8d342f0f3 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -24,6 +24,12 @@ A successful action reports what happened, not just that it ran:| `data.post_state` | The target element's state after the action, when the action has one || `data.surfaces` | Overlays the application had open once the action settled |+Stateful actions (`set-value`, `type`, `clear`, `check`, `uncheck`, `toggle`, `expand`, `collapse`) read fresh state after execution. An observed mismatch returns `ACTION_FAILED` with `error.details.kind: post_action_verification`; a failed read preserves its original error code. Missing evidence alone returns successful `delivered_unverified` with `details.verification_scope: unavailable` and `verification_reason: insufficient_evidence`. Inspect `post_state`, `after_action`, and the delivery disposition before deciding what to do next. `toggle` requires readable before/after checked state; check/uncheck and expand/collapse require the requested final state. Do not blindly repeat an action with uncertain or unverified delivery, especially `toggle`, which could undo the first change.++Headed typing may change the selection when it focuses an inactive field. A range read before that focus change cannot verify insertion into a nonempty field, so the result remains explicitly unverified rather than reporting a false contradiction.++Secure text is intentionally redacted: a successfully delivered text write can return `delivered_unverified` with `verification_scope: unavailable` and `verification_reason: secure_field`, without exposing the value or claiming verification. This exception does not turn a native delivery error into success.+Check `data.surfaces` before assuming an action finished the job. An action thatopens a sheet, menu, or alert leaves the application waiting on that overlay, andthe next command must target it:@@ -39,6 +45,14 @@ the application is waiting for a confirmation the action did not deliver.On macOS, headed clicks on native menu-bar items use AXPress because these items have no ordinary owning window. Other headed ref clicks retain physical target verification. An enabled cursor overlay travels to and highlights that verified target alongside the real pointer.+### Visual click debugging++On macOS, `click REF --debug --screenshot /tmp/click-visual.html` writes a local+HTML artifact with the highlighted pre-dispatch target, an after-command window+capture, and the original command result. It neither enables `--headed` nor+proves delivery from the screenshot. See [Visual debug](commands-observation.md#visual-debug)+for role-group checkbox filters, permissions, new-file requirements, and failure handling.+### `--wait-for` / `--wait-for-gone` (global)Three global flags poll the accessibility tree until a compact selector matches (or, with `--wait-for-gone`, until it no longer matches), then return a snapshot envelope:@@ -131,12 +145,16 @@ agent-desktop type @s8f3k2p9:e2 "multi line\ntext"```Headless `type` uses `AXSelectedText` without focusing the app or synthesizing keys. Pass `--headed` to focus the target and synthesize keyboard input. Use `set-value` when direct semantic value assignment is the intended interaction.+When the value and selection are readable, insertion checks the resulting value. A mismatch or unavailable readback returns `ACTION_FAILED`; inspect the current state and delivery disposition before writing again. Secure-field redaction is the explicit exception described above: a delivered write remains unverified rather than failing solely because its value is hidden.+### set-value```bashagent-desktop set-value @s8f3k2p9:e2 "new value"```Sets the value directly via the AX value attribute. Faster than `type` but may not trigger all UI callbacks. Use for text fields, text areas, and sliders.+`delivered_verified` confirms the target element's value, not an application commit or a dependent document change. The result details identify `verification_scope: element_value` and `application_commit: not_verified`. For example, changing a spreadsheet's row-count text field does not prove the table resized; verify the table or target its native incrementor. A readable cell without `SetValue` is not directly editable: activate it and target the editor it exposes.+### clear```bashagent-desktop clear @s8f3k2p9:e2diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.mdindex 2a6ed3d85..dae7b81cd 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.3",+ "version": "2.4","ok": true,"command": "snapshot","data": {@@ -108,6 +108,48 @@ agent-desktop snapshot --root @e3 --snapshot <snapshot_id> -i- For a Chromium-based app's web contents (Slack, VS Code, Discord, and similar), `launch --cdp` plus a CDP client is a faster alternative to skeleton traversal on a fresh launch — see `references/commands-system.md`- Keep `snapshot_id` when commands must resolve against a specific snapshot instead of the latest snapshot pointer+### Visual debug++On macOS, `--debug --screenshot PATH.html` saves a local HTML viewer with window screenshots, element highlights, and ref labels. With TextEdit open:++```bash+agent-desktop snapshot --app TextEdit --skeleton -i --debug --screenshot /tmp/textedit-visual.html+open /tmp/textedit-visual.html+```++For a click, use a real ref from your snapshot:++```bash+agent-desktop click @s8f3k2p9:e5 --debug --screenshot /tmp/click-visual.html+```++**Using the viewer**+- Expand a role group to inspect its elements; snapshot groups start collapsed.+- Check **Tree items**, **Buttons**, or another role to filter highlights. Multiple checked roles combine; none checked shows all. Checking does not expand the group.+- Select an element to isolate its bounds and ref; select it again to undo. **Show all elements** resets everything. **Highlights** hides or shows the boxes.+- Blue = action ref, amber dashed = drill anchor, gray = context, red = click target. Hidden/offscreen elements and elements without drawable bounds stay listed without boxes. List numbers are not refs.+- Click captures have **Before click** and **After command** views. Only the before image highlights the target; screenshots are not proof of delivery or a live recording.++**Important limits**+- Both flags are required. Choose a new `.html` file in an existing directory; files are never overwritten.+- Requires Accessibility and Screen Recording permissions. Supports window-surface `snapshot` and ref-based `click`, not batch or other commands. It does not enable `--headed`; `-v` is still separate logging.+- Success adds `data.debug` with the artifact path and optional warning. Late capture/write failures preserve the command result; command failures preserve the original error and report artifact metadata on stderr. Preparation errors may prevent dispatch.+- Screenshots and labels are sensitive. No session is needed. Debug snapshots retain full bounds in their persisted refmap for the viewer; JSON still omits bounds unless `--include-bounds` was requested. Debug capture is opt-in, not a byte-identical persistence mode.+- Rebuild after viewer changes and generate a new artifact; saved HTML does not update automatically.++### Live inspector (source checkout)++For an interactive tree and screenshot, run from the repository root with Node 22+:++```bash+cargo build --release -p agent-desktop+npm --prefix tools/inspector run dev+```++Choose an app and select **Inspect app**. Tree arrows load children through the CLI; selecting a row isolates its highlight. **Show all** restores the overview. The right panel provides root-scoped find and property/state reads, with a progress toast while commands run.++No npm dependencies or global tools are needed. The bridge opens a localhost URL, retries busy ports, and keeps separate temporary snapshot state. Use the full launch URL: its fragment carries the capability token, which is not served in public HTML. Accessibility permission is required; without Screen Recording permission the inspector falls back to the accessibility tree and shows a warning. It is read-only and uses the same screenshot styling as saved debug HTML. Keep one active view per server and refresh after app changes or a failed drill, which may already have replaced stored refs. Normal shutdown removes private state; `SIGKILL` or a system crash can leave temporary files. Run tests with `npm --prefix tools/inspector test`.+## findSearch elements by role, name, value, or text content.diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex e2eafadf2..1b0ab6fba 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -430,7 +430,7 @@ Each entry may include `"session": "id"` beside `command` and `args`. If omitted**Per-entry failure shape:**```json{- "version": "2.3",+ "version": "2.4","ok": false,"command": "click","error": {diff --git a/skills/agent-desktop/references/workflows.md b/skills/agent-desktop/references/workflows.mdindex a308c55d6..970f0c1c0 100644--- a/skills/agent-desktop/references/workflows.md+++ b/skills/agent-desktop/references/workflows.md@@ -148,6 +148,26 @@ agent-desktop click @e8 --snapshot <snapshot_id>agent-desktop snapshot --app "System Settings" -i```+## Pattern: Edit One Cell at a Time (Shared Editor)++Spreadsheet cells and other controls that open a shared editor are an observed+sequence, not one action: activate the cell, take a fresh snapshot, target the+editor it exposes, write with `type`/`set-value`, then commit explicitly. The+interaction lease serializes individual actions, not your whole sequence —+parallel writers can steal the shared editor even when each targets a different+row.++- Run the full sequence from one writer; do not parallelize edits to the same+ document or window.+- After any uncertain delivery or timeout from a mutation, inspect the current+ editor/cell/document state (fresh snapshot plus `get --property value`)+ before choosing the next action. Never blindly retry the timed-out command:+ the mutation may already have landed.+- `set-value`/`type` verification covers the element value only+ (`verification_scope: element_value`, `application_commit: not_verified`).+ Confirm document-level effects such as table dimensions with an independent+ read of the document model.+## Pattern: Navigate Menus```bash@@ -349,3 +369,4 @@ agent-desktop batch '[9. **Re-snapshotting everything after one action.** Use scoped re-drill (`--root @ref`) to refresh only the affected region. Other refs stay valid.10. **Assuming headed and headless have the same side effects.** Headless ref actions block implicit focus/cursor input. Headed ref actions intentionally focus the exact source window when required, and headed pointer actions may move the cursor; raw coordinates never infer focus.11. **Hand-rolling raw CDP for a Chromium app.** After `launch --cdp`, connect a real CDP client — `agent-browser connect <port>` (preferred), or Playwright, Puppeteer, `chrome-remote-interface`, and similar — never a hand-written WebSocket client, `Runtime.evaluate` DOM edits, or app-internal APIs (e.g. an app's own JS globals). Those bypass real input, verify nothing, and are app-specific; they break silently on the next app update. If no CDP client is available, ask the user to install agent-browser or stay on accessibility commands.+12. **Parallel writers on a shared editor.** Click-to-edit plus type plus commit is not atomic across CLI invocations. Serialize the whole observed sequence through one writer, and after uncertain delivery inspect state before acting — never blindly retry a timeout from a mutation.diff --git a/src/Cargo.toml b/src/Cargo.tomlindex 6456a5227..541dabe03 100644--- a/src/Cargo.toml+++ b/src/Cargo.toml@@ -7,6 +7,7 @@ autotests = false[dependencies]agent-desktop-core.workspace = true+base64.workspace = trueclap.workspace = trueserde.workspace = trueserde_json.workspace = truediff --git a/src/cli/root.rs b/src/cli/root.rsindex c1ed0409f..716345ba5 100644--- a/src/cli/root.rs+++ b/src/cli/root.rs@@ -18,13 +18,8 @@ const AFTER_HELP: &str = include_str!("help_after.txt");after_help = AFTER_HELP,)]pub(crate) struct Cli {- #[arg(- long,- short = 'v',- global = true,- help = "Enable debug logging to stderr"- )]- pub verbose: bool,+ #[command(flatten)]+ pub visual_debug: crate::visual_debug::options::DebugOptions,#[command(flatten)]pub identity: super::identity::IdentityArgs,#[arg(diff --git a/src/main.rs b/src/main.rsindex 82b301a03..31cb15211 100644--- a/src/main.rs+++ b/src/main.rs@@ -6,6 +6,7 @@ mod cli_args;mod command_policy;mod diagnostic;mod dispatch;+mod visual_debug;/// Shared blanket-default `PlatformAdapter` test double, sourced once from/// `tests/support/noop_ops.rs` (also consumed by the standalone@@ -86,7 +87,7 @@ fn run() -> ExitCode {}};- init_tracing(cli.verbose);+ init_tracing(cli.visual_debug.verbose);let cmd = match cli.command.take() {Some(c) => c,@@ -100,6 +101,10 @@ fn run() -> ExitCode {let cmd_name = cmd.name();+ if let Err(err) = cli.visual_debug.validate(&cmd) {+ return finish(cmd_name, Err(err));+ }+if let Err(err) = agent_desktop_core::validate_state_root_env() {return finish(cmd_name, Err(pre_dispatch_error(err)));}@@ -159,7 +164,7 @@ fn run() -> ExitCode {return finish(cmd_name, Err(err));}}- run_with_adapter(cmd, cmd_name, &context)+ run_with_adapter(cmd, cmd_name, &context, &cli.visual_debug)}}}@@ -206,7 +211,12 @@ fn validate_wait_for_command(cmd: &Commands, wait: &WaitSelector) -> Result<(),Ok(())}-fn run_with_adapter(cmd: Commands, cmd_name: &str, context: &CommandContext) -> ExitCode {+fn run_with_adapter(+ mut cmd: Commands,+ cmd_name: &str,+ context: &CommandContext,+ debug: &visual_debug::options::DebugOptions,+) -> ExitCode {let adapter = build_adapter();let adapter: &dyn agent_desktop_core::PlatformAdapter = &adapter;let report = if command_policy::requires_permission_report(&cmd) {@@ -227,7 +237,31 @@ fn run_with_adapter(cmd: Commands, cmd_name: &str, context: &CommandContext) ->return finish(cmd_name, Err(err));}- let result = dispatch::dispatch(cmd, adapter, &report, context);+ if debug.debug && report.screen_recording_denied() {+ return finish(+ cmd_name,+ Err(pre_dispatch_error(+ AdapterError::new(+ ErrorCode::PermDenied,+ "Visual debug requires Screen Recording permission",+ )+ .with_suggestion(+ report+ .screen_recording_suggestion()+ .unwrap_or("Grant Screen Recording permission and retry"),+ )+ .into(),+ )),+ );+ }+ let capture = match visual_debug::DebugCapture::prepare(&mut cmd, debug, adapter, context) {+ Ok(capture) => capture,+ Err(error) => return finish(cmd_name, Err(pre_dispatch_error(error))),+ };+ let mut result = dispatch::dispatch(cmd, adapter, &report, context);+ if let Some(capture) = capture {+ capture.finish(&mut result, adapter, context);+ }finish(cmd_name, result)}diff --git a/src/tests/main_tests.rs b/src/tests/main_tests.rsindex a4c2b27c1..9b39560f6 100644--- a/src/tests/main_tests.rs+++ b/src/tests/main_tests.rs@@ -1,4 +1,41 @@use agent_desktop_core::{AdapterError, AppError, DeliveryDisposition, RetryDisposition};+use clap::Parser;++#[test]+fn visual_debug_flags_accept_snapshot_and_click() {+ for args in [+ vec![+ "agent-desktop",+ "snapshot",+ "--app",+ "TextEdit",+ "--skeleton",+ "-i",+ "--debug",+ "--screenshot",+ "/tmp/skeleton.html",+ ],+ vec![+ "agent-desktop",+ "click",+ "@sdemo:e1",+ "--debug",+ "--screenshot",+ "/tmp/click.html",+ ],+ ] {+ assert!(crate::Cli::try_parse_from(args).is_ok());+ }+}++#[test]+fn visual_debug_flags_require_explicit_capture_consent_and_path() {+ for flags in [vec!["--debug"], vec!["--screenshot", "/tmp/debug.html"]] {+ let mut args = vec!["agent-desktop", "snapshot"];+ args.extend(flags);+ assert!(crate::Cli::try_parse_from(args).is_err());+ }+}#[test]fn pre_dispatch_failures_are_always_safe_to_retry() {diff --git a/src/visual_debug/capture.rs b/src/visual_debug/capture.rsnew file mode 100644index 000000000..1b8c62f47--- /dev/null+++ b/src/visual_debug/capture.rs@@ -0,0 +1,217 @@+use agent_desktop_core::{+ AccessibilityNode, AdapterError, AppError, Deadline, ImageFormat, PlatformAdapter, Rect,+ RefEntry, WindowInfo, WindowState, context::CommandContext, refs_store::RefStore,+};+use base64::Engine;+use serde_json::{Value, json};++pub(super) fn window_for_entry(+ entry: &RefEntry,+ adapter: &dyn PlatformAdapter,+ deadline: Deadline,+) -> Result<WindowInfo, AppError> {+ let id =+ entry.source.source_window_id.clone().ok_or_else(|| {+ AppError::invalid_input("Debug capture requires an exact source window")+ })?;+ if entry+ .process+ .process_instance+ .as_deref()+ .is_none_or(str::is_empty)+ {+ return Err(AppError::invalid_input(+ "Debug capture requires a process instance",+ ));+ }+ Ok(adapter.resolve_window_strict(+ &WindowInfo {+ id,+ title: entry.source.source_window_title.clone().unwrap_or_default(),+ app: entry.source.source_app.clone().unwrap_or_default(),+ pid: entry.process.pid,+ process_instance: entry.process.process_instance.clone(),+ bounds: None,+ state: WindowState::default(),+ },+ deadline,+ )?)+}++pub(super) fn click_before(+ args: &crate::cli_args::RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<(WindowInfo, Value), AppError> {+ let deadline = Deadline::standard()?;+ let entry = RefStore::for_session(context.session_id())?+ .load_ref(&args.ref_id, args.snapshot_id.as_deref())?;+ let handle = adapter.resolve_element_strict(&entry, deadline)?;+ let bounds = adapter.get_element_bounds(&handle, deadline)?;+ let window = window_for_entry(&entry, adapter, deadline)?;+ let node = json!({+ "ref_id": args.ref_id,+ "role": entry.identity.role,+ "name": entry.identity.name,+ "bounds": bounds,+ "reason": "Requested click target, strictly resolved before dispatch. Not the final dispatch geometry.",+ "kind": "target"+ });+ let mut frame = capture_frame(&window, adapter, deadline)?;+ frame["nodes"] = json!([node]);+ Ok((window, frame))+}++pub(super) fn snapshot_frame(+ data: &Value,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let tree: AccessibilityNode = serde_json::from_value(data["tree"].clone())?;+ let ref_id = first_ref(&tree).ok_or_else(|| {+ AppError::invalid_input("No returned ref identifies an exact window for debug capture")+ })?;+ let entry = RefStore::for_session(context.session_id())?.load_ref(ref_id, None)?;+ let deadline = Deadline::standard()?;+ let window = window_for_entry(&entry, adapter, deadline)?;+ if data["window"]["id"].as_str() != Some(window.id.as_str())+ || entry.source.source_window_bounds_hash != window.bounds.and_then(|b| b.bounds_hash())+ {+ return Err(AdapterError::stale_ref(ref_id).into());+ }+ let mut frame = capture_frame(&window, adapter, deadline)?;+ let mut nodes = Vec::new();+ collect_nodes(&tree, 0, &mut nodes);+ frame["nodes"] = json!(nodes);+ Ok(frame)+}++fn first_ref(node: &AccessibilityNode) -> Option<&str> {+ node.ref_id+ .as_deref()+ .or_else(|| node.children.iter().find_map(first_ref))+}++pub(super) fn collect_nodes(node: &AccessibilityNode, depth: usize, nodes: &mut Vec<Value>) {+ let primary = node+ .presentation+ .available_actions+ .iter()+ .any(|a| a != agent_desktop_core::capability::SET_FOCUS);+ let interactive = agent_desktop_core::roles::is_interactive_role(&node.role);+ let (kind, reason) = if node.ref_id.is_some() && !interactive && !primary {+ (+ "drill",+ "Resolvable container retained as a drill-down anchor for a truncated branch.",+ )+ } else if node.ref_id.is_some() {+ (+ "action",+ "Addressable by interactive role or an advertised primary action; not a guarantee of live actionability.",+ )+ } else if depth == 0 {+ (+ "root",+ "Root of the returned accessibility tree. The screenshot frame is its owning window.",+ )+ } else {+ (+ "context",+ "Structural context retained around returned elements; no action ref assigned.",+ )+ };+ let mut item = json!({+ "role": node.role, "depth": depth, "kind": kind, "reason": reason,+ });+ for (key, value) in [+ ("ref_id", json!(node.ref_id)),+ (+ "name",+ json!(+ node.identity+ .name+ .as_ref()+ .or(node.identity.description.as_ref())+ ),+ ),+ ("bounds", json!(node.presentation.bounds)),+ ("children_count", json!(node.children_count)),+ ] {+ if !value.is_null() {+ item[key] = value;+ }+ }+ if node.subtree_truncated {+ item["subtree_truncated"] = json!(true);+ }+ if node+ .presentation+ .states+ .iter()+ .any(|state| matches!(state.as_str(), "hidden" | "offscreen"))+ {+ item["not_visible"] = json!(true);+ }+ nodes.push(item);+ for child in &node.children {+ collect_nodes(child, depth + 1, nodes);+ }+}++pub(super) fn capture_frame(+ window: &WindowInfo,+ adapter: &dyn PlatformAdapter,+ deadline: Deadline,+) -> Result<Value, AppError> {+ let before = adapter.resolve_window_strict(window, deadline)?;+ let bounds = before+ .bounds+ .ok_or_else(|| AppError::invalid_input("Window bounds unavailable"))?;+ bounds.validate()?;+ if window.bounds.is_some() && window.bounds != before.bounds {+ return Err(AppError::invalid_input(+ "Window moved before debug capture; refresh the snapshot",+ ));+ }+ let image = adapter.screenshot_window_frame(&before, deadline)?;+ let after = adapter.resolve_window_strict(&before, deadline)?;+ if before.bounds != after.bounds {+ return Err(AppError::invalid_input(+ "Window moved during debug capture; refresh the snapshot",+ ));+ }+ validate_frame(bounds, image.width, image.height)?;+ if !matches!(image.format, ImageFormat::Png) || image.data.len() > 64 * 1024 * 1024 {+ return Err(AppError::invalid_input(+ "Debug capture requires a PNG no larger than 64 MiB",+ ));+ }+ Ok(json!({+ "image": format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(&image.data)),+ "window": { "id": before.id, "title": before.title, "app": before.app, "bounds": bounds },+ "width": image.width, "height": image.height,+ "nodes": []+ }))+}++#[cfg(test)]+#[path = "capture_tests.rs"]+mod tests;++fn validate_frame(bounds: Rect, width: u32, height: u32) -> Result<(), AppError> {+ let scale_x = width as f64 / bounds.width;+ let scale_y = height as f64 / bounds.height;+ if width == 0+ || height == 0+ || bounds.width <= 0.0+ || bounds.height <= 0.0+ || !scale_x.is_finite()+ || !scale_y.is_finite()+ || (scale_x - scale_y).abs() > 0.02+ {+ return Err(AppError::invalid_input(+ "Screenshot does not match the window frame; refusing misaligned highlights",+ ));+ }+ Ok(())+}diff --git a/src/visual_debug/capture_tests.rs b/src/visual_debug/capture_tests.rsnew file mode 100644index 000000000..740c7cc83--- /dev/null+++ b/src/visual_debug/capture_tests.rs@@ -0,0 +1,258 @@+use super::*;+use agent_desktop_core::{ActionOps, ImageBuffer, InputOps, ObservationOps, ProcessId, SystemOps};+use std::sync::atomic::{AtomicUsize, Ordering};++#[derive(Default)]+struct CaptureAdapter {+ reads: AtomicUsize,+ move_after_capture: bool,+ invalid_format: bool,+ oversized: bool,+}++impl ActionOps for CaptureAdapter {}+impl InputOps for CaptureAdapter {}+impl ObservationOps for CaptureAdapter {+ fn resolve_element_strict(+ &self,+ _: &RefEntry,+ _: Deadline,+ ) -> Result<agent_desktop_core::NativeHandle, AdapterError> {+ Ok(agent_desktop_core::NativeHandle::null())+ }+ fn get_element_bounds(+ &self,+ _: &agent_desktop_core::NativeHandle,+ _: Deadline,+ ) -> Result<Option<Rect>, AdapterError> {+ Ok(window().bounds)+ }+}+impl SystemOps for CaptureAdapter {+ fn resolve_window_strict(+ &self,+ expected: &WindowInfo,+ _: Deadline,+ ) -> Result<WindowInfo, AdapterError> {+ assert_eq!(expected.id, "w-test");+ assert_eq!(expected.process_instance.as_deref(), Some("test-instance"));+ let mut window = WindowInfo {+ bounds: window().bounds,+ ..expected.clone()+ };+ if self.reads.fetch_add(1, Ordering::Relaxed) > 0 && self.move_after_capture {+ window.bounds.as_mut().unwrap().x += 10.0;+ }+ Ok(window)+ }++ fn screenshot_window_frame(+ &self,+ window: &WindowInfo,+ _: Deadline,+ ) -> Result<ImageBuffer, AdapterError> {+ assert_eq!(window.id, "w-test");+ Ok(ImageBuffer {+ data: if self.oversized {+ vec![0; 64 * 1024 * 1024 + 1]+ } else {+ vec![1, 2, 3]+ },+ format: if self.invalid_format {+ ImageFormat::Jpg+ } else {+ ImageFormat::Png+ },+ width: 1200,+ height: 800,+ scale_factor: 2.0,+ })+ }+}++fn window() -> WindowInfo {+ WindowInfo {+ id: "w-test".into(),+ title: "Test".into(),+ app: "Fixture".into(),+ pid: ProcessId::new(5),+ process_instance: Some("test-instance".into()),+ bounds: Some(Rect {+ x: -1000.0,+ y: 100.0,+ width: 600.0,+ height: 400.0,+ }),+ state: WindowState::default(),+ }+}++#[test]+fn visual_debug_capture_preserves_global_origin_and_retina_frame() {+ let adapter = CaptureAdapter {+ reads: AtomicUsize::new(0),+ move_after_capture: false,+ ..Default::default()+ };+ let frame = capture_frame(&window(), &adapter, Deadline::standard().unwrap()).unwrap();+ assert_eq!(frame["width"], 1200);+ assert_eq!(frame["window"]["bounds"]["x"], -1000.0);+ assert_eq!(frame["image"], "data:image/png;base64,AQID");+ assert_eq!(adapter.reads.load(Ordering::Relaxed), 2);+}++#[test]+fn visual_debug_capture_rejects_window_motion() {+ let adapter = CaptureAdapter {+ reads: AtomicUsize::new(0),+ move_after_capture: true,+ ..Default::default()+ };+ assert!(+ capture_frame(&window(), &adapter, Deadline::standard().unwrap())+ .unwrap_err()+ .to_string()+ .contains("moved")+ );+}++#[test]+fn saved_snapshot_and_click_capture_use_exact_source_evidence() {+ if std::env::var_os("INSPECTOR_CAPTURE_TEST_CHILD").is_none() {+ let home = std::env::temp_dir().join(format!(+ "debug-capture-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir(&home).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o700)).unwrap();+ }+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "visual_debug::capture::tests::saved_snapshot_and_click_capture_use_exact_source_evidence", "--nocapture"])+ .env("INSPECTOR_CAPTURE_TEST_CHILD", "1").env("AGENT_DESKTOP_HOME", &home).output().unwrap();+ std::fs::remove_dir_all(home).unwrap();+ assert!(+ output.status.success(),+ "{}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ return;+ }+ let window = window();+ let entry: RefEntry = serde_json::from_value(json!({+ "pid": 5, "process_instance": "test-instance", "role": "button", "name": "Save",+ "path": [0], "source_surface": "window", "source_window_id": "w-test",+ "source_window_bounds_hash": window.bounds.unwrap().bounds_hash(),+ "states": [], "available_actions": ["Click"], "bounds": window.bounds,+ "bounds_hash": window.bounds.unwrap().bounds_hash()+ }))+ .unwrap();+ let mut refs = agent_desktop_core::refs::RefMap::new();+ refs.try_allocate(entry).unwrap();+ RefStore::new()+ .unwrap()+ .save_snapshot("sfixture", &refs)+ .unwrap();+ let adapter = CaptureAdapter::default();+ let context = CommandContext::default();+ let mut data =+ json!({"window": {"id": "w-test"}, "tree": {"role": "button", "ref_id": "@sfixture:e1"}});+ assert_eq!(+ snapshot_frame(&data, &adapter, &context).unwrap()["nodes"][0]["ref_id"],+ "@sfixture:e1"+ );+ data["window"]["id"] = "w-other".into();+ assert!(+ matches!(snapshot_frame(&data, &adapter, &context), Err(AppError::Adapter(error)) if error.code == agent_desktop_core::ErrorCode::StaleRef)+ );+ use clap::Parser;+ let crate::cli::Commands::Click(args) =+ crate::Cli::try_parse_from(["agent-desktop", "click", "@sfixture:e1"])+ .unwrap()+ .command+ .unwrap()+ else {+ panic!()+ };+ let (_, frame) = click_before(&args, &adapter, &context).unwrap();+ assert_eq!(frame["nodes"][0]["kind"], "target");+ assert_eq!(frame["nodes"][0]["bounds"], json!(window.bounds));+}++#[test]+fn capture_rejects_non_png_and_oversized_images() {+ for (invalid_format, oversized) in [(true, false), (false, true)] {+ let adapter = CaptureAdapter {+ invalid_format,+ oversized,+ ..Default::default()+ };+ let error = capture_frame(&window(), &adapter, Deadline::standard().unwrap()).unwrap_err();+ assert!(error.to_string().contains("PNG no larger than 64 MiB"));+ }+}++#[test]+fn capture_requires_exact_window_and_process_evidence() {+ let mut entry: RefEntry = serde_json::from_value(json!({+ "pid": 5, "role": "button", "path": [], "source_surface": "window",+ "states": [], "available_actions": []+ }))+ .unwrap();+ let adapter = CaptureAdapter::default();+ assert!(+ window_for_entry(&entry, &adapter, Deadline::standard().unwrap())+ .unwrap_err()+ .to_string()+ .contains("exact source window")+ );+ entry.source.source_window_id = Some("w-test".into());+ assert!(+ window_for_entry(&entry, &adapter, Deadline::standard().unwrap())+ .unwrap_err()+ .to_string()+ .contains("process instance")+ );+ entry.process.process_instance = Some(String::new());+ assert!(window_for_entry(&entry, &adapter, Deadline::standard().unwrap()).is_err());+ assert_eq!(adapter.reads.load(Ordering::Relaxed), 0);+}++#[test]+fn snapshot_without_an_addressable_ref_never_captures_a_guessed_window() {+ let adapter = CaptureAdapter::default();+ let error = snapshot_frame(+ &json!({"tree": {"role": "window"}}),+ &adapter,+ &CommandContext::default(),+ )+ .unwrap_err();+ assert!(error.to_string().contains("No returned ref"));+ assert_eq!(adapter.reads.load(Ordering::Relaxed), 0);+}++#[test]+fn visual_debug_frame_rejects_padding_and_empty_geometry() {+ let bounds = window().bounds.unwrap();+ assert!(validate_frame(bounds, 1200, 800).is_ok());+ assert!(validate_frame(bounds, 1320, 920).is_err());+ assert!(validate_frame(bounds, 0, 800).is_err());+ assert!(+ validate_frame(+ Rect {+ width: 0.0,+ ..bounds+ },+ 1200,+ 800+ )+ .is_err()+ );+}diff --git a/src/visual_debug/mod.rs b/src/visual_debug/mod.rsnew file mode 100644index 000000000..a4a326584--- /dev/null+++ b/src/visual_debug/mod.rs@@ -0,0 +1,167 @@+mod capture;+pub(crate) mod options;+mod render;++use std::fs::{File, OpenOptions};+use std::io::Write;+use std::path::PathBuf;++use agent_desktop_core::{+ AppError, Deadline, PlatformAdapter, WindowInfo, context::CommandContext,+};+use serde_json::{Value, json};++use crate::cli::Commands;+use options::DebugOptions;++pub(crate) struct DebugCapture {+ file: File,+ path: PathBuf,+ before: Option<Value>,+ window: Option<WindowInfo>,+ strip_bounds: bool,+ mode: &'static str,+}++impl DebugCapture {+ pub(crate) fn prepare(+ command: &mut Commands,+ options: &DebugOptions,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+ ) -> Result<Option<Self>, AppError> {+ options.validate(command)?;+ let Some(path) = options.screenshot.as_ref() else {+ return Ok(None);+ };+ let (before, window, strip_bounds, mode) = match command {+ Commands::Click(args) => {+ let (window, before) = capture::click_before(args, adapter, context)?;+ (Some(before), Some(window), false, "click")+ }+ Commands::Snapshot(args) => {+ let strip = !args.tree.include_bounds;+ args.tree.include_bounds = true;+ let mode = if args.root.is_some() {+ "drill-down"+ } else if args.tree.skeleton {+ "skeleton"+ } else {+ "snapshot"+ };+ (None, None, strip, mode)+ }+ _ => return Err(AppError::invalid_input("Unsupported debug command")),+ };+ let mut open = OpenOptions::new();+ open.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ open.mode(0o600);+ }+ let file = open.open(path).map_err(|error| AppError::invalid_input(format!(+ "Cannot create debug output '{}': {error}. Choose a new .html path in an existing directory.", path.display()+ )))?;+ Ok(Some(Self {+ file,+ path: path.clone(),+ before,+ window,+ strip_bounds,+ mode,+ }))+ }++ pub(crate) fn finish(+ mut self,+ result: &mut Result<Value, AppError>,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+ ) {+ let mut artifact = json!({+ "mode": self.mode,+ "ok": result.is_ok(),+ "notice": "Local debug artifact: contains sensitive screenshots and accessibility labels. Captures are sequential observations, not a recording or proof of click delivery."+ });+ if let Some(before) = self.before.take() {+ artifact["before"] = before;+ }+ let captured = if let Some(window) = self.window.as_ref() {+ Deadline::standard()+ .map_err(AppError::from)+ .and_then(|deadline| capture::capture_frame(window, adapter, deadline))+ } else if let Ok(data) = result.as_ref() {+ capture::snapshot_frame(data, adapter, context)+ } else {+ Err(AppError::invalid_input(+ "Command failed before a snapshot was available",+ ))+ };+ let warning = match captured {+ Ok(frame) => {+ artifact["after"] = frame;+ None+ }+ Err(error) => {+ let warning = error.to_string();+ artifact["warning"] = json!(warning);+ Some(warning)+ }+ };+ match result.as_ref() {+ Ok(data) => {+ if self.mode == "click" {+ artifact["result"] = data.clone();+ }+ if let Some(id) = data.get("snapshot_id") {+ artifact["snapshot_id"] = id.clone();+ }+ }+ Err(error) => {+ artifact["error"] =+ serde_json::to_value(agent_desktop_core::ErrorPayload::from_app_error(error))+ .unwrap_or_else(|_| json!({"message": error.to_string()}))+ }+ }+ let write_result = render::html(&artifact).and_then(|html| {+ self.file.write_all(html.as_bytes())?;+ self.file.flush()?;+ Ok(())+ });+ let metadata = match write_result {+ Ok(()) => {+ let mut value = json!({"path": self.path, "format": "html"});+ if let Some(warning) = warning {+ value["warning"] = json!(warning);+ }+ value+ }+ Err(error) => json!({"warning": format!("Debug artifact write failed: {error}")}),+ };+ if let Ok(data) = result {+ if self.strip_bounds+ && let Some(tree) = data.get_mut("tree")+ {+ strip_bounds(tree);+ }+ data["debug"] = metadata;+ } else {+ eprintln!("agent-desktop debug: {metadata}");+ }+ }+}++fn strip_bounds(node: &mut Value) {+ if let Some(object) = node.as_object_mut() {+ object.remove("bounds");+ if let Some(children) = object.get_mut("children").and_then(Value::as_array_mut) {+ for child in children {+ strip_bounds(child);+ }+ }+ }+}++#[cfg(test)]+mod tests;diff --git a/src/visual_debug/options.rs b/src/visual_debug/options.rsnew file mode 100644index 000000000..26b1c30ae--- /dev/null+++ b/src/visual_debug/options.rs@@ -0,0 +1,63 @@+use std::path::PathBuf;++use agent_desktop_core::AppError;+use clap::Args;++use crate::cli::Commands;++#[derive(Args, Debug, Default)]+pub(crate) struct DebugOptions {+ #[arg(+ long,+ short = 'v',+ global = true,+ help = "Enable debug logging to stderr"+ )]+ pub verbose: bool,+ #[arg(+ long,+ global = true,+ requires = "screenshot",+ help = "Visual debug for snapshot/click; requires --screenshot PATH.html"+ )]+ pub debug: bool,+ #[arg(+ long,+ global = true,+ requires = "debug",+ value_name = "PATH.html",+ help = "Write a sensitive, local HTML screenshot visualization (new file only)"+ )]+ pub screenshot: Option<PathBuf>,+}++impl DebugOptions {+ pub(crate) fn validate(&self, command: &Commands) -> Result<(), AppError> {+ if !self.debug {+ return Ok(());+ }+ if !matches!(command, Commands::Snapshot(_) | Commands::Click(_)) {+ return Err(AppError::invalid_input(+ "--debug supports snapshot and click only",+ ));+ }+ if let Commands::Snapshot(args) = command {+ if !matches!(args.surface, crate::cli_args::Surface::Window) {+ return Err(AppError::invalid_input(+ "Visual debug currently supports the window surface only",+ ));+ }+ }+ if self+ .screenshot+ .as_ref()+ .and_then(|path| path.extension())+ .is_none_or(|ext| ext != "html")+ {+ return Err(AppError::invalid_input(+ "--screenshot requires a new .html output path",+ ));+ }+ Ok(())+ }+}diff --git a/src/visual_debug/render.rs b/src/visual_debug/render.rsnew file mode 100644index 000000000..635870bde--- /dev/null+++ b/src/visual_debug/render.rs@@ -0,0 +1,22 @@+use agent_desktop_core::AppError;+use serde_json::Value;++pub(super) fn html(data: &Value) -> Result<String, AppError> {+ let json = serde_json::to_string(data)?+ .replace('&', "\\u0026")+ .replace('<', "\\u003c")+ .replace('>', "\\u003e")+ .replace('\u{2028}', "\\u2028")+ .replace('\u{2029}', "\\u2029");+ Ok(include_str!("viewer.html")+ .replace("{{CSS}}", include_str!("viewer.css"))+ .replace(+ "{{JS}}",+ &format!(+ "{}\n{}",+ include_str!("viewer_filter.js"),+ include_str!("viewer.js")+ ),+ )+ .replace("{{DATA}}", &json))+}diff --git a/src/visual_debug/tests.rs b/src/visual_debug/tests.rsnew file mode 100644index 000000000..a24d6146b--- /dev/null+++ b/src/visual_debug/tests.rs@@ -0,0 +1,176 @@+use super::*;+use agent_desktop_core::{AccessibilityNode, AdapterError, ErrorCode};+use clap::Parser;++fn command(args: &[&str]) -> Commands {+ crate::Cli::try_parse_from(std::iter::once("agent-desktop").chain(args.iter().copied()))+ .unwrap()+ .command+ .unwrap()+}++fn output_path() -> PathBuf {+ static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ std::env::temp_dir().join(format!(+ "agent-desktop-debug-test-{}-{}.html",+ std::process::id(),+ NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)+ ))+}++#[test]+fn visual_debug_validation_rejects_unsupported_commands_surfaces_and_extensions() {+ let mut options = DebugOptions {+ verbose: false,+ debug: true,+ screenshot: Some(output_path()),+ };+ for args in [+ vec!["version"],+ vec!["batch", "[]"],+ vec!["snapshot", "--surface", "menu"],+ ] {+ assert!(options.validate(&command(&args)).is_err());+ }+ assert!(+ options+ .validate(&command(&["snapshot", "--skeleton", "-i"]))+ .is_ok()+ );+ options.screenshot = Some(PathBuf::from("capture.png"));+ assert!(options.validate(&command(&["snapshot"])).is_err());+}++#[test]+fn visual_debug_disabled_does_not_change_snapshot_or_use_adapter() {+ let mut cmd = command(&["snapshot", "--compact"]);+ let prepared = DebugCapture::prepare(+ &mut cmd,+ &DebugOptions::default(),+ &crate::test_noop_ops::NoopAdapter,+ &CommandContext::default(),+ )+ .unwrap();+ assert!(prepared.is_none());+ let Commands::Snapshot(args) = cmd else {+ panic!()+ };+ assert!(!args.tree.include_bounds);+ assert!(args.tree.compact);+}++#[test]+fn visual_debug_nodes_distinguish_anchors_actions_and_context() {+ let tree: AccessibilityNode = serde_json::from_value(json!({+ "role": "window", "children": [+ {"role":"group", "ref_id":"@sdemo:e1", "name":"Sidebar", "children_count":20, "available_actions":["SetFocus"]},+ {"role":"button", "ref_id":"@sdemo:e2", "name":"Save"},+ {"role":"scrollarea", "ref_id":"@sdemo:e3", "available_actions":["Scroll"]},+ {"role":"group", "children":[{"role":"statictext", "name":"Context"}]}+ ]+ })).unwrap();+ let mut nodes = Vec::new();+ capture::collect_nodes(&tree, 0, &mut nodes);+ assert_eq!(nodes.len(), 6);+ assert_eq!(nodes[0]["kind"], "root");+ assert_eq!(nodes[1]["kind"], "drill");+ assert_eq!(nodes[1]["children_count"], 20);+ assert_eq!(nodes[2]["kind"], "action");+ assert_eq!(nodes[3]["kind"], "action");+ assert_eq!(nodes[4]["kind"], "context");+ assert_eq!(nodes[5]["depth"], 2);+}++#[test]+fn visual_debug_html_escapes_app_controlled_content() {+ let payload = json!({"name":"</script><script>alert(1)</script>&\u{2028}", "value":"{{JS}}"});+ let html = render::html(&payload).unwrap();+ assert!(!html.contains("<script>alert(1)</script>"));+ assert!(html.contains("\\u003c/script\\u003e"));+ assert!(html.contains("connect-src 'none'"));+ let island = html+ .split("<script id=\"debug-data\" type=\"application/json\">")+ .nth(1)+ .unwrap()+ .split("</script>")+ .next()+ .unwrap();+ assert_eq!(serde_json::from_str::<Value>(island).unwrap(), payload);+}++#[test]+fn visual_debug_post_capture_failure_preserves_success_and_compact_output() {+ let path = output_path();+ let options = DebugOptions {+ verbose: false,+ debug: true,+ screenshot: Some(path.clone()),+ };+ let mut cmd = command(&["snapshot", "--compact"]);+ let adapter = crate::test_noop_ops::NoopAdapter;+ let capture = DebugCapture::prepare(&mut cmd, &options, &adapter, &CommandContext::default())+ .unwrap()+ .unwrap();+ let mut result = Ok(+ json!({"tree":{"role":"window","bounds":{"x":1},"children":[{"role":"button","bounds":{"x":2}}]}}),+ );+ capture.finish(&mut result, &adapter, &CommandContext::default());+ let data = result.unwrap();+ assert!(data["debug"]["warning"].is_string());+ assert!(data["tree"].get("bounds").is_none());+ assert!(data["tree"]["children"][0].get("bounds").is_none());+ assert!(+ std::fs::read_to_string(&path)+ .unwrap()+ .contains("Screenshot unavailable")+ );+ std::fs::remove_file(path).unwrap();+}++#[test]+fn visual_debug_never_overwrites_existing_artifact() {+ let path = output_path();+ std::fs::write(&path, "keep").unwrap();+ let options = DebugOptions {+ verbose: false,+ debug: true,+ screenshot: Some(path.clone()),+ };+ assert!(+ DebugCapture::prepare(+ &mut command(&["snapshot"]),+ &options,+ &crate::test_noop_ops::NoopAdapter,+ &CommandContext::default()+ )+ .is_err()+ );+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep");+ std::fs::remove_file(path).unwrap();+}++#[test]+fn visual_debug_command_failure_preserves_error_disposition() {+ let path = output_path();+ let options = DebugOptions {+ verbose: false,+ debug: true,+ screenshot: Some(path.clone()),+ };+ let adapter = crate::test_noop_ops::NoopAdapter;+ let capture = DebugCapture::prepare(+ &mut command(&["snapshot"]),+ &options,+ &adapter,+ &CommandContext::default(),+ )+ .unwrap()+ .unwrap();+ let mut result = Err(AppError::from(AdapterError::new(+ ErrorCode::ActionFailed,+ "Original failure",+ )));+ capture.finish(&mut result, &adapter, &CommandContext::default());+ assert_eq!(result.unwrap_err().code(), "ACTION_FAILED");+ std::fs::remove_file(path).unwrap();+}diff --git a/src/visual_debug/viewer.css b/src/visual_debug/viewer.cssnew file mode 100644index 000000000..709ef15f9--- /dev/null+++ b/src/visual_debug/viewer.css@@ -0,0 +1,49 @@+:root { color-scheme: light; --bg: #f4f6fa; --panel: #fff; --ink: #141a24; --muted: #525e70; --border: #cdd5e1; --accent: #235bcc; }+* { box-sizing: border-box; }+body { margin: 0; font: 14px/1.5 system-ui, sans-serif; color: var(--ink); background: var(--bg); }+header { padding: 24px 28px 16px; border-bottom: 1px solid var(--border); background: var(--panel); }+h1 { margin: 0 0 12px; font-size: 20px; }+h1 span { font-weight: 400; color: var(--muted); margin-left: 12px; }+h2 { margin-top: 0; font-size: 17px; }+p { max-width: 75ch; color: var(--muted); }+#summary { color: var(--ink); font-weight: 600; overflow-wrap: anywhere; }+main { display: grid; grid-template-columns: minmax(0, 1fr) 360px; }+section { padding: 20px 28px; min-width: 0; }+aside { background: var(--panel); padding: 24px 20px; border-left: 1px solid var(--border); min-width: 0; }+.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }+button { font: inherit; padding: 7px 12px; color: var(--ink); border: 1px solid var(--border); background: var(--panel); border-radius: 5px; cursor: pointer; }+button:hover { background: #eaf0fd; }+button[aria-pressed="true"] { background: #e4ecfc; border-color: var(--accent); }+button:focus-visible, input:focus-visible, summary:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }+button:disabled { opacity: 0.5; cursor: default; }+[hidden] { display: none !important; }+#stage { position: relative; width: 100%; margin-top: 14px; background: #dce2eb; outline: 2px solid var(--accent); }+#capture { display: block; width: 100%; height: auto; }+#overlay { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; overflow: hidden; }+#overlay rect { fill: #235bcc12; stroke: #235bcc; stroke-width: 2; vector-effect: non-scaling-stroke; }+#overlay .drill rect { stroke: #a95b00; fill: #a95b0018; stroke-dasharray: 6 3; }+#overlay .context rect, #overlay .root rect { stroke: #526276; fill: none; stroke-dasharray: 3 3; }+#overlay .target rect { stroke: #c92646; fill: #c9264618; stroke-width: 3; }+#overlay text { font: bold 13px ui-monospace, monospace; fill: #fff; stroke: #141a24; stroke-width: 4; paint-order: stroke; }+#nodes { margin-top: 14px; max-height: 65vh; overflow: auto; }+#filter-status { font-size: 12px; margin-bottom: 0; }+.role-group { padding: 0; border-bottom: 1px solid var(--border); }+.role-header { display: flex; align-items: center; gap: 10px; padding: 3px 4px; }+.role-header input { width: 20px; height: 20px; margin: 0; flex: 0 0 auto; accent-color: var(--accent); cursor: pointer; }+.role-toggle { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; text-align: left; border: 0; font-weight: 600; padding: 9px 4px; }+.role-toggle::before { content: '▸'; width: 12px; color: var(--muted); }+.role-toggle[aria-expanded="true"]::before { content: '▾'; }+.role-items { max-height: 300px; overflow-y: auto; padding: 0 8px; background: var(--bg); }+.role-items .node { background: transparent; }+.role-items .node:hover, .role-items .node[aria-pressed="true"] { background: #e4ecfc; }+.node { width: 100%; display: block; text-align: left; border-radius: 0; border: 0; border-bottom: 1px solid var(--border); padding: 12px 6px; overflow-wrap: anywhere; }+.node strong, .node small { display: block; }+.node small { font-size: 12px; color: var(--muted); margin-top: 5px; }+.node code { font-size: 12px; color: var(--accent); }+#warning { color: #912239; white-space: pre-wrap; overflow-wrap: anywhere; }+details { margin-top: 22px; }+summary { cursor: pointer; }+pre { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }+footer { border-top: 1px solid var(--border); padding: 18px 28px; color: var(--muted); }+@media (max-width: 900px) { main { grid-template-columns: 1fr; } aside { border-left: 0; border-top: 1px solid var(--border); } #nodes { max-height: none; } }+@media (max-width: 480px) { header, section, aside, footer { padding: 16px; } h1 span { display: block; margin-left: 0; } }diff --git a/src/visual_debug/viewer.html b/src/visual_debug/viewer.htmlnew file mode 100644index 000000000..7fb0db891--- /dev/null+++ b/src/visual_debug/viewer.html@@ -0,0 +1,40 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'">+<title>agent-desktop visual debug</title>+<style>{{CSS}}</style>+</head>+<body>+<header>+<h1>agent-desktop <span>Visual debug</span></h1>+<p id="summary"></p>+<p id="explanation"></p>+</header>+<main>+<section aria-label="Screenshot visualization">+<div class="toolbar">+<button id="before" type="button">Before click</button>+<button id="after" type="button">After command</button>+<label><input id="highlights" type="checkbox" checked> Highlights</label>+</div>+<p id="phase" role="status"></p>+<div id="stage"><img id="capture" alt="Captured target application window"><svg id="overlay" xmlns="http://www.w3.org/2000/svg" aria-label="Element highlights"></svg></div>+<p id="warning" role="status"></p>+</section>+<aside aria-label="Returned elements">+<h2 id="list-title">Returned elements</h2>+<p>Check roles to filter highlights. Expand a group to inspect its elements. No roles checked means show all.</p>+<button id="all" type="button">Show all elements</button>+<p id="filter-status" role="status"></p>+<div id="nodes" aria-label="Element groups"></div>+<details><summary>Command result</summary><pre id="result"></pre></details>+</aside>+</main>+<footer id="notice"></footer>+<script id="debug-data" type="application/json">{{DATA}}</script>+<script>{{JS}}</script>+</body>+</html>diff --git a/src/visual_debug/viewer.js b/src/visual_debug/viewer.jsnew file mode 100644index 000000000..05318c4e1--- /dev/null+++ b/src/visual_debug/viewer.js@@ -0,0 +1,161 @@+(() => {+ const data = JSON.parse(document.getElementById('debug-data').textContent);+ const {groupNodes, matchesRole, visibleRect} = DebugViewerFilter;+ const byId = id => document.getElementById(id);+ const ns = 'http://www.w3.org/2000/svg';+ const roles = new Set();+ let phase = data.before ? 'before' : 'after';+ let selected = data.mode === 'click' ? 0 : null;+ const explanations = {+ skeleton: 'Skeleton is a shallow overview (logical depth at most 3), not just the parent window. Amber dashed boxes are drill anchors; blue boxes have action refs; gray boxes provide context. children_count marks children not expanded here.',+ 'drill-down': 'This tree starts at the requested root ref, inside its owning window. Only nodes returned by this drill-down are shown.',+ snapshot: 'These are the nodes returned by this snapshot, with its filters applied. Blue boxes have action refs; gray boxes provide context.',+ click: 'Before shows the strictly resolved target before command dispatch. After is a fresh screenshot of the same window. No post-click target box is drawn because the UI may have changed. This is not a live click recording.'+ };+ byId('explanation').textContent = explanations[data.mode];+ byId('notice').textContent = data.notice;+ byId('warning').textContent = [data.warning, data.error?.message].filter(Boolean).join('\n');+ byId('result').textContent = JSON.stringify(data.result || data.error || {snapshot_id: data.snapshot_id, ok: data.ok}, null, 2);+ byId('before').hidden = data.mode !== 'click';+ byId('after').hidden = data.mode !== 'click';+ byId('before').disabled = !data.before;+ byId('after').disabled = !data.after;+ byId('all').onclick = () => {+ roles.clear();+ selected = null;+ byId('highlights').checked = true;+ renderGroups();+ draw();+ };+ byId('highlights').onchange = draw;+ for (const name of ['before', 'after']) {+ byId(name).onclick = () => {+ phase = name;+ selected = data.mode === 'click' && name === 'before' ? 0 : null;+ render();+ };+ }+ function select(index) {+ selected = selected === index ? null : index;+ byId('nodes').querySelectorAll('.node').forEach(button => {+ button.setAttribute('aria-pressed', String(Number(button.dataset.index) === selected));+ });+ draw();+ }+ function draw() {+ const frame = data[phase];+ const svg = byId('overlay');+ svg.replaceChildren();+ if (!frame || !byId('highlights').checked) return;+ const window = frame.window.bounds;+ svg.setAttribute('viewBox', `0 0 ${window.width} ${window.height}`);+ frame.nodes.forEach((node, index) => {+ if (node.not_visible || !matchesRole(node, roles) || (selected !== null && selected !== index)) return;+ const rect = visibleRect(node.bounds, window);+ if (!rect) return;+ const group = document.createElementNS(ns, 'g');+ group.setAttribute('class', node.kind);+ group.dataset.role = node.role;+ const box = document.createElementNS(ns, 'rect');+ for (const [name, value] of Object.entries(rect)) box.setAttribute(name, value);+ const label = document.createElementNS(ns, 'text');+ const alignRight = selected === index && rect.x > window.width / 2;+ label.setAttribute('text-anchor', alignRight ? 'end' : 'start');+ label.setAttribute('x', alignRight ? Math.min(window.width - 4, rect.x + rect.width) : Math.max(4, Math.min(rect.x + 4, window.width - 32)));+ label.setAttribute('y', Math.max(15, rect.y + 15));+ label.textContent = selected === index ? `${index + 1} ${node.ref_id || node.role}` : String(index + 1);+ group.append(box, label);+ svg.append(group);+ });+ }+ function nodeButton(node, index, frame) {+ const button = document.createElement('button');+ button.type = 'button';+ button.className = 'node';+ button.dataset.index = index;+ button.disabled = !matchesRole(node, roles);+ button.setAttribute('aria-pressed', String(selected === index));+ const title = document.createElement('strong');+ title.textContent = `${index + 1}. ${node.name || node.role}`;+ const ref = document.createElement('code');+ ref.textContent = node.ref_id || 'No ref · context only';+ const reason = document.createElement('small');+ reason.textContent = node.reason;+ if (node.children_count !== undefined) reason.textContent += ` ${node.children_count} unexpanded direct children.`;+ else if (node.subtree_truncated) reason.textContent += ' Descendants truncated; count unavailable.';+ if (node.not_visible) reason.textContent += ' Reported hidden or offscreen; highlight omitted.';+ else if (!visibleRect(node.bounds, frame.window.bounds)) reason.textContent += ' No drawable bounds inside this window.';+ button.append(title, ref, reason);+ button.onclick = () => select(index);+ return button;+ }+ function updateFilterCount() {+ const nodes = data[phase]?.nodes || [];+ const count = nodes.filter(node => matchesRole(node, roles)).length;+ byId('filter-status').textContent = roles.size ? `${count} of ${nodes.length} nodes in selected roles` : `All ${nodes.length} nodes · no role filter`;+ }+ function renderGroups() {+ const frame = data[phase];+ byId('nodes').replaceChildren();+ updateFilterCount();+ if (!frame) return;+ for (const group of groupNodes(frame.nodes)) {+ const section = document.createElement('section');+ section.className = 'role-group';+ section.dataset.role = group.role;+ const header = document.createElement('div');+ header.className = 'role-header';+ const checkbox = document.createElement('input');+ checkbox.type = 'checkbox';+ checkbox.checked = roles.has(group.role);+ checkbox.setAttribute('aria-label', `Show only ${group.label.toLowerCase()}`);+ const toggle = document.createElement('button');+ toggle.type = 'button';+ toggle.className = 'role-toggle';+ toggle.textContent = `${group.label} (${group.items.length})`;+ const list = document.createElement('div');+ list.className = 'role-items';+ list.id = `role-items-${group.role}`;+ const expand = open => { list.hidden = !open; toggle.setAttribute('aria-expanded', String(open)); };+ expand(data.mode === 'click');+ toggle.setAttribute('aria-controls', list.id);+ toggle.onclick = () => expand(list.hidden);+ for (const {node, index} of group.items) list.append(nodeButton(node, index, frame));+ checkbox.onchange = () => {+ if (checkbox.checked) roles.add(group.role); else roles.delete(group.role);+ selected = null;+ byId('highlights').checked = true;+ for (const other of byId('nodes').querySelectorAll('.role-group')) {+ if (roles.size && !roles.has(other.dataset.role)) {+ other.querySelector('.role-items').hidden = true;+ other.querySelector('.role-toggle').setAttribute('aria-expanded', 'false');+ }+ }+ byId('nodes').querySelectorAll('.node').forEach(button => {+ button.setAttribute('aria-pressed', 'false');+ button.disabled = !matchesRole(frame.nodes[Number(button.dataset.index)], roles);+ });+ updateFilterCount();+ draw();+ };+ header.append(checkbox, toggle);+ section.append(header, list);+ byId('nodes').append(section);+ }+ }+ function render() {+ const frame = data[phase];+ byId('stage').hidden = !frame;+ for (const name of ['before', 'after']) byId(name).setAttribute('aria-pressed', String(name === phase));+ byId('phase').textContent = frame ? (phase === 'before' ? 'Before dispatch: requested target' : data.mode === 'click' ? 'After command: observed window' : 'Returned tree over captured window') : 'Screenshot unavailable';+ if (frame) {+ byId('summary').textContent = `${data.mode} · ${frame.window.app} · ${frame.window.title || frame.window.id} · ${data.ok ? 'command succeeded' : 'command failed'}`;+ byId('capture').src = frame.image;+ byId('capture').alt = `${frame.window.app} window, ${phase} command capture`;+ byId('list-title').textContent = `${frame.nodes.length} ${data.mode === 'click' ? 'target elements' : 'returned nodes'}`;+ }+ renderGroups();+ draw();+ }+ render();+})();diff --git a/src/visual_debug/viewer_filter.js b/src/visual_debug/viewer_filter.jsnew file mode 100644index 000000000..93df913bd--- /dev/null+++ b/src/visual_debug/viewer_filter.js@@ -0,0 +1,30 @@+const DebugViewerFilter = (() => {+ const labels = {+ window: 'Windows', group: 'Containers', treeitem: 'Tree items', button: 'Buttons',+ scrollarea: 'Scroll areas', scrollbar: 'Scrollbars', textfield: 'Text fields',+ statictext: 'Static text', checkbox: 'Checkboxes', combobox: 'Combo boxes',+ menubutton: 'Menu buttons', outline: 'Outlines', list: 'Lists', browser: 'Browsers',+ colorwell: 'Color controls', ruler: 'Rulers', handle: 'Handles'+ };+ function groupNodes(nodes) {+ const groups = new Map();+ nodes.forEach((node, index) => {+ if (!groups.has(node.role)) groups.set(node.role, {+ role: node.role, label: Object.hasOwn(labels, node.role) ? labels[node.role] : node.role, items: []+ });+ groups.get(node.role).items.push({node, index});+ });+ return [...groups.values()];+ }+ function matchesRole(node, roles) { return roles.size === 0 || roles.has(node.role); }+ function visibleRect(bounds, window) {+ if (!bounds || ![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)) return null;+ const x = Math.max(0, bounds.x - window.x);+ const y = Math.max(0, bounds.y - window.y);+ const right = Math.min(window.width, bounds.x + bounds.width - window.x);+ const bottom = Math.min(window.height, bounds.y + bounds.height - window.y);+ return right > x && bottom > y ? {x, y, width: right - x, height: bottom - y} : null;+ }+ return {groupNodes, matchesRole, visibleRect};+})();+if (typeof module !== 'undefined') module.exports = DebugViewerFilter;diff --git a/src/visual_debug/viewer_filter.test.js b/src/visual_debug/viewer_filter.test.jsnew file mode 100644index 000000000..0c0e132d1--- /dev/null+++ b/src/visual_debug/viewer_filter.test.js@@ -0,0 +1,34 @@+const {test} = require('node:test');+const assert = require('node:assert/strict');+const {groupNodes, matchesRole, visibleRect} = require('./viewer_filter.js');++const nodes = [{role: 'window'}, {role: 'treeitem'}, {role: 'button'}, {role: 'treeitem'}];++test('role groups retain original indices and refs instead of renumbering targets', () => {+ const groups = groupNodes(nodes);+ assert.deepEqual(groups.map(g => g.role), ['window', 'treeitem', 'button']);+ assert.deepEqual(groups[1].items.map(item => item.index), [1, 3]);+ assert.equal(groups[1].label, 'Tree items');+ assert.equal(groups[1].items[0].node, nodes[1]);+});++test('no role selection shows all; one selection isolates; multiple form a union', () => {+ const roles = new Set();+ const filtered = () => nodes.filter(node => matchesRole(node, roles)).map(node => node.role);+ assert.equal(filtered().length, 4);+ roles.add('treeitem');+ assert.deepEqual(filtered(), ['treeitem', 'treeitem']);+ roles.add('button');+ assert.deepEqual(filtered(), ['treeitem', 'button', 'treeitem']);+ roles.clear();+ assert.equal(filtered().length, 4);+ assert.deepEqual(groupNodes([]), []);+});++test('geometry clips to the window and handles negative monitor origins', () => {+ const window = {x: -1000, y: 50, width: 600, height: 400};+ assert.deepEqual(visibleRect({x: -1010, y: 60, width: 30, height: 20}, window), {x: 0, y: 10, width: 20, height: 20});+ assert.equal(visibleRect({x: 0, y: 60, width: 30, height: 20}, window), null);+ assert.equal(visibleRect(null, window), null);+ assert.equal(visibleRect({x: NaN, y: 60, width: 30, height: 20}, window), null);+});diff --git a/tests/e2e/run.sh b/tests/e2e/run.shindex e2e815f85..f15442f70 100755--- a/tests/e2e/run.sh+++ b/tests/e2e/run.sh@@ -137,7 +137,7 @@ source "$here/scenarios/trace_performance.sh"source "$here/scenarios/notifications.sh"note "Multi-agent cursor probe"-if "$bin" close-app "$app" --force >/dev/null 2>&1; then+if [ "$fixture_owned" -eq 0 ] || "$bin" close-app "$app" --force >/dev/null 2>&1; thenfixture_owned=0for mode in headless headed; docursor_flags=()diff --git a/tests/e2e/safe-semantic.sh b/tests/e2e/safe-semantic.shindex 6b8630704..0a717d690 100755--- a/tests/e2e/safe-semantic.sh+++ b/tests/e2e/safe-semantic.sh@@ -366,6 +366,7 @@ find_target text_field textfield text-input || fail "text field disappeared afterun_set_value "$text_field" "$text_value"await_status text_after text-echo equal "$text_value" || fail "semantic set-value did not reach fixture state"pass "AX set-value produced the fixture-owned binding change"+source "$here/scenarios/silent-text.sh"read_status toggle_before toggle-status || fail "toggle status is unavailable"[ "$toggle_before" = "off" ] || fail "fresh toggle state is not clean"diff --git a/tests/e2e/safe_semantic_guard.py b/tests/e2e/safe_semantic_guard.pyindex 540e3702f..89598c973 100755--- a/tests/e2e/safe_semantic_guard.py+++ b/tests/e2e/safe_semantic_guard.py@@ -12,6 +12,7 @@ SNAPSHOT_PATTERN = re.compile(rf"^{SNAPSHOT_TOKEN}$")SAFE_NAMED_TARGETS = {("button", "primary-button"),("textfield", "text-input"),+ ("textfield", "silent-text-input"),("checkbox", "toggle-box"),}SAFE_STATUS_IDS = {@@ -149,6 +150,12 @@ def validate_command(argv, fixture_app, window_id, mutation_armed):if argv not in (["list-windows"], ["list-windows", "--app", fixture_app]):raise SafetyError("list-windows must be global or fixture-scoped")return+ if command == "get":+ if not window_id or len(argv) != 6 or not REF_PATTERN.fullmatch(argv[1]) \+ or argv[2] != "--snapshot" or not SNAPSHOT_PATTERN.fullmatch(argv[3]) \+ or argv[4:] != ["--property", "value"]:+ raise SafetyError("get requires a snapshot-scoped fixture value target")+ returnif command == "find":if not window_id:raise SafetyError("find requires the exact owned fixture window")diff --git a/tests/e2e/scenarios/silent-text.sh b/tests/e2e/scenarios/silent-text.shnew file mode 100644index 000000000..8f0fa4b29--- /dev/null+++ b/tests/e2e/scenarios/silent-text.sh@@ -0,0 +1,16 @@+find_target silent_field textfield silent-text-input || fail "silent text fixture is not uniquely addressable"+safety_checkpoint || fail "ownership checkpoint failed before silent setter"+silent_output="$(agent_exec 1 type "$(target_ref "$silent_field")" "safe-semantic-must-not-disappear" \+ --snapshot "$(target_snapshot "$silent_field")" --timeout-ms 1500 2>"$suite_root/silent-text.stderr")"+silent_exit=$?+printf '%s' "$silent_output" > "$suite_root/silent-text.json"+[ "$silent_exit" -eq 1 ] || fail "silent setter must return a structured error (exit=$silent_exit): $silent_output"+[ "$(json_field "$silent_output" error.code)" = "ACTION_FAILED" ] || fail "silent setter error code is incorrect: $silent_output"+[ "$(json_field "$silent_output" error.disposition.retry)" = "unsafe" ] || fail "silent setter must forbid blind retry"+silent_state="$(agent_exec 0 get "$(target_ref "$silent_field")" \+ --snapshot "$(target_snapshot "$silent_field")" --property value)" \+ || fail "silent setter readback failed"+printf '%s' "$silent_state" | python3 -c 'import json,sys; d=json.load(sys.stdin); assert d["ok"] and d["data"]["value"] == ""' \+ || fail "silent fixture readback was unexpected: $silent_state"+safety_checkpoint || fail "ownership checkpoint failed after silent setter"+pass "AXSelectedText silent no-op is rejected without retry or focus stealing"diff --git a/tests/e2e/scenarios/surfaces.sh b/tests/e2e/scenarios/surfaces.shindex 2f568146a..3a3324ffc 100644--- a/tests/e2e/scenarios/surfaces.sh+++ b/tests/e2e/scenarios/surfaces.sh@@ -61,6 +61,10 @@ if [ -n "$drag_anchor" ]; thenact_target "$drag_anchor" scroll-to >/dev/null 2>&1sleep 0.3fi+drag_focus="$("$bin" focus-window --app "$app" 2>&1)"+if [ "$(json_field "$drag_focus" ok)" != "True" ]; then+ abort_suite "drag fixture focus failed: $(json_field "$drag_focus" error.code)"+fidrag_snapshot="$("$bin" snapshot --app "$app" --include-bounds --max-depth 30 2>/dev/null)"drag_points="$(printf '%s' "$drag_snapshot" | python3 "$json_tool" tree drag-canvas drag 2>/dev/null)" || drag_points=""if [ -z "$drag_points" ]; thendiff --git a/tests/e2e/scenarios/trace_performance.sh b/tests/e2e/scenarios/trace_performance.shindex 24c1461c6..64dcd43a9 100644--- a/tests/e2e/scenarios/trace_performance.sh+++ b/tests/e2e/scenarios/trace_performance.sh@@ -5,6 +5,10 @@ require_target trace_text textfield text-inputtrace_type="$("$bin" --headed --trace "$trace_file" type "$(target_ref "$trace_text")" \--snapshot "$(target_snapshot "$trace_text")" "sup3r-secret-trace" 2>&1)"sleep 0.2+require_value trace_echo text-echo+assert "headed trace typing reaches the target field" \+ "$([[ "$trace_echo" == *sup3r-secret-trace* ]] && echo 1 || echo 0)" \+ "observed_chars=${#trace_echo}"trace_bytes="$(wc -c < "$trace_file" | tr -d ' ')"trace_resolver="$(grep -q 'ref.resolve' "$trace_file" && echo 1 || echo 0)"trace_leak="$(grep -q 'sup3r-secret-trace' "$trace_file" && echo 1 || echo 0)"@@ -122,6 +126,10 @@ running_before="$(running)""$bin" close-app "$app" --force >/dev/null 2>&1sleep 1.5running_after="$(running)"+if [ "$running_after" = "False" ]; then+ fixture_owned=0+ fixture_started=0+fiassert "force close removes the fixture process" \"$([ "$running_before" = "True" ] && [ "$running_after" = "False" ] && echo 1 || echo 0)" \"before=$running_before after=$running_after"diff --git a/tests/e2e/test_safe_semantic_guard.py b/tests/e2e/test_safe_semantic_guard.pyindex 89c25bdee..5e16be74f 100644--- a/tests/e2e/test_safe_semantic_guard.py+++ b/tests/e2e/test_safe_semantic_guard.py@@ -50,6 +50,13 @@ def action_data(action="click", delivery="delivered_verified", mechanism="semantclass CommandPolicyTests(unittest.TestCase):+ def test_value_readback_requires_owned_window_and_snapshot(self):+ command = ["get", "@snap-1:e2", "--snapshot", "snap-1", "--property", "value"]+ validate_command(command, APP, WINDOW, False)+ for argv, window in [(command, ""), (command[:2], WINDOW), (command[:-1] + ["text"], WINDOW)]:+ with self.assertRaises(SafetyError):+ validate_command(argv, APP, window, False)+def test_allows_only_exact_fixture_scoped_observations(self):validate_command(["version"], APP, "", False)validate_command(["permissions"], APP, "", False)diff --git a/tests/fixture-app/AgentDeskFixture.swift b/tests/fixture-app/AgentDeskFixture.swiftindex ed6aeb606..ef9ed302f 100644--- a/tests/fixture-app/AgentDeskFixture.swift+++ b/tests/fixture-app/AgentDeskFixture.swift@@ -144,6 +144,8 @@ struct ContentView: View {.accessibilityLabel("text-input")StatusReadout(name: "text-echo", value: textValue)+ SilentTextInput().frame(height: 22)+SecureField("Secure Input", text: $secureValue).accessibilityLabel("secure-input")StatusReadout(name: "secure-echo", value: secureValue.isEmpty ? "empty" : "set")diff --git a/tests/fixture-app/SilentTextInput.swift b/tests/fixture-app/SilentTextInput.swiftnew file mode 100644index 000000000..268cb4d1e--- /dev/null+++ b/tests/fixture-app/SilentTextInput.swift@@ -0,0 +1,24 @@+import AppKit+import SwiftUI++struct SilentTextInput: NSViewRepresentable {+ func makeNSView(context: Context) -> SilentTextField { SilentTextField(frame: .zero, textContainer: nil) }+ func updateNSView(_ view: SilentTextField, context: Context) {}+}++final class SilentTextField: NSTextView {+ override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {+ super.init(frame: frameRect, textContainer: container)+ setAccessibilityLabel("silent-text-input")+ }++ required init?(coder: NSCoder) { nil }++ override func accessibilitySelectedText() -> String? { "" }+ override func accessibilitySelectedTextRange() -> NSRange { NSRange(location: 0, length: 0) }+ override func setAccessibilitySelectedText(_ selectedText: String?) {}+ override func isAccessibilitySelectorAllowed(_ selector: Selector) -> Bool {+ selector == #selector(setAccessibilitySelectedText(_:))+ || super.isAccessibilitySelectorAllowed(selector)+ }+}diff --git a/tools/inspector/bridge.mjs b/tools/inspector/bridge.mjsnew file mode 100644index 000000000..cf744a0bf--- /dev/null+++ b/tools/inspector/bridge.mjs@@ -0,0 +1,58 @@+import {createServer} from 'node:http';+import {readFile} from 'node:fs/promises';+import {fileURLToPath} from 'node:url';+import {authorize, fail, readBody} from './http.mjs';++const files = new Map([+ ['/', ['public/index.html', 'text/html']],+ ...['app.js', 'tree-model.js', 'tree-view.js', 'screenshot.js', 'feedback.js'].map(name => [`/${name}`, [`public/${name}`, 'text/javascript']]),+ ['/styles.css', ['public/styles.css', 'text/css']],+ ['/shared/viewer.css', ['../../src/visual_debug/viewer.css', 'text/css']],+ ['/shared/viewer_filter.js', ['../../src/visual_debug/viewer_filter.js', 'text/javascript']],+]);++export function createBridge(inspector, token) {+ let busy = false;+ const server = createServer(async (request, response) => {+ const port = server.address().port;+ const host = `127.0.0.1:${port}`;+ response.setHeader('Cache-Control', 'no-store');+ response.setHeader('X-Content-Type-Options', 'nosniff');+ response.setHeader('Referrer-Policy', 'no-referrer');+ response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'self'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'");+ function send(status, body) {+ response.writeHead(status, {'Content-Type': 'application/json; charset=utf-8'});+ response.end(JSON.stringify(body));+ }+ try {+ if (request.headers.host !== host) throw fail('Invalid local host', 403, 'FORBIDDEN');+ const url = new URL(request.url, `http://${host}`);+ if (url.pathname === '/api' && request.method === 'POST') {+ authorize(request, port, token);+ const body = await readBody(request);+ if (busy) throw fail('Another operation is running; wait for it to finish.', 409, 'BUSY');+ busy = true;+ try { send(200, {ok: true, ...await inspector.execute(body)}); }+ finally { busy = false; }+ return;+ }+ if (request.method !== 'GET') throw fail('Method not allowed', 405);+ if (request.headers['sec-fetch-site'] === 'cross-site') throw fail('Open the inspector from its localhost URL', 403, 'FORBIDDEN');+ const asset = files.get(url.pathname);+ if (!asset) throw fail('Not found', 404);+ const content = await readFile(fileURLToPath(new URL(asset[0], import.meta.url)), 'utf8');+ response.writeHead(200, {'Content-Type': `${asset[1]}; charset=utf-8`});+ response.end(content);+ } catch (error) {+ send(error.status || 500, {ok: false, error: {+ code: error.code || 'INTERNAL', message: error.status ? error.message : 'Inspector failed to process the request.',+ ...(error.detail ? {detail: error.detail} : {}),+ ...(error.refreshRequired ? {refreshRequired: true} : {}),+ }, commands: error.commands || []});+ }+ });+ server.headersTimeout = 5000;+ server.requestTimeout = 10000;+ server.maxConnections = 20;+ return server;+}diff --git a/tools/inspector/cli.mjs b/tools/inspector/cli.mjsnew file mode 100644index 000000000..dd039bd0c--- /dev/null+++ b/tools/inspector/cli.mjs@@ -0,0 +1,96 @@+import {execFile} from 'node:child_process';+import {promisify} from 'node:util';+import {readFile, stat, unlink} from 'node:fs/promises';+import {join} from 'node:path';+import {randomUUID} from 'node:crypto';+import {fail} from './http.mjs';++const execute = promisify(execFile);++export function identityKey(entry) {+ return JSON.stringify([entry.pid, entry.process_instance, entry.source_window_id,+ entry.source_surface, entry.path || [], entry.role, entry.name || '', entry.native_id || null, entry.bounds || null]);+}++export function createCli(binary, home) {+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('AGENT_DESKTOP_')));+ env.AGENT_DESKTOP_HOME = home;++ async function run(args, log) {+ const started = Date.now();+ let stdout;+ let processError;+ try {+ ({stdout} = await execute(binary, args, {env, timeout: 20000, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024, shell: false}));+ } catch (error) { stdout = error.stdout; processError = error; }+ let envelope;+ try { envelope = JSON.parse(stdout); } catch {+ const message = processError?.code === 'ENOENT' ? 'CLI binary not found. Run cargo build --release -p agent-desktop first.' : 'CLI did not return a valid JSON response (timeout, output limit, or incompatible binary).';+ throw fail(message, 502, 'CLI_FAILED');+ }+ log?.push({stateRoot: home, binary, args: args.map((arg, index) => args[index - 1] === '--screenshot' ? '<temporary-capture.html>' : arg), command: envelope.command, ok: envelope.ok, elapsedMs: Date.now() - started});+ if (!envelope.ok) {+ throw Object.assign(fail(envelope.error?.message || 'CLI command failed', 422, envelope.error?.code || 'CLI_FAILED'), {detail: envelope.error});+ }+ if (processError) throw fail('CLI exited unsuccessfully after emitting a response', 502, 'CLI_FAILED');+ return envelope.data;+ }++ async function entries(refs) {+ const maps = new Map();+ const result = new Map();+ for (const ref of refs) {+ const match = /^@(s[a-z0-9]+):(e[1-9][0-9]*)$/.exec(ref);+ if (!match) throw fail('CLI returned an invalid ref', 502);+ if (!maps.has(match[1])) {+ const file = join(home, 'snapshots', match[1], 'refmap.json');+ if ((await stat(file)).size > 1048576) throw fail('Refmap exceeds its size limit', 502);+ maps.set(match[1], JSON.parse(await readFile(file, 'utf8')).inner);+ }+ const entry = maps.get(match[1])?.[`@${match[2]}`];+ if (entry) result.set(ref, entry);+ }+ return result;+ }++ async function capture(args, log) {+ const path = join(home, `capture-${randomUUID()}.html`);+ try {+ let data;+ try { data = await run([...args, '--include-bounds', '--debug', '--screenshot', path], log); }+ catch (error) {+ if (error.code !== 'PERM_DENIED') throw error;+ data = await run([...args, '--include-bounds'], log);+ data.debug = {warning: 'Screenshot permission unavailable. Showing the accessibility tree only.'};+ }+ let artifact = {};+ if (!data.debug?.warning) {+ if ((await stat(path)).size > 128 * 1024 * 1024) throw fail('Capture exceeds its size limit', 502);+ const html = await readFile(path, 'utf8');+ const island = html.split('<script id="debug-data" type="application/json">')[1]?.split('</script>')[0];+ if (!island) throw fail('CLI debug format is incompatible; rebuild the repository binary', 502);+ artifact = JSON.parse(island);+ }+ const nodes = [];+ const walk = node => { nodes.push(node); for (const child of node.children || []) walk(child); };+ walk(data.tree);+ const saved = await entries(nodes.flatMap(node => node.ref_id ? [node.ref_id] : []));+ const visuals = artifact.after?.nodes || [];+ if (artifact.after && (visuals.length !== nodes.length || nodes.some((node, index) =>+ node.role !== visuals[index].role || node.ref_id !== visuals[index].ref_id))) {+ throw fail('CLI debug tree is incompatible with the snapshot; rebuild the repository binary', 502);+ }+ nodes.forEach((node, index) => {+ if (saved.has(node.ref_id)) node.identity_key = identityKey(saved.get(node.ref_id));+ node.kind = visuals[index]?.kind || (node.ref_id ? 'action' : 'context');+ node.reason = visuals[index]?.reason || '';+ });+ return {tree: data.tree, window: data.window, snapshotId: data.snapshot_id,+ complete: data.complete, frame: artifact.after || null, warning: artifact.warning || data.debug?.warning || null};+ } finally { await unlink(path).catch(error => {+ if (error.code !== 'ENOENT') console.error(`Temporary capture cleanup failed: ${error.message}`);+ }); }+ }++ return {run, entries, capture};+}diff --git a/tools/inspector/http.mjs b/tools/inspector/http.mjsnew file mode 100644index 000000000..6d7cf0993--- /dev/null+++ b/tools/inspector/http.mjs@@ -0,0 +1,79 @@+import {timingSafeEqual} from 'node:crypto';++const operations = {+ apps: [], windows: ['app'], snapshot: ['app', 'windowId'],+ expand: ['revision', 'ref'], find: ['revision', 'ref', 'name', 'field', 'role', 'exact'],+ get: ['revision', 'ref', 'property'], is: ['revision', 'ref', 'property'],+};+const properties = {+ get: ['text', 'value', 'title', 'bounds', 'role', 'states'],+ is: ['visible', 'enabled', 'checked', 'focused', 'expanded', 'selected'],+};++export function fail(message, status = 400, code = 'INVALID_ARGS') {+ return Object.assign(new Error(message), {status, code});+}++export function validateRequest(body) {+ if (!body || typeof body !== 'object' || Array.isArray(body) || !Object.hasOwn(operations, body.operation)) {+ throw fail('Unsupported inspector operation');+ }+ const allowed = operations[body.operation];+ if (Object.keys(body).some(key => key !== 'operation' && !allowed.includes(key))) throw fail('Unknown request field');+ for (const key of ['app', 'windowId', 'ref', 'name', 'role', 'property']) {+ if (body[key] !== undefined && (typeof body[key] !== 'string' || body[key].length > 512 || /[\x00-\x1f]/.test(body[key]))) {+ throw fail(`Invalid ${key}`);+ }+ }+ if (['windows', 'snapshot'].includes(body.operation) && (!body.app?.trim() || body.app.startsWith('-'))) throw fail('Choose an application');+ if (body.windowId !== undefined && !body.windowId) throw fail('Choose a window');+ if (body.ref !== undefined && !/^@s[a-z0-9]+:e[1-9][0-9]*$/.test(body.ref)) throw fail('Expected a qualified snapshot ref');+ if (['expand', 'get', 'is'].includes(body.operation) && !body.ref) throw fail('Select a ref-addressable element');+ if (allowed.includes('revision') && (!Number.isSafeInteger(body.revision) || body.revision < 1)) throw fail('Refresh the inspector first');+ if (body.exact !== undefined && typeof body.exact !== 'boolean') throw fail('Invalid exact flag');+ if (body.field !== undefined && !['name', 'value', 'text'].includes(body.field)) throw fail('Choose Name, Value, or Text');+ if (body.operation === 'find' && !body.name?.trim() && !body.role?.trim()) throw fail('Enter a search term or role to find');+ if (body.role && !/^[a-z][a-z0-9-]{0,63}$/.test(body.role)) throw fail('Use a canonical role such as button or textfield');+ if (properties[body.operation] && !properties[body.operation].includes(body.property)) throw fail('Unsupported property');+ return body;+}++export function authorize(request, port, token) {+ const host = `127.0.0.1:${port}`;+ const supplied = Buffer.from(request.headers['x-inspector-token'] || '');+ const expected = Buffer.from(token);+ if (request.headers.host !== host || request.headers.origin !== `http://${host}` ||+ supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) {+ throw fail('Request not authorized for this inspector', 403, 'FORBIDDEN');+ }+}++export async function readBody(request) {+ if (request.headers['content-type']?.split(';')[0] !== 'application/json') throw fail('Expected application/json', 415);+ let size = 0;+ const chunks = [];+ for await (const chunk of request) {+ size += chunk.length;+ if (size > 8192) throw fail('Request too large', 413);+ chunks.push(chunk);+ }+ try { return validateRequest(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }+ catch (error) { if (error.status) throw error; throw fail('Invalid JSON'); }+}++export async function listenAvailable(server, startingPort = 4317) {+ if (!Number.isInteger(startingPort) || startingPort < 0 || startingPort > 65535) throw fail('Invalid port');+ for (let attempt = 0; attempt <= 20; attempt++) {+ const port = attempt === 20 ? 0 : startingPort === 0 ? 0 : Math.min(startingPort + attempt, 65535);+ try {+ await new Promise((resolve, reject) => {+ const onError = error => { server.off('listening', onListening); reject(error); };+ const onListening = () => { server.off('error', onError); resolve(); };+ server.once('error', onError).once('listening', onListening).listen(port, '127.0.0.1');+ });+ return server.address().port;+ } catch (error) {+ if (error.code !== 'EADDRINUSE' || attempt === 20) throw error;+ }+ }+}diff --git a/tools/inspector/inspector.mjs b/tools/inspector/inspector.mjsnew file mode 100644index 000000000..4b35ec1d3--- /dev/null+++ b/tools/inspector/inspector.mjs@@ -0,0 +1,88 @@+import {fail, validateRequest} from './http.mjs';+import {identityKey} from './cli.mjs';+import {indexTree, replaceBranch, findIdentity, findContextMatch} from './public/tree-model.js';++export function createInspector(cli) {+ let view = null;+ let revision = 0;+ let searchRefs = new Set();++ function requireCurrent(body) {+ if (!view || body.revision !== revision) throw fail('This view is out of date. Refresh the window.', 409, 'STALE_VIEW');+ if (body.ref && !indexTree(view.tree).some(item => item.node.ref_id === body.ref) && !searchRefs.has(body.ref)) {+ throw fail('Ref does not belong to the current inspector view', 409, 'STALE_REF');+ }+ }++ function scopeArgs(ref) {+ return ref ? ['--root', ref] : [`--app=${view.app}`, `--window-id=${view.window.id}`];+ }++ async function observe(ref, depth, log) {+ if (ref && !indexTree(view.tree).some(item => item.node.ref_id === ref)) throw fail('Expand a node in the loaded tree', 409);+ const args = ['snapshot', ...scopeArgs(ref), '--max-depth', String(depth)];+ try {+ const next = await cli.capture(args, log);+ if (next.window.id !== view.window.id) throw fail('Source window changed. Refresh.', 409, 'STALE_VIEW');+ view = {...view, ...next, tree: ref ? replaceBranch(view.tree, ref, next.tree) : next.tree};+ searchRefs.clear();+ revision++;+ return next.tree.ref_id || null;+ } catch (error) {+ view = null;+ revision++;+ error.refreshRequired = true;+ throw error;+ }+ }++ async function execute(body) {+ validateRequest(body);+ const log = [];+ try {+ if (body.operation === 'apps') {+ const windows = await cli.run(['list-windows'], log);+ const names = [...new Set(windows.filter(window => window.accessible !== false).map(window => window.app_name).filter(Boolean))];+ return {apps: names.map(name => ({name})), commands: log};+ }+ if (body.operation === 'windows') return {windows: await cli.run(['list-windows', `--app=${body.app}`], log), commands: log};+ if (body.operation === 'snapshot') {+ const args = ['snapshot', `--app=${body.app}`, '--skeleton'];+ if (body.windowId) args.push(`--window-id=${body.windowId}`);+ const next = await cli.capture(args, log);+ view = {...next, app: body.app};+ revision++;+ searchRefs.clear();+ return {view, revision, commands: log};+ }+ requireCurrent(body);+ if (body.operation === 'expand') {+ const selectedRef = await observe(body.ref, 3, log);+ return {view, revision, selectedRef, commands: log};+ }+ if (body.operation === 'find') {+ const args = ['find', ...scopeArgs(body.ref), '--limit', '20'];+ if (body.name) args.push(`--${body.field || 'text'}=${body.name}`);+ if (body.role) args.push(`--role=${body.role}`);+ if (body.exact) args.push('--exact');+ const result = await cli.run(args, log);+ const matches = result.matches || [];+ const saved = await cli.entries(matches.flatMap(match => match.ref_id ? [match.ref_id] : []));+ let selectedRef = body.ref || null;+ if (matches.length) selectedRef = await observe(body.ref, 10, log);+ searchRefs = new Set(saved.keys());+ const mapped = matches.map(match => {+ const entry = saved.get(match.ref_id);+ const target = match.ref_id ? (entry ? findIdentity(view.tree, identityKey(entry)) : null) : findContextMatch(view.tree, match);+ return {...match, treeRef: target?.key || null};+ });+ return {view, revision, selectedRef, matches: mapped,+ totalMatches: result.total_matches, truncated: result.truncated, commands: log};+ }+ const result = await cli.run([body.operation, body.ref, '--property', body.property], log);+ return {result, revision, commands: log};+ } catch (error) { error.commands = log; throw error; }+ }++ return {execute};+}diff --git a/tools/inspector/package-lock.json b/tools/inspector/package-lock.jsonnew file mode 100644index 000000000..3d8442b40--- /dev/null+++ b/tools/inspector/package-lock.json@@ -0,0 +1,16 @@+{+ "name": "agent-desktop-inspector",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "agent-desktop-inspector",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22"+ }+ }+ }+}diff --git a/tools/inspector/package.json b/tools/inspector/package.jsonnew file mode 100644index 000000000..0f934f348--- /dev/null+++ b/tools/inspector/package.json@@ -0,0 +1,14 @@+{+ "name": "agent-desktop-inspector",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "description": "Local, read-only visual inspector for agent-desktop",+ "license": "Apache-2.0",+ "engines": { "node": ">=22" },+ "scripts": {+ "dev": "node server.mjs",+ "start": "node server.mjs",+ "test": "node --test test/*.test.mjs"+ }+}diff --git a/tools/inspector/public/app.js b/tools/inspector/public/app.jsnew file mode 100644index 000000000..4570b1902--- /dev/null+++ b/tools/inspector/public/app.js@@ -0,0 +1,296 @@+import {indexTree, ancestors} from './tree-model.js';+import {renderTree, revealTreeRow} from './tree-view.js';+import {renderScreenshot} from './screenshot.js';+import {startFeedback, finishFeedback, formatCommand} from './feedback.js';++const byId = id => document.getElementById(id);+const token = new URLSearchParams(location.hash.slice(1)).get('token') || '';+const state = {view: null, revision: 0, selectedKey: null, open: new Set(), matches: [], busy: false, invalid: false};+const history = [];+let resultInfo = '';+let highlightMatches = false;+const properties = {get: ['value', 'text', 'title', 'bounds', 'role', 'states'], is: ['visible', 'enabled', 'checked', 'focused', 'expanded', 'selected']};++function selected() { return indexTree(state.view?.tree).find(item => item.key === state.selectedKey); }+function scoped() {+ const item = selected();+ return item?.node.ref_id ? {ref: item.node.ref_id} : {};+}+function canSearch() { const item = selected(); return Boolean(item && (item.node.ref_id || item.parentKey === null)); }+function canExpand(node) { return Boolean(node?.ref_id && (node.children_count || node.subtree_truncated || node.children?.length)); }++function showCommands(commands) {+ history.push(...commands);+ if (history.length > 50) history.splice(0, history.length - 50);+ byId('commands').replaceChildren();+ for (const command of [...history].reverse()) {+ const li = document.createElement('li');+ const code = document.createElement('code');+ code.textContent = formatCommand(command);+ const status = document.createElement('span');+ status.textContent = `${command.ok ? 'Succeeded' : 'Failed'} · ${command.elapsedMs} ms`;+ li.append(code, status);+ byId('commands').append(li);+ }+ byId('command-summary').textContent = `Command history (${history.length})`;+}++async function perform(body, label, apply) {+ if (state.busy) return;+ state.busy = true;+ try {+ byId('error').hidden = true;+ byId('status').textContent = label;+ startFeedback(body.operation === 'find' && !body.ref ? {...body, app: state.view.app, windowId: state.view.window.id} : body, label);+ render();+ const response = await fetch('/api', {method: 'POST', headers: {'Content-Type': 'application/json', 'X-Inspector-Token': token}, body: JSON.stringify(body), signal: AbortSignal.timeout(60000)});+ const payload = await response.json();+ showCommands(payload.commands || []);+ if (!payload.ok) throw Object.assign(new Error(payload.error.message), payload.error);+ if (payload.view) state.view = payload.view;+ if (payload.revision) state.revision = payload.revision;+ apply?.(payload);+ byId('status').textContent = state.view ? 'Ready. Select an element or explore a branch.' : byId('window').value ? 'Window ready. Select Inspect app to begin.' : 'Choose an app with an open window.';+ finishFeedback(true, body.operation === 'find' ? resultInfo : 'Response received.');+ } catch (error) {+ const code = typeof error.code === 'string' ? error.code : null;+ if (!code || error.refreshRequired || ['STALE_VIEW', 'STALE_REF', 'WINDOW_NOT_FOUND', 'APP_NOT_FOUND', 'ELEMENT_NOT_FOUND', 'AMBIGUOUS_TARGET'].includes(code)) state.invalid = true;+ byId('error').textContent = `${code ? `${code}: ` : ''}${error.message}${error.detail?.suggestion ? ` ${error.detail.suggestion}` : ''}${state.invalid && state.view ? ' Refresh the app before continuing.' : ''}`;+ byId('error').hidden = false;+ byId('status').textContent = 'Could not complete the read. Your app was not clicked or edited.';+ finishFeedback(false, error.message);+ } finally { state.busy = false; render(); }+}++function select(key) {+ if (state.busy) return;+ state.selectedKey = key;+ highlightMatches = false;+ byId('highlights').checked = true;+ for (const parent of ancestors(indexTree(state.view.tree), key)) state.open.add(parent);+ byId('read-result').textContent = '';+ render();+ const row = [...byId('tree').querySelectorAll('.tree-row')].find(row => row.dataset.key === key);+ revealTreeRow(byId('tree'), row);+ row?.querySelector('.tree-select')?.focus({preventScroll: true});+}++async function expand(ref) {+ await perform({operation: 'expand', ref, revision: state.revision}, 'Loading children from the app…', payload => {+ state.matches = [];+ highlightMatches = false;+ resultInfo = '';+ state.selectedKey = payload.selectedRef || indexTree(state.view.tree)[0].key;+ state.open.add(state.selectedKey);+ for (const parent of ancestors(indexTree(state.view.tree), state.selectedKey)) state.open.add(parent);+ });+}++function renderSelection(item) {+ const node = item?.node;+ const available = !state.busy && !state.invalid;+ byId('selected-name').textContent = node ? node.name || node.description || node.role : 'Select an element';+ byId('selected-role').textContent = node ? `Role: ${node.role}` : 'Its details and available reads will appear here.';+ byId('selected-ref').textContent = node?.ref_id || (node ? 'Context node · no ref' : '');+ byId('selected-states').textContent = node?.states?.length ? node.states.join(' · ') : '';+ byId('expand').disabled = !available || !canExpand(node);+ byId('expand').textContent = node?.children_count || node?.subtree_truncated ? 'Load children' : 'Reload branch';+ byId('scope-note').textContent = !node ? 'Select a node in the tree or screenshot.' : state.invalid ? 'Refresh to restore live reads.' : node.ref_id ? 'Find searches inside this element. Reads target this ref.' : item.parentKey === null ? 'Find searches this window. Select a child ref for property reads.' : 'This context node has no ref. Select a ref-addressable parent to search or load more.';+ byId('find').disabled = !available || !canSearch();+ byId('read').disabled = !available || !node?.ref_id;+ const {children, identity_key, ...details} = node || {};+ byId('element-details').textContent = node ? JSON.stringify(details, null, 2) : 'No selection';+}++function renderResults() {+ byId('result-count').textContent = resultInfo;+ byId('results').replaceChildren();+ for (const match of state.matches) {+ const button = document.createElement('button');+ button.className = 'result';+ button.type = 'button';+ button.textContent = match.name || match.role;+ const detail = document.createElement('small');+ detail.textContent = `${match.role}${match.treeRef ? ' · reveal in tree' : ' · not present in the loaded tree'}`;+ button.append(detail);+ button.disabled = state.busy || !match.treeRef;+ button.onclick = () => select(match.treeRef);+ if (!match.treeRef) button.title = 'No unique identity match in the captured tree; no guessed highlight is shown.';+ byId('results').append(button);+ }+}++function render() {+ const items = indexTree(state.view?.tree);+ const item = items.find(item => item.key === state.selectedKey);+ byId('tree-empty').hidden = Boolean(state.view);+ byId('node-count').textContent = state.view ? `${items.length} loaded` : '';+ for (const id of ['app', 'window', 'reload-apps', 'find-name', 'find-field', 'find-role', 'find-exact', 'read-kind', 'property']) byId(id).disabled = state.busy;+ byId('load').disabled = state.busy || !byId('app').value || !byId('window').value;+ byId('load').textContent = state.view && state.view.app === byId('app').value ? 'Refresh app' : 'Inspect app';+ renderTree(byId('tree'), state, {select, expand, render});+ renderSelection(item);+ renderResults();+ byId('show-all').disabled = state.busy || !state.view;+ document.querySelector('.workspace').setAttribute('aria-busy', String(state.busy));+ byId('roles').replaceChildren(...[...new Set(items.map(item => item.node.role))].sort().map(role => new Option(role, role)));+ byId('preview-hint').textContent = highlightMatches ? 'Showing search matches. Select a result to isolate it.' : state.selectedKey ? 'Showing only the selected element. Show all restores the overview.' : 'Select a highlight to inspect it. This never clicks the app.';+ renderScreenshot(state.view, highlightMatches ? null : state.selectedKey, items, highlightMatches ? new Set(state.matches.map(match => match.treeRef).filter(Boolean)) : null, select);+}++function setProperties() {+ byId('property').replaceChildren(...properties[byId('read-kind').value].map(name => new Option(name, name)));+}++async function loadApps() {+ const previous = byId('app').value;+ await perform({operation: 'apps'}, 'Reading running applications…', payload => {+ const names = [...new Set((payload.apps || []).filter(app => app.presentation !== 'background').map(app => app.name))].sort((a, b) => a.localeCompare(b));+ byId('app').replaceChildren(new Option('Choose a running app…', ''), ...names.map(name => new Option(name, name)));+ if (names.includes(previous)) byId('app').value = previous;+ });+}++byId('app').onchange = async () => {+ if (state.busy) return;+ state.view = null;+ state.selectedKey = null;+ state.matches = [];+ resultInfo = '';+ state.open.clear();+ byId('window').replaceChildren();+ byId('window-field').hidden = true;+ if (!byId('app').value) { render(); return; }+ await perform({operation: 'windows', app: byId('app').value}, 'Reading app windows…', payload => {+ const windows = (payload.windows || []).filter(window => window.accessible !== false);+ windows.sort((a, b) => Number(b.is_focused) - Number(a.is_focused));+ byId('window').replaceChildren(...windows.map(window => new Option(window.title || window.id, window.id)));+ byId('window-field').hidden = windows.length <= 1;+ if (!windows.length) throw new Error('This app has no accessible window. Open a window, then choose the app again.');+ });+};+byId('reload-apps').onclick = loadApps;+byId('app-form').onsubmit = async event => {+ event.preventDefault();+ const app = byId('app').value;+ await perform({operation: 'snapshot', app, windowId: byId('window').value}, 'Capturing the skeleton and window…', payload => {+ state.invalid = false;+ state.matches = [];+ highlightMatches = false;+ resultInfo = '';+ state.selectedKey = indexTree(payload.view.tree)[0].key;+ state.open = new Set([state.selectedKey]);+ });+};+byId('expand').onclick = () => { const ref = selected()?.node.ref_id; if (ref) expand(ref); };+byId('find-form').onsubmit = async event => {+ event.preventDefault();+ if (!canSearch() || state.invalid) return;+ await perform({operation: 'find', revision: state.revision, ...scoped(), name: byId('find-name').value.trim(), field: byId('find-field').value, role: byId('find-role').value.trim(), exact: byId('find-exact').checked}, 'Finding matches and revealing the selected region…', payload => {+ state.matches = payload.matches;+ highlightMatches = true;+ resultInfo = payload.matches.length ? `${payload.matches.length} of ${payload.totalMatches} matches${payload.truncated ? ' · first 20 shown' : ''}` : 'No matches in this selection. Try a different search field, term, or role.';+ state.selectedKey = payload.selectedRef || indexTree(state.view.tree)[0].key;+ const items = indexTree(state.view.tree);+ for (const match of state.matches) for (const parent of ancestors(items, match.treeRef)) state.open.add(parent);+ });+};+byId('read-kind').onchange = setProperties;+byId('read-form').onsubmit = async event => {+ event.preventDefault();+ const ref = selected()?.node.ref_id;+ if (!ref || state.invalid) return;+ await perform({operation: byId('read-kind').value, revision: state.revision, ref, property: byId('property').value}, 'Reading the element from the app…', payload => {+ byId('read-result').textContent = JSON.stringify(payload.result, null, 2);+ });+};+byId('highlights').onchange = render;+byId('show-all').onclick = () => {+ state.selectedKey = null;+ state.matches = [];+ highlightMatches = false;+ resultInfo = '';+ byId('highlights').checked = true;+ render();+};+byId('toast-dismiss').onclick = () => { byId('toast').hidden = true; };++const workspace = document.querySelector('.workspace');+const MIN_PANE = 180;+const MAX_PANE = 640;++function applyPanes() {+ const leftHidden = localStorage.getItem('inspector-left') === 'hidden';+ const rightHidden = localStorage.getItem('inspector-right') === 'hidden';+ workspace.classList.toggle('left-hidden', leftHidden);+ workspace.classList.toggle('right-hidden', rightHidden);+ byId('tree-pane').hidden = leftHidden;+ byId('inspect-pane').hidden = rightHidden;+ byId('resize-left').hidden = leftHidden;+ byId('resize-right').hidden = rightHidden;+ byId('show-left').hidden = !leftHidden;+ byId('show-right').hidden = !rightHidden;+ for (const key of ['left-w', 'right-w']) {+ const stored = Number(localStorage.getItem(`inspector-${key}`));+ if (stored >= MIN_PANE) workspace.style.setProperty(`--${key}`, `${stored}px`);+ }+}++function setupToggle(hideId, showId, side) {+ byId(hideId).onclick = () => { localStorage.setItem(`inspector-${side}`, 'hidden'); applyPanes(); };+ byId(showId).onclick = () => { localStorage.setItem(`inspector-${side}`, 'open'); applyPanes(); };+}++function setupResize(handleId, side) {+ const handle = byId(handleId);+ let startX = 0;+ let startWidth = 0;+ let pointerId = null;+ const move = event => {+ if (event.pointerId !== pointerId) return;+ const delta = side === 'left' ? event.clientX - startX : startX - event.clientX;+ const width = Math.min(MAX_PANE, Math.max(MIN_PANE, startWidth + delta));+ workspace.style.setProperty(`--${side}-w`, `${width}px`);+ };+ const stop = () => {+ if (pointerId === null) return;+ const captured = pointerId;+ pointerId = null;+ if (handle.hasPointerCapture(captured)) handle.releasePointerCapture(captured);+ handle.classList.remove('dragging');+ document.body.style.userSelect = '';+ localStorage.setItem(`inspector-${side}-w`, parseInt(getComputedStyle(workspace).getPropertyValue(`--${side}-w`), 10) || '');+ };+ handle.onpointermove = move;+ handle.onpointerup = stop;+ handle.onpointercancel = stop;+ handle.onlostpointercapture = stop;+ handle.onpointerdown = event => {+ if (pointerId !== null || event.button !== 0) return;+ event.preventDefault();+ handle.setPointerCapture(event.pointerId);+ pointerId = event.pointerId;+ startX = event.clientX;+ startWidth = byId(side === 'left' ? 'tree-pane' : 'inspect-pane').getBoundingClientRect().width;+ handle.classList.add('dragging');+ document.body.style.userSelect = 'none';+ };+ handle.onkeydown = event => {+ const step = event.shiftKey ? 40 : 16;+ const current = parseInt(getComputedStyle(workspace).getPropertyValue(`--${side}-w`), 10) || (side === 'left' ? 280 : 310);+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;+ event.preventDefault();+ const next = Math.min(MAX_PANE, Math.max(MIN_PANE, current + (event.key === 'ArrowLeft' ? -step : step) * (side === 'left' ? 1 : -1)));+ workspace.style.setProperty(`--${side}-w`, `${next}px`);+ localStorage.setItem(`inspector-${side}-w`, String(next));+ };+}++applyPanes();+setupToggle('hide-left', 'show-left', 'left');+setupToggle('hide-right', 'show-right', 'right');+setupResize('resize-left', 'left');+setupResize('resize-right', 'right');+setProperties();+render();+await loadApps();diff --git a/tools/inspector/public/feedback.js b/tools/inspector/public/feedback.jsnew file mode 100644index 000000000..94729bdce--- /dev/null+++ b/tools/inspector/public/feedback.js@@ -0,0 +1,40 @@+const quote = value => /\s/.test(value) ? JSON.stringify(value) : value;+const shellQuote = value => /^[a-zA-Z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;++export function formatCommand({args, stateRoot, binary = 'agent-desktop'}) {+ const prefix = stateRoot ? `env -u AGENT_DESKTOP_SESSION ${shellQuote(`AGENT_DESKTOP_HOME=${stateRoot}`)} ` : '';+ return `${prefix}${[binary, ...args].map(shellQuote).join(' ')}`;+}++export function commandPreview(body) {+ const scope = body.ref ? ['--root', body.ref] : body.app ? [`--app=${body.app}`] : [];+ let args;+ switch (body.operation) {+ case 'apps': args = ['list-windows']; break;+ case 'windows': args = ['list-windows', ...scope]; break;+ case 'snapshot': args = ['snapshot', ...scope, ...(body.windowId ? [`--window-id=${body.windowId}`] : []), '--skeleton']; break;+ case 'expand': args = ['snapshot', ...scope, '--max-depth', '3']; break;+ case 'find': args = ['find', ...scope, ...(!body.ref && body.windowId ? [`--window-id=${body.windowId}`] : []), ...(body.name ? [`--${body.field || 'text'}=${body.name}`] : []), ...(body.role ? [`--role=${body.role}`] : []), ...(body.exact ? ['--exact'] : [])]; break;+ default: args = [body.operation, body.ref, '--property', body.property];+ }+ return `agent-desktop ${args.map(quote).join(' ')}`;+}++let timer;+export function startFeedback(body, message) {+ clearTimeout(timer);+ const toast = document.getElementById('toast');+ toast.hidden = false;+ toast.dataset.state = 'running';+ document.getElementById('toast-title').textContent = 'Running command';+ document.getElementById('toast-command').textContent = commandPreview(body);+ document.getElementById('toast-message').textContent = body.operation === 'find' ? 'Searching, then loading the matching region for display…' : message;+}++export function finishFeedback(ok, message) {+ const toast = document.getElementById('toast');+ toast.dataset.state = ok ? 'success' : 'error';+ document.getElementById('toast-title').textContent = ok ? 'Done' : 'Could not complete';+ document.getElementById('toast-message').textContent = message;+ timer = setTimeout(() => { toast.hidden = true; }, ok ? 3000 : 7000);+}diff --git a/tools/inspector/public/index.html b/tools/inspector/public/index.htmlnew file mode 100644index 000000000..619c161b6--- /dev/null+++ b/tools/inspector/public/index.html@@ -0,0 +1,68 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>agent-desktop · Live Inspector</title>+<link rel="stylesheet" href="/shared/viewer.css">+<link rel="stylesheet" href="/styles.css">+<script src="/shared/viewer_filter.js" defer></script>+<script src="/app.js" type="module"></script>+</head>+<body>+<header>+<div class="heading"><h1>agent-desktop <span>Live Inspector</span></h1><span class="readonly">Read-only</span></div>+<form id="app-form" class="app-picker">+<label>Application<select id="app" required><option value="">Loading applications…</option></select></label>+<label id="window-field" hidden>Window<select id="window"></select></label>+<button id="load" type="submit" class="primary" disabled>Inspect app</button>+<button id="reload-apps" type="button">Reload apps</button>+</form>+<p id="status" role="status" aria-live="polite">Choose a running app to see its interface.</p>+<div id="error" role="alert" hidden></div>+</header>+<main class="workspace">+<div id="show-left" class="pane-show" hidden><button type="button" class="pane-toggle" title="Show elements sidebar" aria-label="Show elements sidebar">›</button></div>+<nav id="tree-pane" class="tree-pane" aria-label="Application element hierarchy">+<div class="pane-heading"><h2>Elements</h2><span class="pane-heading-tools"><span id="node-count"></span><button id="hide-left" type="button" class="pane-toggle" title="Hide elements sidebar" aria-label="Hide elements sidebar">‹</button></span></div>+<p class="hint">Select a row to highlight it. Use an arrow to open a branch.</p>+<div id="tree-empty" class="empty">Your app’s element tree will appear here.</div>+<div id="tree"></div>+</nav>+<div id="resize-left" class="pane-resize" role="separator" aria-orientation="vertical" aria-label="Resize elements sidebar" tabindex="0"></div>+<section class="preview-pane" aria-label="Window screenshot">+<div class="pane-heading"><h2 id="window-title">Window preview</h2><div class="preview-controls"><button id="show-right" type="button" class="pane-toggle" title="Show inspector sidebar" aria-label="Show inspector sidebar" hidden>‹</button><button id="show-all" type="button" disabled>Show all</button><label><input id="highlights" type="checkbox" checked> Highlights</label></div></div>+<p id="preview-hint" class="hint">Selecting a highlight inspects the element. It never clicks the app.</p>+<div id="preview-empty" class="empty">Choose an app, then select <strong>Inspect app</strong>.</div>+<div id="stage" hidden><img id="capture" alt="Selected application window"><svg id="overlay" xmlns="http://www.w3.org/2000/svg" aria-label="Selectable element highlights"></svg></div>+<p id="capture-warning" class="hint"></p>+</section>+<div id="resize-right" class="pane-resize" role="separator" aria-orientation="vertical" aria-label="Resize inspector sidebar" tabindex="0"></div>+<aside id="inspect-pane" class="inspect-pane" aria-label="Selected element and scoped commands">+<h2 id="selected-name">Select an element</h2>+<p id="selected-role" class="hint">Its details and available reads will appear here.</p>+<code id="selected-ref"></code>+<p id="selected-states" class="hint"></p>+<button id="expand" type="button" disabled>Load children</button>+<p id="scope-note" class="hint"></p>+<form id="find-form">+<h3>Find inside selection</h3>+<label>Search field<select id="find-field"><option value="text">Text (name, value, descendants)</option><option value="name">Name only</option><option value="value">Value only</option></select></label>+<p class="hint">Text searches names, values, descriptions, and descendant content within the selected scope.</p>+<label>Search term<input id="find-name" type="search" placeholder="For example, Save" maxlength="512"></label>+<div class="search-options"><label>Role<input id="find-role" list="roles" placeholder="Any role" maxlength="64"></label><datalist id="roles"></datalist><label class="exact"><input id="find-exact" type="checkbox"> Exact match</label></div>+<button id="find" class="primary" type="submit" disabled>Find</button>+</form>+<p id="result-count" role="status"></p>+<div id="results"></div>+<details id="read-options"><summary>Read a property or state</summary>+<form id="read-form"><label>Read<select id="read-kind"><option value="get">Property</option><option value="is">State</option></select></label><label>Which one?<select id="property"></select></label><button id="read" type="submit" disabled>Read from app</button></form>+<pre id="read-result"></pre></details>+<details><summary>Element details</summary><pre id="element-details">No selection</pre></details>+<button id="hide-right" type="button" class="pane-toggle pane-toggle-hide" title="Hide inspector sidebar" aria-label="Hide inspector sidebar">›</button>+</aside>+</main>+<footer><details id="command-log"><summary id="command-summary">Command history</summary><ol id="commands"></ol></details><p class="hint">Local inspector · screenshots and labels may contain sensitive content. Refresh after the app changes.</p></footer>+<div id="toast" class="toast" role="status" aria-live="polite" hidden><div class="toast-heading"><span class="spinner" aria-hidden="true"></span><strong id="toast-title"></strong><button id="toast-dismiss" type="button" aria-label="Dismiss command notification">×</button></div><code id="toast-command"></code><p id="toast-message"></p></div>+</body>+</html>diff --git a/tools/inspector/public/screenshot.js b/tools/inspector/public/screenshot.jsnew file mode 100644index 000000000..cf1761b94--- /dev/null+++ b/tools/inspector/public/screenshot.js@@ -0,0 +1,50 @@+import {highlightItems} from './tree-model.js';++export function renderScreenshot(view, selection, items, matchRefs, onSelect) {+ const byId = id => document.getElementById(id);+ const frame = view?.frame;+ const svg = byId('overlay');+ svg.replaceChildren();+ byId('stage').hidden = !frame;+ byId('preview-empty').hidden = Boolean(frame);+ byId('capture-warning').textContent = view?.warning || (view?.complete === false ? 'Partial snapshot: some elements were not captured. Refresh to try again.' : '');+ if (!view) {+ byId('window-title').textContent = 'Window preview';+ byId('preview-empty').textContent = 'Choose an app, then select Inspect app.';+ return;+ }+ byId('window-title').textContent = view.window.title || view.app;+ if (!frame) {+ byId('preview-empty').textContent = 'Screenshot unavailable. You can still explore the tree.';+ return;+ }+ const image = byId('capture');+ if (image.getAttribute('src') !== frame.image) image.src = frame.image;+ image.alt = `${view.app}: ${frame.window.title || 'window'}`;+ if (!byId('highlights').checked) return;+ const bounds = frame.window.bounds;+ svg.setAttribute('viewBox', `0 0 ${bounds.width} ${bounds.height}`);+ const nodes = highlightItems(items, selection, matchRefs);+ nodes.sort((a, b) => ((b.node.bounds?.width || 0) * (b.node.bounds?.height || 0)) - ((a.node.bounds?.width || 0) * (a.node.bounds?.height || 0)));+ for (const item of nodes) {+ const node = item.node;+ const rect = DebugViewerFilter.visibleRect(node.bounds, bounds);+ if (!rect) continue;+ const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');+ group.setAttribute('class', `selectable ${node.kind || 'context'}${item.key === selection ? ' selection' : ''}${matchRefs?.has(node.ref_id) ? ' search-match' : ''}`);+ group.setAttribute('role', 'button');+ group.setAttribute('tabindex', '0');+ group.setAttribute('aria-label', `Inspect ${node.name || node.role}`);+ group.dataset.key = item.key;+ const box = document.createElementNS('http://www.w3.org/2000/svg', 'rect');+ for (const [key, value] of Object.entries(rect)) box.setAttribute(key, value);+ const title = document.createElementNS('http://www.w3.org/2000/svg', 'title');+ title.textContent = `${node.name || node.role} · ${node.role}`;+ group.append(title, box);+ group.onclick = () => onSelect(item.key);+ group.onkeydown = event => {+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); onSelect(item.key); }+ };+ svg.append(group);+ }+}diff --git a/tools/inspector/public/styles.css b/tools/inspector/public/styles.cssnew file mode 100644index 000000000..dee35a764--- /dev/null+++ b/tools/inspector/public/styles.css@@ -0,0 +1,93 @@+body { min-width: 320px; }+[hidden] { display: none !important; }+header { padding: 20px 24px 14px; }+.heading, .pane-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }+.heading h1 { margin-bottom: 0; }+.readonly { color: #21634b; background: #e7f3ed; border: 1px solid #b4d4c2; border-radius: 4px; padding: 3px 9px; font-size: 12px; white-space: nowrap; }+.app-picker { display: flex; flex-wrap: wrap; align-items: end; gap: 12px; margin-top: 18px; }+label { display: flex; flex-direction: column; gap: 5px; font-size: 12px; font-weight: 600; }+input, select { min-width: 0; width: 100%; min-height: 36px; border: 1px solid var(--border); border-radius: 4px; padding: 7px 9px; background: var(--panel); color: var(--ink); font: inherit; font-size: 14px; }+input[type="checkbox"] { width: 16px; min-height: 16px; height: 16px; accent-color: var(--accent); }+.app-picker label { min-width: 220px; max-width: 400px; flex: 0 1 280px; }+.app-picker button { min-height: 36px; }+button.primary { color: white; background: var(--accent); border-color: var(--accent); }+button.primary:hover { background: #19479f; }+button:disabled, input:disabled, select:disabled { opacity: .55; cursor: default; }+#status { margin: 12px 0 0; font-size: 13px; }+#error { margin-top: 12px; padding: 10px 12px; border: 1px solid #e3b5be; background: #fff0f3; color: #842238; overflow-wrap: anywhere; }+.workspace { display: grid; grid-template-columns: min(var(--left-w, 280px), calc((100vw - 332px) / 2)) 6px minmax(320px, 1fr) 6px min(var(--right-w, 310px), calc((100vw - 332px) / 2)); min-height: 620px; align-items: start; }+.workspace.left-hidden { grid-template-columns: 28px 0 minmax(320px, 1fr) 6px min(var(--right-w, 310px), calc((100vw - 332px) / 2)); }+.workspace.right-hidden { grid-template-columns: min(var(--left-w, 280px), calc((100vw - 332px) / 2)) 6px minmax(320px, 1fr) 0 0; }+.workspace.left-hidden.right-hidden { grid-template-columns: 28px 0 minmax(320px, 1fr) 0 0; }+.tree-pane, #show-left { grid-column: 1; grid-row: 1; }+#resize-left { grid-column: 2; grid-row: 1; }+.preview-pane { grid-column: 3; grid-row: 1; }+#resize-right { grid-column: 4; grid-row: 1; }+.inspect-pane { grid-column: 5; grid-row: 1; }+.pane-resize { align-self: stretch; cursor: col-resize; background: transparent; border-left: 1px solid var(--border); min-height: 620px; }+.pane-resize:hover, .pane-resize:focus-visible, .pane-resize.dragging { background: #dce7f8; outline: none; }+.pane-show, .pane-toggle-hide { padding: 0; }+.pane-show { align-self: start; background: var(--panel); border-right: 1px solid var(--border); padding-top: 20px; min-height: 620px; }+.pane-show button, .pane-toggle { font-size: 15px; line-height: 1; padding: 6px 8px; }+.pane-toggle-hide { margin-top: 18px; align-self: flex-start; }+.pane-heading-tools { display: flex; align-items: center; gap: 8px; }+.tree-pane, .preview-pane, .inspect-pane { padding: 20px 18px; min-width: 0; }+.tree-pane { background: var(--panel); border-right: 1px solid var(--border); align-self: stretch; display: flex; flex-direction: column; }+.tree-pane .pane-heading, .tree-pane .hint, .tree-pane #tree-empty { flex: 0 0 auto; }+.inspect-pane { align-self: stretch; }+.pane-heading h2 { font-size: 15px; margin: 0; }+.pane-heading label { flex-direction: row; align-items: center; font-size: 12px; }+#node-count { font-size: 12px; color: var(--muted); }+.hint { font-size: 12px; line-height: 1.55; }+.empty { margin: 40px auto; padding: 24px; max-width: 45ch; text-align: center; color: var(--muted); }+#tree { max-height: 72vh; overflow: auto; padding: 2px; flex: 1 1 auto; }+.tree-list { list-style: none; padding: 0; margin: 0; }+#tree > .tree-list { width: max-content; min-width: 100%; }+.tree-list .tree-list { padding-left: 15px; border-left: 1px solid var(--border); margin-left: 12px; }+.tree-row { display: flex; align-items: center; gap: 2px; border-radius: 4px; margin: 2px 0; }+.tree-row.selected { background: #e4ecfc; outline: 1px solid #a8bfe8; }+.tree-row.matched { background: #fff3d9; }+.tree-row.matched.selected { outline: 2px solid var(--accent); }+.tree-toggle { flex: 0 0 24px; width: 24px; padding: 5px 0; background: transparent; border: 0; }+.tree-spacer { width: 24px; flex: 0 0 24px; text-align: center; color: var(--muted); }+.tree-select { border: 0; background: transparent; text-align: left; min-width: 0; padding: 6px 5px; flex: 1; }+.tree-select strong { display: block; font-size: 13px; font-weight: 500; white-space: nowrap; }+.tree-select small { color: var(--muted); font-size: 11px; }+#stage { outline: 1px solid var(--border); border-radius: 4px; }+#overlay { pointer-events: none; }+#overlay .selectable { pointer-events: all; cursor: pointer; }+#overlay .selectable:hover rect { stroke-width: 3; }+#overlay .selection rect { stroke: #235bcc; stroke-width: 3; fill: #235bcc15; }+#overlay .search-match rect { stroke: #a95b00; stroke-width: 3; fill: #a95b0015; }+#selected-name { margin-bottom: 6px; font-size: 17px; overflow-wrap: anywhere; }+#selected-ref { display: block; overflow-wrap: anywhere; font-size: 12px; color: var(--accent); }+h3 { font-size: 14px; margin: 0 0 12px; }+#find-form { padding-top: 18px; margin-top: 18px; border-top: 1px solid var(--border); }+.search-options { display: flex; gap: 10px; align-items: end; margin: 10px 0 12px; }+.search-options > label:first-child { flex: 1; min-width: 0; }+.exact { flex-direction: row; align-items: center; padding-bottom: 10px; white-space: nowrap; }+#result-count { font-size: 12px; }+#results { max-height: 220px; overflow: auto; }+.result { width: 100%; text-align: left; margin-bottom: 5px; font-size: 12px; overflow-wrap: anywhere; }+.result small { display: block; color: var(--muted); }+#read-form { display: grid; gap: 9px; margin-top: 12px; }+#commands { max-height: 200px; overflow: auto; padding-left: 22px; }+#commands li { margin: 10px 0; overflow-wrap: anywhere; font-size: 12px; }+#commands code { display: block; }+footer { padding: 14px 24px; background: var(--panel); }+footer details { margin: 0; }+.preview-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }+.preview-controls button { font-size: 12px; padding: 4px 8px; }+.toast { position: fixed; bottom: 20px; right: 20px; z-index: 10; width: min(420px, calc(100vw - 32px)); padding: 14px 16px; border: 1px solid var(--border); border-radius: 8px; background: var(--panel); box-shadow: 0 6px 24px #141a2426; }+.toast-heading { display: flex; align-items: center; gap: 9px; }+.toast-heading button { margin-left: auto; border: 0; padding: 0 5px; font-size: 22px; line-height: 1; }+.toast code { display: block; margin-top: 9px; overflow-wrap: anywhere; font-size: 12px; }+.toast p { margin: 7px 0 0; font-size: 12px; }+.toast[data-state="success"] { border-color: #7ba28b; }+.toast[data-state="error"] { border-color: #cb8794; }+.spinner { width: 14px; height: 14px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; }+.toast:not([data-state="running"]) .spinner { display: none; }+@keyframes spin { to { transform: rotate(360deg); } }+@media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }+@media (max-width: 1120px) { .workspace, .workspace.right-hidden { grid-template-columns: 250px minmax(0, 1fr); } .workspace.left-hidden, .workspace.left-hidden.right-hidden { grid-template-columns: 28px minmax(0, 1fr); } .pane-resize { display: none; } .preview-pane { grid-column: 2; } .inspect-pane { grid-column: 1 / -1; grid-row: 2; border-top: 1px solid var(--border); border-left: 0; } }+@media (max-width: 650px) { .workspace { display: flex; flex-direction: column; } .tree-pane, .preview-pane, .inspect-pane { width: 100%; } .tree-pane { border-right: 0; border-bottom: 1px solid var(--border); } #tree { max-height: 330px; } #show-left { min-height: 0; padding: 8px; width: 100%; } .app-picker label { flex: 1 1 100%; max-width: none; } .heading { align-items: start; } .heading h1 span { display: block; margin: 0; font-size: 16px; } }diff --git a/tools/inspector/public/tree-model.js b/tools/inspector/public/tree-model.jsnew file mode 100644index 000000000..207be576f--- /dev/null+++ b/tools/inspector/public/tree-model.js@@ -0,0 +1,44 @@+export function indexTree(tree) {+ const items = [];+ function visit(node, path, parentKey) {+ const key = node.ref_id || `node:${path}`;+ items.push({node, key, parentKey});+ (node.children || []).forEach((child, index) => visit(child, `${path}.${index}`, key));+ }+ if (tree) visit(tree, '0', null);+ return items;+}++export function replaceBranch(tree, ref, replacement) {+ if (tree.ref_id === ref) return replacement;+ return {...tree, children: (tree.children || []).map(child => replaceBranch(child, ref, replacement))};+}++export function findIdentity(tree, identity) {+ if (!identity) return null;+ const matches = indexTree(tree).filter(item => item.node.identity_key === identity);+ return matches.length === 1 ? matches[0] : null;+}++export function findContextMatch(tree, match) {+ const fields = ['x', 'y', 'width', 'height'];+ if (!match.bounds || !fields.every(field => Number.isFinite(match.bounds[field])) || match.bounds.width <= 0 || match.bounds.height <= 0) return null;+ const matches = indexTree(tree).filter(({node}) => node.role === match.role && node.bounds && fields.every(field => node.bounds[field] === match.bounds[field]));+ return matches.length === 1 ? matches[0] : null;+}++export function highlightItems(items, selection, matchRefs) {+ return items.filter(item => {+ if (item.node.states?.some(state => state === 'hidden' || state === 'offscreen')) return false;+ if (selection !== null) return item.key === selection;+ return matchRefs === null || matchRefs.has(item.node.ref_id || item.key);+ });+}++export function ancestors(items, key) {+ const lookup = new Map(items.map(item => [item.key, item]));+ const result = [];+ let item = lookup.get(key);+ while (item?.parentKey) { result.push(item.parentKey); item = lookup.get(item.parentKey); }+ return result;+}diff --git a/tools/inspector/public/tree-view.js b/tools/inspector/public/tree-view.jsnew file mode 100644index 000000000..b6bddb4a1--- /dev/null+++ b/tools/inspector/public/tree-view.js@@ -0,0 +1,84 @@+export function revealTreeRow(container, row) {+ if (!row || !container.clientWidth) return;+ const viewport = container.getBoundingClientRect();+ const bounds = row.getBoundingClientRect();+ const left = bounds.left - viewport.left - 2;+ const top = bounds.top - viewport.top - 2;+ const right = left + Math.min(bounds.width, container.clientWidth - 4) - container.clientWidth + 4;+ const bottom = top + bounds.height - container.clientHeight + 4;+ container.scrollLeft += left < 0 ? left : Math.max(0, right);+ container.scrollTop += top < 0 ? top : Math.max(0, bottom);+}++export function renderTree(container, state, handlers) {+ const scrollTop = container.scrollTop;+ const scrollLeft = container.scrollLeft;+ container.replaceChildren();+ if (!state.view) return;+ const matched = new Set(state.matches.flatMap(match => match.treeRef ? [match.treeRef] : []));+ function branch(node, path) {+ const key = node.ref_id || `node:${path}`;+ const name = node.name || node.description || node.role;+ const li = document.createElement('li');+ const row = document.createElement('div');+ row.className = 'tree-row';+ row.dataset.key = key;+ row.classList.toggle('selected', state.selectedKey === key);+ row.classList.toggle('matched', matched.has(key));+ const children = node.children || [];+ const truncated = Boolean(node.children_count || node.subtree_truncated);+ if (children.length || truncated) {+ const toggle = document.createElement('button');+ toggle.type = 'button';+ toggle.className = 'tree-toggle';+ toggle.textContent = state.open.has(key) ? '▾' : '▸';+ toggle.setAttribute('aria-label', `${state.open.has(key) ? 'Collapse' : 'Expand'} ${name}`);+ toggle.setAttribute('aria-expanded', String(state.open.has(key)));+ toggle.disabled = state.busy || state.invalid || (!children.length && !node.ref_id);+ if (!children.length && !node.ref_id) toggle.title = 'No ref for further reads. Select a ref-addressable ancestor.';+ toggle.onclick = () => {+ if (state.open.has(key)) state.open.delete(key);+ else if (truncated && node.ref_id) { handlers.expand(node.ref_id); return; }+ else state.open.add(key);+ handlers.render();+ container.querySelectorAll('.tree-row').forEach(row => {+ if (row.dataset.key === key) row.querySelector('.tree-toggle')?.focus({preventScroll: true});+ });+ };+ row.append(toggle);+ } else {+ const spacer = document.createElement('span');+ spacer.className = 'tree-spacer';+ spacer.textContent = '·';+ spacer.setAttribute('aria-hidden', 'true');+ row.append(spacer);+ }+ const select = document.createElement('button');+ select.type = 'button';+ select.className = 'tree-select';+ select.disabled = state.busy;+ select.setAttribute('aria-pressed', String(state.selectedKey === key));+ select.title = `${name} (${node.role})`;+ const title = document.createElement('strong');+ title.textContent = name;+ const subtitle = document.createElement('small');+ subtitle.textContent = `${node.role}${node.children_count ? ` · ${node.children_count} children to load` : node.subtree_truncated ? ' · incomplete' : ''}`;+ select.append(title, subtitle);+ select.onclick = () => handlers.select(key);+ row.append(select);+ li.append(row);+ if (state.open.has(key) && children.length) {+ const list = document.createElement('ul');+ list.className = 'tree-list';+ children.forEach((child, index) => list.append(branch(child, `${path}.${index}`)));+ li.append(list);+ }+ return li;+ }+ const list = document.createElement('ul');+ list.className = 'tree-list';+ list.append(branch(state.view.tree, '0'));+ container.append(list);+ container.scrollTop = scrollTop;+ container.scrollLeft = scrollLeft;+}diff --git a/tools/inspector/server.mjs b/tools/inspector/server.mjsnew file mode 100644index 000000000..69d1755ed--- /dev/null+++ b/tools/inspector/server.mjs@@ -0,0 +1,53 @@+import {access, mkdtemp, rm} from 'node:fs/promises';+import {constants, rmSync} from 'node:fs';+import {tmpdir} from 'node:os';+import {join, resolve} from 'node:path';+import {fileURLToPath} from 'node:url';+import {randomBytes} from 'node:crypto';+import {parseArgs} from 'node:util';+import {spawn} from 'node:child_process';+import {createCli} from './cli.mjs';+import {createInspector} from './inspector.mjs';+import {createBridge} from './bridge.mjs';+import {listenAvailable} from './http.mjs';++const {values} = parseArgs({options: {port: {type: 'string'}, bin: {type: 'string'}, 'no-open': {type: 'boolean'}}});+const port = Number(values.port ?? process.env.PORT ?? 4317);+const defaultBinary = fileURLToPath(new URL(`../../target/release/agent-desktop${process.platform === 'win32' ? '.exe' : ''}`, import.meta.url));+const binary = resolve(values.bin || process.env.AGENT_DESKTOP_BIN || defaultBinary);+let home;+try {+ await access(binary, constants.X_OK);+ home = await mkdtemp(join(tmpdir(), 'agent-desktop-inspector-'));+ process.on('exit', () => {+ try { rmSync(home, {recursive: true, force: true}); }+ catch (error) { console.error(`Temporary state cleanup failed: ${error.message}`); }+ });+ const token = randomBytes(32).toString('hex');+ const server = createBridge(createInspector(createCli(binary, home)), token);+ const actualPort = await listenAvailable(server, port);+ const url = `http://127.0.0.1:${actualPort}/#token=${token}`;+ console.log(`agent-desktop inspector: ${url}`);+ console.log('Read-only. Screenshots and labels are sensitive. Press Ctrl+C to stop.');+ let closing = false;+ const stop = () => {+ if (closing) return;+ closing = true;+ server.close();+ server.closeAllConnections();+ };+ process.on('SIGINT', stop);+ process.on('SIGTERM', stop);+ if (!values['no-open']) {+ const opener = process.platform === 'darwin' ? '/usr/bin/open' : process.platform === 'linux' ? 'xdg-open' : null;+ if (opener) {+ const child = spawn(opener, [url], {stdio: 'ignore', shell: false});+ child.on('error', () => console.error('Open the localhost URL above in your browser.'));+ child.unref();+ }+ }+} catch (error) {+ if (home) await rm(home, {recursive: true, force: true});+ console.error(error.code === 'ENOENT' ? 'Build the CLI first: cargo build --release -p agent-desktop (or pass --bin PATH).' : error.message);+ process.exitCode = 1;+}diff --git a/tools/inspector/test/app.test.mjs b/tools/inspector/test/app.test.mjsnew file mode 100644index 000000000..9864ce4a0--- /dev/null+++ b/tools/inspector/test/app.test.mjs@@ -0,0 +1,67 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {readFile} from 'node:fs/promises';+import {runInNewContext} from 'node:vm';++const source = await readFile(new URL('../public/app.js', import.meta.url), 'utf8');+const performSource = source.slice(source.indexOf('async function perform('), source.indexOf('\nfunction select('));++function client(overrides = {}) {+ const elements = new Map();+ const context = {+ state: {busy: false, invalid: false, view: null}, token: 'test',+ byId: id => { if (!elements.has(id)) elements.set(id, {}); return elements.get(id); },+ startFeedback() {}, finishFeedback() {}, render() {}, showCommands() {},+ AbortSignal, fetch: async () => ({json: async () => ({ok: true})}), ...overrides,+ };+ runInNewContext(performSource, context);+ return context;+}++test('feedback initialization failures always release the busy guard', async () => {+ const context = client({startFeedback() { throw new Error('feedback failed'); }});+ await context.perform({operation: 'apps'}, 'Loading');+ assert.equal(context.state.busy, false);+ context.startFeedback = () => {};+ await context.perform({operation: 'apps'}, 'Retry');+ assert.equal(context.byId('status').textContent, 'Choose an app with an open window.');+});++test('numeric DOMException codes are treated as transport failures, not CLI error codes', async () => {+ const context = client({fetch: async () => { throw new DOMException('signal timed out', 'TimeoutError'); }});+ await context.perform({operation: 'apps'}, 'Loading');+ assert.equal(context.state.invalid, true);+ assert.doesNotMatch(context.byId('error').textContent, /^23:/);+ assert.equal(context.state.busy, false);+});++test('pane dragging releases capture on pointerup, cancellation, and lost capture', () => {+ for (const stop of ['onpointerup', 'onpointercancel', 'onlostpointercapture']) {+ let width = '280px';+ let captured = false;+ const handle = {classList: {add() {}, remove() {}}, setPointerCapture() { captured = true; },+ hasPointerCapture: () => captured, releasePointerCapture() { captured = false; }};+ const context = {MIN_PANE: 180, MAX_PANE: 640,+ byId: id => id === 'resize-left' ? handle : {getBoundingClientRect: () => ({width: 280})},+ document: {body: {style: {}}}, localStorage: {setItem() {}},+ workspace: {style: {setProperty: (_, value) => { width = value; }}},+ getComputedStyle: () => ({getPropertyValue: () => width})};+ runInNewContext(source.slice(source.indexOf('function setupResize('), source.indexOf('\napplyPanes();')), context);+ context.setupResize('resize-left', 'left');+ handle.onpointerdown({button: 0, pointerId: 1, clientX: 0, preventDefault() {}});+ handle.onpointermove({pointerId: 1, clientX: 20});+ assert.equal(width, '300px');+ handle[stop]();+ assert.equal(captured, false);+ assert.equal(context.document.body.style.userSelect, '');+ handle.onpointermove({pointerId: 1, clientX: 60});+ assert.equal(width, '300px');+ }+});++test('structured CLI errors preserve a healthy view unless refresh is required', async () => {+ const context = client({fetch: async () => ({json: async () => ({ok: false, error: {code: 'TIMEOUT', message: 'Read timed out'}})})});+ await context.perform({operation: 'apps'}, 'Loading');+ assert.equal(context.state.invalid, false);+ assert.match(context.byId('error').textContent, /^TIMEOUT:/);+});diff --git a/tools/inspector/test/bridge.test.mjs b/tools/inspector/test/bridge.test.mjsnew file mode 100644index 000000000..d595c600a--- /dev/null+++ b/tools/inspector/test/bridge.test.mjs@@ -0,0 +1,62 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {createBridge} from '../bridge.mjs';+import {listenAvailable} from '../http.mjs';++async function start(t, execute) {+ const token = 'test-token';+ const server = createBridge({execute}, token);+ const port = await listenAvailable(server, 0);+ t.after(() => { server.closeAllConnections(); server.close(); });+ const url = `http://127.0.0.1:${port}`;+ return {url, headers: {origin: url, 'x-inspector-token': token, 'content-type': 'application/json'}};+}++test('real HTTP bridge rejects cross-origin, unauthenticated, and mutating requests', async t => {+ let calls = 0;+ const {url, headers} = await start(t, async () => { calls++; return {apps: []}; });+ for (const changed of [{origin: 'http://evil.test'}, {'x-inspector-token': ''}]) {+ const response = await fetch(`${url}/api`, {method: 'POST', headers: {...headers, ...changed}, body: '{"operation":"apps"}'});+ assert.equal(response.status, 403);+ }+ const denied = await fetch(`${url}/api`, {method: 'POST', headers, body: '{"operation":"click","ref":"@sone:e1"}'});+ assert.equal(denied.status, 400);+ assert.equal(calls, 0);+ const allowed = await fetch(`${url}/api`, {method: 'POST', headers, body: '{"operation":"apps"}'});+ assert.deepEqual(await allowed.json(), {ok: true, apps: []});+ assert.equal(calls, 1);+ assert.equal(allowed.headers.get('access-control-allow-origin'), null);+});++test('public assets never disclose the capability token and retain browser isolation headers', async t => {+ const {url} = await start(t, () => assert.fail('Must not dispatch'));+ const response = await fetch(url);+ assert.equal(response.status, 200);+ assert.ok(!(await response.text()).includes('test-token'));+ assert.match(response.headers.get('content-security-policy'), /frame-ancestors 'none'/);+ assert.equal(response.headers.get('cache-control'), 'no-store');+ assert.equal((await fetch(url, {headers: {'sec-fetch-site': 'cross-site'}})).status, 403);+ assert.equal((await fetch(url, {method: 'PUT'})).status, 405);+});++test('oversized bodies and filesystem paths are not accepted', async t => {+ const {url, headers} = await start(t, () => assert.fail('Must not dispatch'));+ const response = await fetch(`${url}/api`, {method: 'POST', headers, body: JSON.stringify({operation: 'apps', text: 'a'.repeat(9000)})});+ assert.equal(response.status, 413);+ assert.equal((await fetch(`${url}/server.mjs`)).status, 404);+ assert.equal((await fetch(`${url}/api`)).status, 404);+});++test('simultaneous requests cannot race snapshot ownership', async t => {+ let release;+ const pending = new Promise(resolve => { release = resolve; });+ let entered;+ const started = new Promise(resolve => { entered = resolve; });+ const {url, headers} = await start(t, () => { entered(); return pending; });+ const first = fetch(`${url}/api`, {method: 'POST', headers, body: '{"operation":"apps"}'});+ await started;+ const second = await fetch(`${url}/api`, {method: 'POST', headers, body: '{"operation":"apps"}'});+ assert.equal(second.status, 409);+ release({apps: []});+ assert.equal((await first).status, 200);+});diff --git a/tools/inspector/test/cli.test.mjs b/tools/inspector/test/cli.test.mjsnew file mode 100644index 000000000..ea0b4bf8e--- /dev/null+++ b/tools/inspector/test/cli.test.mjs@@ -0,0 +1,110 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {mkdtemp, mkdir, writeFile, readdir, rm} from 'node:fs/promises';+import {join} from 'node:path';+import {tmpdir} from 'node:os';+import {fileURLToPath} from 'node:url';+import {createCli} from '../cli.mjs';+import {commandPreview, formatCommand} from '../public/feedback.js';++const fixture = fileURLToPath(new URL('./fixture-cli.mjs', import.meta.url));++test('capture joins artifact classifications and saved identity, then removes the temporary HTML', async t => {+ const home = await mkdtemp(join(tmpdir(), 'inspector-capture-'));+ t.after(() => rm(home, {recursive: true, force: true}));+ const cli = createCli(process.execPath, home);+ const result = await cli.capture([fixture, '--capture']);+ assert.equal(result.snapshotId, 'sone');+ assert.equal(result.tree.kind, 'root');+ assert.equal(result.tree.children[0].reason, 'Addressable');+ assert.ok(result.tree.children[0].identity_key);+ assert.deepEqual(await readdir(home), ['snapshots']);+});++test('capture preserves a successful tree when debug output is unavailable', async t => {+ const home = await mkdtemp(join(tmpdir(), 'inspector-warning-'));+ t.after(() => rm(home, {recursive: true, force: true}));+ const result = await createCli(process.execPath, home).capture([fixture, '--capture', '--warning']);+ assert.equal(result.frame, null);+ assert.equal(result.warning, 'Screenshot unavailable');+ assert.ok(result.tree.children[0].identity_key);+});++test('capture cleanup failure cannot replace the original structured CLI error', async t => {+ const home = await mkdtemp(join(tmpdir(), 'inspector-cleanup-'));+ t.after(() => rm(home, {recursive: true, force: true}));+ const warning = t.mock.method(console, 'error', () => {});+ await assert.rejects(createCli(process.execPath, home).capture([fixture, '--fail', '--cleanup-failure']), {code: 'STALE_REF'});+ assert.equal(warning.mock.callCount(), 1);+});++test('screen recording denial falls back to one plain observation', async t => {+ const home = await mkdtemp(join(tmpdir(), 'inspector-permission-'));+ t.after(() => rm(home, {recursive: true, force: true}));+ const log = [];+ const result = await createCli(process.execPath, home).capture([fixture, '--capture', '--deny-screen'], log);+ assert.equal(result.frame, null);+ assert.match(result.warning, /permission/);+ assert.ok(result.tree.children[0].identity_key);+ assert.equal(log.length, 2);+ assert.ok(!log[1].args.includes('--debug'));+ assert.ok(!log[1].args.includes('--screenshot'));+});++test('capture rejects a mismatched visual tree rather than silently mislabeling nodes', async t => {+ const home = await mkdtemp(join(tmpdir(), 'inspector-mismatch-'));+ t.after(() => rm(home, {recursive: true, force: true}));+ await assert.rejects(createCli(process.execPath, home).capture([fixture, '--capture', '--mismatch']), /incompatible/);+ assert.deepEqual(await readdir(home), ['snapshots']);+});++test('CLI execution preserves argument boundaries and isolates snapshot state', async t => {+ const home = await mkdtemp(join(tmpdir(), 'inspector-test-'));+ t.after(() => rm(home, {recursive: true, force: true}));+ const previous = process.env.AGENT_DESKTOP_SESSION;+ process.env.AGENT_DESKTOP_SESSION = 'unrelated-session';+ let cli;+ try { cli = createCli(process.execPath, home); }+ finally { if (previous === undefined) delete process.env.AGENT_DESKTOP_SESSION; else process.env.AGENT_DESKTOP_SESSION = previous; }+ const query = '--name=a; $(echo should-not-run) "quoted"';+ const log = [];+ const result = await cli.run([fixture, query], log);+ assert.equal(log[0].stateRoot, home);+ assert.equal(log[0].binary, process.execPath);+ assert.deepEqual(result.args, [query]);+ assert.equal(result.stateRoot, home);+ assert.equal(result.session, null);+});++test('ref lookup uses each qualified snapshot in the inspector store, not the latest snapshot', async t => {+ const home = await mkdtemp(join(tmpdir(), 'inspector-refs-'));+ t.after(() => rm(home, {recursive: true, force: true}));+ for (const id of ['sone', 'stwo']) {+ const directory = join(home, 'snapshots', id);+ await mkdir(directory, {recursive: true});+ await writeFile(join(directory, 'refmap.json'), JSON.stringify({inner: {'@e1': {name: id}}}));+ }+ const entries = await createCli(process.execPath, home).entries(['@sone:e1', '@stwo:e1']);+ assert.equal(entries.get('@sone:e1').name, 'sone');+ assert.equal(entries.get('@stwo:e1').name, 'stwo');+});++test('command history includes the private store and safely quotes shell arguments', () => {+ assert.equal(formatCommand({binary: '/path with spaces/agent-desktop', stateRoot: '/tmp/inspector', args: ['find', '--root', '@sone:e1', '--name=$(echo bad)']}),+ "env -u AGENT_DESKTOP_SESSION AGENT_DESKTOP_HOME=/tmp/inspector '/path with spaces/agent-desktop' find --root @sone:e1 '--name=$(echo bad)'");+});++test('nonzero CLI exits retain the structured error instead of guessing success', async () => {+ const cli = createCli(process.execPath, tmpdir());+ await assert.rejects(cli.run([fixture, '--fail']), {code: 'STALE_REF', message: 'Refresh the snapshot'});+});++test('progress shows the actual requested root and property command', () => {+ assert.equal(commandPreview({operation: 'expand', ref: '@sone:e3'}), 'agent-desktop snapshot --root @sone:e3 --max-depth 3');+ assert.equal(commandPreview({operation: 'is', ref: '@sone:e3', property: 'visible'}), 'agent-desktop is @sone:e3 --property visible');+ assert.match(commandPreview({operation: 'find', ref: '@sone:e3', name: 'Save as'}), /--root @sone:e3 "--text=Save as"/);+ assert.match(commandPreview({operation: 'find', ref: '@sone:e3', field: 'name', name: 'Save as'}), /--root @sone:e3 "--name=Save as"/);+ for (const field of ['value', 'text']) {+ assert.equal(commandPreview({operation: 'find', ref: '@sone:e3', field, name: 'agent'}), `agent-desktop find --root @sone:e3 --${field}=agent`);+ }+});diff --git a/tools/inspector/test/fixture-cli.mjs b/tools/inspector/test/fixture-cli.mjsnew file mode 100644index 000000000..febdd0433--- /dev/null+++ b/tools/inspector/test/fixture-cli.mjs@@ -0,0 +1,29 @@+import {mkdir, writeFile} from 'node:fs/promises';+import {join} from 'node:path';++const args = process.argv.slice(2);+if (args.includes('--cleanup-failure')) await mkdir(args[args.indexOf('--screenshot') + 1]);+if (args.includes('--deny-screen') && args.includes('--debug')) {+ console.log(JSON.stringify({ok: false, command: 'snapshot', error: {code: 'PERM_DENIED', message: 'Screen Recording required'}}));+ process.exitCode = 1;+} else if (args.includes('--fail')) {+ console.log(JSON.stringify({ok: false, command: 'snapshot', error: {code: 'STALE_REF', message: 'Refresh the snapshot'}}));+ process.exitCode = 1;+} else if (args.includes('--capture')) {+ const tree = {role: 'window', children: [{role: 'button', ref_id: '@sone:e1', name: 'Save'}]};+ const data = {tree, window: {id: 'w-1'}, snapshot_id: 'sone', complete: true};+ const directory = join(process.env.AGENT_DESKTOP_HOME, 'snapshots', 'sone');+ await mkdir(directory, {recursive: true});+ await writeFile(join(directory, 'refmap.json'), JSON.stringify({inner: {'@e1': {pid: 1, role: 'button', name: 'Save', path: [0]}}}));+ if (args.includes('--warning')) {+ data.debug = {warning: 'Screenshot unavailable'};+ } else if (args.includes('--debug')) {+ const nodes = [{role: 'window', kind: 'root'}, {role: 'button', ref_id: '@sone:e1', kind: 'action', reason: 'Addressable'}];+ const artifact = {after: {window: data.window, nodes: args.includes('--mismatch') ? [] : nodes}};+ const path = args[args.indexOf('--screenshot') + 1];+ await writeFile(path, `<script id="debug-data" type="application/json">${JSON.stringify(artifact)}</script>`);+ }+ console.log(JSON.stringify({ok: true, command: 'snapshot', data}));+} else {+ console.log(JSON.stringify({ok: true, command: 'fixture', data: {args, stateRoot: process.env.AGENT_DESKTOP_HOME, session: process.env.AGENT_DESKTOP_SESSION || null}}));+}diff --git a/tools/inspector/test/highlights.test.mjs b/tools/inspector/test/highlights.test.mjsnew file mode 100644index 000000000..abdc1528c--- /dev/null+++ b/tools/inspector/test/highlights.test.mjs@@ -0,0 +1,22 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {highlightItems} from '../public/tree-model.js';++const items = [+ {key: 'window', node: {role: 'window'}},+ {key: 'a', node: {ref_id: '@sone:e1'}},+ {key: 'b', node: {ref_id: '@sone:e2'}},+ {key: 'hidden', node: {states: ['hidden']}},+];++test('selecting one node isolates only that highlight, even with search results', () => {+ assert.deepEqual(highlightItems(items, 'a', new Set(['@sone:e1', '@sone:e2'])).map(item => item.key), ['a']);+ assert.deepEqual(highlightItems(items, 'window', null).map(item => item.key), ['window']);+ assert.deepEqual(highlightItems(items, 'hidden', null), []);+});++test('search highlights only matches and explicit overview shows all visible nodes', () => {+ assert.deepEqual(highlightItems(items, null, new Set(['@sone:e2'])).map(item => item.key), ['b']);+ assert.deepEqual(highlightItems(items, null, new Set()), []);+ assert.deepEqual(highlightItems(items, null, null).map(item => item.key), ['window', 'a', 'b']);+});diff --git a/tools/inspector/test/inspector.test.mjs b/tools/inspector/test/inspector.test.mjsnew file mode 100644index 000000000..efb8666bc--- /dev/null+++ b/tools/inspector/test/inspector.test.mjs@@ -0,0 +1,144 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {createInspector} from '../inspector.mjs';+import {identityKey} from '../cli.mjs';+import {indexTree, replaceBranch, findIdentity, ancestors} from '../public/tree-model.js';+import {revealTreeRow} from '../public/tree-view.js';++const root = {role: 'window', children: [+ {role: 'group', ref_id: '@sone:e1', children: [{role: 'button', ref_id: '@sone:e2'}]},+ {role: 'button', ref_id: '@sone:e3'},+]};+const view = tree => ({tree, window: {id: 'w-1'}, snapshotId: 'sone', frame: null});++test('revealing a deep row scrolls only the tree and keeps the start of long labels visible', () => {+ const container = {scrollLeft: 0, scrollTop: 0, clientWidth: 240, clientHeight: 300,+ getBoundingClientRect: () => ({left: 20, top: 200})};+ const row = {getBoundingClientRect: () => ({left: 360, top: 550, width: 900, height: 40})};+ revealTreeRow(container, row);+ assert.equal(container.scrollLeft, 338);+ assert.equal(container.scrollTop, 92);+ container.clientWidth = 0;+ revealTreeRow(container, row);+ assert.equal(container.scrollLeft, 338);+});++test('revealing an already visible row does not move the tree', () => {+ const container = {scrollLeft: 50, scrollTop: 75, clientWidth: 240, clientHeight: 300,+ getBoundingClientRect: () => ({left: 20, top: 200})};+ revealTreeRow(container, {getBoundingClientRect: () => ({left: 22, top: 202, width: 100, height: 40})});+ assert.equal(container.scrollLeft, 50);+ assert.equal(container.scrollTop, 75);+});++test('replacing a branch removes old descendants and preserves siblings', () => {+ const tree = replaceBranch(root, '@sone:e1', {role: 'group', ref_id: '@sone:e4', children: [{role: 'button', ref_id: '@sone:e5'}]});+ assert.deepEqual(indexTree(tree).map(item => item.node.ref_id), [undefined, '@sone:e4', '@sone:e5', '@sone:e3']);+ assert.deepEqual(ancestors(indexTree(tree), '@sone:e5'), ['@sone:e4', 'node:0']);+ assert.equal(root.children[0].ref_id, '@sone:e1');+});++test('search never connects nodes by a shared name or ambiguous identity', () => {+ assert.equal(findIdentity(root, 'missing'), null);+ assert.equal(findIdentity({identity_key: 'same', children: [{identity_key: 'same'}]}, 'same'), null);+});++test('inspector rejects stale revisions and foreign refs before calling CLI', async () => {+ const calls = [];+ const cli = {capture: async args => { calls.push(args); return view(root); }, run: async args => { calls.push(args); return {}; }};+ const inspector = createInspector(cli);+ const loaded = await inspector.execute({operation: 'snapshot', app: 'TextEdit'});+ await assert.rejects(inspector.execute({operation: 'expand', revision: loaded.revision + 1, ref: '@sone:e1'}), {code: 'STALE_VIEW'});+ await assert.rejects(inspector.execute({operation: 'get', revision: loaded.revision, ref: '@sother:e1', property: 'value'}), {code: 'STALE_REF'});+ assert.equal(calls.length, 1);+});++test('root-scoped find uses CLI results and refreshes only that branch for reveal', async () => {+ const entry = {pid: 1, process_instance: 'one', source_window_id: 'w-1', path: [0, 0], role: 'button', name: 'Save'};+ const calls = [];+ let captures = 0;+ const cli = {+ capture: async args => {+ calls.push(args);+ return view(captures++ === 0 ? root : {role: 'group', ref_id: '@sone:e4', children: [{role: 'button', ref_id: '@sone:e5', identity_key: identityKey(entry)}]});+ },+ run: async args => { calls.push(args); return {matches: [{ref_id: '@sfind:e1', role: 'button', name: 'Save'}], total_matches: 1}; },+ entries: async () => new Map([['@sfind:e1', entry]]),+ };+ const inspector = createInspector(cli);+ const loaded = await inspector.execute({operation: 'snapshot', app: 'TextEdit'});+ const result = await inspector.execute({operation: 'find', revision: loaded.revision, ref: '@sone:e1', name: 'Save'});+ assert.deepEqual(calls[1], ['find', '--root', '@sone:e1', '--limit', '20', '--text=Save']);+ assert.deepEqual(calls[2].slice(0, 3), ['snapshot', '--root', '@sone:e1']);+ assert.equal(result.matches[0].treeRef, '@sone:e5');+ assert.equal(result.view.tree.children[1].ref_id, '@sone:e3');+ assert.equal(result.revision, 2);+});++test('find sends the selected field without changing the root, role, or exact flag', async () => {+ const calls = [];+ const cli = {+ capture: async () => view(root),+ run: async args => { calls.push(args); return {matches: [], total_matches: 0}; },+ entries: async () => new Map(),+ };+ const inspector = createInspector(cli);+ await inspector.execute({operation: 'snapshot', app: 'Finder'});+ for (const field of ['name', 'value', 'text']) {+ await inspector.execute({operation: 'find', revision: 1, ref: '@sone:e1', field, name: 'agent', role: 'textfield', exact: true});+ assert.deepEqual(calls.at(-1), ['find', '--root', '@sone:e1', '--limit', '20', `--${field}=agent`, '--role=textfield', '--exact']);+ }+});++test('an incomplete name search stays an error and allows an explicit value search', async () => {+ const calls = [];+ const inspector = createInspector({+ capture: async () => view(root),+ run: async args => {+ calls.push(args);+ if (args.includes('--name=agent')) throw Object.assign(new Error('Incomplete name evidence'), {code: 'TIMEOUT'});+ return {matches: [], total_matches: 0};+ },+ entries: async () => new Map(),+ });+ await inspector.execute({operation: 'snapshot', app: 'Finder'});+ const request = {operation: 'find', revision: 1, ref: '@sone:e1', field: 'name', name: 'agent'};+ await assert.rejects(inspector.execute(request), {code: 'TIMEOUT'});+ assert.equal(calls.length, 1);+ await inspector.execute({...request, field: 'value'});+ assert.equal(calls.length, 2);+ assert.ok(calls[1].includes('--value=agent'));+});++test('non-actionable groups are revealed by unique native geometry, never by name alone', async () => {+ const bounds = {x: 10, y: 20, width: 100, height: 30};+ const group = {role: 'group', bounds, children: [{role: 'textfield', value: 'Agent.pdf'}]};+ const tree = {role: 'list', ref_id: '@sone:e1', children: [group]};+ const cli = {+ capture: async () => view(tree),+ run: async () => ({matches: [{role: 'group', name: '(unnamed group)', bounds}], total_matches: 1}),+ entries: async () => new Map(),+ };+ const inspector = createInspector(cli);+ const loaded = await inspector.execute({operation: 'snapshot', app: 'AnyApp'});+ const request = {operation: 'find', revision: loaded.revision, ref: '@sone:e1', name: 'Agent', role: 'group'};+ const result = await inspector.execute(request);+ assert.equal(result.matches[0].treeRef, 'node:0.0');+ assert.equal(result.view.tree.children[0].ref_id, undefined);+ await assert.rejects(inspector.execute({operation: 'get', revision: result.revision, ref: 'node:0.0', property: 'value'}), {code: 'INVALID_ARGS'});++ tree.children.push({...group});+ const ambiguous = await inspector.execute({...request, revision: result.revision});+ assert.equal(ambiguous.matches[0].treeRef, null);+ tree.children = [{...group, bounds: {...bounds, x: 11}}];+ const moved = await inspector.execute({...request, revision: ambiguous.revision});+ assert.equal(moved.matches[0].treeRef, null);+});++test('a failed drill invalidates the view rather than leaving replaced refs usable', async () => {+ let captures = 0;+ const inspector = createInspector({capture: async () => { if (captures++) throw new Error('Capture failed'); return view(root); }});+ await inspector.execute({operation: 'snapshot', app: 'TextEdit'});+ await assert.rejects(inspector.execute({operation: 'expand', revision: 1, ref: '@sone:e1'}), {refreshRequired: true});+ await assert.rejects(inspector.execute({operation: 'get', revision: 1, ref: '@sone:e1', property: 'value'}), {code: 'STALE_VIEW'});+});diff --git a/tools/inspector/test/security.test.mjs b/tools/inspector/test/security.test.mjsnew file mode 100644index 000000000..e6f3bcf8f--- /dev/null+++ b/tools/inspector/test/security.test.mjs@@ -0,0 +1,43 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {createServer} from 'node:http';+import {authorize, listenAvailable, validateRequest} from '../http.mjs';++const token = 'local-test-token';+const request = (headers = {}) => ({headers: {host: '127.0.0.1:4317', origin: 'http://127.0.0.1:4317', 'x-inspector-token': token, ...headers}});++test('API requires the exact local host, origin, and capability token', () => {+ assert.doesNotThrow(() => authorize(request(), 4317, token));+ for (const headers of [+ {host: 'evil.test:4317'}, {origin: 'https://evil.test'}, {origin: undefined},+ {'x-inspector-token': undefined}, {'x-inspector-token': 'wrong'}, {host: '127.0.0.1:4318'},+ ]) assert.throws(() => authorize(request(headers), 4317, token));+});++test('only typed, read-only operations are accepted', () => {+ assert.deepEqual(validateRequest({operation: 'find', revision: 1, ref: '@sabc:e1', name: 'a; touch /tmp/no', role: 'button'}).name, 'a; touch /tmp/no');+ for (const body of [+ {operation: 'click'}, {operation: 'exec', command: 'whoami'},+ {operation: 'snapshot', app: '--headed'}, {operation: 'get', revision: 1, ref: '../secret', property: 'value'},+ {operation: 'get', revision: 1, ref: '@sabc:e1', property: '--trace'},+ {operation: 'find', revision: 1, name: 'x', extra: true},+ {operation: 'snapshot', app: 'x'.repeat(513)},+ ]) assert.throws(() => validateRequest(body));+});++test('find allows only the supported search fields', () => {+ const request = {operation: 'find', revision: 1, ref: '@sabc:e1', name: 'agent'};+ for (const field of ['name', 'value', 'text']) assert.doesNotThrow(() => validateRequest({...request, field}));+ for (const field of ['', 'trace', '--headed', null, 1, ['name']]) assert.throws(() => validateRequest({...request, field}));+});++test('a busy starting port falls back to another loopback port', async t => {+ const occupied = createServer();+ await listenAvailable(occupied, 0);+ const port = occupied.address().port;+ const server = createServer();+ t.after(() => { occupied.close(); server.close(); });+ await listenAvailable(server, port);+ assert.notEqual(server.address().port, port);+ assert.equal(server.address().address, '127.0.0.1');+});diff --git a/tools/inspector/test/server.test.mjs b/tools/inspector/test/server.test.mjsnew file mode 100644index 000000000..b315f5505--- /dev/null+++ b/tools/inspector/test/server.test.mjs@@ -0,0 +1,31 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {spawn} from 'node:child_process';+import {once} from 'node:events';+import {mkdtemp, readdir, rm} from 'node:fs/promises';+import {createConnection} from 'node:net';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {fileURLToPath} from 'node:url';++test('shutdown closes incomplete HTTP connections and removes private state', {timeout: 10000, skip: process.platform === 'win32'}, async t => {+ const root = await mkdtemp(join(tmpdir(), 'inspector-shutdown-'));+ const child = spawn(process.execPath, [fileURLToPath(new URL('../server.mjs', import.meta.url)), '--port', '0', '--bin', process.execPath, '--no-open'],+ {env: {...process.env, TMPDIR: root}, stdio: ['ignore', 'pipe', 'pipe']});+ t.after(async () => { child.kill('SIGKILL'); await rm(root, {recursive: true, force: true}); });+ const exited = once(child, 'exit');+ const port = await new Promise((resolve, reject) => {+ let output = '';+ child.stdout.on('data', data => { output += data; const match = /127\.0\.0\.1:(\d+)/.exec(output); if (match) resolve(Number(match[1])); });+ child.on('error', reject);+ child.on('exit', () => reject(new Error('Server exited before listening')));+ });+ assert.equal((await readdir(root)).length, 1);+ const connection = createConnection({host: '127.0.0.1', port});+ t.after(() => connection.destroy());+ await once(connection, 'connect');+ connection.write('GET / HTTP/1.1\r\n');+ child.kill('SIGTERM');+ assert.deepEqual(await exited, [0, null]);+ assert.deepEqual(await readdir(root), []);+});