Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
chore: stack the reviewed open PRs onto main (#257)
Lahfir9d7ba42a94bc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e671b639a..6e7e66c2d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -137,6 +137,11 @@ jobs:clang -fobjc-arc -Werror -framework AppKit -framework QuartzCore -framework CoreGraphics tests/native/cursor_overlay_trail_test.m -o "$RUNNER_TEMP/cursor-trail-test""$RUNNER_TEMP/cursor-trail-test"+ - name: Native AppKit inventory names+ run: |+ clang -fobjc-arc -fblocks -Wall -Wextra -Werror -framework AppKit tests/native/appkit_workspace_name_test.m -o "$RUNNER_TEMP/appkit-workspace-name-test"+ "$RUNNER_TEMP/appkit-workspace-name-test"+- name: Locator benchmark adapter contractrun: scripts/cargo-test-isolated-home.sh test --locked -p agent-desktop-core --example locator_benchmarkdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 34867a187..b3eb77a64 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## Unreleased++### Bug Fixes++* Preserve macOS applications with missing localized display names in the complete inventory, using their executable name or bundle identifier. Such applications no longer block unrelated app-scoped snapshots, window lists, and screenshots.+## [0.9.4](https://github.com/lahfir/agent-desktop/compare/v0.9.3...v0.9.4) (2026-09-23)diff --git a/Cargo.toml b/Cargo.tomlindex 912276fc9..03b5015d1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -12,7 +12,7 @@ version = "0.9.4" # x-release-please-version[workspace.dependencies]clap = { version = "4.6", features = ["derive"] }serde = { version = "1.0", features = ["derive"] }-serde_json = "1.0"+serde_json = { version = "1.0", features = ["float_roundtrip"] }thiserror = "2.0"tracing = "0.1"tracing-subscriber = { version = "0.3", features = ["env-filter"] }diff --git a/README.md b/README.mdindex 135f96c21..3fe6fe0ec 100644--- a/README.md+++ b/README.md@@ -74,6 +74,8 @@ cp target/release/agent-desktop /usr/local/bin/Requires Rust 1.89+ and macOS 13.0+.+On macOS, application names use AppKit's localized display name. If it is unavailable, the inventory uses the executable name, then the bundle identifier, while retaining the application's process identity.+### PermissionsmacOS requires Accessibility permission. Screenshots also require Screen Recording permission, and the Notification Center opener requires Automation permission for System Events. Plain permission checks never prompt. Request missing permissions in a bounded isolated helper with:diff --git a/crates/core/src/deadline.rs b/crates/core/src/deadline.rsindex 0d8aa8103..95a967378 100644--- a/crates/core/src/deadline.rs+++ b/crates/core/src/deadline.rs@@ -112,6 +112,23 @@ impl Deadline {}}+ /// Moves the expiry back by time spent on work that is not charged to this+ /// operation. An inherited deadline still bounds the result.+ pub(crate) fn extended_by(self, pause: Duration) -> Self {+ let extended = Self {+ expires_at: self+ .expires_at+ .checked_add(pause)+ .unwrap_or(self.expires_at),+ ..self+ };+ INHERITED_DEADLINE.with(|inherited| {+ inherited+ .get()+ .map_or(extended, |parent| extended.min_expiry(parent))+ })+ }+pub fn is_expired(self) -> bool {self.remaining().is_zero()}diff --git a/crates/core/src/deadline_tests.rs b/crates/core/src/deadline_tests.rsindex b629b51f7..7d1c40463 100644--- a/crates/core/src/deadline_tests.rs+++ b/crates/core/src/deadline_tests.rs@@ -46,3 +46,25 @@ fn detached_recovery_budget_survives_an_expired_inherited_scope() {assert!(!cleanup.is_expired());assert!(cleanup.remaining() > Duration::from_millis(50));}++#[test]+fn extension_moves_the_expiry_and_keeps_the_timeout() {+ let deadline = Deadline::after(1_000).unwrap();++ let extended = deadline.extended_by(Duration::from_millis(500));++ let longer = extended.remaining();+ assert!(longer >= deadline.remaining() + Duration::from_millis(500));+ assert_eq!(extended.timeout_ms(), 1_000);+}++#[test]+fn extension_stays_inside_an_inherited_deadline() {+ let inherited = Deadline::after(25).unwrap();+ let _scope = super::enter_scope(Some(inherited));+ let local = Deadline::after(20).unwrap();++ let extended = local.extended_by(Duration::from_secs(5));++ assert!(extended.remaining() <= Duration::from_millis(25));+}diff --git a/crates/core/src/refs_serde_tests.rs b/crates/core/src/refs_serde_tests.rsindex bd4a763d1..7fd7c7fa3 100644--- a/crates/core/src/refs_serde_tests.rs+++ b/crates/core/src/refs_serde_tests.rs@@ -207,3 +207,28 @@ fn ref_entry_full_roundtrip_preserves_all_fields() {assert_eq!(back, original);}++#[test]+fn refmap_round_trip_keeps_bounds_on_a_rounding_boundary() {+ let bounds = crate::Rect {+ x: 505.24,+ y: 505.04499999999996,+ width: 1168.09,+ height: 25.024999999999977,+ };+ let mut entry = minimal_entry("button");+ entry.geometry = crate::RefGeometry {+ bounds: Some(bounds),+ bounds_hash: bounds.bounds_hash(),+ };+ let mut map = RefMap::new();+ let ref_id = map.try_allocate(entry).unwrap();++ let json = map.serialize_with_size_check().unwrap();+ assert!(json.contains("505.04499999999996"), "json={json}");+ let restored: RefMap = serde_json::from_str(&json).unwrap();++ restored.validate().unwrap();+ let restored_bounds = restored.get(&ref_id).unwrap().geometry.bounds.unwrap();+ assert_eq!(restored_bounds.y.to_bits(), bounds.y.to_bits());+}diff --git a/crates/core/src/renderer_accessibility.rs b/crates/core/src/renderer_accessibility.rsindex deea11212..6d2d2d61f 100644--- a/crates/core/src/renderer_accessibility.rs+++ b/crates/core/src/renderer_accessibility.rs@@ -18,16 +18,15 @@ pub(crate) fn observe_tree(root: ObservationRoot<'_>,request: &ObservationRequest,) -> Result<ObservedTree, AppError> {+ let mut request = *request;let mut activated = false;let mut retry_delay = INITIAL_ACTIVATION_RETRY;loop {- match adapter.observe_tree(root, request) {+ match adapter.observe_tree(root, &request) {Ok(tree) => return Ok(tree),Err(error) if error.requires_renderer_accessibility_activation() => {if !activated {- let acquired = adapter.acquire_interaction_lease(request.deadline)?;- adapter.activate_renderer_accessibility(root_process(root)?, &acquired)?;- drop(acquired);+ request.deadline = activate(adapter, root, request.deadline)?;activated = true;}let remaining = request.deadline.remaining();@@ -42,6 +41,27 @@ pub(crate) fn observe_tree(}}+fn activate(+ adapter: &dyn PlatformAdapter,+ root: ObservationRoot<'_>,+ observing: crate::Deadline,+) -> Result<crate::Deadline, AppError> {+ let started = std::time::Instant::now();+ switch_on(adapter, root).map_err(|error| match error {+ AppError::Adapter(ref adapter_error) if adapter_error.code == crate::ErrorCode::Timeout => {+ observing.timeout_error().into()+ }+ other => other,+ })?;+ Ok(observing.extended_by(started.elapsed()))+}++fn switch_on(adapter: &dyn PlatformAdapter, root: ObservationRoot<'_>) -> Result<(), AppError> {+ let acquired = adapter.acquire_interaction_lease(crate::Deadline::standard()?)?;+ adapter.activate_renderer_accessibility(root_process(root)?, &acquired)?;+ Ok(())+}+fn root_process(root: ObservationRoot<'_>) -> Result<crate::ProcessIdentity, AppError> {match root {ObservationRoot::Window(window) => windowdiff --git a/crates/core/src/renderer_accessibility_tests.rs b/crates/core/src/renderer_accessibility_tests.rsindex b6f8fa997..d2b4912bc 100644--- a/crates/core/src/renderer_accessibility_tests.rs+++ b/crates/core/src/renderer_accessibility_tests.rs@@ -169,3 +169,202 @@ fn a_renderer_that_never_activates_is_not_re_walked_continuously() {over a hundred of them, got {attempts}");}++struct SwitchAdapter {+ needs: std::time::Duration,+ takes: std::time::Duration,+ switched: AtomicBool,+ offered_ms: std::sync::atomic::AtomicU64,+ walks: std::sync::Mutex<Vec<Walk>>,+}++struct Walk {+ expires_no_earlier_than: std::time::Instant,+ expires_no_later_than: std::time::Instant,+ timeout_ms: u64,+}++impl ObservationOps for SwitchAdapter {+ fn observe_tree(+ &self,+ root: ObservationRoot<'_>,+ request: &ObservationRequest,+ ) -> Result<ObservedTree, crate::AdapterError> {+ let before = std::time::Instant::now();+ let remaining = request.deadline.remaining();+ let after = std::time::Instant::now();+ let mut walks = self.walks.lock().unwrap();+ walks.push(Walk {+ expires_no_earlier_than: before + remaining,+ expires_no_later_than: after + remaining,+ timeout_ms: request.deadline.timeout_ms(),+ });+ if walks.len() == 1 {+ return Err(+ crate::AdapterError::renderer_accessibility_activation_required(+ "activation required",+ ),+ );+ }+ crate::adapter::observed_tree(+ &root,+ crate::AccessibilityNode {+ ref_id: None,+ role: "window".into(),+ identity: Default::default(),+ presentation: Default::default(),+ children_count: None,+ subtree_truncated: false,+ children: Vec::new(),+ },+ )+ }+}++impl ActionOps for SwitchAdapter {}+impl InputOps for SwitchAdapter {}++impl SystemOps for SwitchAdapter {+ fn acquire_interaction_lease(+ &self,+ deadline: crate::Deadline,+ ) -> Result<crate::InteractionLease, crate::AdapterError> {+ crate::InteractionLease::guarded(deadline, ())+ }++ fn activate_renderer_accessibility(+ &self,+ _process: crate::ProcessIdentity,+ lease: &crate::InteractionLease,+ ) -> Result<(), crate::AdapterError> {+ self.offered_ms+ .store(lease.deadline().remaining_ms(), Ordering::SeqCst);+ if lease.deadline().remaining() <= self.needs {+ return Err(lease.deadline().timeout_error());+ }+ std::thread::sleep(self.takes);+ self.switched.store(true, Ordering::SeqCst);+ Ok(())+ }+}++fn switch(needs_ms: u64, takes_ms: u64) -> SwitchAdapter {+ SwitchAdapter {+ needs: std::time::Duration::from_millis(needs_ms),+ takes: std::time::Duration::from_millis(takes_ms),+ switched: AtomicBool::new(false),+ offered_ms: std::sync::atomic::AtomicU64::new(0),+ walks: std::sync::Mutex::new(Vec::new()),+ }+}++fn renderer_window() -> crate::WindowInfo {+ crate::WindowInfo {+ id: "w-1".into(),+ title: "Renderer".into(),+ app: "Renderer".into(),+ pid: crate::ProcessId::new(42),+ process_instance: Some("instance-1".into()),+ bounds: None,+ state: Default::default(),+ }+}++fn snapshot_request(deadline: crate::Deadline) -> ObservationRequest {+ ObservationRequest::snapshot(&crate::TreeOptions::default(), deadline)+ .validate()+ .unwrap()+}++#[test]+fn time_spent_switching_is_given_back_to_the_observation() {+ let adapter = switch(0, 300);+ let window = renderer_window();+ let request = snapshot_request(crate::Deadline::after(60_000).unwrap());++ observe_tree(&adapter, ObservationRoot::Window(&window), &request)+ .expect("the walk after the switch has the budget the first walk left");++ let walks = adapter.walks.lock().unwrap();+ let given_back = walks[1]+ .expires_no_later_than+ .duration_since(walks[0].expires_no_earlier_than);+ assert!(+ given_back >= adapter.takes,+ "the switch took {:?} and the observation was given back {given_back:?}",+ adapter.takes+ );+ assert_eq!(+ walks[1].timeout_ms, 60_000,+ "the resumed deadline still describes the operation it belongs to"+ );+ assert!(+ adapter.offered_ms.load(Ordering::SeqCst) <= crate::DEFAULT_OPERATION_TIMEOUT_MS,+ "a long operation does not lend the switch its whole timeout"+ );+}++#[test]+fn a_spent_observation_still_switches_so_the_next_one_is_ready() {+ let adapter = switch(1_000, 0);+ let window = renderer_window();+ let spent = crate::Deadline::after(500)+ .unwrap()+ .capped(std::time::Duration::ZERO);++ let error = observe_tree(+ &adapter,+ ObservationRoot::Window(&window),+ &snapshot_request(spent),+ )+ .expect_err("an observation with nothing left does not walk again");++ assert!(matches!(+ error,+ AppError::Adapter(ref adapter_error) if adapter_error.code == crate::ErrorCode::Timeout+ ));+ assert!(+ adapter.switched.load(Ordering::SeqCst),+ "the switch needs 1000ms and was offered {}ms, so it would be refused every time",+ adapter.offered_ms.load(Ordering::SeqCst)+ );+ assert_eq!(adapter.walks.lock().unwrap().len(), 1);+}++#[test]+fn a_refused_switch_reports_the_operation_budget_and_is_not_retried() {+ let adapter = switch(10_000, 0);+ let window = renderer_window();+ let request = snapshot_request(crate::Deadline::after(3_000).unwrap());++ let error = observe_tree(&adapter, ObservationRoot::Window(&window), &request)+ .expect_err("a switch that cannot run fails the observation");++ let AppError::Adapter(error) = error else {+ panic!("expected an adapter error");+ };+ assert_eq!(error.code, crate::ErrorCode::Timeout);+ let details = error.details.expect("a timeout describes its deadline");+ assert_eq!(details["timeout_ms"], 3_000);+ assert!(!adapter.switched.load(Ordering::SeqCst));+ assert_eq!(adapter.walks.lock().unwrap().len(), 1);+}++#[test]+fn the_credit_for_switch_time_stays_inside_an_inherited_deadline() {+ let adapter = switch(0, 300);+ let window = renderer_window();+ let request = snapshot_request(crate::Deadline::after(60_000).unwrap());+ let parent = crate::Deadline::detached_after(1_000).unwrap();+ let bound = std::time::Instant::now() + std::time::Duration::from_millis(1_000);+ let _scope = crate::deadline::enter_scope(Some(parent));++ observe_tree(&adapter, ObservationRoot::Window(&window), &request)+ .expect("the walk after the switch still fits the inherited deadline");++ let walks = adapter.walks.lock().unwrap();+ assert!(+ walks[1].expires_no_earlier_than <= bound,+ "the resumed walk outlives the deadline the command inherited"+ );+}diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rsindex 1627d8135..0e5c5d155 100644--- a/crates/core/src/snapshot.rs+++ b/crates/core/src/snapshot.rs@@ -37,14 +37,11 @@ pub fn build(window_id: Option<&str>,deadline: crate::Deadline,) -> Result<SnapshotResult, AppError> {- let window = resolve_window_for_surface(adapter, app_name, window_id, opts.surface, deadline)?;+ let windows = surface_windows(adapter, app_name, window_id, opts.surface, deadline)?;let observation_options = opts.with_ref_identity_bounds();- let (raw_tree, complete, nodes_observed) = crate::renderer_accessibility::observe_tree(- adapter,- ObservationRoot::Window(&window),- &ObservationRequest::snapshot(&observation_options, deadline).validate()?,- )?- .into_accessibility_tree_partial()?;+ let request = ObservationRequest::snapshot(&observation_options, deadline).validate()?;+ let (window, observed) = observe_first_owner(adapter, windows, &request)?;+ let (raw_tree, complete, nodes_observed) = observed.into_accessibility_tree_partial()?;let mut refmap = RefMap::new();let config = RefAllocConfig {@@ -106,6 +103,61 @@ pub(crate) fn resolve_window_for_surface()}+fn surface_windows(+ adapter: &dyn PlatformAdapter,+ app_name: Option<&str>,+ window_id: Option<&str>,+ surface: crate::SnapshotSurface,+ deadline: crate::Deadline,+) -> Result<Vec<WindowInfo>, AppError> {+ use crate::SnapshotSurface::{Alert, Popover, Sheet};+ if window_id.is_none() && matches!(surface, Sheet | Popover | Alert) {+ let mut windows = match app_name {+ Some(_) => windows_for_app(adapter, app_name, deadline)?,+ None => frontmost_process_windows(adapter, surface, deadline)?,+ };+ windows.retain(|window| window.state.accessible);+ let windows = crate::window_lookup::surface_owner_order(windows);+ if !windows.is_empty() {+ return Ok(windows);+ }+ }+ Ok(vec![resolve_window_for_surface(+ adapter, app_name, window_id, surface, deadline,+ )?])+}++fn frontmost_process_windows(+ adapter: &dyn PlatformAdapter,+ surface: crate::SnapshotSurface,+ deadline: crate::Deadline,+) -> Result<Vec<WindowInfo>, AppError> {+ let owner = resolve_window_for_surface(adapter, None, None, surface, deadline)?;+ let mut windows = windows_for_app(adapter, Some(owner.app.as_str()), deadline)?;+ windows.retain(|window| window.pid == owner.pid);+ if windows.is_empty() {+ windows.push(owner);+ }+ Ok(windows)+}++fn observe_first_owner(+ adapter: &dyn PlatformAdapter,+ windows: Vec<WindowInfo>,+ request: &ObservationRequest,+) -> Result<(WindowInfo, crate::live_locator::ObservedTree), AppError> {+ let mut windows = windows.into_iter().peekable();+ while let Some(window) = windows.next() {+ let root = ObservationRoot::Window(&window);+ match crate::renderer_accessibility::observe_tree(adapter, root, request) {+ Err(AppError::Adapter(error))+ if error.code == crate::ErrorCode::ElementNotFound && windows.peek().is_some() => {}+ result => return result.map(|observed| (window, observed)),+ }+ }+ Err(crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No window to observe").into())+}+fn windows_for_app(adapter: &dyn PlatformAdapter,app_name: Option<&str>,diff --git a/crates/core/src/snapshot_window_tests.rs b/crates/core/src/snapshot_window_tests.rsindex 4f7c843ab..bcb4030f9 100644--- a/crates/core/src/snapshot_window_tests.rs+++ b/crates/core/src/snapshot_window_tests.rs@@ -62,3 +62,150 @@ fn running_application_without_a_window_is_not_reported_as_absent() {assert_eq!(error.code(), "WINDOW_NOT_FOUND");}++struct SurfaceAdapter {+ windows: Vec<WindowInfo>,+ surface_on: &'static str,+}++impl ObservationOps for SurfaceAdapter {+ fn list_windows(+ &self,+ filter: &WindowFilter,+ _deadline: crate::Deadline,+ ) -> Result<Vec<WindowInfo>, crate::AdapterError> {+ Ok(self+ .windows+ .iter()+ .filter(|window| !filter.focused_only || window.state.is_focused)+ .cloned()+ .collect())+ }++ fn observe_tree(+ &self,+ root: ObservationRoot<'_>,+ _request: &ObservationRequest,+ ) -> Result<crate::live_locator::ObservedTree, crate::AdapterError> {+ let ObservationRoot::Window(window) = root else {+ panic!("a snapshot observes a window root");+ };+ if !window.state.accessible {+ return Err(crate::AdapterError::new(+ crate::ErrorCode::ActionNotSupported,+ "Window exists but is not exposed through accessibility",+ ));+ }+ if window.id != self.surface_on {+ return Err(crate::AdapterError::new(+ crate::ErrorCode::ElementNotFound,+ "No open alert in this window",+ ));+ }+ crate::adapter::observed_tree(+ &root,+ AccessibilityNode {+ ref_id: None,+ role: "sheet".into(),+ identity: Default::default(),+ presentation: Default::default(),+ children_count: None,+ subtree_truncated: false,+ children: Vec::new(),+ },+ )+ }+}++impl ActionOps for SurfaceAdapter {}+impl InputOps for SurfaceAdapter {}+impl SystemOps for SurfaceAdapter {}++fn app_window(id: &str, focused: bool) -> WindowInfo {+ WindowInfo {+ id: id.into(),+ state: crate::WindowState {+ is_focused: focused,+ visible: Some(true),+ ..Default::default()+ },+ ..window("TextEdit")+ }+}++fn alert_options() -> TreeOptions {+ TreeOptions {+ surface: crate::SnapshotSurface::Alert,+ ..Default::default()+ }+}++#[test]+fn an_unpinned_alert_is_found_on_whichever_window_holds_it() {+ let mut sheet_window = app_window("w-sheet", false);+ sheet_window.state.accessible = false;+ let adapter = SurfaceAdapter {+ windows: vec![+ sheet_window,+ app_window("w-1", true),+ app_window("w-2", false),+ ],+ surface_on: "w-2",+ };++ let result = build(+ &adapter,+ &alert_options(),+ Some("TextEdit"),+ None,+ crate::Deadline::after(1_000).unwrap(),+ )+ .unwrap();++ assert_eq!(result.window.id, "w-2");+}++#[test]+fn a_pinned_window_never_reads_another_windows_alert() {+ let adapter = SurfaceAdapter {+ windows: vec![app_window("w-1", true), app_window("w-2", false)],+ surface_on: "w-2",+ };++ let error = build(+ &adapter,+ &alert_options(),+ Some("TextEdit"),+ Some("w-1"),+ crate::Deadline::after(1_000).unwrap(),+ )+ .err()+ .expect("the pinned window has no alert");++ assert_eq!(error.code(), "ELEMENT_NOT_FOUND");+}++#[test]+fn an_alert_without_app_is_found_on_another_window_of_the_frontmost_app() {+ let mut other_process = app_window("w-9", false);+ other_process.pid = crate::ProcessId::new(99);+ let adapter = SurfaceAdapter {+ windows: vec![+ app_window("w-1", true),+ other_process,+ app_window("w-2", false),+ ],+ surface_on: "w-2",+ };++ let result = build(+ &adapter,+ &alert_options(),+ None,+ None,+ crate::Deadline::after(1_000).unwrap(),+ )+ .unwrap();++ assert_eq!(result.window.id, "w-2");+}diff --git a/crates/core/src/window_lookup.rs b/crates/core/src/window_lookup.rsindex 7d7fefb0d..9f8100280 100644--- a/crates/core/src/window_lookup.rs+++ b/crates/core/src/window_lookup.rs@@ -71,6 +71,13 @@ pub(crate) fn select_surface_owner(Ok(candidates.swap_remove(best))}+/// Orders an app's windows the way a surface owner is chosen: focused first,+/// then visible, then the rest, each group in the order the platform listed.+pub(crate) fn surface_owner_order(mut candidates: Vec<WindowInfo>) -> Vec<WindowInfo> {+ candidates.sort_by_key(|window| (!window.state.is_focused, window.state.visible != Some(true)));+ candidates+}+pub(crate) fn select_window(mut candidates: Vec<WindowInfo>,empty_error: crate::AdapterError,diff --git a/crates/macos/src/actions/toggle_state.rs b/crates/macos/src/actions/toggle_state.rsindex 4ad5a4f16..aacef684d 100644--- a/crates/macos/src/actions/toggle_state.rs+++ b/crates/macos/src/actions/toggle_state.rs@@ -37,12 +37,7 @@ pub(crate) fn toggle());}let before = read_value(el, deadline)?;- let ctx = ChainContext {- dynamic_value: None,- verified_point: None,- deadline,- };- let mut steps = execute_chain(el, &chain_defs::SEMANTIC_CLICK_CHAIN, &ctx, policy)?;+ let mut steps = semantic_click(el, policy, deadline)?;let verified = if let Some(before) = before {wait_for_value_change(el, &before, deadline).map_err(after_delivery)?;true@@ -73,32 +68,139 @@ pub(crate) fn check_uncheck().with_suggestion("Only works on checkboxes, switches, and radio buttons."));}- if checked_state(el, deadline)? == Some(want_checked) {- return Ok(vec![already_in_state_step()]);- }- prepare(el, deadline)?;- if ax_helpers::is_attr_settable(el, "AXValue", deadline)? && {- prepare(el, deadline)?;- ax_helpers::set_ax_bool_or_err(el, "AXValue", want_checked, deadline)?- } {- wait_for_checked_state(el, want_checked, deadline).map_err(after_delivery)?;- return Ok(vec![- ActionStep::succeeded("AXValue")- .with_mechanism(StepMechanism::SemanticApi)- .with_verified(true),- ]);- }+ let press_after_ignored_write = want_checked+ || agent_desktop_core::Role::from_token(role.as_deref().unwrap_or_default())+ != agent_desktop_core::Role::RadioButton;+ run_check(+ &mut LiveToggleTarget {+ el,+ policy,+ deadline,+ },+ want_checked,+ press_after_ignored_write,+ )+}++fn semantic_click(+ el: &AXElement,+ policy: InteractionPolicy,+ deadline: Deadline,+) -> Result<Vec<ActionStep>, AdapterError> {let ctx = ChainContext {dynamic_value: None,verified_point: None,deadline,};- let mut steps = execute_chain(el, &chain_defs::SEMANTIC_CLICK_CHAIN, &ctx, policy)?;- wait_for_checked_state(el, want_checked, deadline).map_err(after_delivery)?;+ execute_chain(el, &chain_defs::SEMANTIC_CLICK_CHAIN, &ctx, policy)+}++trait CheckTarget {+ fn checked(&mut self) -> Result<Option<bool>, AdapterError>;+ fn value_settable(&mut self) -> Result<bool, AdapterError>;+ fn write_value(&mut self, want_checked: bool) -> Result<bool, AdapterError>;+ fn settle(&mut self, want_checked: bool) -> Result<Option<bool>, AdapterError>;+ fn click(&mut self) -> Result<Vec<ActionStep>, AdapterError>;+}++struct LiveToggleTarget<'a> {+ el: &'a AXElement,+ policy: InteractionPolicy,+ deadline: Deadline,+}++impl CheckTarget for LiveToggleTarget<'_> {+ fn checked(&mut self) -> Result<Option<bool>, AdapterError> {+ checked_state(self.el, self.deadline)+ }++ fn value_settable(&mut self) -> Result<bool, AdapterError> {+ prepare(self.el, self.deadline)?;+ ax_helpers::is_attr_settable(self.el, "AXValue", self.deadline)+ }++ fn write_value(&mut self, want_checked: bool) -> Result<bool, AdapterError> {+ prepare(self.el, self.deadline)?;+ ax_helpers::set_ax_bool_or_err(self.el, "AXValue", want_checked, self.deadline)+ }++ fn settle(&mut self, want_checked: bool) -> Result<Option<bool>, AdapterError> {+ settle_checked_state(self.el, want_checked, self.deadline)+ }++ fn click(&mut self) -> Result<Vec<ActionStep>, AdapterError> {+ semantic_click(self.el, self.policy, self.deadline)+ }+}++#[path = "toggle_state_radio.rs"]+mod radio;++fn run_check(+ target: &mut impl CheckTarget,+ want_checked: bool,+ press_after_ignored_write: bool,+) -> Result<Vec<ActionStep>, AdapterError> {+ if target.checked()? == Some(want_checked) {+ return Ok(vec![already_in_state_step()]);+ }+ let mut steps = Vec::new();+ let mut wrote = false;+ if target.value_settable()? {+ if target.write_value(want_checked)? {+ wrote = true;+ } else {+ steps.push(ignored_write_step());+ }+ }+ if wrote {+ if target.settle(want_checked).map_err(after_delivery)? == Some(want_checked) {+ return Ok(vec![value_write_step()]);+ }+ match target.checked().map_err(after_delivery)? {+ Some(state) if state == want_checked => return Ok(vec![value_write_step()]),+ Some(_) if press_after_ignored_write => steps.push(ignored_write_step()),+ Some(_) => return Err(after_delivery(radio::uncheck_unsupported())),+ None => return Err(after_delivery(state_not_reached())),+ }+ }+ if !wrote && !press_after_ignored_write {+ return radio::refuse_uncheck(target, want_checked, !steps.is_empty());+ }+ let clicked = target+ .click()+ .map_err(|error| if wrote { after_delivery(error) } else { error })?;+ steps.extend(clicked);+ if target.settle(want_checked).map_err(after_delivery)? != Some(want_checked) {+ return Err(after_delivery(state_not_reached()));+ }mark_last_verified(&mut steps, true);Ok(steps)}+fn ignored_write_step() -> ActionStep {+ ActionStep::attempted("AXValue").with_mechanism(StepMechanism::SemanticApi)+}++fn value_write_step() -> ActionStep {+ ActionStep::succeeded("AXValue")+ .with_mechanism(StepMechanism::SemanticApi)+ .with_verified(true)+}++fn state_not_reached() -> AdapterError {+ AdapterError::new(+ ErrorCode::ActionFailed,+ "check/uncheck did not reach the requested state",+ )+ .with_details(serde_json::json!({+ "verification": "requested_checked_state_not_observed"+ }))+ .with_suggestion(+ "Refresh the snapshot and inspect the checked state before deciding whether to retry.",+ )+}+fn already_in_state_step() -> ActionStep {ActionStep::skipped("AlreadyInState").with_verified(true)}@@ -117,27 +219,16 @@ fn checked_state(el: &AXElement, deadline: Deadline) -> Result<Option<bool>, AdaOk(read_value(el, deadline)?.and_then(|value| parse_checked_value(&value)))}-fn wait_for_checked_state(+fn settle_checked_state(el: &AXElement,want_checked: bool,action_deadline: Deadline,-) -> Result<(), AdapterError> {+) -> Result<Option<bool>, AdapterError> {let deadline = verification_deadline(action_deadline)?;loop {- if checked_state(el, action_deadline)? == Some(want_checked) {- return Ok(());- }- if std::time::Instant::now() >= deadline {- return Err(AdapterError::new(- ErrorCode::ActionFailed,- "check/uncheck did not reach the requested state",- )- .with_details(serde_json::json!({- "verification": "requested_checked_state_not_observed"- }))- .with_suggestion(- "Refresh the snapshot and inspect the checked state before deciding whether to retry.",- ));+ let state = checked_state(el, action_deadline)?;+ if state == Some(want_checked) || std::time::Instant::now() >= deadline {+ return Ok(state);}sleep_poll(deadline, action_deadline)?;}@@ -292,3 +383,7 @@ mod tests {assert_eq!(step.verified(), Some(true));}}++#[cfg(test)]+#[path = "toggle_state_check_tests.rs"]+mod check_tests;diff --git a/crates/macos/src/actions/toggle_state_check_tests.rs b/crates/macos/src/actions/toggle_state_check_tests.rsnew file mode 100644index 000000000..a0004a6dd--- /dev/null+++ b/crates/macos/src/actions/toggle_state_check_tests.rs@@ -0,0 +1,214 @@+use std::collections::VecDeque;++use agent_desktop_core::{+ ActionStep, AdapterError, DeliverySemantics, ErrorCode, action_step_outcome::ActionStepOutcome,+};++use super::{CheckTarget, run_check};++struct Scripted {+ reads: VecDeque<Option<bool>>,+ settles: VecDeque<Option<bool>>,+ settable: bool,+ write_accepted: bool,+ writes: usize,+ clicks: usize,+}++impl Scripted {+ fn new(reads: &[Option<bool>], settles: &[Option<bool>], settable: bool) -> Self {+ Self {+ reads: reads.iter().copied().collect(),+ settles: settles.iter().copied().collect(),+ settable,+ write_accepted: true,+ writes: 0,+ clicks: 0,+ }+ }+}++impl CheckTarget for Scripted {+ fn checked(&mut self) -> Result<Option<bool>, AdapterError> {+ Ok(self.reads.pop_front().expect("unexpected state read"))+ }++ fn value_settable(&mut self) -> Result<bool, AdapterError> {+ Ok(self.settable)+ }++ fn write_value(&mut self, _want_checked: bool) -> Result<bool, AdapterError> {+ self.writes += 1;+ Ok(self.write_accepted)+ }++ fn settle(&mut self, _want_checked: bool) -> Result<Option<bool>, AdapterError> {+ Ok(self.settles.pop_front().expect("unexpected settle"))+ }++ fn click(&mut self) -> Result<Vec<ActionStep>, AdapterError> {+ self.clicks += 1;+ Ok(vec![ActionStep::succeeded("AXPress").with_verified(false)])+ }+}++fn labels(steps: &[ActionStep]) -> Vec<(String, Option<bool>)> {+ steps+ .iter()+ .map(|step| (step.label().to_string(), step.verified()))+ .collect()+}++#[test]+fn already_checked_sends_nothing() {+ let mut target = Scripted::new(&[Some(true)], &[], true);+ let steps = run_check(&mut target, true, true).unwrap();+ assert_eq!(labels(&steps), [("AlreadyInState".into(), Some(true))]);+ assert_eq!((target.writes, target.clicks), (0, 0));+}++#[test]+fn already_unchecked_sends_nothing() {+ let mut target = Scripted::new(&[Some(false)], &[], true);+ let steps = run_check(&mut target, false, true).unwrap();+ assert_eq!(labels(&steps), [("AlreadyInState".into(), Some(true))]);+ assert_eq!((target.writes, target.clicks), (0, 0));+}++#[test]+fn a_value_write_that_lands_does_not_click() {+ let mut target = Scripted::new(&[Some(false)], &[Some(true)], true);+ let steps = run_check(&mut target, true, true).unwrap();+ assert_eq!(labels(&steps), [("AXValue".into(), Some(true))]);+ assert_eq!((target.writes, target.clicks), (1, 0));+}++#[test]+fn an_accepted_write_that_changes_nothing_falls_back_to_one_click() {+ let mut target = Scripted::new(+ &[Some(false), Some(false)],+ &[Some(false), Some(true)],+ true,+ );+ let steps = run_check(&mut target, true, true).unwrap();+ assert_eq!(+ labels(&steps),+ [("AXValue".into(), None), ("AXPress".into(), Some(true))]+ );+ assert!(matches!(steps[0].outcome, ActionStepOutcome::Attempted));+ assert_eq!((target.writes, target.clicks), (1, 1));+}++#[test]+fn a_write_that_lands_late_is_not_clicked_back() {+ let mut target = Scripted::new(&[Some(false), Some(true)], &[Some(false)], true);+ let steps = run_check(&mut target, true, true).unwrap();+ assert_eq!(labels(&steps), [("AXValue".into(), Some(true))]);+ assert_eq!(target.clicks, 0);+}++#[test]+fn an_indeterminate_state_after_the_write_stops_without_clicking() {+ let mut target = Scripted::new(&[Some(false), None], &[Some(false)], true);+ let error = run_check(&mut target, true, true).unwrap_err();+ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ assert_eq!(target.clicks, 0);+}++#[test]+fn a_click_that_does_not_reach_the_state_fails_as_delivered_unverified() {+ let mut target = Scripted::new(+ &[Some(false), Some(false)],+ &[Some(false), Some(false)],+ true,+ );+ let error = run_check(&mut target, true, true).unwrap_err();+ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ assert_eq!(target.clicks, 1);+}++#[test]+fn an_element_without_a_settable_value_is_clicked_directly() {+ let mut target = Scripted::new(&[Some(true)], &[Some(false)], false);+ let steps = run_check(&mut target, false, true).unwrap();+ assert_eq!(labels(&steps), [("AXPress".into(), Some(true))]);+ assert_eq!((target.writes, target.clicks), (0, 1));+}++#[test]+fn unchecking_a_radio_that_ignores_the_write_does_not_press_it() {+ let mut target = Scripted::new(&[Some(true), Some(true)], &[Some(true)], true);+ let error = run_check(&mut target, false, false).unwrap_err();+ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ assert_eq!(target.clicks, 0);+}++#[test]+fn a_refused_write_records_the_attempted_step_before_the_click() {+ let mut target = Scripted::new(&[Some(false)], &[Some(true)], true);+ target.write_accepted = false;+ let steps = run_check(&mut target, true, true).unwrap();+ assert_eq!(+ labels(&steps),+ [("AXValue".into(), None), ("AXPress".into(), Some(true))]+ );+ assert!(matches!(steps[0].outcome, ActionStepOutcome::Attempted));+}++#[test]+fn unchecking_a_radio_that_ignores_the_write_suggests_a_sibling() {+ let mut target = Scripted::new(&[Some(true), Some(true)], &[Some(true)], true);+ let error = run_check(&mut target, false, false).unwrap_err();+ let suggestion = error.suggestion.as_deref().unwrap_or_default();+ assert!(suggestion.contains("sibling radio"), "{suggestion}");+}++#[test]+fn unchecking_a_radio_whose_value_is_not_settable_sends_nothing() {+ let mut target = Scripted::new(&[Some(true)], &[], false);+ let error = run_check(&mut target, false, false).unwrap_err();+ assert!(+ error+ .suggestion+ .unwrap_or_default()+ .contains("sibling radio")+ );+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());+ assert_eq!((target.writes, target.clicks), (0, 0));+}++#[test]+fn unchecking_a_radio_that_refuses_the_write_does_not_press_it() {+ let mut target = Scripted::new(&[Some(true), Some(true)], &[], true);+ target.write_accepted = false;+ let error = run_check(&mut target, false, false).unwrap_err();+ assert!(+ error+ .suggestion+ .unwrap_or_default()+ .contains("sibling radio")+ );+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());+ assert_eq!((target.writes, target.clicks), (1, 0));+}++#[test]+fn a_radio_that_refuses_the_write_but_changes_reports_the_change() {+ let mut target = Scripted::new(&[Some(true), Some(false)], &[], true);+ target.write_accepted = false;+ let steps = run_check(&mut target, false, false).unwrap();+ assert_eq!(labels(&steps), [("AXValue".into(), Some(true))]);+ assert_eq!(target.clicks, 0);+}++#[test]+fn a_radio_whose_state_is_unreadable_after_a_refused_write_is_not_called_undelivered() {+ let mut target = Scripted::new(&[Some(true), None], &[], true);+ target.write_accepted = false;+ let error = run_check(&mut target, false, false).unwrap_err();+ assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());+ assert_eq!(target.clicks, 0);+}diff --git a/crates/macos/src/actions/toggle_state_radio.rs b/crates/macos/src/actions/toggle_state_radio.rsnew file mode 100644index 000000000..0296b1317--- /dev/null+++ b/crates/macos/src/actions/toggle_state_radio.rs@@ -0,0 +1,32 @@+use agent_desktop_core::{ActionStep, AdapterError, DeliverySemantics, ErrorCode};++use super::{CheckTarget, after_delivery, value_write_step};++pub(super) fn refuse_uncheck(+ target: &mut impl CheckTarget,+ want_checked: bool,+ write_refused: bool,+) -> Result<Vec<ActionStep>, AdapterError> {+ if !write_refused {+ return Err(uncheck_unsupported());+ }+ match target.checked().map_err(after_delivery)? {+ Some(state) if state == want_checked => Ok(vec![value_write_step()]),+ Some(_) => Err(uncheck_unsupported()),+ None => Err(after_delivery(uncheck_unsupported())),+ }+}++pub(super) fn uncheck_unsupported() -> AdapterError {+ AdapterError::new(+ ErrorCode::ActionFailed,+ "a radio button cannot be unchecked directly",+ )+ .with_details(serde_json::json!({+ "verification": "requested_checked_state_not_observed"+ }))+ .with_suggestion(+ "A radio button cannot be unchecked directly. Select a sibling radio button in the same group instead.",+ )+ .with_disposition(DeliverySemantics::not_delivered())+}diff --git a/crates/macos/src/input/keyboard_layout.rs b/crates/macos/src/input/keyboard_layout.rsnew file mode 100644index 000000000..6a1f47586--- /dev/null+++ b/crates/macos/src/input/keyboard_layout.rs@@ -0,0 +1,162 @@+#[derive(Debug, PartialEq, Eq)]+pub(crate) enum LayoutLookup {+ Found(u16),+ NoKeyForSymbol,+ LayoutUnavailable,+}++pub(crate) fn code_for_symbol(symbol: char) -> LayoutLookup {+ match platform::with_translator(|translate| find_code(symbol, translate)) {+ Some(Some(code)) => LayoutLookup::Found(code),+ Some(None) => LayoutLookup::NoKeyForSymbol,+ None => LayoutLookup::LayoutUnavailable,+ }+}++fn accepted_character(status: i32, dead_key_state: u32, units: &[u16]) -> Option<char> {+ match (status, dead_key_state, units) {+ (0, 0, [unit]) => char::from_u32(u32::from(*unit)),+ _ => None,+ }+}++pub(crate) fn find_code(symbol: char, translate: impl Fn(u16) -> Option<char>) -> Option<u16> {+ (0..128).find(|&code| translate(code) == Some(symbol))+}++#[cfg(target_os = "macos")]+mod platform {+ use core_foundation_sys::{+ base::CFRelease,+ data::{CFDataGetBytePtr, CFDataGetLength, CFDataRef},+ string::CFStringRef,+ };+ use std::ffi::c_void;++ const KUC_KEY_ACTION_DOWN: u16 = 0;+ const KUC_KEY_TRANSLATE_DEAD_KEYS: u32 = 0;++ #[link(name = "Carbon", kind = "framework")]+ unsafe extern "C" {+ fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut c_void;+ fn TISGetInputSourceProperty(source: *mut c_void, key: CFStringRef) -> *const c_void;+ static kTISPropertyUnicodeKeyLayoutData: CFStringRef;+ fn LMGetKbdType() -> u8;+ fn pthread_main_np() -> i32;+ fn UCKeyTranslate(+ layout: *const c_void,+ virtual_key_code: u16,+ key_action: u16,+ modifier_key_state: u32,+ keyboard_type: u32,+ key_translate_options: u32,+ dead_key_state: *mut u32,+ max_string_length: usize,+ actual_string_length: *mut usize,+ unicode_string: *mut u16,+ ) -> i32;+ }++ pub(super) fn with_translator<T>(+ run: impl FnOnce(&dyn Fn(u16) -> Option<char>) -> T,+ ) -> Option<T> {+ unsafe {+ if pthread_main_np() != 1 {+ return None;+ }+ let source = TISCopyCurrentKeyboardLayoutInputSource();+ if source.is_null() {+ return None;+ }+ let data =+ TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) as CFDataRef;+ let layout = if data.is_null() || CFDataGetLength(data) <= 0 {+ std::ptr::null()+ } else {+ CFDataGetBytePtr(data).cast::<c_void>()+ };+ let result = (!layout.is_null()).then(|| {+ let keyboard_type = u32::from(LMGetKbdType());+ run(&|code| translate(layout, keyboard_type, code))+ });+ CFRelease(source.cast_const());+ result+ }+ }++ unsafe fn translate(layout: *const c_void, keyboard_type: u32, code: u16) -> Option<char> {+ let mut dead_key_state = 0;+ let mut length = 0;+ let mut buffer = [0_u16; 4];+ let status = unsafe {+ UCKeyTranslate(+ layout,+ code,+ KUC_KEY_ACTION_DOWN,+ 0,+ keyboard_type,+ KUC_KEY_TRANSLATE_DEAD_KEYS,+ &mut dead_key_state,+ buffer.len(),+ &mut length,+ buffer.as_mut_ptr(),+ )+ };+ super::accepted_character(status, dead_key_state, buffer.get(..length)?)+ }+}++#[cfg(not(target_os = "macos"))]+mod platform {+ pub(super) fn with_translator<T>(+ _run: impl FnOnce(&dyn Fn(u16) -> Option<char>) -> T,+ ) -> Option<T> {+ None+ }+}++#[cfg(test)]+mod tests {+ use super::{accepted_character, find_code};++ fn jis(code: u16) -> Option<char> {+ match code {+ 30 => Some('['),+ 33 => Some('@'),+ 42 => Some(']'),+ 43 => Some(','),+ _ => None,+ }+ }++ #[test]+ fn finds_the_key_that_types_the_symbol_in_the_layout() {+ assert_eq!(find_code('[', jis), Some(30));+ assert_eq!(find_code(']', jis), Some(42));+ assert_eq!(find_code(',', jis), Some(43));+ }++ #[test]+ fn returns_none_when_no_key_types_the_symbol() {+ assert_eq!(find_code('`', jis), None);+ }++ #[test]+ fn a_dead_key_is_not_a_typable_symbol() {+ assert_eq!(accepted_character(0, 0, &[0x2c]), Some(','));+ assert_eq!(accepted_character(0, 7, &[0x60]), None);+ assert_eq!(accepted_character(0, 7, &[]), None);+ assert_eq!(accepted_character(-1, 0, &[0x2c]), None);+ assert_eq!(accepted_character(0, 0, &[0x2c, 0x2c]), None);+ assert_eq!(accepted_character(0, 0, &[]), None);+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn the_layout_is_never_read_off_the_main_thread() {+ let lookup = std::thread::spawn(|| super::code_for_symbol(','))+ .join()+ .unwrap();+ assert_eq!(lookup, super::LayoutLookup::LayoutUnavailable);+ }+}diff --git a/crates/macos/src/input/keyboard_map.rs b/crates/macos/src/input/keyboard_map.rsindex d6a3da8a8..4a39bced8 100644--- a/crates/macos/src/input/keyboard_map.rs+++ b/crates/macos/src/input/keyboard_map.rs@@ -1,4 +1,25 @@-use agent_desktop_core::{AdapterError, ErrorCode};+use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode};++const PUNCTUATION: [(char, &str); 11] = [+ (',', "comma"),+ ('.', "period"),+ ('/', "slash"),+ (';', "semicolon"),+ ('\'', "quote"),+ ('[', "leftbracket"),+ (']', "rightbracket"),+ ('\\', "backslash"),+ ('-', "minus"),+ ('=', "equal"),+ ('`', "grave"),+];++pub(crate) fn punctuation(key: &str) -> Option<char> {+ PUNCTUATION+ .iter()+ .find(|(symbol, name)| *name == key || key.chars().eq(std::iter::once(*symbol)))+ .map(|(symbol, _)| *symbol)+}pub(crate) fn key_name_to_code(key: &str) -> Result<u16, AdapterError> {let code = match key {@@ -69,19 +90,50 @@ pub(crate) fn key_name_to_code(key: &str) -> Result<u16, AdapterError> {"f11" => 103,"f12" => 111,other => {+ if let Some(symbol) = punctuation(other) {+ return layout_code(+ symbol,+ crate::input::keyboard_layout::code_for_symbol(symbol),+ );+ }return Err(AdapterError::new(ErrorCode::InvalidArgs,format!("Unknown key: '{other}'"),)- .with_suggestion("Valid keys: a-z, 0-9, return, escape, tab, space, delete, left, right, up, down, f1-f12"))+ .with_suggestion("Valid keys: a-z, 0-9, return, escape, tab, space, delete, left, right, up, down, f1-f12, and , . / ; ' [ ] \\ - = ` (or comma, period, slash, semicolon, quote, leftbracket, rightbracket, backslash, minus, equal, grave)"));}};Ok(code)}+fn layout_code(+ symbol: char,+ lookup: crate::input::keyboard_layout::LayoutLookup,+) -> Result<u16, AdapterError> {+ use crate::input::keyboard_layout::LayoutLookup;+ match lookup {+ LayoutLookup::Found(code) => Ok(code),+ LayoutLookup::NoKeyForSymbol => Err(AdapterError::new(+ ErrorCode::InvalidArgs,+ format!("No unmodified key types '{symbol}' in the active keyboard layout"),+ )+ .with_suggestion(+ "This symbol needs a modifier or is missing in the active layout; nothing was sent",+ )),+ LayoutLookup::LayoutUnavailable => Err(AdapterError::new(+ ErrorCode::ActionFailed,+ format!("Could not read the active keyboard layout to resolve '{symbol}'"),+ )+ .with_disposition(DeliverySemantics::not_delivered())+ .with_suggestion(+ "Nothing was sent; the layout is readable only from the process main thread. Retry from the main thread or with a named key",+ )),+ }+}+#[cfg(test)]mod tests {- use agent_desktop_core::ErrorCode;+ use agent_desktop_core::{DeliverySemantics, ErrorCode};use super::key_name_to_code;@@ -110,6 +162,40 @@ mod tests {assert_eq!(key_name_to_code("up").unwrap(), 126);}+ #[test]+ fn punctuation_resolves_by_symbol_and_by_name() {+ for (symbol, name) in super::PUNCTUATION {+ assert_eq!(super::punctuation(&symbol.to_string()), Some(symbol));+ assert_eq!(super::punctuation(name), Some(symbol));+ }+ assert_eq!(super::punctuation(",,"), None);+ }++ #[test]+ fn punctuation_is_sent_only_when_the_active_layout_resolves_it() {+ use crate::input::keyboard_layout::LayoutLookup;+ assert_eq!(+ super::layout_code(',', LayoutLookup::Found(43)).unwrap(),+ 43+ );+ assert_eq!(+ super::layout_code('[', LayoutLookup::Found(30)).unwrap(),+ 30+ );+ let err = super::layout_code('`', LayoutLookup::NoKeyForSymbol).unwrap_err();+ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains('`'));+ }++ #[test]+ fn an_unreadable_layout_is_an_environment_fault_that_is_safe_to_retry() {+ use crate::input::keyboard_layout::LayoutLookup;+ let err = super::layout_code('`', LayoutLookup::LayoutUnavailable).unwrap_err();+ assert_eq!(err.code, ErrorCode::ActionFailed);+ assert_eq!(err.disposition, DeliverySemantics::not_delivered());+ assert!(err.message.contains('`'));+ }+#[test]fn unknown_key_name_returns_invalid_args_error_with_suggestion() {let err = key_name_to_code("hyperkey").unwrap_err();diff --git a/crates/macos/src/input/mod.rs b/crates/macos/src/input/mod.rsindex d5656e3d6..9d996320c 100644--- a/crates/macos/src/input/mod.rs+++ b/crates/macos/src/input/mod.rs@@ -6,6 +6,7 @@ mod interactive_test;pub(crate) mod keyboard;#[cfg(target_os = "macos")]mod keyboard_event;+pub(crate) mod keyboard_layout;pub(crate) mod keyboard_map;pub(crate) mod mouse;#[cfg(target_os = "macos")]diff --git a/crates/macos/src/system/appkit_bridge.m b/crates/macos/src/system/appkit_bridge.mindex 1594cf01c..343e97a1b 100644--- a/crates/macos/src/system/appkit_bridge.m+++ b/crates/macos/src/system/appkit_bridge.m@@ -13,6 +13,9 @@ typedef struct {typedef struct {uint8_t status;+ const char *failureField;+ int32_t failureIndex;+ int32_t failurePID;uint8_t *bytes;size_t length;} AgentDesktopBytesResult;@@ -94,8 +97,27 @@ uint8_t agent_desktop_ensure_cocoa_multithreaded(void) {}}+static NSString *agent_desktop_non_blank(NSString *value) {+ NSString *trimmed = [value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ return trimmed.length == 0 ? nil : value;+}++static NSString *agent_desktop_application_name(NSRunningApplication *app) {+ NSString *name = agent_desktop_non_blank(app.localizedName);+ if (name == nil) {+ name = agent_desktop_non_blank(app.executableURL.lastPathComponent);+ }+ if (name == nil) {+ name = agent_desktop_non_blank(app.bundleIdentifier);+ }+ return name;+}+AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {- AgentDesktopBytesResult result = { .status = 5, .bytes = NULL, .length = 0 };+ AgentDesktopBytesResult result = {+ .status = 5, .failureField = NULL, .failureIndex = -1,+ .failurePID = 0, .bytes = NULL, .length = 0+ };@try {@autoreleasepool {NSWorkspace *workspace = [NSWorkspace sharedWorkspace];@@ -110,31 +132,41 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {if (frontmost != nil) {if (![frontmost isKindOfClass:[NSRunningApplication class]]) {result.status = 2;+ result.failureField = "frontmost_class";return result;}frontmostPID = frontmost.processIdentifier;- NSDate *frontmostLaunchDate = frontmost.launchDate;- if (frontmostPID <= 0) {- result.status = 2;- return result;- }- if (frontmostLaunchDate != nil) {- double launchTime = frontmostLaunchDate.timeIntervalSince1970;- if (!isfinite(launchTime) || launchTime <= 0.0) {- result.status = 2;- return result;+ if (frontmostPID > 0) {+ NSDate *frontmostLaunchDate = frontmost.launchDate;+ if (frontmostLaunchDate != nil) {+ double launchTime = frontmostLaunchDate.timeIntervalSince1970;+ if (!isfinite(launchTime) || launchTime <= 0.0) {+ result.status = 2;+ result.failureField = "frontmost_launch_time";+ result.failurePID = frontmostPID;+ return result;+ }+ frontmostLaunchTime = @(launchTime);}- frontmostLaunchTime = @(launchTime);+ } else {+ frontmostPID = 0;}}NSMutableArray<NSDictionary *> *records =[NSMutableArray arrayWithCapacity:running.count];NSMutableSet<NSNumber *> *seen = [NSMutableSet setWithCapacity:running.count];- for (NSRunningApplication *app in running) {+ for (NSUInteger index = 0; index < running.count; index++) {+ NSRunningApplication *app = running[index];if (![app isKindOfClass:[NSRunningApplication class]]) {result.status = 2;+ result.failureField = "application_class";+ result.failureIndex = (int32_t)index;return result;}+ int32_t pid = app.processIdentifier;+ if (pid <= 0) {+ continue;+ }NSApplicationActivationPolicy policy = app.activationPolicy;NSString *policyName = nil;switch (policy) {@@ -148,21 +180,29 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {continue;default:result.status = 2;+ result.failureField = "activation_policy";+ result.failureIndex = (int32_t)index;+ result.failurePID = pid;return result;}if (policyName == nil) {continue;}- int32_t pid = app.processIdentifier;- NSString *name = app.localizedName;- if (pid <= 0 || name == nil || name.length == 0 ||+ NSString *name = agent_desktop_application_name(app);+ if (name == nil || name.length == 0 ||[name lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 16384) {result.status = 2;+ result.failureField = "application_name";+ result.failureIndex = (int32_t)index;+ result.failurePID = pid;return result;}NSNumber *pidNumber = @(pid);if ([seen containsObject:pidNumber]) {result.status = 2;+ result.failureField = "duplicate_pid";+ result.failureIndex = (int32_t)index;+ result.failurePID = pid;return result;}[seen addObject:pidNumber];@@ -172,6 +212,9 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {double seconds = launchDate.timeIntervalSince1970;if (!isfinite(seconds) || seconds <= 0.0) {result.status = 2;+ result.failureField = "application_launch_time";+ result.failureIndex = (int32_t)index;+ result.failurePID = pid;return result;}launchTime = @(seconds);@@ -186,6 +229,9 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {if (bundle != nil) {if ([bundle lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 16384) {result.status = 2;+ result.failureField = "bundle_identifier";+ result.failureIndex = (int32_t)index;+ result.failurePID = pid;return result;}record[@"bundle_id"] = bundle;diff --git a/crates/macos/src/system/appkit_bridge.rs b/crates/macos/src/system/appkit_bridge.rsindex 9b82f04b3..9218a9923 100644--- a/crates/macos/src/system/appkit_bridge.rs+++ b/crates/macos/src/system/appkit_bridge.rs@@ -21,6 +21,9 @@ struct TerminateResult {#[repr(C)]struct BytesResult {status: u8,+ failure_field: *const std::ffi::c_char,+ failure_index: i32,+ failure_pid: i32,bytes: *mut u8,length: usize,}@@ -65,7 +68,7 @@ pub(crate) fn workspace_snapshot_json() -> Result<Vec<u8>, AdapterError> {let result = unsafe { agent_desktop_copy_workspace_snapshot_json() };let bytes = BridgeBytes(result.bytes);if result.status != 0 {- return Err(bridge_error("workspace_snapshot", result.status, false));+ return Err(workspace_snapshot_error(&result));}if result.length > MAX_BRIDGE_BYTES || (result.length > 0 && bytes.0.is_null()) {return Err(bridge_error("workspace_snapshot", u8::MAX, false));@@ -76,6 +79,32 @@ pub(crate) fn workspace_snapshot_json() -> Result<Vec<u8>, AdapterError> {Ok(unsafe { std::slice::from_raw_parts(bytes.0, result.length) }.to_vec())}+#[cfg(target_os = "macos")]+fn workspace_snapshot_error(result: &BytesResult) -> AdapterError {+ let field = if result.failure_field.is_null() {+ None+ } else {+ Some(+ unsafe { std::ffi::CStr::from_ptr(result.failure_field) }+ .to_string_lossy()+ .into_owned(),+ )+ };+ let mut details = serde_json::json!({+ "kind": "appkit_bridge",+ "operation": "workspace_snapshot",+ "status": result.status,+ "failure_field": field,+ "failure_index": (result.failure_index >= 0).then_some(result.failure_index),+ "failure_pid": (result.failure_pid > 0).then_some(result.failure_pid),+ "retryable": true,+ });+ if let Some(fields) = details.as_object_mut() {+ fields.retain(|_, value| !value.is_null());+ }+ bridge_error("workspace_snapshot", result.status, false).with_details(details)+}+#[cfg(target_os = "macos")]struct BridgeBytes(*mut u8);@@ -196,6 +225,48 @@ mod tests {assert_eq!(details["retryable"], true);}+ #[cfg(target_os = "macos")]+ #[test]+ fn workspace_snapshot_failure_identifies_field_without_exposing_application_name() {+ let field = b"application_name\0";+ let result = BytesResult {+ status: 2,+ failure_field: field.as_ptr().cast(),+ failure_index: 7,+ failure_pid: 123,+ bytes: std::ptr::null_mut(),+ length: 0,+ };++ let details = workspace_snapshot_error(&result).details.unwrap();+ assert_eq!(details["kind"], "appkit_bridge");+ assert_eq!(details["operation"], "workspace_snapshot");+ assert_eq!(details["status"], 2);+ assert_eq!(details["failure_field"], "application_name");+ assert_eq!(details["failure_index"], 7);+ assert_eq!(details["failure_pid"], 123);+ assert_eq!(details["retryable"], true);+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn workspace_snapshot_failure_without_context_omits_the_unset_fields() {+ let result = BytesResult {+ status: 1,+ failure_field: std::ptr::null(),+ failure_index: -1,+ failure_pid: 0,+ bytes: std::ptr::null_mut(),+ length: 0,+ };++ let details = workspace_snapshot_error(&result).details.unwrap();+ for key in ["failure_field", "failure_index", "failure_pid"] {+ assert!(details.get(key).is_none(), "{key} is omitted, not null");+ }+ assert_eq!(details["status"], 1);+ }+#[cfg(target_os = "macos")]#[test]fn post_selector_exception_is_delivery_uncertain() {diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rsindex fb36e07c5..290275f5d 100644--- a/crates/macos/src/system/key_dispatch.rs+++ b/crates/macos/src/system/key_dispatch.rs@@ -52,6 +52,7 @@ fn press_for_app(return post_delivery_process_result(&process, semantic_step(action));}+ crate::input::keyboard_map::key_name_to_code(&combo.key)?;if policy.allow_focus_steal {crate::system::process_identity::require_core(&process)?;crate::system::focus::verify_app_focused(pid, deadline)?;diff --git a/crates/macos/src/system/key_dispatch_menu.rs b/crates/macos/src/system/key_dispatch_menu.rsindex 820572bea..9ca43ddf9 100644--- a/crates/macos/src/system/key_dispatch_menu.rs+++ b/crates/macos/src/system/key_dispatch_menu.rs@@ -164,6 +164,9 @@ fn read_menu_item_modifiers(}fn single_uppercase_character(key: &str) -> Option<String> {+ if let Some(symbol) = crate::input::keyboard_map::punctuation(key) {+ return Some(symbol.to_string());+ }(key.chars().count() == 1).then(|| key.to_uppercase())}diff --git a/crates/macos/src/system/key_dispatch_menu_tests.rs b/crates/macos/src/system/key_dispatch_menu_tests.rsindex 5d9656f6b..cd0c1677d 100644--- a/crates/macos/src/system/key_dispatch_menu_tests.rs+++ b/crates/macos/src/system/key_dispatch_menu_tests.rs@@ -13,6 +13,12 @@ fn menu_shortcut_requires_one_character() {assert!(single_uppercase_character("enter").is_none());}+#[test]+fn menu_shortcut_matches_punctuation_by_name_and_symbol() {+ assert_eq!(single_uppercase_character("comma").as_deref(), Some(","));+ assert_eq!(single_uppercase_character(",").as_deref(), Some(","));+}+#[test]fn menu_modifier_encoding_distinguishes_command_from_no_command() {assert_eq!(diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rsindex b55fa23b6..127050206 100644--- a/crates/macos/src/system/key_dispatch_tests.rs+++ b/crates/macos/src/system/key_dispatch_tests.rs@@ -96,3 +96,25 @@ fn a_missing_focused_element_names_both_recovery_routes() {assert!(suggestion.contains("--headed"), "{suggestion}");assert!(suggestion.contains("--surface menubar"), "{suggestion}");}++#[test]+fn an_unresolvable_key_fails_before_any_focus_change() {+ let pid = std::process::id();+ let instance = crate::system::process_identity::token_for_pid(pid as i32)+ .unwrap()+ .unwrap();+ let error = press_for_app_impl(+ ProcessIdentity::new(pid, instance),+ &key("comma", Vec::new()),+ agent_desktop_core::InteractionPolicy::headed(),+ Deadline::standard().unwrap(),+ )+ .unwrap_err();+ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());+ assert!(+ error.message.contains("keyboard layout"),+ "{}",+ error.message+ );+}diff --git a/crates/macos/src/system/window_inventory_global.rs b/crates/macos/src/system/window_inventory_global.rsindex 93572ff66..323fea38e 100644--- a/crates/macos/src/system/window_inventory_global.rs+++ b/crates/macos/src/system/window_inventory_global.rs@@ -370,19 +370,31 @@ fn retryable_global_error(error: &AdapterError) -> bool {}fn global_timeout(attempts: u64, last_error: Option<&AdapterError>) -> AdapterError {- AdapterError::timeout("Global application window inventory did not stabilize before deadline")- .with_details(serde_json::json!({+ let last = |key: &str| last_error.and_then(|error| error.details.as_ref()?.get(key).cloned());+ let mut details = serde_json::json!({"kind": "global_window_inventory_unstable","attempts": attempts,"last_code": last_error.map(|error| error.code.as_str()),- "last_kind": last_error- .and_then(|error| error.details.as_ref())- .and_then(|details| details.get("kind")),+ "last_kind": last("kind"),+ "last_operation": last("operation"),+ "last_status": last("status"),+ "last_failure_field": last("failure_field"),+ "last_failure_index": last("failure_index"),+ "last_failure_pid": last("failure_pid"),"complete": false,"retryable": true,- }))+ });+ if let Some(fields) = details.as_object_mut() {+ fields.retain(|_, value| !value.is_null());+ }+ AdapterError::timeout("Global application window inventory did not stabilize before deadline")+ .with_details(details)}+#[cfg(test)]+#[path = "window_inventory_global_timeout_tests.rs"]+mod timeout_tests;+#[cfg(test)]#[path = "window_inventory_global_tests.rs"]mod tests;diff --git a/crates/macos/src/system/window_inventory_global_timeout_tests.rs b/crates/macos/src/system/window_inventory_global_timeout_tests.rsnew file mode 100644index 000000000..7f60e010c--- /dev/null+++ b/crates/macos/src/system/window_inventory_global_timeout_tests.rs@@ -0,0 +1,62 @@+use super::*;++#[test]+fn persistent_appkit_bridge_failure_preserves_operation_and_status() {+ let error = stabilize_global_with(+ Instant::now() + std::time::Duration::from_millis(20),+ || {+ Err(AdapterError::new(+ ErrorCode::AppUnresponsive,+ "AppKit workspace snapshot failed",+ )+ .with_details(serde_json::json!({+ "kind": "appkit_bridge",+ "operation": "workspace_snapshot",+ "status": 2,+ "failure_field": "application_name",+ "failure_index": 7,+ "failure_pid": 123,+ "retryable": true,+ })))+ },+ )+ .unwrap_err();++ let details = error.details.unwrap();+ assert_eq!(details["last_kind"], "appkit_bridge");+ assert_eq!(details["last_operation"], "workspace_snapshot");+ assert_eq!(details["last_status"], 2);+ assert_eq!(details["last_failure_field"], "application_name");+ assert_eq!(details["last_failure_index"], 7);+ assert_eq!(details["last_failure_pid"], 123);+}++#[test]+fn a_failure_without_context_leaves_the_last_failure_fields_out() {+ let error = stabilize_global_with(+ Instant::now() + std::time::Duration::from_millis(20),+ || {+ Err(AdapterError::new(+ ErrorCode::AppUnresponsive,+ "AppKit workspace snapshot failed",+ )+ .with_details(serde_json::json!({+ "kind": "appkit_bridge",+ "operation": "workspace_snapshot",+ "status": 1,+ "retryable": true,+ })))+ },+ )+ .unwrap_err();++ let details = error.details.unwrap();+ for key in [+ "last_failure_field",+ "last_failure_index",+ "last_failure_pid",+ ] {+ assert!(details.get(key).is_none(), "{key} is omitted, not null");+ }+ assert_eq!(details["last_status"], 1);+}diff --git a/crates/macos/src/system/workspace_apps.rs b/crates/macos/src/system/workspace_apps.rsindex 4973882fe..38668dfa6 100644--- a/crates/macos/src/system/workspace_apps.rs+++ b/crates/macos/src/system/workspace_apps.rs@@ -337,6 +337,10 @@ fn inventory_error(message: &str) -> AdapterError {}))}+#[cfg(test)]+#[path = "workspace_apps_pid_tests.rs"]+mod pid_tests;+#[cfg(test)]#[path = "workspace_apps_tests.rs"]mod tests;diff --git a/crates/macos/src/system/workspace_apps_pid_tests.rs b/crates/macos/src/system/workspace_apps_pid_tests.rsnew file mode 100644index 000000000..e9dab5f0b--- /dev/null+++ b/crates/macos/src/system/workspace_apps_pid_tests.rs@@ -0,0 +1,57 @@+use super::*;++fn deadline() -> Instant {+ Instant::now() + std::time::Duration::from_secs(1)+}++fn snapshot_with(application_pid: i32, frontmost_pid: i32) -> String {+ format!(+ r#"{{+ "applications":[+ {{"name":"Mail","pid":{application_pid},"launch_time":100.25,"activation_policy":"regular"}}+ ],+ "frontmost_pid":{frontmost_pid},+ "frontmost_launch_time":null+ }}"#+ )+}++#[test]+fn owner_snapshot_rejects_non_positive_application_pid() {+ for pid in [0, -1] {+ let bytes = snapshot_with(pid, 0);+ let error = window_owner_snapshot_from_json(bytes.as_bytes(), deadline())+ .err()+ .unwrap();++ assert_eq!(error.code, ErrorCode::AppUnresponsive);+ }+}++#[test]+fn owner_snapshot_rejects_negative_frontmost_pid() {+ let bytes = snapshot_with(10, -1);+ let error = window_owner_snapshot_from_json(bytes.as_bytes(), deadline())+ .err()+ .unwrap();++ assert_eq!(error.code, ErrorCode::AppUnresponsive);+}++#[test]+fn owner_snapshot_treats_zero_frontmost_pid_without_launch_time_as_none() {+ let bytes = snapshot_with(10, 0);+ let snapshot = window_owner_snapshot_from_json(bytes.as_bytes(), deadline()).unwrap();++ assert!(snapshot.frontmost().is_none());+}++#[test]+fn app_listing_rejects_non_positive_application_pid() {+ for pid in [0, -1] {+ let bytes = snapshot_with(pid, 0);+ let error = apps_from_json(bytes.as_bytes(), deadline()).err().unwrap();++ assert_eq!(error.code, ErrorCode::AppUnresponsive);+ }+}diff --git a/crates/macos/src/tree/query/mod.rs b/crates/macos/src/tree/query/mod.rsindex cd0d68dbe..676e2354d 100644--- a/crates/macos/src/tree/query/mod.rs+++ b/crates/macos/src/tree/query/mod.rs@@ -173,6 +173,19 @@ fn resolve_window_surface(crate::tree::locator_deadline::remaining(deadline)?;let pid = crate::system::process_identity::to_pid_t(window.pid)?;let element = match surface {+ SnapshotSurface::Sheet | SnapshotSurface::Popover | SnapshotSurface::Alert => {+ let owner = crate::system::window_resolve::window_element_for_info_with_deadline(+ window, deadline,+ )?;+ crate::tree::surfaces::surface_in_window(&owner, surface, deadline)?.ok_or_else(+ || {+ AdapterError::new(+ ErrorCode::ElementNotFound,+ format!("No open {} in window {}", surface.as_str(), window.id),+ )+ },+ )?+ }SnapshotSurface::Window => {crate::system::window_resolve::window_element_for_info_with_deadline(window, deadline)?}@@ -182,12 +195,6 @@ fn resolve_window_surface(.ok_or_else(|| AdapterError::element_not_found("No open context menu"))?,SnapshotSurface::Menubar => crate::tree::surfaces::menubar_for_pid(pid, deadline)?.ok_or_else(|| AdapterError::element_not_found("No menu bar found"))?,- SnapshotSurface::Sheet => crate::tree::surfaces::sheet_for_pid(pid, deadline)?- .ok_or_else(|| AdapterError::element_not_found("No open sheet"))?,- SnapshotSurface::Popover => crate::tree::surfaces::popover_for_pid(pid, deadline)?- .ok_or_else(|| AdapterError::element_not_found("No visible popover"))?,- SnapshotSurface::Alert => crate::tree::surfaces::alert_for_pid(pid, deadline)?- .ok_or_else(|| AdapterError::element_not_found("No open alert or dialog"))?,_ => return Err(AdapterError::not_supported("snapshot surface")),};crate::tree::locator_deadline::remaining(deadline)?;diff --git a/crates/macos/src/tree/resolve_roots.rs b/crates/macos/src/tree/resolve_roots.rsindex 76ab8d108..933d9c889 100644--- a/crates/macos/src/tree/resolve_roots.rs+++ b/crates/macos/src/tree/resolve_roots.rs@@ -22,7 +22,7 @@ pub(super) fn candidate_roots(let application = element_for_pid(pid);if entry.source.source_surface != SnapshotSurface::Window {verify_source_application(&application, entry, context)?;- return source_surface_scoped_roots(entry, deadline);+ return source_surface_scoped_roots(&application, entry, context);}if source_window_scope_required(entry) && entry.source.source_window_id.is_some() {return source_window_scoped_roots(&application, entry, context);@@ -63,11 +63,29 @@ pub(super) fn candidate_roots(#[cfg(target_os = "macos")]fn source_surface_scoped_roots(+ application: &AXElement,entry: &RefEntry,- deadline: std::time::Instant,+ context: &mut ResolveReadContext,) -> Result<CandidateRoots, AdapterError> {+ let deadline = context.deadline;let pid = crate::system::process_identity::to_pid_t(entry.process.pid)?;let root = match entry.source.source_surface {+ SnapshotSurface::Sheet | SnapshotSurface::Popover | SnapshotSurface::Alert+ if entry.source.source_window_id.is_some() =>+ {+ match source_window_scoped_roots(application, entry, context)?+ .roots+ .into_iter()+ .next()+ {+ Some(window) => super::surfaces::surface_in_window(+ &window,+ entry.source.source_surface,+ deadline,+ )?,+ None => None,+ }+ }SnapshotSurface::Focused => super::surfaces::focused_surface_for_pid(pid, deadline)?,SnapshotSurface::Menu => super::surfaces::menu_element_for_pid(pid, deadline)?,SnapshotSurface::Menubar => super::surfaces::menubar_for_pid(pid, deadline)?,diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rsindex a3f7ac26a..9f91f3a1b 100644--- a/crates/macos/src/tree/surfaces.rs+++ b/crates/macos/src/tree/surfaces.rs@@ -1,5 +1,5 @@use super::{AXElement, element::element_for_pid, surface_read};-use agent_desktop_core::{AdapterError, ErrorCode};+use agent_desktop_core::{AdapterError, ErrorCode, SnapshotSurface};use std::time::Instant;const MAX_SURFACE_NODES: usize = 2_048;@@ -151,11 +151,42 @@ fn first_child_with_role_or_subrole(let Some(window) = focused_surface_for_pid(pid, deadline)? else {return Ok(None);};- if role_or_subrole_matches(&window, target, deadline)? {- return Ok(Some(window));+ first_in_window(&window, deadline, |element| {+ role_or_subrole_matches(element, target, deadline)+ })+}++/// Finds a sheet, popover or alert on this window or its direct children only.+#[cfg(target_os = "macos")]+pub(crate) fn surface_in_window(+ window: &AXElement,+ surface: SnapshotSurface,+ deadline: Instant,+) -> Result<Option<AXElement>, AdapterError> {+ let target = match surface {+ SnapshotSurface::Sheet => "AXSheet",+ SnapshotSurface::Popover => "AXPopover",+ SnapshotSurface::Alert => {+ return first_in_window(window, deadline, |element| is_alert(element, deadline));+ }+ _ => return Err(AdapterError::not_supported("window-owned surface")),+ };+ first_in_window(window, deadline, |element| {+ role_or_subrole_matches(element, target, deadline)+ })+}++#[cfg(target_os = "macos")]+fn first_in_window(+ window: &AXElement,+ deadline: Instant,+ matches: impl Fn(&AXElement) -> Result<bool, AdapterError>,+) -> Result<Option<AXElement>, AdapterError> {+ if matches(window)? {+ return Ok(Some(window.clone()));}- for child in surface_read::elements(&window, "AXChildren", deadline)? {- if role_or_subrole_matches(&child, target, deadline)? {+ for child in surface_read::elements(window, "AXChildren", deadline)? {+ if matches(&child)? {return Ok(Some(child));}}diff --git a/scripts/jev/act.mjs b/scripts/jev/act.mjsindex 555b3d40b..c19386b22 100644--- a/scripts/jev/act.mjs+++ b/scripts/jev/act.mjs@@ -18,7 +18,7 @@ import { existsSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";-import { collect, describe, label, offerable, overlayRole } from "./screen.mjs";+import { collect, describe, label, offerable, outsideWindow, overlayRole } from "./screen.mjs";import { NO_MATCH, resolveModel, typesafeApi, route } from "./policy.mjs";export { collect, describe, label, offerable, overlayRole, route };@@ -199,12 +199,19 @@ const fail = (message, extra = {}) => {const main = async (argv) => {const flag = (n) => {const i = argv.indexOf(`--${n}`);- return i === -1 ? null : argv[i + 1];+ if (i === -1) return null;+ const value = argv[i + 1];+ if (value === undefined || value.startsWith("--")) {+ console.error(`--${n} needs a value`);+ process.exit(2);+ }+ return value;};const bools = new Set(["--execute", "--raw"]);const app = flag("app");const text = flag("text");const root = flag("root");+ const windowId = flag("window-id");const execute = argv.includes("--execute");const bin = flag("bin") ?? (existsSync(join(REPO, "target/release/agent-desktop"))? join(REPO, "target/release/agent-desktop")@@ -214,24 +221,32 @@ const main = async (argv) => {.join(" ");if (!app || !intent) {- console.error('usage: act.mjs --app <name> [--text "…"] [--root @ref] [--execute] "<intent>"');+ console.error('usage: act.mjs --app <name> [--window-id <id>] [--text "…"] [--root @ref] [--execute] "<intent>"');process.exit(2);}if (!process.env.TYPESAFE_API_KEY) fail("TYPESAFE_API_KEY unset");- const base = ["snapshot", "--app", app, "-i", "--compact", "--include-bounds"];+ const scope = windowId ? ["--app", app, "--window-id", windowId] : ["--app", app];+ const base = ["snapshot", ...scope, "-i", "--compact", "--include-bounds"];let snap = run(bin, root ? [...base, "--root", root] : base);if (!snap.ok) fail(`snapshot failed: ${snap.error?.code}`, { detail: snap.error?.message });+ if (root && windowId && outsideWindow(snap.data, windowId)) {+ fail("root_outside_window", { detail: `the region is not in window ${windowId}` });+ }const overlay = overlayRole(snap.data.tree);if (overlay && !root) {- const surfaceSnap = run(bin, ["snapshot", "--app", app, "--surface", overlay, "-i", "--compact", "--include-bounds"]);+ const surfaceSnap = run(bin, ["snapshot", ...scope, "--surface", overlay, "-i", "--compact", "--include-bounds"]);+ if (surfaceSnap.ok && windowId && outsideWindow(surfaceSnap.data, windowId)) {+ fail("surface_outside_window", { detail: `the ${overlay} is not in window ${windowId}` });+ }if (surfaceSnap.ok) snap = surfaceSnap;}const surface = {app: snap.data.app ?? app,window: snap.data.window?.title ?? null,+ window_id: snap.data.window?.id ?? windowId,overlay,};let candidates = offerable(collect(snap.data.tree));@@ -275,6 +290,7 @@ const main = async (argv) => {intent,app: surface.app,window: surface.window,+ window_id: surface.window_id,surface: overlay ?? "window",element: node? { ref: node.ref_id, role: node.role, name: node.name ?? node.description ?? null, where: node.path.join(" > ") }diff --git a/scripts/jev/desktop.mjs b/scripts/jev/desktop.mjsindex 91a5231ce..683ddb691 100644--- a/scripts/jev/desktop.mjs+++ b/scripts/jev/desktop.mjs@@ -7,8 +7,9 @@ import { execFileSync } from "node:child_process";import { existsSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";+import { setTimeout as sleep } from "node:timers/promises";-import { collect, offerable, overlayRole } from "./screen.mjs";+import { collect, offerable, outsideWindow, overlayRole } from "./screen.mjs";import { ARGV } from "./policy.mjs";const REPO = join(dirname(fileURLToPath(import.meta.url)), "..", "..");@@ -53,21 +54,31 @@ export const stopCursor = () => cli("cursor-overlay", "disable");* which is what makes it worth drilling into. A sheet or menu owns the screen* while it is up, so it is read instead of the window behind it.*/-export const observe = (app, root) => {- const base = ["snapshot", "--app", app, "-i", "--compact", "--include-bounds"];+export const observe = (app, root, windowId = null) => {+ const scope = windowId ? ["--app", app, "--window-id", windowId] : ["--app", app];+ const base = ["snapshot", ...scope, "-i", "--compact", "--include-bounds"];+ const unreadable = (what, error) => Object.assign(new Error(`${what} could not be read: ${error?.code}`),+ { code: error?.code ?? null });let snap = root ? cli(...base, "--root", root) : cli(...base, "--skeleton");- if (!snap.ok && root) throw new Error(`that region could not be read: ${snap.error?.code}`);- if (!snap.ok) snap = cli(...base, "--max-depth", "4");- if (!snap.ok) throw new Error(`the screen could not be read: ${snap.error?.code}`);+ if (!snap.ok && root) throw unreadable("that region", snap.error);+ if (snap.ok && root && windowId && outsideWindow(snap.data, windowId)) {+ throw Object.assign(new Error(`that region is not in window ${windowId}`), { code: "ROOT_OUTSIDE_WINDOW" });+ }+ if (!snap.ok && snap.error?.code !== "WINDOW_NOT_FOUND") snap = cli(...base, "--max-depth", "4");+ if (!snap.ok) throw unreadable("the screen", snap.error);const surface = root ? null : overlayRole(snap.data.tree);if (surface) {- const scoped = cli("snapshot", "--app", app, "--surface", surface, "-i", "--compact", "--include-bounds");+ const scoped = cli("snapshot", ...scope, "--surface", surface, "-i", "--compact", "--include-bounds");+ if (scoped.ok && windowId && outsideWindow(scoped.data, windowId)) {+ throw Object.assign(new Error(`the ${surface} is not in window ${windowId}`), { code: "SURFACE_OUTSIDE_WINDOW" });+ }if (scoped.ok) snap = scoped;}const nodes = offerable(collect(snap.data.tree));return {nodes,- screen: { app, window: snap.data.window?.title ?? null, surface: surface ?? "window", root },+ screen: { app, window: snap.data.window?.title ?? null, window_id: snap.data.window?.id ?? windowId,+ surface: surface ?? "window", root },};};@@ -95,31 +106,78 @@ export const clipboardGuard = () => {};};+const verifyWindowMs = (raw) => {+ const value = Number(raw ?? 2000);+ if (!Number.isFinite(value) || value < 0 || value > 60000) {+ throw new Error(`JEV_VERIFY_MS must be a number of milliseconds from 0 to 60000, not ${JSON.stringify(raw)}`);+ }+ return value;+};+const VERIFY_MS = verifyWindowMs(process.env.JEV_VERIFY_MS);+const VERIFY_INTERVAL_MS = 100;++const awaitFieldText = async (ref, text) => {+ const deadline = Date.now() + VERIFY_MS;+ for (;;) {+ const observed = cli("get", ref, "--property", "value");+ if (observed.ok && observed.data?.value === text) return { held: true, observed };+ if (Date.now() >= deadline) return { held: false, observed };+ await sleep(VERIFY_INTERVAL_MS);+ }+};++const verificationFailure = (observed) => ({+ code: "TEXT_VERIFICATION_FAILED",+ message: "after the paste the field does not hold the requested text",+ disposition: { delivery: "delivered_unverified", retry: "unsafe" },+ ...(observed.ok ? {} : { details: { read_error: observed.error ?? null } }),+});+/*** Text goes in through whichever route the application accepts. A direct value* write is one verified call, and the applications that refuse it report that* refusal, so the paste path runs only when it is needed. A paste arrives whole* where one key press per character loses characters and capitals.*/-export const enterText = (app, node, text, clipboard) => {+export const enterText = async ({ app, windowId = null }, node, text, clipboard) => {const written = cli("set-value", node.ref_id, text);if (written.ok) return { route: "set-value", result: written };+ const failure = written.error;+ if (failure && failure.code !== "SPAWN_FAILED" && !failure.disposition) {+ return { route: "set-value", result: { ok: false, error: {+ code: "BINARY_TOO_OLD",+ message: "this agent-desktop binary reports no error disposition; the paste fallback needs a binary whose failed set-value says whether a retry is safe",+ details: { cause: failure },+ } } };+ }+ if (failure?.disposition?.retry !== "safe") return { route: "set-value", result: written };const focused = cli("focus", node.ref_id);- if (!focused.ok) return { route: "set-value", result: written };+ if (!focused.ok) return { route: "paste", result: focused };clipboard.borrow();- cli("clipboard-set", text);- return { route: "paste", result: cli("press", "cmd+v", "--app", app) };+ const copied = cli("clipboard-set", text);+ if (!copied.ok) return { route: "paste", result: copied };+ const pasted = cli("press", "cmd+v", "--app", app, ...(windowId ? ["--window-id", windowId] : []));+ if (!pasted.ok) return { route: "paste", result: pasted };+ const { held, observed } = await awaitFieldText(node.ref_id, text);+ if (!held) return { route: "paste", result: { ok: false, error: verificationFailure(observed) } };+ return { route: "paste", result: { ...pasted, data: {+ ...pasted.data, disposition: { delivery: "delivered_verified", retry: "unsafe" },+ } } };};-export const execute = (app, operation, node, text, clipboard) => {- if (operation === "WAIT") return { ok: true, delivery: "waited" };+export const execute = async (target, operation, node, text, clipboard) => {+ if (operation === "WAIT") {+ await sleep(250);+ return { ok: true, delivery: "waited" };+ }if (operation === "DRILL") return { ok: true, delivery: "looked", root: node.ref_id };if (operation === "WIDEN") return { ok: true, delivery: "looked", root: null };if (operation === "TYPE_TEXT") {- const { route, result } = enterText(app, node, text, clipboard);- return { ok: result.ok, delivery: result.data?.disposition?.delivery ?? result.error?.code ?? null, route };+ const { route, result } = await enterText(target, node, text, clipboard);+ return { ok: result.ok, delivery: result.data?.disposition?.delivery ?? result.error?.disposition?.delivery ?? null,+ error: result.error ?? null, route };}const result = cli(...ARGV[operation](node.ref_id));- return { ok: result.ok, delivery: result.data?.disposition?.delivery ?? result.error?.code ?? null };+ return { ok: result.ok, delivery: result.data?.disposition?.delivery ?? result.error?.disposition?.delivery ?? null,+ error: result.error ?? null };};-diff --git a/scripts/jev/run.integration.test.mjs b/scripts/jev/run.integration.test.mjsnew file mode 100644index 000000000..8794d8810--- /dev/null+++ b/scripts/jev/run.integration.test.mjs@@ -0,0 +1,287 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { execute } from "./desktop.mjs";++const directory = mkdtempSync(join(tmpdir(), "jev-loop-test-"));+const entry = join(dirname(fileURLToPath(import.meta.url)), "run.mjs");+const log = join(directory, "commands.jsonl");+const preload = join(directory, "fetch.mjs");++const fake = `+const { appendFileSync } = require('node:fs');+const { basename } = require('node:path');+const command = basename(process.argv[1]);+const args = process.argv.slice(2);+const mode = process.env.JEV_TEST_MODE;+appendFileSync(process.env.JEV_TEST_LOG, JSON.stringify({command,args})+'\\n');+const error = (code, retry='unsafe', delivery='delivery_uncertain') =>+ ({ok:false,error:{code,message:'試験の失敗',disposition:{retry,delivery}}});+let result = {ok:true,data:{disposition:{delivery:'delivered_verified',retry:'unsafe'}}};+const clicked = () => require('node:fs').readFileSync(process.env.JEV_TEST_LOG,'utf8').includes('"command":"click"');+if (command === 'snapshot' && mode === 'window_closed' && clicked()) result = error('WINDOW_NOT_FOUND','safe','not_delivered');+else if (command === 'snapshot' && mode === 'closed_top' &&+ require('node:fs').readFileSync(process.env.JEV_TEST_LOG,'utf8').split('\\n').filter(l=>l.includes('"command":"snapshot"')).length >= 3)+ result = error('WINDOW_NOT_FOUND','safe','not_delivered');+else if (command === 'snapshot') {+ const at = args.indexOf('--window-id');+ const pinned = at === -1 ? 'w-default' : args[at + 1];+ const surfaced = args.includes('--surface');+ const rooted = args.includes('--root');+ let id = pinned;+ if (surfaced && mode === 'surface_other') id = 'w-other';+ if (rooted && mode === 'root_other') id = 'w-other';+ const window = surfaced && mode === 'surface_noid' ? {title:'試験'} : {title:'試験',id};+ const sheet = mode.startsWith('surface') && !surfaced ? [{role:'sheet',children:[]}] : [];+ result = {ok:true,data:{window,tree:{+ role:'window',children:[+ {ref_id:'@s1:e1',role:'button',name:'試験ボタン',available_actions:['Click']},+ {ref_id:'@s1:e2',role:'textfield',name:'試験欄',value:'',available_actions:['SetValue']},+ ...sheet+ ]}}};+}+if (command === 'click' && mode === 'click_error') result=error('ACTION_FAILED');+if (command === 'set-value') result= mode==='unsafe_type'+ ? error('TIMEOUT') : mode==='old_binary'+ ? {ok:false,error:{code:'ACTION_NOT_SUPPORTED',message:'古い'}}+ : error('ACTION_NOT_SUPPORTED','safe','not_delivered');+if (command === 'focus' && mode==='focus_error') result=error('ACTION_FAILED','unsafe','not_delivered');+if (command === 'press' && mode==='press_error') result=error('ACTION_FAILED');+if (command === 'clipboard-get') result={ok:true,data:{text:'元の文字'}};+if (command === 'clipboard-set' && mode==='clipboard_error' && args[0]==='試験')+ result=error('COPY_FAILED','safe','not_delivered');+if (command === 'get') {+ const reads = require('node:fs').readFileSync(process.env.JEV_TEST_LOG,'utf8').split('\\n')+ .filter(l => l.includes('"command":"get"')).length;+ result = mode==='get_error' ? error('ACTION_FAILED','unsafe','not_delivered')+ : {ok:true,data:{value:mode==='paste_wrong'?'違う文字':mode==='paste_late'&&reads<3?'':'試験'}};+}+console.log(JSON.stringify(result));+`;+for (const command of ["snapshot", "click", "set-value", "focus", "clipboard-get", "clipboard-set", "press", "get"]) {+ writeFileSync(join(directory, command), fake);+}+writeFileSync(preload, `+let calls=0;+globalThis.fetch=async (_url,options)=>{+ calls++;+ const body=JSON.parse(options.body), mode=process.env.JEV_TEST_MODE;+ const operation=mode==='wait'?(calls<=3?'WAIT':'DONE'):mode==='closed_top'?'WAIT':(mode==='done'||mode.startsWith('surface')||mode.endsWith('_other'))?'DONE':+ mode==='blocked'?'BLOCKED':mode==='click_error'||mode==='window_closed'?'CLICK':(mode==='paste_correct'||mode==='paste_late')&&calls>1?'DONE':'TYPE_TEXT';+ const answers={};+ for (const [id,question] of Object.entries(body.questions)) {+ const ids=Object.keys(question.criteria);+ const selected=id==='operation'?operation:ids[0];+ answers[id]={choice:selected,confidence:1,probabilities:Object.fromEntries(ids.map(x=>[x,Number(x===selected)]))};+ }+ return {ok:true,status:200,json:async()=>({answers})};+};+`);++const actEntry = join(dirname(fileURLToPath(import.meta.url)), "act.mjs");+const actPreload = join(directory, "act-fetch.mjs");+writeFileSync(actPreload, `+globalThis.fetch=async (_url,options)=>{+ const body=JSON.parse(options.body);+ const ref=Object.keys(body.questions.target.criteria)[0];+ const noul={type:'noul',noul:0.1};+ return {ok:true,status:200,json:async()=>({answers:{+ target:{type:'choice',choice:ref,confidence:0.95,probabilities:{[ref]:0.95}},+ command:{type:'choice',choice:'click',confidence:0.95},+ present:{type:'noul',noul:0.95},destructive:noul,needs_text:noul}})};+};+`);++const act = (mode, extra = []) => {+ writeFileSync(log, "");+ const result = spawnSync(process.execPath, ["--import", pathToFileURL(actPreload).href, actEntry,+ "--app", "試験アプリ", "--bin", process.execPath, ...extra, "試験ボタンを押す"], {+ cwd: directory,+ encoding: "utf8",+ timeout: 10000,+ env: { ...process.env, TYPESAFE_API_KEY: "fixture", JEV_TEST_MODE: mode, JEV_TEST_LOG: log },+ });+ assert.ifError(result.error);+ const commands = readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse);+ return { ...result, commands, out: result.stdout.trim() ? JSON.parse(result.stdout) : null };+};++const run = (mode, extra = []) => {+ writeFileSync(log, "");+ const result = spawnSync(process.execPath, ["--import", pathToFileURL(preload).href, entry,+ "--app", "試験アプリ", ...extra, "--text", "試験", "試験を完了する"], {+ cwd: directory,+ encoding: "utf8",+ timeout: 10000,+ env: { ...process.env, JEV_VERIFY_MS: "600", TYPESAFE_API_KEY: "fixture", AGENT_DESKTOP_BIN: process.execPath,+ JEV_TEST_MODE: mode, JEV_TEST_LOG: log },+ });+ assert.ifError(result.error);+ assert.equal(result.stderr, "");+ const events = result.stdout.trim().split("\n").map(JSON.parse);+ const commands = readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse);+ return { ...result, events, commands, stop: events.at(-1) };+};++try {+ const started = performance.now();+ await execute({ app: "試験アプリ" }, "WAIT", null, null, null);+ assert.ok(performance.now() - started >= 230, "WAIT actually waits");++ const waited = run("wait");+ assert.equal(waited.status, 0);+ assert.equal(waited.stop.stop, "done");+ assert.equal(waited.events.filter(event => event.turn).length, 3);++ const failed = run("click_error");+ assert.equal(failed.status, 1);+ assert.equal(failed.stop.stop, "action_failed");+ assert.equal(failed.stop.error.code, "ACTION_FAILED");+ assert.equal(failed.stop.error.disposition.retry, "unsafe");+ assert.equal(failed.commands.filter(command => command.command === "click").length, 1);++ const unsafe = run("unsafe_type");+ assert.equal(unsafe.status, 1);+ assert.equal(unsafe.stop.error.code, "TIMEOUT");+ assert.equal(unsafe.commands.some(command => command.command === "focus" || command.command === "press"), false);++ const copyFailed = run("clipboard_error");+ assert.equal(copyFailed.status, 1);+ assert.equal(copyFailed.stop.error.code, "COPY_FAILED");+ assert.equal(copyFailed.commands.some(command => command.command === "press"), false);++ const wrongText = run("paste_wrong");+ assert.equal(wrongText.status, 1);+ assert.equal(wrongText.stop.error.code, "TEXT_VERIFICATION_FAILED");+ assert.equal(wrongText.commands.filter(command => command.command === "press").length, 1);+ assert.ok(wrongText.commands.filter(command => command.command === "get").length > 1, "a mismatch is re-read until the deadline");++ const late = run("paste_late");+ assert.equal(late.status, 0);+ assert.equal(late.events[0].turn.delivery, "delivered_verified");+ assert.equal(late.commands.filter(command => command.command === "press").length, 1, "the paste is not repeated");+ assert.equal(late.commands.filter(command => command.command === "get").length, 3);++ const old = run("old_binary");+ assert.equal(old.status, 1);+ assert.equal(old.stop.error.code, "BINARY_TOO_OLD");+ assert.equal(old.commands.some(command => command.command === "focus"), false);++ const focusFailed = run("focus_error");+ assert.equal(focusFailed.status, 1);+ assert.equal(focusFailed.stop.stop, "action_failed");+ assert.equal(focusFailed.stop.error.code, "ACTION_FAILED");+ assert.equal(focusFailed.events.filter(event => event.turn).at(-1).turn.ok, false);+ assert.equal(focusFailed.commands.some(command => command.command === "press"), false);++ const pressFailed = run("press_error");+ assert.equal(pressFailed.status, 1);+ assert.equal(pressFailed.stop.stop, "action_failed");+ assert.equal(pressFailed.stop.error.code, "ACTION_FAILED");+ assert.equal(pressFailed.commands.some(command => command.command === "get"), false);++ const readFailed = run("get_error");+ assert.equal(readFailed.status, 1);+ assert.equal(readFailed.stop.stop, "action_failed");+ assert.equal(readFailed.stop.error.code, "TEXT_VERIFICATION_FAILED");+ assert.equal(readFailed.stop.error.details.read_error.code, "ACTION_FAILED");++ const windowed = run("done", ["--window-id", "w-42"]);+ assert.equal(windowed.status, 0);+ const snapshots = windowed.commands.filter(command => command.command === "snapshot");+ assert.ok(snapshots.length > 0);+ for (const { args } of snapshots) assert.deepEqual(args.slice(args.indexOf("--window-id"), args.indexOf("--window-id") + 2), ["--window-id", "w-42"]);+ assert.equal(windowed.stop.screen.window_id, "w-42");+ assert.ok(snapshots.every(({ args }) => args.includes("--window-id")));+ assert.equal(run("done").commands.some(command => command.args.includes("--window-id")), false);++ const windowPaste = run("paste_correct", ["--window-id", "w-42"]);+ assert.equal(windowPaste.status, 0);+ const press = windowPaste.commands.find(command => command.command === "press");+ assert.deepEqual(press.args.slice(press.args.indexOf("--window-id"), press.args.indexOf("--window-id") + 2), ["--window-id", "w-42"]);++ const closed = run("window_closed", ["--window-id", "w-42"]);+ assert.equal(closed.status, 1);+ assert.equal(closed.stop.stop, "window_closed");+ assert.equal(closed.events.filter(event => event.turn).length, 1);+ assert.equal(closed.events.find(event => event.turn).turn.ok, true);+ const afterClick = closed.commands.slice(closed.commands.findIndex(command => command.command === "click") + 1);+ assert.equal(afterClick.filter(command => command.command === "snapshot").length, 1);++ const surfaced = run("surface_ok", ["--window-id", "w-42"]);+ assert.equal(surfaced.status, 0);+ const surfaceReads = surfaced.commands.filter(command => command.args.includes("--surface"));+ assert.ok(surfaceReads.length > 0, "the surface path runs");+ for (const { args } of surfaceReads) assert.deepEqual(args.slice(args.indexOf("--window-id"), args.indexOf("--window-id") + 2), ["--window-id", "w-42"]);+ assert.equal(surfaced.stop.screen.surface, "sheet");++ for (const mode of ["surface_other", "surface_noid"]) {+ const outside = run(mode, ["--window-id", "w-42"]);+ assert.equal(outside.status, 1, mode);+ assert.equal(outside.stop.stop, "surface_outside_window", mode);+ assert.equal(outside.commands.some(command => ["click", "set-value", "press"].includes(command.command)), false, mode);+ }++ const rootOutside = run("root_other", ["--window-id", "w-42", "--root", "@s1:e1"]);+ assert.equal(rootOutside.status, 1);+ assert.equal(rootOutside.stop.stop, "root_outside_window");+ const rootInside = run("done", ["--window-id", "w-42", "--root", "@s1:e1"]);+ assert.equal(rootInside.status, 0);++ const closedTop = run("closed_top", ["--window-id", "w-42"]);+ assert.equal(closedTop.status, 1);+ assert.equal(closedTop.stop.stop, "window_closed");+ assert.equal(closedTop.stop.error, undefined);+ assert.equal(closedTop.stop.screen.window_id, "w-42");++ for (const bad of ["abc", "Infinity", "-1"]) {+ writeFileSync(log, "");+ const refused = spawnSync(process.execPath, ["--import", pathToFileURL(preload).href, entry,+ "--app", "試験アプリ", "--text", "試験", "試験を完了する"], { cwd: directory, encoding: "utf8", timeout: 10000,+ env: { ...process.env, JEV_VERIFY_MS: bad, TYPESAFE_API_KEY: "fixture", AGENT_DESKTOP_BIN: process.execPath,+ JEV_TEST_MODE: "paste_wrong", JEV_TEST_LOG: log } });+ assert.notEqual(refused.status, 0, `JEV_VERIFY_MS=${bad} is refused`);+ assert.match(refused.stderr, /JEV_VERIFY_MS must be a number/);+ assert.equal(readFileSync(log, "utf8"), "", `JEV_VERIFY_MS=${bad} runs no command`);+ }++ for (const tail of [["--window-id"], ["--window-id", "--cursor"]]) {+ const extra = tail;+ const usage = spawnSync(process.execPath, [entry, "--app", "試験アプリ", "試験", ...extra],+ { encoding: "utf8", env: { ...process.env, TYPESAFE_API_KEY: "fixture" } });+ assert.equal(usage.status, 2, extra.join(" "));+ assert.match(usage.stderr, /needs a value/);+ }++ const actWindowed = act("surface_ok", ["--window-id", "w-42"]);+ assert.equal(actWindowed.status, 0);+ assert.equal(actWindowed.out.window_id, "w-42");+ assert.equal(actWindowed.out.surface, "sheet");+ const actReads = actWindowed.commands.filter(command => command.command === "snapshot");+ assert.equal(actReads.length, 2);+ for (const { args } of actReads) assert.deepEqual(args.slice(args.indexOf("--window-id"), args.indexOf("--window-id") + 2), ["--window-id", "w-42"]);++ for (const mode of ["surface_other", "surface_noid"]) {+ const outside = act(mode, ["--window-id", "w-42"]);+ assert.equal(outside.status, 1, mode);+ assert.equal(outside.out.error, "surface_outside_window", mode);+ }+ const actRoot = act("root_other", ["--window-id", "w-42", "--root", "@s1:e1"]);+ assert.equal(actRoot.status, 1);+ assert.equal(actRoot.out.error, "root_outside_window");+ const actUsage = act("done", ["--window-id", "--execute"]);+ assert.equal(actUsage.status, 2);++ assert.equal(run("blocked").status, 1);+ assert.equal(run("done").status, 0);+ const pasted = run("paste_correct");+ assert.equal(pasted.status, 0);+ assert.equal(pasted.commands.filter(command => command.command === "press").length, 1);+ assert.equal(pasted.events[0].turn.delivery, "delivered_verified");+ console.log("ok");+} finally {+ rmSync(directory, { recursive: true, force: true });+}diff --git a/scripts/jev/run.mjs b/scripts/jev/run.mjsindex 940e67996..9da917985 100644--- a/scripts/jev/run.mjs+++ b/scripts/jev/run.mjs@@ -55,10 +55,18 @@ export const decide = (goal, screen, space, history, values) =>export const rateRisk = (goal, screen, operation, node, values) =>post(typesafeApi(), process.env.TYPESAFE_API_KEY, riskRequest(goal, screen, operation, node, { values }));+const WINDOW_STOPS = {+ WINDOW_NOT_FOUND: "window_closed",+ SURFACE_OUTSIDE_WINDOW: "surface_outside_window",+ ROOT_OUTSIDE_WINDOW: "root_outside_window",+};++const windowStop = (error, windowId) => (windowId ? WINDOW_STOPS[error.code] ?? null : null);+export const run = async function* (goal,app,- { root = null, text = null, cursor = false, values = true } = {},+ { root = null, windowId = null, text = null, cursor = false, values = true } = {},) {if (!process.env.TYPESAFE_API_KEY) throw new Error("TYPESAFE_API_KEY unset");const supply = textSupply(text);@@ -66,8 +74,19 @@ export const run = async function* (const clipboard = clipboardGuard();const state = { steps: 0, calls: 0, history: [], operation: null, root };try {+ let last = null;for (;;) {- const { nodes, screen } = observe(app, state.root);+ let seen;+ try {+ seen = observe(app, state.root, windowId);+ } catch (error) {+ const stop = windowStop(error, windowId);+ if (!stop) throw error;+ yield { stop, screen: last, history: state.history };+ return;+ }+ const { nodes, screen } = seen;+ last = screen;const before = fingerprint(nodes);const space = actionSpace(nodes, { drillable: !state.root, typable: supply.available(), values });if (!space.elements.length) {@@ -133,7 +152,7 @@ export const run = async function* (return;}}- const outcome = execute(app, state.operation, node, value, clipboard);+ const outcome = await execute({ app, windowId }, state.operation, node, value, clipboard);state.steps += 1;const turn = {step: state.steps,@@ -144,13 +163,30 @@ export const run = async function* (confidence,ok: outcome.ok,delivery: outcome.delivery,+ error: outcome.error ?? null,route: outcome.route ?? null,truncated: space.truncated,changed: null,};state.history.push(turn);+ if (!outcome.ok) {+ yield { turn, screen };+ yield { stop: "action_failed", screen, error: outcome.error, history: state.history };+ return;+ }if ("root" in outcome) state.root = outcome.root;- turn.changed = "root" in outcome || fingerprint(observe(app, state.root).nodes) !== before;+ let after;+ try {+ after = "root" in outcome ? null : observe(app, state.root, windowId);+ } catch (error) {+ const stop = windowStop(error, windowId);+ if (!stop) throw error;+ turn.changed = true;+ yield { turn, screen };+ yield { stop, screen, history: state.history };+ return;+ }+ turn.changed = "root" in outcome || fingerprint(after.nodes) !== before;yield { turn, screen };const settled = shouldStop(state);if (settled) {@@ -167,10 +203,17 @@ export const run = async function* (const main = async (argv) => {const flag = (name) => {const at = argv.indexOf(`--${name}`);- return at === -1 ? null : argv[at + 1];+ if (at === -1) return null;+ const value = argv[at + 1];+ if (value === undefined || value.startsWith("--")) {+ console.error(`--${name} needs a value`);+ process.exit(2);+ }+ return value;};const app = flag("app");const root = flag("root");+ const windowId = flag("window-id");const text = argv.flatMap((a, i) => (argv[i - 1] === "--text" ? [a] : []));const cursor = argv.includes("--cursor");const values = !argv.includes("--no-values");@@ -179,11 +222,14 @@ const main = async (argv) => {.join(" ");if (!app || !goal) {console.error(- 'usage: run.mjs --app <name> [--cursor] [--no-values] [--root @ref] [--text "value"]... "<goal>"',+ 'usage: run.mjs --app <name> [--window-id <id>] [--cursor] [--no-values] [--root @ref] [--text "value"]... "<goal>"',);process.exit(2);}- for await (const event of run(goal, app, { root, text, cursor, values })) console.log(JSON.stringify(event));+ for await (const event of run(goal, app, { root, windowId, text, cursor, values })) {+ console.log(JSON.stringify(event));+ if (event.stop && event.stop !== "done") process.exitCode = 1;+ }};if (process.argv[1] === fileURLToPath(import.meta.url)) {diff --git a/scripts/jev/screen.mjs b/scripts/jev/screen.mjsindex b8d4c2d4b..67d6c0e8d 100644--- a/scripts/jev/screen.mjs+++ b/scripts/jev/screen.mjs@@ -20,6 +20,11 @@ export const collect = (tree) => {/** A sheet, menu or alert owns input while it is up, and the window tree marks* its elements offscreen. Reading the surface is the only way to act on it. */+export const outsideWindow = (data, windowId) => {+ const ids = [data?.window?.id, data?.surface?.window_id].filter((id) => id !== undefined && id !== null);+ return ids.length === 0 || ids.some((id) => id !== windowId);+};+export const overlayRole = (tree) => {let found = null;const walk = (n) => {diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex c4c10faa5..70dfd3f49 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -273,6 +273,7 @@ agent-desktop --headed batch '[Use the actual window title for the current app language. To check a window that may already be open, use `wait --window "Musical Typing" --app "GarageBand" --timeout 5000`. A failed wait does not make the preceding press safe to repeat.**Key names:** `return`, `escape`, `tab`, `space`, `delete`, `up`, `down`, `left`, `right`, `f1`-`f12`+**Punctuation (macOS):** `,` `.` `/` `;` `'` `[` `]` `\` `-` `=` `` ` ``, or by name: `comma`, `period`, `slash`, `semicolon`, `quote`, `leftbracket`, `rightbracket`, `backslash`, `minus`, `equal`, `grave`. Each symbol is sent with the key that types it in the active keyboard layout, so `press cmd+,` opens an app's Settings on ANSI and JIS keyboards alike.**Modifiers:** `cmd`, `ctrl`, `alt`, `shift` — combine with `+`Dangerous shortcuts (e.g. `cmd+q`, `ctrl+cmd+q`, `cmd+alt+esc`, `cmd+shift+delete`) are refused with `POLICY_DENIED`. Normalization covers modifier order and key-name aliases (`escape`/`esc`, `backspace`/`delete`). The block is the **platform adapter's** decision, not core's — the calling agent stays in control: pass `--force` to send a flagged `press` combo anyway (`agent-desktop press cmd+q --force`). The reserved held-key names reject even when `--force` is present.diff --git a/skills/jev-desktop/SKILL.md b/skills/jev-desktop/SKILL.mdindex e12666866..5ec768aca 100644--- a/skills/jev-desktop/SKILL.md+++ b/skills/jev-desktop/SKILL.md@@ -87,7 +87,9 @@ A screen with more actionable elements than a choice can carry says so, in therequest and in the turn it reports, and the policy is told to look inside aregion rather than call the goal impossible.-`--root @ref` starts inside a region when you already know which one.+`--root @ref` starts inside a region when you already know which one. `--window-id <id>`+reads one window when the app has several open and none is focused, such as a Settings window next to+the main one while another app is in front. Every stop reports the window it read in `screen.window_id`.## One step at a time@@ -121,6 +123,7 @@ node scripts/jev/act.mjs --app TextEdit --execute \| Flag | Meaning || --- | --- || `--app <name>` | Required. |+| `--window-id <id>` | Read one window of the app, by the id `agent-desktop list-windows --app <name>` reports. Needed only when the app has more than one visible window and none of them is focused, which otherwise fails with `AMBIGUOUS_TARGET`. The run stays on that window: a window the run opens elsewhere is not read, and if the window closes after an action, `run.mjs` reports that turn and stops with `window_closed`. `run.mjs` takes it too. || `--execute` | Run the command when `decision` is `act`. Without it, nothing runs. || `--text "…"` | Text the intent needs. Jev returns choices, never strings. || `--root @ref` | Resolve inside one container instead of the whole window. |@@ -219,7 +222,12 @@ is alpha and may change shape.## Checks+`WAIT` in `run.mjs` pauses 250 ms before the screen is read again. A failed operation stops the run at once as `action_failed`, keeping the error code and delivery state, and is never repeated. The CLI exits 0 only when the run stops at `done`; every other stop exits 1.++Text falls back from a direct value write to a paste only when the write reports that nothing was delivered and a retry is safe. A failed clipboard write is reported as the stop reason. After a paste the field is read back; if it does not hold the requested text the run stops with `TEXT_VERIFICATION_FAILED` and does not type again. The read-back compares the exact string, so a field that normalizes text (trims, changes case or line endings) reports a failure even when the text landed; the read is retried until a short deadline before it fails.+```shnode scripts/jev/act.test.mjsnode scripts/jev/run.test.mjs+node scripts/jev/run.integration.test.mjs```diff --git a/tests/native/appkit_workspace_name_test.m b/tests/native/appkit_workspace_name_test.mnew file mode 100644index 000000000..c5e4c0748--- /dev/null+++ b/tests/native/appkit_workspace_name_test.m@@ -0,0 +1,94 @@+#import "../../crates/macos/src/system/appkit_bridge.m"+#import <objc/runtime.h>++static void require(bool condition, const char *message) {+ if (!condition) {+ fprintf(stderr, "%s\n", message);+ exit(1);+ }+}++@interface InventoryTestApplication : NSRunningApplication+@property(nonatomic, copy) NSString *testName;+@property(nonatomic, copy) NSURL *testExecutable;+@property(nonatomic, copy) NSString *testBundle;+@property(nonatomic) pid_t testPID;+@end++@implementation InventoryTestApplication+- (NSString *)localizedName { return self.testName; }+- (NSURL *)executableURL { return self.testExecutable; }+- (NSString *)bundleIdentifier { return self.testBundle; }+- (pid_t)processIdentifier { return self.testPID; }+- (NSApplicationActivationPolicy)activationPolicy { return NSApplicationActivationPolicyAccessory; }+- (NSDate *)launchDate { return [NSDate dateWithTimeIntervalSince1970:100]; }+@end++static NSArray *testApplications;++@interface NSWorkspace (InventoryNameTest)+- (NSArray *)inventoryTestApplications;+- (NSRunningApplication *)inventoryTestFrontmost;+@end++@implementation NSWorkspace (InventoryNameTest)+- (NSArray *)inventoryTestApplications { return testApplications; }+- (NSRunningApplication *)inventoryTestFrontmost { return nil; }+@end++static InventoryTestApplication *application(NSString *name, NSString *executable, NSString *bundle, pid_t pid) {+ InventoryTestApplication *app = [InventoryTestApplication new];+ app.testName = name;+ app.testExecutable = executable == nil ? nil : [NSURL fileURLWithPath:executable];+ app.testBundle = bundle;+ app.testPID = pid;+ return app;+}++static NSDictionary *snapshot(void) {+ AgentDesktopBytesResult result = agent_desktop_copy_workspace_snapshot_json();+ require(result.status == 0, "snapshot status");+ NSData *data = [NSData dataWithBytes:result.bytes length:result.length];+ agent_desktop_free_bridge_bytes(result.bytes);+ NSDictionary *value = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ require(value != nil, "snapshot json");+ return value;+}++int main(void) {+ @autoreleasepool {+ method_exchangeImplementations(class_getInstanceMethod(NSWorkspace.class, @selector(runningApplications)),+ class_getInstanceMethod(NSWorkspace.class, @selector(inventoryTestApplications)));+ method_exchangeImplementations(class_getInstanceMethod(NSWorkspace.class, @selector(frontmostApplication)),+ class_getInstanceMethod(NSWorkspace.class, @selector(inventoryTestFrontmost)));+ testApplications = @[+ application(@"Approval Box", @"/tmp/ApprovalBox", @"dev.example.approvalbox", 10),+ application(@"", @"/System/FollowUpUI", @"com.apple.FollowUpUI", 11),+ application(nil, @"/tmp/Unnamed", @"dev.example.unnamed", 12),+ application(nil, nil, @"dev.example.bundle", 13),+ application(@" \t\n", @"/tmp/Blank", @"dev.example.blank", 16)+ ];+ NSArray *records = snapshot()[@"applications"];+ require(records.count == 5, "record count");+ require([records[0][@"name"] isEqualToString:@"Approval Box"], "name 0");+ require([records[1][@"name"] isEqualToString:@"FollowUpUI"], "name 1");+ require([records[2][@"name"] isEqualToString:@"Unnamed"], "name 2");+ require([records[3][@"name"] isEqualToString:@"dev.example.bundle"], "name 3");+ require([records[4][@"name"] isEqualToString:@"Blank"], "whitespace-only name falls back");+ require([records[1][@"pid"] intValue] == 11, "fallback pid");+ require([records[1][@"bundle_id"] isEqualToString:@"com.apple.FollowUpUI"], "fallback bundle id");+ require([records[1][@"launch_time"] doubleValue] == 100.0, "fallback launch time");+ require([records[1][@"activation_policy"] isEqualToString:@"accessory"], "fallback activation policy");+ testApplications = @[application(nil, nil, nil, 14)];+ AgentDesktopBytesResult missing = agent_desktop_copy_workspace_snapshot_json();+ require(missing.status == 2, "nameless status");+ require(missing.bytes == NULL, "nameless bytes");+ NSString *oversized = [@"x" stringByPaddingToLength:16385 withString:@"x" startingAtIndex:0];+ testApplications = @[application(oversized, @"/tmp/Valid", @"dev.example.valid", 15)];+ AgentDesktopBytesResult invalid = agent_desktop_copy_workspace_snapshot_json();+ require(invalid.status == 2, "oversized status");+ require(invalid.bytes == NULL, "oversized bytes");+ puts("AppKit inventory name regression tests passed");+ }+ return 0;+}