Skip to content

Computer use CLI for AI agents

feat!: decide macOS delivery by observation and stop launch waiting on an uncaused event (#125)

Lahfir298f1ff21530
diff --git a/CLAUDE.md b/CLAUDE.md
index feee51c1c..63c05bd44 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -286,7 +286,7 @@ Every command produces a response envelope:
```json
{
- "version": "2.2",
+ "version": "2.3",
"ok": true,
"command": "snapshot",
"data": {
@@ -302,7 +302,7 @@ Error responses:
```json
{
- "version": "2.2",
+ "version": "2.3",
"ok": false,
"command": "click",
"error": {
diff --git a/crates/core/examples/locator_benchmark/adapter.rs b/crates/core/examples/locator_benchmark/adapter.rs
index 9d107ad43..ad438b9b9 100644
--- a/crates/core/examples/locator_benchmark/adapter.rs
+++ b/crates/core/examples/locator_benchmark/adapter.rs
@@ -39,7 +39,7 @@ impl ObservationOps for FixtureAdapter<'_> {
live_target_tree(
self.fixture,
index,
- ObservationSource::from_root(&root),
+ ObservationSource::from_root(&root, request.surface),
request,
)
}
diff --git a/crates/core/examples/locator_benchmark/fixture_builder.rs b/crates/core/examples/locator_benchmark/fixture_builder.rs
index c91c31a04..40925ec56 100644
--- a/crates/core/examples/locator_benchmark/fixture_builder.rs
+++ b/crates/core/examples/locator_benchmark/fixture_builder.rs
@@ -13,7 +13,10 @@ pub(crate) fn live_tree(
live_tree_from_roots(
fixture,
&fixture.roots,
- ObservationSource::Window(fixture.window.clone()),
+ ObservationSource::Window {
+ window: fixture.window.clone(),
+ surface: agent_desktop_core::SnapshotSurface::Window,
+ },
requirements,
)
}
diff --git a/crates/core/examples/locator_benchmark/live.rs b/crates/core/examples/locator_benchmark/live.rs
index b91f4950c..5c6cce1f1 100644
--- a/crates/core/examples/locator_benchmark/live.rs
+++ b/crates/core/examples/locator_benchmark/live.rs
@@ -66,6 +66,7 @@ fn run_live(
selection,
deadline: Deadline::after(5_000)?,
max_raw_depth: 50,
+ surface: None,
materialization,
};
let adapter = FixtureAdapter { fixture };
diff --git a/crates/core/src/action.rs b/crates/core/src/action.rs
index 5faa9239a..93b7284b9 100644
--- a/crates/core/src/action.rs
+++ b/crates/core/src/action.rs
@@ -96,6 +96,22 @@ impl Action {
)
}
+ /// Whether the action can leave the application showing a sheet, menu, or
+ /// alert. Listing surfaces costs a walk of the application's overlays, so
+ /// only the actions that can raise one pay for it.
+ pub fn may_raise_surface(&self) -> bool {
+ matches!(
+ self,
+ Self::Click
+ | Self::DoubleClick
+ | Self::RightClick
+ | Self::TripleClick
+ | Self::Expand
+ | Self::Select(_)
+ | Self::PressKey(_)
+ )
+ }
+
pub fn requires_scroll_into_view(&self) -> bool {
matches!(
self,
diff --git a/crates/core/src/action_result.rs b/crates/core/src/action_result.rs
index 2372271e6..bd0416f9d 100644
--- a/crates/core/src/action_result.rs
+++ b/crates/core/src/action_result.rs
@@ -11,6 +11,11 @@ pub struct ActionResult {
pub post_state: Option<ElementState>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub steps: Vec<ActionStep>,
+ /// Overlays the application had open once the action settled. An action can
+ /// leave a sheet, menu, or alert on screen, and without this the caller has
+ /// to go hunting through windows to discover it.
+ #[serde(skip_serializing_if = "Vec::is_empty", default)]
+ pub surfaces: Vec<crate::SurfaceInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<serde_json::Value>,
#[serde(
@@ -49,6 +54,7 @@ impl ActionResult {
action: action.into(),
post_state: None,
steps: Vec::new(),
+ surfaces: Vec::new(),
details: None,
disposition: DeliverySemantics::not_delivered(),
}
@@ -59,6 +65,7 @@ impl ActionResult {
action: action.into(),
post_state: None,
steps: Vec::new(),
+ surfaces: Vec::new(),
details: None,
disposition: default_action_disposition(),
}
diff --git a/crates/core/src/actionability/gates.rs b/crates/core/src/actionability/gates.rs
index 85a049475..2880d19e6 100644
--- a/crates/core/src/actionability/gates.rs
+++ b/crates/core/src/actionability/gates.rs
@@ -19,7 +19,13 @@ pub(super) fn visibility(evidence: &ActionabilityEvidence) -> ActionabilityCheck
}
match evidence.state.offscreen {
Some(true) => return fail("visible", "live offscreen state is true"),
- None => return unknown("visible", "live offscreen state unavailable"),
+ None if !evidence.states_complete => {
+ return unknown("visible", "live offscreen state unavailable");
+ }
+ None if crate::state::has_state(&evidence.state.states, crate::state::OFFSCREEN) => {
+ return fail("visible", "canonical offscreen state is present");
+ }
+ None => {}
Some(false) => {}
}
let Some(bounds) = evidence.bounds else {
diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs
index 86e035d8f..c415dad4c 100644
--- a/crates/core/src/adapter/system.rs
+++ b/crates/core/src/adapter/system.rs
@@ -66,7 +66,7 @@ pub trait SystemOps: Send + Sync {
_id: &str,
_options: &crate::launch_options::LaunchOptions,
_lease: &InteractionLease,
- ) -> Result<WindowInfo, AdapterError> {
+ ) -> Result<crate::launch_result::LaunchResult, AdapterError> {
Err(AdapterError::not_supported("launch_app"))
}
diff --git a/crates/core/src/adapter/test_support.rs b/crates/core/src/adapter/test_support.rs
index 1b53ce53a..464666de6 100644
--- a/crates/core/src/adapter/test_support.rs
+++ b/crates/core/src/adapter/test_support.rs
@@ -161,7 +161,7 @@ pub(crate) fn observed_tree(
ObservedTree::from_roots(
vec![subtree(node)],
- ObservationSource::from_root(root),
+ ObservationSource::from_root(root, root.surface()),
LocatorStats::default(),
true,
)
diff --git a/crates/core/src/app_info.rs b/crates/core/src/app_info.rs
index c452c1707..c686ee134 100644
--- a/crates/core/src/app_info.rs
+++ b/crates/core/src/app_info.rs
@@ -2,6 +2,19 @@ use serde::{Deserialize, Serialize};
use crate::ProcessId;
+/// How an application presents itself to the user, so an agent can tell a
+/// window-owning app from one that only appears on a hotkey or lives in the
+/// menu bar or tray.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum AppPresentation {
+ /// Owns ordinary windows and appears in the Dock or taskbar.
+ Foreground,
+ /// No Dock or taskbar entry. Menu bar and tray items live here, as do
+ /// overlays summoned by a hotkey; their windows may exist only while shown.
+ Background,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppInfo {
pub name: String,
@@ -10,4 +23,6 @@ pub struct AppInfo {
pub bundle_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub process_instance: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub presentation: Option<AppPresentation>,
}
diff --git a/crates/core/src/app_lookup_tests.rs b/crates/core/src/app_lookup_tests.rs
index 59c346b1e..9190e0ce3 100644
--- a/crates/core/src/app_lookup_tests.rs
+++ b/crates/core/src/app_lookup_tests.rs
@@ -34,6 +34,7 @@ fn app(instance: Option<&str>) -> AppInfo {
pid: crate::ProcessId::new(42),
bundle_id: Some("com.example.app".into()),
process_instance: instance.map(str::to_string),
+ presentation: None,
}
}
diff --git a/crates/core/src/commands/close_app_tests.rs b/crates/core/src/commands/close_app_tests.rs
index d99f39b02..e18980ed2 100644
--- a/crates/core/src/commands/close_app_tests.rs
+++ b/crates/core/src/commands/close_app_tests.rs
@@ -11,6 +11,7 @@ impl ObservationOps for ProtectiveAdapter {
pid: crate::ProcessId::new(42),
bundle_id: Some("com.apple.TextEdit".into()),
process_instance: Some("textedit-instance".into()),
+ presentation: None,
}])
}
}
@@ -45,6 +46,7 @@ impl ObservationOps for FailingAdapter {
pid: crate::ProcessId::new(77),
bundle_id: None,
process_instance: Some("ghost-instance".into()),
+ presentation: None,
}])
}
}
diff --git a/crates/core/src/commands/find.rs b/crates/core/src/commands/find.rs
index 0d92815ea..32adbcc65 100644
--- a/crates/core/src/commands/find.rs
+++ b/crates/core/src/commands/find.rs
@@ -39,6 +39,9 @@ pub struct FindSelectionArgs {
pub struct FindArgs {
pub app: Option<String>,
pub window_id: Option<String>,
+ pub root: Option<String>,
+ pub snapshot: Option<String>,
+ pub surface: crate::SnapshotSurface,
pub filter: FindFilterArgs,
pub states: Vec<StatePredicate>,
pub selection: FindSelectionArgs,
@@ -50,6 +53,8 @@ pub fn execute(
context: &CommandContext,
) -> Result<Value, AppError> {
validate_find_mode(&args)?;
+ super::surface_scope::reject_root_with_surface("find", args.root.as_deref(), args.surface)?;
+ super::surface_scope::require_supported(args.surface, adapter)?;
let query = locator_query_from_args(&args)?;
query.validate_states().map_err(AppError::Adapter)?;
@@ -230,6 +235,10 @@ mod live;
#[path = "find_tests.rs"]
mod tests;
+#[cfg(test)]
+#[path = "find_live_test_support.rs"]
+mod test_support;
+
#[cfg(test)]
#[path = "find_live_tests.rs"]
mod live_tests;
diff --git a/crates/core/src/commands/find_live.rs b/crates/core/src/commands/find_live.rs
index 8cd2b52ce..1b518be8a 100644
--- a/crates/core/src/commands/find_live.rs
+++ b/crates/core/src/commands/find_live.rs
@@ -24,14 +24,39 @@ pub(super) fn execute(
context: &CommandContext,
) -> Result<Value, AppError> {
let deadline = crate::Deadline::from_duration(LOCATOR_TIMEOUT)?;
- let window = snapshot::resolve_window(
- adapter,
- args.app.as_deref(),
- args.window_id.as_deref(),
- deadline,
- )?;
let request = resolve_request(args, deadline);
- let mut resolution = resolve_query(adapter, query, ObservationRoot::Window(&window), &request)?;
+ let mut resolution = match args.root.as_deref() {
+ Some(root_ref) => {
+ let (_, local_root_ref) =
+ crate::ref_token::resolve_ref_target(root_ref, args.snapshot.as_deref())?;
+ let entry = crate::commands::helpers::load_ref_entry(
+ root_ref,
+ args.snapshot.as_deref(),
+ context,
+ )?;
+ let handle = adapter.resolve_element_strict(&entry, deadline)?;
+ resolve_query(
+ adapter,
+ query,
+ ObservationRoot::Element {
+ handle: &handle,
+ entry: &entry,
+ root_ref: Some(&local_root_ref),
+ },
+ &request,
+ )?
+ }
+ None => {
+ let window = snapshot::resolve_window_for_surface(
+ adapter,
+ args.app.as_deref(),
+ args.window_id.as_deref(),
+ args.surface,
+ deadline,
+ )?;
+ resolve_query(adapter, query, ObservationRoot::Window(&window), &request)?
+ }
+ };
require_complete(&resolution)?;
let ref_count = resolution.refmap.as_ref().map(RefMap::len);
let snapshot_id = match resolution.refmap.take() {
@@ -72,6 +97,7 @@ fn resolve_request(args: &FindArgs, deadline: crate::Deadline) -> LocatorResolve
selection,
deadline,
max_raw_depth: MAX_RAW_DEPTH,
+ surface: (args.surface != crate::SnapshotSurface::Window).then_some(args.surface),
materialization: if args.selection.count {
LocatorMaterialization::None
} else {
@@ -194,6 +220,9 @@ mod tests {
FindArgs {
app: None,
window_id: None,
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: crate::commands::find::FindFilterArgs {
role: None,
name: None,
diff --git a/crates/core/src/commands/find_live_test_support.rs b/crates/core/src/commands/find_live_test_support.rs
new file mode 100644
index 000000000..8630c2dc6
--- /dev/null
+++ b/crates/core/src/commands/find_live_test_support.rs
@@ -0,0 +1,134 @@
+use crate::{
+ AdapterError, WindowInfo,
+ adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps, WindowFilter},
+ live_locator::{
+ IdentifierEvidence, LocatorEvidence, LocatorField, LocatorRefEvidence, LocatorStats,
+ ObservationRequest, ObservationRoot, ObservationSource, ObservedSubtree, ObservedTree,
+ },
+};
+
+pub(crate) struct LiveFindAdapter {
+ structurally_complete: bool,
+}
+
+impl LiveFindAdapter {
+ pub(crate) fn complete() -> Self {
+ Self {
+ structurally_complete: true,
+ }
+ }
+
+ pub(crate) fn incomplete() -> Self {
+ Self {
+ structurally_complete: false,
+ }
+ }
+
+ fn evidence(role: &str, name: Option<&str>) -> LocatorEvidence {
+ LocatorEvidence {
+ role: LocatorField::Known(role.into()),
+ name: name
+ .map(|value| LocatorField::Known(value.into()))
+ .unwrap_or(LocatorField::Absent),
+ description: LocatorField::Absent,
+ value: LocatorField::Absent,
+ identifiers: IdentifierEvidence::absent(),
+ states: LocatorField::Known(Vec::new()),
+ ref_evidence: LocatorRefEvidence {
+ bounds: LocatorField::Absent,
+ available_actions: LocatorField::Known(Vec::new()),
+ },
+ }
+ }
+
+ fn node(&self, evidence: LocatorEvidence, children: Vec<ObservedSubtree>) -> ObservedSubtree {
+ ObservedSubtree::new(evidence, children, self.structurally_complete, None)
+ }
+}
+
+impl ObservationOps for LiveFindAdapter {
+ fn observe_tree(
+ &self,
+ root: ObservationRoot<'_>,
+ request: &ObservationRequest,
+ ) -> Result<ObservedTree, AdapterError> {
+ if let ObservationRoot::Element { entry, .. } = &root {
+ return ObservedTree::from_roots(
+ vec![self.node(
+ Self::evidence(&entry.identity.role, entry.identity.name.as_deref()),
+ Vec::new(),
+ )],
+ ObservationSource::from_root(&root, request.surface),
+ LocatorStats::default(),
+ self.structurally_complete,
+ );
+ }
+ let ObservationRoot::Window(window) = &root else {
+ return Err(AdapterError::internal("expected locator root"));
+ };
+ let window = *window;
+ let marker = if window.id == "w-2" {
+ "OnlyInWindowTwo"
+ } else {
+ "OnlyInWindowOne"
+ };
+ let child = self.node(Self::evidence("button", Some(marker)), Vec::new());
+ let root_node = self.node(Self::evidence("window", Some(&window.title)), vec![child]);
+ ObservedTree::from_roots(
+ vec![root_node],
+ ObservationSource::from_root(&root, request.surface),
+ LocatorStats::default(),
+ self.structurally_complete,
+ )
+ }
+
+ fn list_windows(
+ &self,
+ _filter: &WindowFilter,
+ _deadline: crate::Deadline,
+ ) -> Result<Vec<WindowInfo>, AdapterError> {
+ Ok(vec![
+ WindowInfo {
+ id: "w-1".into(),
+ title: "First".into(),
+ app: "FixtureApp".into(),
+ pid: crate::ProcessId::new(101),
+ process_instance: Some("test-instance".into()),
+ bounds: None,
+ state: crate::WindowState {
+ is_focused: true,
+ ..Default::default()
+ },
+ },
+ WindowInfo {
+ id: "w-2".into(),
+ title: "Second".into(),
+ app: "FixtureApp".into(),
+ pid: crate::ProcessId::new(102),
+ process_instance: Some("test-instance".into()),
+ bounds: None,
+ state: crate::WindowState {
+ is_focused: false,
+ ..Default::default()
+ },
+ },
+ ])
+ }
+
+ fn resolve_locator_anchor(
+ &self,
+ _entry: &crate::refs::RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+}
+
+impl ActionOps for LiveFindAdapter {}
+
+impl InputOps for LiveFindAdapter {}
+impl SystemOps for LiveFindAdapter {
+ fn supported_surfaces(&self) -> Vec<crate::SnapshotSurface> {
+ vec![crate::SnapshotSurface::Window]
+ }
+}
diff --git a/crates/core/src/commands/find_live_tests.rs b/crates/core/src/commands/find_live_tests.rs
index 25a8ad50b..4313644b4 100644
--- a/crates/core/src/commands/find_live_tests.rs
+++ b/crates/core/src/commands/find_live_tests.rs
@@ -1,142 +1,23 @@
+use super::test_support::LiveFindAdapter;
use super::*;
use crate::{
- AdapterError, WindowInfo,
- adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps, WindowFilter},
+ AppError,
+ adapter::{ObservationOps, WindowFilter},
live_locator::{
- IdentifierEvidence, LocatorEvidence, LocatorField, LocatorMaterialization,
- LocatorRefEvidence, LocatorResolveRequest, LocatorSelection, LocatorStats,
- ObservationRequest, ObservationRoot, ObservationSource, ObservedSubtree, ObservedTree,
+ LocatorMaterialization, LocatorResolveRequest, LocatorSelection, ObservationRoot,
require_unique, resolve_query,
},
refs_store::RefStore,
refs_test_support::HomeGuard,
};
-pub(super) struct LiveFindAdapter {
- structurally_complete: bool,
-}
-
-impl LiveFindAdapter {
- pub(super) fn complete() -> Self {
- Self {
- structurally_complete: true,
- }
- }
-
- fn incomplete() -> Self {
- Self {
- structurally_complete: false,
- }
- }
-
- fn evidence(role: &str, name: Option<&str>) -> LocatorEvidence {
- LocatorEvidence {
- role: LocatorField::Known(role.into()),
- name: name
- .map(|value| LocatorField::Known(value.into()))
- .unwrap_or(LocatorField::Absent),
- description: LocatorField::Absent,
- value: LocatorField::Absent,
- identifiers: IdentifierEvidence::absent(),
- states: LocatorField::Known(Vec::new()),
- ref_evidence: LocatorRefEvidence {
- bounds: LocatorField::Absent,
- available_actions: LocatorField::Known(Vec::new()),
- },
- }
- }
-
- fn node(&self, evidence: LocatorEvidence, children: Vec<ObservedSubtree>) -> ObservedSubtree {
- ObservedSubtree::new(evidence, children, self.structurally_complete, None)
- }
-}
-
-impl ObservationOps for LiveFindAdapter {
- fn observe_tree(
- &self,
- root: ObservationRoot<'_>,
- _request: &ObservationRequest,
- ) -> Result<ObservedTree, AdapterError> {
- if let ObservationRoot::Element { entry, .. } = &root {
- return ObservedTree::from_roots(
- vec![self.node(
- Self::evidence(&entry.identity.role, entry.identity.name.as_deref()),
- Vec::new(),
- )],
- ObservationSource::from_root(&root),
- LocatorStats::default(),
- self.structurally_complete,
- );
- }
- let ObservationRoot::Window(window) = &root else {
- return Err(AdapterError::internal("expected locator root"));
- };
- let window = *window;
- let marker = if window.id == "w-2" {
- "OnlyInWindowTwo"
- } else {
- "OnlyInWindowOne"
- };
- let child = self.node(Self::evidence("button", Some(marker)), Vec::new());
- let root_node = self.node(Self::evidence("window", Some(&window.title)), vec![child]);
- ObservedTree::from_roots(
- vec![root_node],
- ObservationSource::from_root(&root),
- LocatorStats::default(),
- self.structurally_complete,
- )
- }
-
- fn list_windows(
- &self,
- _filter: &WindowFilter,
- _deadline: crate::Deadline,
- ) -> Result<Vec<WindowInfo>, AdapterError> {
- Ok(vec![
- WindowInfo {
- id: "w-1".into(),
- title: "First".into(),
- app: "FixtureApp".into(),
- pid: crate::ProcessId::new(101),
- process_instance: Some("test-instance".into()),
- bounds: None,
- state: crate::WindowState {
- is_focused: true,
- ..Default::default()
- },
- },
- WindowInfo {
- id: "w-2".into(),
- title: "Second".into(),
- app: "FixtureApp".into(),
- pid: crate::ProcessId::new(102),
- process_instance: Some("test-instance".into()),
- bounds: None,
- state: crate::WindowState {
- is_focused: false,
- ..Default::default()
- },
- },
- ])
- }
-
- fn resolve_locator_anchor(
- &self,
- _entry: &crate::refs::RefEntry,
- _deadline: crate::Deadline,
- ) -> Result<NativeHandle, AdapterError> {
- Ok(NativeHandle::null())
- }
-}
-
-impl ActionOps for LiveFindAdapter {}
-
-impl InputOps for LiveFindAdapter {}
-impl SystemOps for LiveFindAdapter {}
fn named_find(window_id: &str, name: &str) -> FindArgs {
FindArgs {
app: None,
window_id: Some(window_id.into()),
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: FindFilterArgs {
name: Some(name.into()),
role: None,
@@ -161,6 +42,9 @@ fn unfiltered_find(window_id: &str, selection: FindSelectionArgs) -> FindArgs {
FindArgs {
app: None,
window_id: Some(window_id.into()),
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: FindFilterArgs {
role: None,
name: None,
@@ -366,6 +250,7 @@ fn strict_live_resolution_reports_bounded_ambiguous_candidates() {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(1)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::FullRefMap,
};
let resolution = resolve_query(
diff --git a/crates/core/src/commands/find_tests.rs b/crates/core/src/commands/find_tests.rs
index fbaef50a0..bda1b4322 100644
--- a/crates/core/src/commands/find_tests.rs
+++ b/crates/core/src/commands/find_tests.rs
@@ -130,6 +130,9 @@ fn limit_conflicts_with_single_result_modes_for_batch_too() {
let err = validate_find_mode(&FindArgs {
app: None,
window_id: None,
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: no_filter(),
states: vec![],
selection: FindSelectionArgs {
@@ -176,6 +179,9 @@ fn role_alias_is_preserved_until_live_validation() {
let query = query_from_args(&FindArgs {
app: None,
window_id: None,
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: FindFilterArgs {
role: Some("textarea".into()),
..no_filter()
@@ -197,6 +203,9 @@ fn unknown_role_is_preserved_until_validation() {
let query = query_from_args(&FindArgs {
app: None,
window_id: None,
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: FindFilterArgs {
role: Some("navbar".into()),
..no_filter()
@@ -224,6 +233,9 @@ fn empty_role_filtered_result_reports_roles_present_from_tree() {
let query = query_from_args(&FindArgs {
app: None,
window_id: None,
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: FindFilterArgs {
role: Some("navbar".into()),
..no_filter()
@@ -247,6 +259,9 @@ fn roles_present_hint_is_omitted_when_a_match_is_found() {
let query = query_from_args(&FindArgs {
app: None,
window_id: None,
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: FindFilterArgs {
role: Some("textfield".into()),
..no_filter()
@@ -268,6 +283,9 @@ fn find_args_scoped_to_window(window_id: &str) -> FindArgs {
FindArgs {
app: None,
window_id: Some(window_id.into()),
+ root: None,
+ snapshot: None,
+ surface: crate::SnapshotSurface::Window,
filter: FindFilterArgs {
name: Some("OnlyInWindowTwo".into()),
..no_filter()
@@ -281,7 +299,7 @@ fn find_args_scoped_to_window(window_id: &str) -> FindArgs {
fn find_scopes_matches_to_requested_window_id() {
let _guard = HomeGuard::new();
let context = CommandContext::default();
- let adapter = super::live_tests::LiveFindAdapter::complete();
+ let adapter = super::test_support::LiveFindAdapter::complete();
let from_window_two = execute(find_args_scoped_to_window("w-2"), &adapter, &context)
.expect("find scoped to w-2 should succeed");
diff --git a/crates/core/src/commands/helpers_tests.rs b/crates/core/src/commands/helpers_tests.rs
index 287d3a3d0..dc13b1036 100644
--- a/crates/core/src/commands/helpers_tests.rs
+++ b/crates/core/src/commands/helpers_tests.rs
@@ -110,6 +110,7 @@ impl ObservationOps for RestoreWithoutWindowAdapter {
pid: crate::ProcessId::new(42),
bundle_id: None,
process_instance: Some("test-instance".into()),
+ presentation: None,
}])
}
diff --git a/crates/core/src/commands/launch.rs b/crates/core/src/commands/launch.rs
index 730738559..eb21e3e16 100644
--- a/crates/core/src/commands/launch.rs
+++ b/crates/core/src/commands/launch.rs
@@ -14,8 +14,8 @@ pub fn execute(args: LaunchArgs, adapter: &dyn PlatformAdapter) -> Result<Value,
crate::Deadline::after(args.options.timeout_ms)?
};
let lease = adapter.acquire_interaction_lease(deadline)?;
- let window = adapter.launch_app(&args.app, &args.options, &lease)?;
- Ok(serde_json::to_value(window)?)
+ let launched = adapter.launch_app(&args.app, &args.options, &lease)?;
+ Ok(serde_json::to_value(launched)?)
}
#[cfg(test)]
diff --git a/crates/core/src/commands/launch_tests.rs b/crates/core/src/commands/launch_tests.rs
index cd11e20a0..b5ad70169 100644
--- a/crates/core/src/commands/launch_tests.rs
+++ b/crates/core/src/commands/launch_tests.rs
@@ -27,15 +27,20 @@ impl SystemOps for LaunchAdapter {
_id: &str,
_options: &LaunchOptions,
_lease: &InteractionLease,
- ) -> Result<WindowInfo, AdapterError> {
- Ok(WindowInfo {
- id: "w-1".into(),
- title: "Fixture".into(),
+ ) -> Result<crate::launch_result::LaunchResult, AdapterError> {
+ Ok(crate::launch_result::LaunchResult {
app: "Fixture".into(),
pid: ProcessId::new(42),
process_instance: Some("42:1".into()),
- bounds: None,
- state: WindowState::default(),
+ window: Some(WindowInfo {
+ id: "w-1".into(),
+ title: "Fixture".into(),
+ app: "Fixture".into(),
+ pid: ProcessId::new(42),
+ process_instance: Some("42:1".into()),
+ bounds: None,
+ state: WindowState::default(),
+ }),
})
}
}
diff --git a/crates/core/src/commands/list_apps_tests.rs b/crates/core/src/commands/list_apps_tests.rs
index 5718b756f..cc8498bc8 100644
--- a/crates/core/src/commands/list_apps_tests.rs
+++ b/crates/core/src/commands/list_apps_tests.rs
@@ -12,12 +12,14 @@ impl ObservationOps for AppsAdapter {
pid: crate::ProcessId::new(1),
bundle_id: Some("com.apple.finder".into()),
process_instance: Some("test-instance".into()),
+ presentation: None,
},
AppInfo {
name: "TextEdit".into(),
pid: crate::ProcessId::new(2),
bundle_id: Some("com.apple.TextEdit".into()),
process_instance: Some("test-instance".into()),
+ presentation: None,
},
])
}
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index ea5435c9c..5f2a42592 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -62,6 +62,7 @@ pub mod set_value;
pub mod skills;
pub mod snapshot;
pub mod status;
+pub(crate) mod surface_scope;
pub mod toggle;
pub mod trace;
pub mod triple_click;
diff --git a/crates/core/src/commands/press_tests.rs b/crates/core/src/commands/press_tests.rs
index 13ef95ded..e5054ab02 100644
--- a/crates/core/src/commands/press_tests.rs
+++ b/crates/core/src/commands/press_tests.rs
@@ -66,6 +66,7 @@ impl ObservationOps for CapturingAdapter {
pid: crate::ProcessId::new(42),
bundle_id: Some("com.example.Editor".into()),
process_instance: Some("generation-1".into()),
+ presentation: None,
}])
}
diff --git a/crates/core/src/commands/screenshot_tests.rs b/crates/core/src/commands/screenshot_tests.rs
index 403ce4b58..ee063e14f 100644
--- a/crates/core/src/commands/screenshot_tests.rs
+++ b/crates/core/src/commands/screenshot_tests.rs
@@ -35,6 +35,7 @@ impl ObservationOps for ScreenshotAdapter {
pid: crate::ProcessId::new(700),
bundle_id: Some("com.example.app".into()),
process_instance: Some("instance-700".into()),
+ presentation: None,
}])
}
diff --git a/crates/core/src/commands/snapshot.rs b/crates/core/src/commands/snapshot.rs
index 7ac0cc176..28144cd1e 100644
--- a/crates/core/src/commands/snapshot.rs
+++ b/crates/core/src/commands/snapshot.rs
@@ -60,15 +60,11 @@ pub fn execute(
"Run snapshot without --root, or omit the wait selector flags.",
));
}
- if !matches!(args.surface, SnapshotSurface::Window) {
- return Err(AppError::invalid_input(
- "--root cannot be combined with --surface",
- ));
- }
+ super::surface_scope::reject_root_with_surface("snapshot", Some(root), args.surface)?;
validate_ref_id(root)?;
}
- validate_surface_support(args.surface, adapter)?;
+ super::surface_scope::require_supported(args.surface, adapter)?;
let opts = tree_options(&args);
@@ -108,33 +104,6 @@ pub fn execute(
format_result(result)
}
-fn validate_surface_support(
- requested: SnapshotSurface,
- adapter: &dyn PlatformAdapter,
-) -> Result<(), AppError> {
- let supported = adapter.supported_surfaces();
- if supported.contains(&requested) {
- return Ok(());
- }
- let supported = supported
- .into_iter()
- .map(SnapshotSurface::as_str)
- .collect::<Vec<_>>();
- Err(crate::AdapterError::new(
- crate::ErrorCode::PlatformNotSupported,
- format!(
- "Snapshot surface '{}' is not supported on this platform",
- requested.as_str()
- ),
- )
- .with_details(json!({
- "requested_surface": requested.as_str(),
- "supported_surfaces": supported
- }))
- .with_suggestion("Choose one of the supported snapshot surfaces")
- .into())
-}
-
fn format_result(result: snapshot::SnapshotResult) -> Result<Value, AppError> {
format_snapshot_fields(&result, None, None)
}
diff --git a/crates/core/src/commands/surface_scope.rs b/crates/core/src/commands/surface_scope.rs
new file mode 100644
index 000000000..0a5a6f30f
--- /dev/null
+++ b/crates/core/src/commands/surface_scope.rs
@@ -0,0 +1,56 @@
+use serde_json::json;
+
+use crate::{AppError, SnapshotSurface, adapter::PlatformAdapter};
+
+/// A ref already carries the surface it was captured from, so naming a second
+/// one asks for two roots at once.
+pub(crate) fn reject_root_with_surface(
+ command: &str,
+ root: Option<&str>,
+ surface: SnapshotSurface,
+) -> Result<(), AppError> {
+ if root.is_none() || matches!(surface, SnapshotSurface::Window) {
+ return Ok(());
+ }
+ Err(AppError::invalid_input_with_suggestion(
+ "--root cannot be combined with --surface",
+ format!(
+ "A ref is already scoped to its own surface. Run `{command} --surface` without \
+ --root, or drop --surface."
+ ),
+ ))
+}
+
+/// Every surface, including the window, requires the adapter to declare it. An
+/// adapter that declares none is unimplemented and must fail closed rather than
+/// observe through a partially wired platform.
+pub(crate) fn require_supported(
+ requested: SnapshotSurface,
+ adapter: &dyn PlatformAdapter,
+) -> Result<(), AppError> {
+ let supported = adapter.supported_surfaces();
+ if supported.contains(&requested) {
+ return Ok(());
+ }
+ let supported = supported
+ .into_iter()
+ .map(SnapshotSurface::as_str)
+ .collect::<Vec<_>>();
+ Err(crate::AdapterError::new(
+ crate::ErrorCode::PlatformNotSupported,
+ format!(
+ "Snapshot surface '{}' is not supported on this platform",
+ requested.as_str()
+ ),
+ )
+ .with_details(json!({
+ "requested_surface": requested.as_str(),
+ "supported_surfaces": supported
+ }))
+ .with_suggestion("Choose one of the supported snapshot surfaces")
+ .into())
+}
+
+#[cfg(test)]
+#[path = "surface_scope_tests.rs"]
+mod tests;
diff --git a/crates/core/src/commands/surface_scope_tests.rs b/crates/core/src/commands/surface_scope_tests.rs
new file mode 100644
index 000000000..d19ac928e
--- /dev/null
+++ b/crates/core/src/commands/surface_scope_tests.rs
@@ -0,0 +1,19 @@
+use super::reject_root_with_surface;
+use crate::SnapshotSurface;
+
+#[test]
+fn a_ref_root_may_keep_the_default_window_surface() {
+ assert!(reject_root_with_surface("find", Some("@s1:e2"), SnapshotSurface::Window).is_ok());
+}
+
+#[test]
+fn a_ref_root_rejects_an_explicit_second_surface() {
+ let error = reject_root_with_surface("find", Some("@s1:e2"), SnapshotSurface::Menubar)
+ .expect_err("a ref already carries its surface");
+ assert!(error.to_string().contains("--surface"));
+}
+
+#[test]
+fn a_surface_without_a_root_is_allowed() {
+ assert!(reject_root_with_surface("find", None, SnapshotSurface::Menubar).is_ok());
+}
diff --git a/crates/core/src/commands/wait_event_tests.rs b/crates/core/src/commands/wait_event_tests.rs
index f42a74602..0c34d3124 100644
--- a/crates/core/src/commands/wait_event_tests.rs
+++ b/crates/core/src/commands/wait_event_tests.rs
@@ -103,6 +103,7 @@ fn app(name: &str, instance: &str) -> AppInfo {
pid: crate::ProcessId::new(42),
bundle_id: Some("com.example.editor".into()),
process_instance: Some(instance.into()),
+ presentation: None,
}
}
@@ -329,6 +330,7 @@ fn failed_inventory_poll_never_reports_app_termination() {
pid: crate::ProcessId::new(42),
bundle_id: Some("com.apple.TextEdit".into()),
process_instance: Some("test-instance".into()),
+ presentation: None,
}]);
let err = wait_for_event(request, &adapter, Some(Ok(baseline))).unwrap_err();
diff --git a/crates/core/src/commands/wait_scenario_tests.rs b/crates/core/src/commands/wait_scenario_tests.rs
index 34117f15b..b010d3d29 100644
--- a/crates/core/src/commands/wait_scenario_tests.rs
+++ b/crates/core/src/commands/wait_scenario_tests.rs
@@ -111,6 +111,7 @@ impl ObservationOps for MenuWaitAdapter {
pid: crate::ProcessId::new(42),
bundle_id: None,
process_instance: Some("test-instance".into()),
+ presentation: None,
}])
}
}
diff --git a/crates/core/src/commands/wait_selector.rs b/crates/core/src/commands/wait_selector.rs
index 11dec5d2b..68e715679 100644
--- a/crates/core/src/commands/wait_selector.rs
+++ b/crates/core/src/commands/wait_selector.rs
@@ -173,10 +173,11 @@ fn observe_selector(
query: &crate::LocatorQuery,
deadline: crate::Deadline,
) -> Result<Option<bool>, AppError> {
- let window = snapshot::resolve_window(
+ let window = snapshot::resolve_window_for_surface(
adapter,
input.app.as_deref(),
input.window_id.as_deref(),
+ input.opts.surface,
deadline,
)?;
let resolution = resolve_query(
@@ -187,6 +188,8 @@ fn observe_selector(
selection: LocatorSelection::First,
deadline,
max_raw_depth: 50,
+ surface: (input.opts.surface != crate::SnapshotSurface::Window)
+ .then_some(input.opts.surface),
materialization: LocatorMaterialization::None,
},
)?;
diff --git a/crates/core/src/launch_options.rs b/crates/core/src/launch_options.rs
index 110d11390..429c12254 100644
--- a/crates/core/src/launch_options.rs
+++ b/crates/core/src/launch_options.rs
@@ -13,6 +13,11 @@ pub struct LaunchOptions {
pub cwd: Option<PathBuf>,
pub timeout_ms: u64,
pub attach_if_running: bool,
+ /// Brings the application forward so it presents a window. A document-based
+ /// application creates its first window in response to activation, so a
+ /// caller that needs a window has to ask for one; waiting without asking
+ /// waits for an event that never fires.
+ pub activate: bool,
}
impl Default for LaunchOptions {
@@ -23,6 +28,7 @@ impl Default for LaunchOptions {
cwd: None,
timeout_ms: 5_000,
attach_if_running: true,
+ activate: false,
}
}
}
diff --git a/crates/core/src/launch_result.rs b/crates/core/src/launch_result.rs
new file mode 100644
index 000000000..d821a617b
--- /dev/null
+++ b/crates/core/src/launch_result.rs
@@ -0,0 +1,19 @@
+use serde::{Deserialize, Serialize};
+
+use crate::{ProcessId, WindowInfo};
+
+/// What a launch can honestly report. The process starting and the application
+/// presenting a window are separate outcomes: a background application never
+/// shows one, and a document-based application creates its first window only
+/// once it is brought forward. Reporting them separately lets a caller wait for
+/// the window it actually asked for instead of a deadline. Run `list-apps` for
+/// the presentation of an application that reports no window.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LaunchResult {
+ pub app: String,
+ pub pid: ProcessId,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub process_instance: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub window: Option<WindowInfo>,
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index d572aec6f..c6bd53a71 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -44,6 +44,7 @@ mod interaction_lease;
pub mod interaction_policy;
mod key_combo;
pub mod launch_options;
+pub mod launch_result;
pub mod live_element;
mod live_identity;
mod live_locator;
@@ -160,7 +161,7 @@ pub use adapter::system::SystemOps;
pub use adapter_error::AdapterError;
pub use adapter_session::AdapterSession;
pub use app_error::AppError;
-pub use app_info::AppInfo;
+pub use app_info::{AppInfo, AppPresentation};
pub use clipboard_content::ClipboardContent;
pub use clipboard_format::ClipboardFormat;
pub use containment_predicate::ContainmentPredicate;
diff --git a/crates/core/src/live_locator/evaluator_identifier_tests.rs b/crates/core/src/live_locator/evaluator_identifier_tests.rs
index 69ca57950..31c2f0331 100644
--- a/crates/core/src/live_locator/evaluator_identifier_tests.rs
+++ b/crates/core/src/live_locator/evaluator_identifier_tests.rs
@@ -14,6 +14,7 @@ fn request() -> LocatorResolveRequest {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(5)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
}
}
diff --git a/crates/core/src/live_locator/evaluator_tests.rs b/crates/core/src/live_locator/evaluator_tests.rs
index e760f77c5..828320b3f 100644
--- a/crates/core/src/live_locator/evaluator_tests.rs
+++ b/crates/core/src/live_locator/evaluator_tests.rs
@@ -14,6 +14,7 @@ fn request(selection: LocatorSelection) -> LocatorResolveRequest {
selection,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(5)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
}
}
diff --git a/crates/core/src/live_locator/evidence_requirements.rs b/crates/core/src/live_locator/evidence_requirements.rs
index cb860b435..794b15361 100644
--- a/crates/core/src/live_locator/evidence_requirements.rs
+++ b/crates/core/src/live_locator/evidence_requirements.rs
@@ -99,6 +99,7 @@ mod tests {
selection: LocatorSelection::First,
deadline: crate::Deadline::after(500).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
};
diff --git a/crates/core/src/live_locator/hydrate.rs b/crates/core/src/live_locator/hydrate.rs
index fe05976a2..fb78dce96 100644
--- a/crates/core/src/live_locator/hydrate.rs
+++ b/crates/core/src/live_locator/hydrate.rs
@@ -95,6 +95,7 @@ pub(super) fn selected_matches(
query,
&super::LocatorResolveRequest {
selection: super::LocatorSelection::First,
+ surface: None,
materialization: super::LocatorMaterialization::None,
..*request
},
diff --git a/crates/core/src/live_locator/locator_resolve_request.rs b/crates/core/src/live_locator/locator_resolve_request.rs
index 80851fee4..e3cbf998b 100644
--- a/crates/core/src/live_locator/locator_resolve_request.rs
+++ b/crates/core/src/live_locator/locator_resolve_request.rs
@@ -7,4 +7,8 @@ pub struct LocatorResolveRequest {
pub deadline: Deadline,
pub max_raw_depth: u8,
pub materialization: LocatorMaterialization,
+ /// Overrides the surface implied by the root. A window root otherwise means
+ /// the window surface, which leaves menu bars and other overlays
+ /// unreachable by a targeted search.
+ pub surface: Option<crate::SnapshotSurface>,
}
diff --git a/crates/core/src/live_locator/materialize.rs b/crates/core/src/live_locator/materialize.rs
index b2cdfd2de..d39541bf6 100644
--- a/crates/core/src/live_locator/materialize.rs
+++ b/crates/core/src/live_locator/materialize.rs
@@ -98,13 +98,14 @@ pub(crate) fn ref_entry(
fn apply_source(entry: &mut RefEntry, source: &ObservationSource, node_path: &RefPath) {
match source {
- ObservationSource::Window(window) => {
+ ObservationSource::Window { window, surface } => {
entry.process.pid = window.pid;
entry.source.source_app = Some(window.app.clone());
entry.source.source_window_id = Some(window.id.clone());
entry.source.source_window_title = Some(window.title.clone());
entry.source.source_window_bounds_hash =
window.bounds.as_ref().and_then(crate::Rect::bounds_hash);
+ entry.source.source_surface = *surface;
entry.process.process_instance = window.process_instance.clone();
}
ObservationSource::Element {
diff --git a/crates/core/src/live_locator/materialize_tests.rs b/crates/core/src/live_locator/materialize_tests.rs
index 4be7535ac..e9cc3b3c2 100644
--- a/crates/core/src/live_locator/materialize_tests.rs
+++ b/crates/core/src/live_locator/materialize_tests.rs
@@ -17,6 +17,7 @@ fn request() -> LocatorResolveRequest {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(5)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::FullRefMap,
}
}
@@ -50,6 +51,7 @@ fn selected_materialization_persists_only_returned_matches() {
selection: LocatorSelection::First,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(5)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
},
)
@@ -190,7 +192,7 @@ fn window_source_materialization_preserves_geometry_generation_evidence() {
vec![0],
true,
);
- let ObservationSource::Window(window) = &mut observed.source else {
+ let ObservationSource::Window { window, .. } = &mut observed.source else {
panic!("fixture must use a window source");
};
window.bounds = Some(bounds);
diff --git a/crates/core/src/live_locator/observation_request.rs b/crates/core/src/live_locator/observation_request.rs
index 98010f213..1044051da 100644
--- a/crates/core/src/live_locator/observation_request.rs
+++ b/crates/core/src/live_locator/observation_request.rs
@@ -82,7 +82,7 @@ impl ObservationRequest {
deadline: Deadline,
) -> Self {
Self {
- surface: root.surface(),
+ surface: request.surface.unwrap_or_else(|| root.surface()),
..Self::locator(query, request, deadline)
}
}
diff --git a/crates/core/src/live_locator/observation_source.rs b/crates/core/src/live_locator/observation_source.rs
index 3c68bc335..858a6180c 100644
--- a/crates/core/src/live_locator/observation_source.rs
+++ b/crates/core/src/live_locator/observation_source.rs
@@ -4,7 +4,13 @@ use super::ObservationRoot;
#[derive(Debug, Clone)]
pub enum ObservationSource {
- Window(WindowInfo),
+ Window {
+ window: WindowInfo,
+ /// The surface actually walked. A ref that was found on the menu bar
+ /// must record that, or re-resolving it later searches the window and
+ /// reports the element missing.
+ surface: crate::SnapshotSurface,
+ },
Element {
entry: Box<RefEntry>,
root_ref: Option<String>,
@@ -12,9 +18,12 @@ pub enum ObservationSource {
}
impl ObservationSource {
- pub fn from_root(root: &ObservationRoot<'_>) -> Self {
+ pub fn from_root(root: &ObservationRoot<'_>, surface: crate::SnapshotSurface) -> Self {
match root {
- ObservationRoot::Window(window) => Self::Window((*window).clone()),
+ ObservationRoot::Window(window) => Self::Window {
+ window: (*window).clone(),
+ surface,
+ },
ObservationRoot::Element {
entry, root_ref, ..
} => Self::Element {
diff --git a/crates/core/src/live_locator/observed_tree_tests.rs b/crates/core/src/live_locator/observed_tree_tests.rs
index 7b2dd0b7e..be11d762d 100644
--- a/crates/core/src/live_locator/observed_tree_tests.rs
+++ b/crates/core/src/live_locator/observed_tree_tests.rs
@@ -10,18 +10,21 @@ use crate::{
use super::test_support::evidence;
fn source() -> ObservationSource {
- ObservationSource::Window(WindowInfo {
- id: "w-1".into(),
- title: "Fixture".into(),
- app: "FixtureApp".into(),
- pid: crate::ProcessId::new(42),
- process_instance: Some("test-instance".into()),
- bounds: None,
- state: crate::WindowState {
- is_focused: true,
- ..Default::default()
+ ObservationSource::Window {
+ surface: crate::SnapshotSurface::Window,
+ window: WindowInfo {
+ id: "w-1".into(),
+ title: "Fixture".into(),
+ app: "FixtureApp".into(),
+ pid: crate::ProcessId::new(42),
+ process_instance: Some("test-instance".into()),
+ bounds: None,
+ state: crate::WindowState {
+ is_focused: true,
+ ..Default::default()
+ },
},
- })
+ }
}
fn subtree(role: &str, name: &str, children: Vec<ObservedSubtree>) -> ObservedSubtree {
@@ -120,6 +123,7 @@ fn snapshot_projection_and_find_share_the_same_observation() {
selection: LocatorSelection::Count,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(1)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
},
)
diff --git a/crates/core/src/live_locator/ownership_tests.rs b/crates/core/src/live_locator/ownership_tests.rs
index 8a00a0847..e321b37a3 100644
--- a/crates/core/src/live_locator/ownership_tests.rs
+++ b/crates/core/src/live_locator/ownership_tests.rs
@@ -10,6 +10,7 @@ fn request(selection: LocatorSelection) -> LocatorResolveRequest {
selection,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(5)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
}
}
diff --git a/crates/core/src/live_locator/resolve.rs b/crates/core/src/live_locator/resolve.rs
index 814a0b305..46c1666ae 100644
--- a/crates/core/src/live_locator/resolve.rs
+++ b/crates/core/src/live_locator/resolve.rs
@@ -210,6 +210,7 @@ pub fn find_first_entry(
selection: super::LocatorSelection::First,
deadline: crate::Deadline::from_duration(timeout)?,
max_raw_depth: 50,
+ surface: None,
materialization: super::LocatorMaterialization::SelectedMatches,
},
)
diff --git a/crates/core/src/live_locator/resolve_query_hydration_tests.rs b/crates/core/src/live_locator/resolve_query_hydration_tests.rs
index a5b1d51f7..0b17f6c92 100644
--- a/crates/core/src/live_locator/resolve_query_hydration_tests.rs
+++ b/crates/core/src/live_locator/resolve_query_hydration_tests.rs
@@ -73,6 +73,7 @@ fn hydration_retry_preserves_failed_attempt_statistics() {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::after(5_000).unwrap(),
max_raw_depth: 10,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
};
@@ -134,6 +135,7 @@ fn selected_hydration_rejects_incomplete_snapshot_evidence() {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::after(35).unwrap(),
max_raw_depth: 10,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
};
diff --git a/crates/core/src/live_locator/resolve_query_tests.rs b/crates/core/src/live_locator/resolve_query_tests.rs
index d776b625c..484825c3f 100644
--- a/crates/core/src/live_locator/resolve_query_tests.rs
+++ b/crates/core/src/live_locator/resolve_query_tests.rs
@@ -41,6 +41,7 @@ fn request_with_timeout(timeout: std::time::Duration) -> LocatorResolveRequest {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::from_duration(timeout).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
}
}
diff --git a/crates/core/src/live_locator/resolve_tests.rs b/crates/core/src/live_locator/resolve_tests.rs
index f1bbd5995..cb1af9c26 100644
--- a/crates/core/src/live_locator/resolve_tests.rs
+++ b/crates/core/src/live_locator/resolve_tests.rs
@@ -11,6 +11,7 @@ fn request() -> LocatorResolveRequest {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(5)).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
}
}
diff --git a/crates/core/src/live_locator/scrollarea_name_tests.rs b/crates/core/src/live_locator/scrollarea_name_tests.rs
index e8f2d264d..b49c87a34 100644
--- a/crates/core/src/live_locator/scrollarea_name_tests.rs
+++ b/crates/core/src/live_locator/scrollarea_name_tests.rs
@@ -29,6 +29,7 @@ fn exact_named_scroll_area_is_unique_among_unnamed_scroll_containers() {
selection: LocatorSelection::Strict,
deadline: crate::Deadline::after(500).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
};
diff --git a/crates/core/src/live_locator/selected_hydration_churn_tests.rs b/crates/core/src/live_locator/selected_hydration_churn_tests.rs
index 96f6b5442..4d1896eed 100644
--- a/crates/core/src/live_locator/selected_hydration_churn_tests.rs
+++ b/crates/core/src/live_locator/selected_hydration_churn_tests.rs
@@ -205,6 +205,7 @@ fn selected_request() -> LocatorResolveRequest {
selection: LocatorSelection::First,
deadline: crate::Deadline::after(5_000).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
}
}
@@ -247,7 +248,7 @@ fn single_hydration_tree(
vec![0],
true,
);
- tree.source = ObservationSource::from_root(&root);
+ tree.source = ObservationSource::from_root(&root, crate::SnapshotSurface::Window);
tree.structurally_complete = topology_complete;
tree
}
diff --git a/crates/core/src/live_locator/selected_hydration_contract_tests.rs b/crates/core/src/live_locator/selected_hydration_contract_tests.rs
index 9ea0b606e..30d73deca 100644
--- a/crates/core/src/live_locator/selected_hydration_contract_tests.rs
+++ b/crates/core/src/live_locator/selected_hydration_contract_tests.rs
@@ -194,7 +194,7 @@ fn hydrated_tree(root: ObservationRoot<'_>, mode: Mode) -> ObservedTree {
vec![0],
true,
);
- tree.source = ObservationSource::from_root(&root);
+ tree.source = ObservationSource::from_root(&root, crate::SnapshotSurface::Window);
tree
}
@@ -235,6 +235,7 @@ fn selected_request() -> LocatorResolveRequest {
selection: LocatorSelection::First,
deadline: crate::Deadline::after(5_000).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
}
}
diff --git a/crates/core/src/live_locator/selected_hydration_subtree_tests.rs b/crates/core/src/live_locator/selected_hydration_subtree_tests.rs
index ea08d5ab0..3471676db 100644
--- a/crates/core/src/live_locator/selected_hydration_subtree_tests.rs
+++ b/crates/core/src/live_locator/selected_hydration_subtree_tests.rs
@@ -210,7 +210,7 @@ fn selected_tree(root: ObservationRoot<'_>, mode: Mode) -> ObservedTree {
nodes[last].completeness.subtree_complete = false;
}
let mut tree = super::test_support::tree(nodes, vec![0], !incomplete);
- tree.source = ObservationSource::from_root(&root);
+ tree.source = ObservationSource::from_root(&root, crate::SnapshotSurface::Window);
tree
}
@@ -296,6 +296,7 @@ fn request() -> LocatorResolveRequest {
selection: LocatorSelection::First,
deadline: crate::Deadline::after(5_000).unwrap(),
max_raw_depth: 10,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
}
}
diff --git a/crates/core/src/live_locator/selected_hydration_tests.rs b/crates/core/src/live_locator/selected_hydration_tests.rs
index 7a9edb559..779e532b0 100644
--- a/crates/core/src/live_locator/selected_hydration_tests.rs
+++ b/crates/core/src/live_locator/selected_hydration_tests.rs
@@ -101,6 +101,7 @@ fn role_only_selected_hydration_anchors_before_hydrating_without_rewalking_large
selection: LocatorSelection::First,
deadline: crate::Deadline::after(5_000).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::SelectedMatches,
};
@@ -231,7 +232,7 @@ fn hydrated_button_tree(root: ObservationRoot<'_>) -> ObservedTree {
vec![0],
true,
);
- tree.source = ObservationSource::from_root(&root);
+ tree.source = ObservationSource::from_root(&root, crate::SnapshotSurface::Window);
tree.stats.traversal.nodes_visited = 1;
tree.stats.reads.counts.attribute_batches = 1;
tree.stats.reads.counts.attributes_requested = 23;
diff --git a/crates/core/src/live_locator/selection_completeness_tests.rs b/crates/core/src/live_locator/selection_completeness_tests.rs
index 6be039ccf..22269c8e0 100644
--- a/crates/core/src/live_locator/selection_completeness_tests.rs
+++ b/crates/core/src/live_locator/selection_completeness_tests.rs
@@ -122,6 +122,7 @@ fn first_request() -> LocatorResolveRequest {
selection: LocatorSelection::First,
deadline: crate::Deadline::after(500).unwrap(),
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
}
}
diff --git a/crates/core/src/live_locator/test_support.rs b/crates/core/src/live_locator/test_support.rs
index bc90ea5c2..13e2a3d7e 100644
--- a/crates/core/src/live_locator/test_support.rs
+++ b/crates/core/src/live_locator/test_support.rs
@@ -61,7 +61,10 @@ pub(crate) fn tree(
ObservedTree {
nodes,
roots,
- source: ObservationSource::Window(window()),
+ source: ObservationSource::Window {
+ window: window(),
+ surface: crate::SnapshotSurface::Window,
+ },
stats: LocatorStats::default(),
structurally_complete,
}
diff --git a/crates/core/src/live_locator/validation_tests.rs b/crates/core/src/live_locator/validation_tests.rs
index 7ef333bb5..fdfd790c3 100644
--- a/crates/core/src/live_locator/validation_tests.rs
+++ b/crates/core/src/live_locator/validation_tests.rs
@@ -17,6 +17,7 @@ fn request(max_raw_depth: u8) -> LocatorResolveRequest {
selection: LocatorSelection::All { limit: None },
deadline: crate::Deadline::from_duration(std::time::Duration::from_secs(5)).unwrap(),
max_raw_depth,
+ surface: None,
materialization: LocatorMaterialization::None,
}
}
diff --git a/crates/core/src/node_tests.rs b/crates/core/src/node_tests.rs
index 443805536..98ec1bfde 100644
--- a/crates/core/src/node_tests.rs
+++ b/crates/core/src/node_tests.rs
@@ -84,6 +84,7 @@ fn app_info_bundle_id_none_omitted_from_json() {
pid: crate::ProcessId::new(42),
bundle_id: None,
process_instance: Some("test-instance".into()),
+ presentation: None,
};
let json = serde_json::to_string(&info).unwrap();
assert!(
@@ -100,6 +101,7 @@ fn app_info_bundle_id_some_present_in_json() {
pid: crate::ProcessId::new(7),
bundle_id: Some("com.apple.Safari".into()),
process_instance: Some("test-instance".into()),
+ presentation: None,
};
let json = serde_json::to_string(&info).unwrap();
assert!(
@@ -117,6 +119,7 @@ fn app_info_roundtrip_preserves_all_fields() {
pid: crate::ProcessId::new(1234),
bundle_id: Some("com.apple.TextEdit".into()),
process_instance: Some("test-instance".into()),
+ presentation: None,
};
let json = serde_json::to_string(&original).unwrap();
let back: AppInfo = serde_json::from_str(&json).unwrap();
diff --git a/crates/core/src/output.rs b/crates/core/src/output.rs
index 9890ffb7d..b0760e002 100644
--- a/crates/core/src/output.rs
+++ b/crates/core/src/output.rs
@@ -4,7 +4,7 @@ use serde_json::Value;
use crate::recovery_hint::RecoveryHint;
use crate::{AppError, DeliverySemantics, ErrorCode, RetryDisposition};
-pub const ENVELOPE_VERSION: &str = "2.2";
+pub const ENVELOPE_VERSION: &str = "2.3";
/// Structured output envelope used by the CLI and future programmatic transports.
#[derive(Debug, Serialize)]
diff --git a/crates/core/src/ref_action.rs b/crates/core/src/ref_action.rs
index 2e99b4576..8be9afbbe 100644
--- a/crates/core/src/ref_action.rs
+++ b/crates/core/src/ref_action.rs
@@ -99,17 +99,21 @@ pub(crate) fn dispatch_resolved(
}
request = request
.with_verified_point(preflight.verified_point)
- .with_expected_process(expected_process);
+ .with_expected_process(expected_process.clone());
let final_target = ResolvedRefAction::new(target, &handle);
final_target.context.trace_lazy(
"action.dispatch.start",
|| json!({ "ref": final_target.ref_id, "action": request.action.name() }),
)?;
let action_name = request.action.name();
+ let raises_surface = request.action.may_raise_surface();
let dispatch_result = final_target
.adapter
.execute_action(final_target.handle, request, lease);
- let result = dispatch_result?;
+ let mut result = dispatch_result?;
+ if raises_surface {
+ result.surfaces = settled_surfaces(&final_target, expected_process);
+ }
final_target
.context
.trace_lazy(
@@ -120,6 +124,20 @@ pub(crate) fn dispatch_resolved(
Ok(result)
}
+/// An action that opens a sheet, menu, or alert leaves the caller staring at a
+/// success envelope with no hint that the application is now waiting on a
+/// dialog. Reporting the overlays saves a round of window archaeology. Purely
+/// informational, so a failed read never disturbs delivered work.
+fn settled_surfaces(
+ target: &ResolvedRefAction<'_>,
+ process: crate::ProcessIdentity,
+) -> Vec<crate::SurfaceInfo> {
+ target
+ .adapter
+ .list_surfaces(process, target.deadline)
+ .unwrap_or_default()
+}
+
pub(crate) fn mark_pre_dispatch_resolution_failure(error: AdapterError) -> AdapterError {
match error.disposition {
crate::DeliverySemantics::Unknown | crate::DeliverySemantics::NotDelivered => {
diff --git a/crates/core/src/ref_action_wait.rs b/crates/core/src/ref_action_wait.rs
index 4cbf0d12b..b74e36a69 100644
--- a/crates/core/src/ref_action_wait.rs
+++ b/crates/core/src/ref_action_wait.rs
@@ -133,6 +133,10 @@ mod process_state_tests;
#[path = "ref_action_wait_app_not_found_tests.rs"]
mod app_not_found_tests;
+#[cfg(test)]
+#[path = "ref_action_wait_success_tests.rs"]
+mod success_tests;
+
#[cfg(test)]
#[path = "ref_action_exactly_once_tests.rs"]
mod exactly_once_tests;
diff --git a/crates/core/src/ref_action_wait_app_not_found_tests.rs b/crates/core/src/ref_action_wait_app_not_found_tests.rs
index 99e9e6924..8333e42ff 100644
--- a/crates/core/src/ref_action_wait_app_not_found_tests.rs
+++ b/crates/core/src/ref_action_wait_app_not_found_tests.rs
@@ -180,6 +180,7 @@ impl ObservationOps for AppNotFoundUnresponsiveProcessAdapter {
pid: crate::ProcessId::new(1),
bundle_id: None,
process_instance: Some("test-instance".into()),
+ presentation: None,
}])
}
diff --git a/crates/core/src/ref_action_wait_process_state_tests.rs b/crates/core/src/ref_action_wait_process_state_tests.rs
index 9fa09651a..2fb838dbe 100644
--- a/crates/core/src/ref_action_wait_process_state_tests.rs
+++ b/crates/core/src/ref_action_wait_process_state_tests.rs
@@ -75,6 +75,7 @@ fn app(name: &str) -> AppInfo {
pid: crate::ProcessId::new(1),
bundle_id: None,
process_instance: Some("test-instance".into()),
+ presentation: None,
}
}
@@ -333,68 +334,3 @@ fn terminal_stale_ref_against_crashed_process_carries_process_state_detail() {
"STALE_REF against a crashed pid must carry details.process_state = \"crashed\""
);
}
-
-struct SuccessWithUnresponsiveProbeAdapter {
- probe_calls: AtomicU32,
-}
-
-impl ObservationOps for SuccessWithUnresponsiveProbeAdapter {
- fn resolve_element_strict(
- &self,
- _entry: &RefEntry,
- _deadline: crate::Deadline,
- ) -> Result<NativeHandle, AdapterError> {
- Ok(NativeHandle::null())
- }
-
- crate::adapter::complete_live_observation!("button", "Run", [capability::CLICK]);
-}
-
-impl ActionOps for SuccessWithUnresponsiveProbeAdapter {
- fn execute_action(
- &self,
- _handle: &NativeHandle,
- _request: ActionRequest,
- _lease: &crate::InteractionLease,
- ) -> Result<crate::action_result::ActionResult, AdapterError> {
- Ok(crate::action_result::ActionResult::delivered_unverified(
- "click",
- ))
- }
-}
-
-impl InputOps for SuccessWithUnresponsiveProbeAdapter {}
-
-impl SystemOps for SuccessWithUnresponsiveProbeAdapter {
- crate::adapter::guarded_interaction_lease!();
-
- fn process_state(
- &self,
- _process: crate::ProcessIdentity,
- _deadline: crate::Deadline,
- ) -> Result<crate::process_state::ProcessState, AdapterError> {
- self.probe_calls.fetch_add(1, Ordering::SeqCst);
- Ok(crate::process_state::ProcessState::Unresponsive)
- }
-}
-
-#[test]
-fn enrichment_never_converts_a_successful_action_into_a_failure() {
- let adapter = SuccessWithUnresponsiveProbeAdapter {
- probe_calls: AtomicU32::new(0),
- };
-
- let result = execute_with_auto_wait(
- RefActionWaitCtx {
- adapter: &adapter,
- entry: &entry(),
- ref_id: "@e1",
- context: &CommandContext::default(),
- },
- ActionRequest::headless(Action::Click),
- crate::ref_action::dispatch_resolved,
- )
- .unwrap();
- assert_eq!(result.action, "click");
- assert_eq!(adapter.probe_calls.load(Ordering::SeqCst), 0);
-}
diff --git a/crates/core/src/ref_action_wait_success_tests.rs b/crates/core/src/ref_action_wait_success_tests.rs
new file mode 100644
index 000000000..9d2c04aee
--- /dev/null
+++ b/crates/core/src/ref_action_wait_success_tests.rs
@@ -0,0 +1,119 @@
+use super::*;
+use crate::{
+ AdapterError,
+ action::Action,
+ adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps},
+ capability,
+};
+use std::sync::atomic::{AtomicU32, Ordering};
+
+/// Covers the branch where a successful action must never be rewritten into a
+/// failure by process-state enrichment, split out of
+/// `ref_action_wait_process_state_tests.rs` to keep both files under the
+/// repo's 400 LOC hard limit.
+fn entry() -> RefEntry {
+ let bounds = crate::Rect {
+ x: 1.0,
+ y: 1.0,
+ width: 20.0,
+ height: 20.0,
+ };
+ RefEntry {
+ process: crate::RefProcess {
+ pid: crate::ProcessId::new(1),
+ process_instance: Some("test-instance".into()),
+ },
+ identity: crate::RefEntryIdentity {
+ role: "button".into(),
+ name: Some("Run".into()),
+ value: None,
+ description: None,
+ native_id: None,
+ },
+ geometry: crate::RefGeometry {
+ bounds: Some(bounds),
+ bounds_hash: bounds.bounds_hash(),
+ },
+ capabilities: crate::RefCapabilities {
+ states: vec![],
+ available_actions: vec![capability::CLICK.into()],
+ },
+ source: crate::RefSource {
+ source_app: Some("Original".into()),
+ source_window_id: None,
+ source_window_title: None,
+ source_window_bounds_hash: None,
+ source_surface: crate::snapshot_surface::SnapshotSurface::Window,
+ },
+ scope: crate::RefScope {
+ root_ref: None,
+ path_is_absolute: false,
+ path: smallvec::SmallVec::new(),
+ },
+ }
+}
+
+struct SuccessWithUnresponsiveProbeAdapter {
+ probe_calls: AtomicU32,
+}
+
+impl ObservationOps for SuccessWithUnresponsiveProbeAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ crate::adapter::complete_live_observation!("button", "Run", [capability::CLICK]);
+}
+
+impl ActionOps for SuccessWithUnresponsiveProbeAdapter {
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ _request: ActionRequest,
+ _lease: &crate::InteractionLease,
+ ) -> Result<crate::action_result::ActionResult, AdapterError> {
+ Ok(crate::action_result::ActionResult::delivered_unverified(
+ "click",
+ ))
+ }
+}
+
+impl InputOps for SuccessWithUnresponsiveProbeAdapter {}
+
+impl SystemOps for SuccessWithUnresponsiveProbeAdapter {
+ crate::adapter::guarded_interaction_lease!();
+
+ fn process_state(
+ &self,
+ _process: crate::ProcessIdentity,
+ _deadline: crate::Deadline,
+ ) -> Result<crate::process_state::ProcessState, AdapterError> {
+ self.probe_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(crate::process_state::ProcessState::Unresponsive)
+ }
+}
+
+#[test]
+fn enrichment_never_converts_a_successful_action_into_a_failure() {
+ let adapter = SuccessWithUnresponsiveProbeAdapter {
+ probe_calls: AtomicU32::new(0),
+ };
+
+ let result = execute_with_auto_wait(
+ RefActionWaitCtx {
+ adapter: &adapter,
+ entry: &entry(),
+ ref_id: "@e1",
+ context: &CommandContext::default(),
+ },
+ ActionRequest::headless(Action::Click),
+ crate::ref_action::dispatch_resolved,
+ )
+ .unwrap();
+ assert_eq!(result.action, "click");
+ assert_eq!(adapter.probe_calls.load(Ordering::SeqCst), 0);
+}
diff --git a/crates/core/src/signals_tests.rs b/crates/core/src/signals_tests.rs
index dba68ba56..540a3c1ce 100644
--- a/crates/core/src/signals_tests.rs
+++ b/crates/core/src/signals_tests.rs
@@ -25,6 +25,7 @@ fn app_with_instance(name: &str, pid: u32, instance: &str) -> AppInfo {
pid: crate::ProcessId::new(pid),
bundle_id: None,
process_instance: Some(instance.into()),
+ presentation: None,
}
}
diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs
index ded5a5ad2..b1b6e8cfa 100644
--- a/crates/core/src/snapshot.rs
+++ b/crates/core/src/snapshot.rs
@@ -37,7 +37,7 @@ pub fn build(
window_id: Option<&str>,
deadline: crate::Deadline,
) -> Result<SnapshotResult, AppError> {
- let window = resolve_window(adapter, app_name, window_id, deadline)?;
+ let window = resolve_window_for_surface(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,
@@ -81,6 +81,57 @@ pub fn build(
})
}
+/// Resolves the window that identifies the process to observe. An app-level
+/// surface is not owned by a single window, so several open windows must not be
+/// reported as ambiguous when one is requested.
+pub(crate) fn resolve_window_for_surface(
+ adapter: &dyn PlatformAdapter,
+ app_name: Option<&str>,
+ window_id: Option<&str>,
+ surface: crate::SnapshotSurface,
+ deadline: crate::Deadline,
+) -> Result<WindowInfo, AppError> {
+ if window_id.is_some() || matches!(surface, crate::SnapshotSurface::Window) {
+ return resolve_window(adapter, app_name, window_id, deadline);
+ }
+ crate::window_lookup::select_surface_owner(
+ windows_for_app(adapter, app_name, deadline)?,
+ crate::AdapterError::new(
+ crate::ErrorCode::AppNotFound,
+ format!(
+ "No window found to identify the application owning surface '{}'",
+ surface.as_str()
+ ),
+ ),
+ )
+}
+
+fn windows_for_app(
+ adapter: &dyn PlatformAdapter,
+ app_name: Option<&str>,
+ deadline: crate::Deadline,
+) -> Result<Vec<WindowInfo>, AppError> {
+ let filter = WindowFilter {
+ focused_only: app_name.is_none(),
+ app: app_name.map(str::to_string),
+ };
+ Ok(windows_matching_app(
+ adapter.list_windows(&filter, deadline)?,
+ app_name,
+ ))
+}
+
+/// The adapter filter is advisory, so the app name is applied again here.
+fn windows_matching_app(windows: Vec<WindowInfo>, app_name: Option<&str>) -> Vec<WindowInfo> {
+ match app_name {
+ Some(app) => windows
+ .into_iter()
+ .filter(|window| window.app.eq_ignore_ascii_case(app))
+ .collect(),
+ None => windows,
+ }
+}
+
pub(crate) fn resolve_window(
adapter: &dyn PlatformAdapter,
app_name: Option<&str>,
@@ -105,12 +156,8 @@ pub(crate) fn resolve_window(
)
})
} else if let Some(app) = app_name {
- let candidates = windows
- .into_iter()
- .filter(|window| window.app.eq_ignore_ascii_case(app))
- .collect::<Vec<_>>();
crate::window_lookup::select_window(
- candidates,
+ windows_matching_app(windows, app_name),
crate::AdapterError::new(
crate::ErrorCode::AppNotFound,
format!("No window found for app '{app}'"),
diff --git a/crates/core/src/window_lookup.rs b/crates/core/src/window_lookup.rs
index df9261787..9286860c2 100644
--- a/crates/core/src/window_lookup.rs
+++ b/crates/core/src/window_lookup.rs
@@ -47,6 +47,30 @@ pub(crate) fn find_window_for_process(
)
}
+/// A menu bar, menu, or alert belongs to the application, not to one of its
+/// windows, so several open windows are not an ambiguity for those surfaces —
+/// any window of the app names the same process. Prefers a focused or visible
+/// window so the caller still gets the most relevant identity.
+pub(crate) fn select_surface_owner(
+ candidates: Vec<WindowInfo>,
+ empty_error: crate::AdapterError,
+) -> Result<WindowInfo, AppError> {
+ if candidates.is_empty() {
+ return Err(empty_error.into());
+ }
+ let best = candidates
+ .iter()
+ .position(|window| window.state.is_focused)
+ .or_else(|| {
+ candidates
+ .iter()
+ .position(|window| window.state.visible == Some(true))
+ })
+ .unwrap_or(0);
+ let mut candidates = candidates;
+ Ok(candidates.swap_remove(best))
+}
+
pub(crate) fn select_window(
mut candidates: Vec<WindowInfo>,
empty_error: crate::AdapterError,
diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h
index b969d4656..5b3f8e483 100644
--- a/crates/ffi/include/agent_desktop.h
+++ b/crates/ffi/include/agent_desktop.h
@@ -1269,8 +1269,9 @@ AdResult ad_close_app(const struct AdAdapter *adapter, const char *id, bool forc
/**
* Launches the application identified by `id` (bundle id on macOS,
* executable path on other platforms) and, on success, writes the
- * first window that becomes available into `*out`. Waits up to
- * `timeout_ms` for the window to appear; zero means "no wait".
+ * first window that becomes available into `*out`. Waits for the windows
+ * the launch itself produces, bounded by `timeout_ms`; zero means "no wait".
+ * An application that presents no window fails with `WINDOW_NOT_FOUND`.
*
* The returned `AdWindowInfo` owns heap-allocated interior strings that
* must be released with `ad_release_window_fields` once done. On error
@@ -1420,7 +1421,7 @@ AdResult ad_execute_by_ref_timeout(const struct AdAdapter *adapter,
* to disk, and writes the JSON envelope into `*out`.
*
* The JSON shape matches `agent-desktop snapshot`:
- * `{"version":"2.2","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.
+ * `{"version":"2.3","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.
*
* **`*out` ownership and error behaviour:**
* - On success (`AD_RESULT_OK`): `*out` is a heap-allocated JSON string with `"ok":true`.
diff --git a/crates/ffi/src/apps/launch.rs b/crates/ffi/src/apps/launch.rs
index 4395000ac..f6336c66d 100644
--- a/crates/ffi/src/apps/launch.rs
+++ b/crates/ffi/src/apps/launch.rs
@@ -5,12 +5,26 @@ use crate::convert::window::{
use crate::error::{AdResult, set_last_error};
use crate::ffi_try::trap_panic;
use crate::types::{AdExactWindowInfo, AdWindowInfo};
+use agent_desktop_core::{AdapterError, ErrorCode, WindowInfo, launch_result::LaunchResult};
use std::os::raw::c_char;
+/// The C entry points hand back one window, so a launch that produced none is
+/// an error at this boundary even though it is a valid result in core.
+fn launched_window(launched: LaunchResult) -> Result<WindowInfo, AdapterError> {
+ launched.window.ok_or_else(|| {
+ AdapterError::new(
+ ErrorCode::WindowNotFound,
+ "Application is running, but it has presented no window",
+ )
+ .with_suggestion("Launch with activation, or wait for the window before reading it.")
+ })
+}
+
/// Launches the application identified by `id` (bundle id on macOS,
/// executable path on other platforms) and, on success, writes the
-/// first window that becomes available into `*out`. Waits up to
-/// `timeout_ms` for the window to appear; zero means "no wait".
+/// first window that becomes available into `*out`. Waits for the windows
+/// the launch itself produces, bounded by `timeout_ms`; zero means "no wait".
+/// An application that presents no window fails with `WINDOW_NOT_FOUND`.
///
/// The returned `AdWindowInfo` owns heap-allocated interior strings that
/// must be released with `ad_release_window_fields` once done. On error
@@ -57,7 +71,11 @@ pub unsafe extern "C" fn ad_launch_app(
return crate::error::last_error_code();
}
};
- match adapter.inner.launch_app(&id_str, &options, &lease) {
+ match adapter
+ .inner
+ .launch_app(&id_str, &options, &lease)
+ .and_then(launched_window)
+ {
Ok(win) => {
*out = window_info_to_c(&win);
AdResult::Ok
@@ -112,7 +130,11 @@ pub unsafe extern "C" fn ad_launch_app_exact(
return crate::error::last_error_code();
}
};
- match adapter.inner.launch_app(&id, &options, &lease) {
+ match adapter
+ .inner
+ .launch_app(&id, &options, &lease)
+ .and_then(launched_window)
+ {
Ok(window) => match validate_exact_window_info(&window) {
Ok(()) => {
*out = exact_window_info_to_c(&window);
@@ -181,19 +203,24 @@ mod tests {
_id: &str,
options: &LaunchOptions,
_lease: &InteractionLease,
- ) -> Result<WindowInfo, AdapterError> {
+ ) -> Result<LaunchResult, AdapterError> {
self.probe.calls.fetch_add(1, Ordering::SeqCst);
self.probe
.timeout_ms
.store(options.timeout_ms, Ordering::SeqCst);
- Ok(WindowInfo {
- id: "w-launch".into(),
- title: "Launched".into(),
+ Ok(LaunchResult {
app: "Fixture".into(),
pid: ProcessId::new(42),
process_instance: Some("fixture-42".into()),
- bounds: None,
- state: WindowState::default(),
+ window: Some(WindowInfo {
+ id: "w-launch".into(),
+ title: "Launched".into(),
+ app: "Fixture".into(),
+ pid: ProcessId::new(42),
+ process_instance: Some("fixture-42".into()),
+ bounds: None,
+ state: WindowState::default(),
+ }),
})
}
}
diff --git a/crates/ffi/src/commands/snapshot.rs b/crates/ffi/src/commands/snapshot.rs
index 6a0b590bb..d090ad743 100644
--- a/crates/ffi/src/commands/snapshot.rs
+++ b/crates/ffi/src/commands/snapshot.rs
@@ -15,7 +15,7 @@ use std::ptr;
/// to disk, and writes the JSON envelope into `*out`.
///
/// The JSON shape matches `agent-desktop snapshot`:
-/// `{"version":"2.2","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.
+/// `{"version":"2.3","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.
///
/// **`*out` ownership and error behaviour:**
/// - On success (`AD_RESULT_OK`): `*out` is a heap-allocated JSON string with `"ok":true`.
diff --git a/crates/ffi/src/convert/app.rs b/crates/ffi/src/convert/app.rs
index bad502dfb..ed672e833 100644
--- a/crates/ffi/src/convert/app.rs
+++ b/crates/ffi/src/convert/app.rs
@@ -33,6 +33,7 @@ mod tests {
pid: agent_desktop_core::ProcessId::new(42),
bundle_id: Some("com.apple.finder".into()),
process_instance: Some("42:100".into()),
+ presentation: None,
};
let c = app_info_to_c(&a);
assert_eq!(unsafe { c_to_string(c.name) }.as_deref(), Some("Finder"));
diff --git a/crates/ffi/src/observation/find.rs b/crates/ffi/src/observation/find.rs
index 17c5bbac7..5c72788d8 100644
--- a/crates/ffi/src/observation/find.rs
+++ b/crates/ffi/src/observation/find.rs
@@ -197,6 +197,7 @@ pub(crate) unsafe fn decode_query(
selection,
deadline,
max_raw_depth: 50,
+ surface: None,
materialization: LocatorMaterialization::None,
},
))
diff --git a/crates/ffi/src/observation/find_abi_tests.rs b/crates/ffi/src/observation/find_abi_tests.rs
index b76fccbdc..bc620cf6e 100644
--- a/crates/ffi/src/observation/find_abi_tests.rs
+++ b/crates/ffi/src/observation/find_abi_tests.rs
@@ -37,7 +37,10 @@ impl ObservationOps for CardinalityAdapter {
}
ObservedTree::from_roots(
roots,
- ObservationSource::Window(window.clone()),
+ ObservationSource::Window {
+ window: window.clone(),
+ surface: agent_desktop_core::SnapshotSurface::Window,
+ },
Default::default(),
self.complete,
)
diff --git a/crates/ffi/src/observation/is_abi_tests.rs b/crates/ffi/src/observation/is_abi_tests.rs
index dfe19cf45..8e33f294d 100644
--- a/crates/ffi/src/observation/is_abi_tests.rs
+++ b/crates/ffi/src/observation/is_abi_tests.rs
@@ -26,7 +26,10 @@ impl ObservationOps for DuplicateAdapter {
};
ObservedTree::from_roots(
vec![button(Vec::new()), button(vec!["disabled".into()])],
- ObservationSource::Window(window.clone()),
+ ObservationSource::Window {
+ window: window.clone(),
+ surface: agent_desktop_core::SnapshotSurface::Window,
+ },
Default::default(),
true,
)
diff --git a/crates/ffi/src/surfaces/list.rs b/crates/ffi/src/surfaces/list.rs
index 6bf7a8a30..95dfc1be5 100644
--- a/crates/ffi/src/surfaces/list.rs
+++ b/crates/ffi/src/surfaces/list.rs
@@ -268,6 +268,7 @@ mod tests {
pid: agent_desktop_core::ProcessId::new(pid),
bundle_id: None,
process_instance: Some(instance.into()),
+ presentation: None,
}
}
diff --git a/crates/macos/src/actions/activate_descendant.rs b/crates/macos/src/actions/activate_descendant.rs
new file mode 100644
index 000000000..ad8574527
--- /dev/null
+++ b/crates/macos/src/actions/activate_descendant.rs
@@ -0,0 +1,63 @@
+#[cfg(target_os = "macos")]
+mod imp {
+ use agent_desktop_core::{AdapterError, Deadline};
+
+ use crate::actions::chain_delivery::DeliveryOutcome;
+ use crate::tree::AXElement;
+
+ const MAX_CANDIDATES: usize = 4;
+
+ /// A row often publishes no activation itself while the cell inside it
+ /// does: Finder's sidebar `treeitem` is inert and its `cell` carries
+ /// `AXOpen`. Without this the chain falls through to writing selection,
+ /// which the row accepts and reports back while the application never
+ /// navigates.
+ ///
+ /// Descending is a guess about which child owns the row's behaviour, so
+ /// only an observed effect ends the chain here. A child that merely claims
+ /// success — Xcode's rows answer that to `AXConfirm` and do nothing — must
+ /// not consume the selection step that actually works for them.
+ pub(crate) fn activate_descendant(
+ element: &AXElement,
+ deadline: Deadline,
+ ) -> Result<DeliveryOutcome, AdapterError> {
+ let instant = crate::tree::locator_deadline::from_operation(deadline)?;
+ let children = crate::tree::attributes::copy_ax_array_prefix_result(
+ element,
+ "AXChildren",
+ MAX_CANDIDATES,
+ instant,
+ )
+ .ok()
+ .flatten()
+ .unwrap_or_default();
+
+ for child in children {
+ for action in crate::tree::action_list::PRIMARY_ACTIVATION_ACTIONS {
+ let outcome =
+ crate::actions::ax_helpers::perform_observed_action(&child, action, deadline)?;
+ if outcome.was_verified() {
+ return Ok(outcome);
+ }
+ }
+ }
+ Ok(DeliveryOutcome::NotDelivered)
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+mod imp {
+ use agent_desktop_core::{AdapterError, Deadline};
+
+ use crate::actions::chain_delivery::DeliveryOutcome;
+ use crate::tree::AXElement;
+
+ pub(crate) fn activate_descendant(
+ _element: &AXElement,
+ _deadline: Deadline,
+ ) -> Result<DeliveryOutcome, AdapterError> {
+ Ok(DeliveryOutcome::NotDelivered)
+ }
+}
+
+pub(crate) use imp::activate_descendant;
diff --git a/crates/macos/src/actions/activation_effect.rs b/crates/macos/src/actions/activation_effect.rs
new file mode 100644
index 000000000..445fff980
--- /dev/null
+++ b/crates/macos/src/actions/activation_effect.rs
@@ -0,0 +1,112 @@
+#[cfg(target_os = "macos")]
+mod imp {
+ use agent_desktop_core::Deadline;
+
+ use crate::tree::AXElement;
+
+ const SETTLE_POLL_MS: u64 = 40;
+ const SETTLE_BUDGET_MS: u64 = 400;
+
+ /// The readback for `perform`, which has no written attribute to re-read.
+ #[derive(Default)]
+ pub(crate) struct FocusState {
+ window_title: Option<String>,
+ focused_element: Option<AXElement>,
+ }
+
+ /// Accessibility hands back a fresh reference for the same element on every
+ /// read, and reuses a released one for a different element later, so a raw
+ /// pointer answers neither question this comparison asks. `CFEqual` is the
+ /// identity the framework defines.
+ impl PartialEq for FocusState {
+ fn eq(&self, other: &Self) -> bool {
+ self.window_title == other.window_title
+ && match (&self.focused_element, &other.focused_element) {
+ (None, None) => true,
+ (Some(mine), Some(theirs)) => crate::tree::same_element(mine, theirs),
+ _ => false,
+ }
+ }
+ }
+
+ pub(crate) fn focus_state(element: &AXElement, deadline: Deadline) -> FocusState {
+ let Some(app) = crate::system::app_ops::pid_from_element(element, deadline)
+ .map(crate::tree::element_for_pid)
+ else {
+ return FocusState::default();
+ };
+ FocusState {
+ window_title: read_element(&app, "AXFocusedWindow", deadline).and_then(|window| {
+ crate::tree::attributes::copy_string_attr_result(&window, "AXTitle", deadline)
+ .ok()
+ .flatten()
+ }),
+ focused_element: read_element(&app, "AXFocusedUIElement", deadline),
+ }
+ }
+
+ pub(crate) fn changed_now(
+ before: &FocusState,
+ element: &AXElement,
+ deadline: Deadline,
+ ) -> bool {
+ focus_state(element, deadline) != *before
+ }
+
+ pub(crate) fn settled_change(
+ before: &FocusState,
+ element: &AXElement,
+ deadline: Deadline,
+ ) -> bool {
+ let started = std::time::Instant::now();
+ loop {
+ if focus_state(element, deadline) != *before {
+ return true;
+ }
+ if started.elapsed() >= std::time::Duration::from_millis(SETTLE_BUDGET_MS)
+ || deadline.is_expired()
+ {
+ return false;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(SETTLE_POLL_MS));
+ }
+ }
+
+ fn read_element(app: &AXElement, attr: &str, deadline: Deadline) -> Option<AXElement> {
+ crate::tree::attributes::copy_element_attr_result(app, attr, deadline)
+ .ok()
+ .flatten()
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+mod imp {
+ use agent_desktop_core::Deadline;
+
+ use crate::tree::AXElement;
+
+ #[derive(Default, PartialEq)]
+ pub(crate) struct FocusState;
+
+ pub(crate) fn focus_state(_element: &AXElement, _deadline: Deadline) -> FocusState {
+ FocusState
+ }
+
+ pub(crate) fn changed_now(
+ _before: &FocusState,
+ _element: &AXElement,
+ _deadline: Deadline,
+ ) -> bool {
+ false
+ }
+
+ pub(crate) fn settled_change(
+ _before: &FocusState,
+ _element: &AXElement,
+ _deadline: Deadline,
+ ) -> bool {
+ false
+ }
+}
+
+pub(crate) use imp::{changed_now, focus_state, settled_change};
diff --git a/crates/macos/src/actions/ax_helpers.rs b/crates/macos/src/actions/ax_helpers.rs
index d20ca853a..a0efc9f65 100644
--- a/crates/macos/src/actions/ax_helpers.rs
+++ b/crates/macos/src/actions/ax_helpers.rs
@@ -19,11 +19,63 @@ mod imp {
deadline: agent_desktop_core::Deadline,
) -> Result<bool, AdapterError> {
let action = CFString::new(name);
- run_mutation(el, name, "AXUIElementPerformAction", deadline, |deadline| {
+ run_mutation(el, name, ax_mutation::PERFORM_API, deadline, |deadline| {
crate::tree::ax_ipc::perform_action(el, action.as_concrete_TypeRef(), deadline)
})
}
+ /// Decides delivery from what the application did, not what it claimed.
+ /// Unadvertised actions are never performed, because a responder can answer
+ /// `kAXErrorSuccess` to an action it never published and never ran. Only an
+ /// uninformative code needs the settle poll to decide delivery at all; a
+ /// reported success is already delivered, so observing it merely upgrades
+ /// the report to verified and must not cost the caller a wait.
+ pub(crate) fn perform_observed_action(
+ el: &AXElement,
+ name: &str,
+ deadline: agent_desktop_core::Deadline,
+ ) -> Result<crate::actions::chain_delivery::DeliveryOutcome, AdapterError> {
+ use crate::actions::activation_effect;
+ use crate::actions::chain_delivery::DeliveryOutcome;
+ use ax_mutation::PerformSignal;
+
+ if !advertises_action(el, name, deadline) {
+ return Ok(DeliveryOutcome::NotDelivered);
+ }
+ let before = activation_effect::focus_state(el, deadline);
+ let action = CFString::new(name);
+ let error =
+ crate::tree::ax_ipc::perform_action(el, action.as_concrete_TypeRef(), deadline)?;
+ match ax_mutation::classify_perform(name, error)? {
+ PerformSignal::ReportedUnsupported => Ok(DeliveryOutcome::NotDelivered),
+ PerformSignal::ReportedDelivered => Ok(DeliveryOutcome::from_delivery(
+ true,
+ activation_effect::changed_now(&before, el, deadline),
+ )),
+ PerformSignal::Uninformative => Ok(DeliveryOutcome::from_delivery(
+ activation_effect::settled_change(&before, el, deadline),
+ true,
+ )),
+ }
+ }
+
+ fn advertises_action(
+ el: &AXElement,
+ name: &str,
+ deadline: agent_desktop_core::Deadline,
+ ) -> bool {
+ let mut usage = crate::tree::observation_usage::ObservationUsage::with_defaults();
+ let read = crate::tree::capabilities::copy_action_names_with_status(
+ el,
+ std::time::Instant::now() + deadline.remaining(),
+ &mut usage,
+ );
+ match read.value {
+ Some(actions) => actions.iter().any(|action| action == name),
+ None => true,
+ }
+ }
+
pub(crate) fn set_ax_bool_or_err(
el: &AXElement,
attr: &str,
@@ -334,6 +386,6 @@ mod imp {
}
pub(crate) use imp::{
- ax_focus_or_err, element_role, is_attr_settable, set_ax_bool_or_err, set_ax_string_or_err,
- set_ax_value_coerced, try_ax_action_or_err,
+ ax_focus_or_err, element_role, is_attr_settable, perform_observed_action, set_ax_bool_or_err,
+ set_ax_string_or_err, set_ax_value_coerced, try_ax_action_or_err,
};
diff --git a/crates/macos/src/actions/ax_mutation.rs b/crates/macos/src/actions/ax_mutation.rs
index 10384e89e..344b3ccf6 100644
--- a/crates/macos/src/actions/ax_mutation.rs
+++ b/crates/macos/src/actions/ax_mutation.rs
@@ -1,10 +1,12 @@
use accessibility_sys::{
kAXErrorAPIDisabled, kAXErrorActionUnsupported, kAXErrorAttributeUnsupported,
- kAXErrorCannotComplete, kAXErrorIllegalArgument, kAXErrorInvalidUIElement, kAXErrorNoValue,
- kAXErrorNotImplemented, kAXErrorSuccess,
+ kAXErrorCannotComplete, kAXErrorFailure, kAXErrorIllegalArgument, kAXErrorInvalidUIElement,
+ kAXErrorNoValue, kAXErrorNotImplemented, kAXErrorSuccess,
};
use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode};
+pub(crate) const PERFORM_API: &str = "AXUIElementPerformAction";
+
pub(crate) fn classify_result(
_element: &crate::tree::AXElement,
operation: &str,
@@ -15,8 +17,21 @@ pub(crate) fn classify_result(
}
fn classify(operation: &str, api: &str, error: i32) -> Result<bool, AdapterError> {
+ signal_or_error(operation, api, error).map(|signal| signal == PerformSignal::ReportedDelivered)
+}
+
+fn signal_or_error(operation: &str, api: &str, error: i32) -> Result<PerformSignal, AdapterError> {
if error == kAXErrorSuccess {
- return Ok(true);
+ return Ok(PerformSignal::ReportedDelivered);
+ }
+ if error == kAXErrorActionUnsupported
+ || error == kAXErrorNotImplemented
+ || error == kAXErrorFailure
+ {
+ return Ok(PerformSignal::ReportedUnsupported);
+ }
+ if error == kAXErrorAttributeUnsupported || error == kAXErrorNoValue {
+ return Ok(PerformSignal::Uninformative);
}
if error == kAXErrorAPIDisabled {
return Err(AdapterError::permission_denied()
@@ -25,13 +40,6 @@ fn classify(operation: &str, api: &str, error: i32) -> Result<bool, AdapterError
))
.with_disposition(DeliverySemantics::not_delivered()));
}
- if error == kAXErrorActionUnsupported
- || error == kAXErrorAttributeUnsupported
- || error == kAXErrorNoValue
- || error == kAXErrorNotImplemented
- {
- return Ok(false);
- }
if error == kAXErrorInvalidUIElement {
return Err(AdapterError::new(
ErrorCode::StaleRef,
@@ -77,11 +85,25 @@ fn classify(operation: &str, api: &str, error: i32) -> Result<bool, AdapterError
))
}
+/// How much a perform return code proves. Responders break the contract in both
+/// directions — a code that reports failure after acting, and success after
+/// doing nothing — so delivery is settled by observation, not by the code.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum PerformSignal {
+ ReportedDelivered,
+ ReportedUnsupported,
+ Uninformative,
+}
+
+pub(crate) fn classify_perform(operation: &str, error: i32) -> Result<PerformSignal, AdapterError> {
+ signal_or_error(operation, PERFORM_API, error)
+}
+
#[cfg(test)]
mod tests {
use accessibility_sys::{
- kAXErrorAPIDisabled, kAXErrorActionUnsupported, kAXErrorCannotComplete,
- kAXErrorInvalidUIElement, kAXErrorSuccess,
+ kAXErrorAPIDisabled, kAXErrorActionUnsupported, kAXErrorAttributeUnsupported,
+ kAXErrorCannotComplete, kAXErrorInvalidUIElement, kAXErrorSuccess,
};
use agent_desktop_core::{DeliveryDisposition, ErrorCode, RetryDisposition};
@@ -99,6 +121,43 @@ mod tests {
assert!(!result.unwrap());
}
+ #[test]
+ fn perform_codes_are_graded_by_how_much_they_prove() {
+ use super::{PerformSignal, classify_perform};
+
+ assert_eq!(
+ classify_perform("AXPress", kAXErrorSuccess).unwrap(),
+ PerformSignal::ReportedDelivered
+ );
+ assert_eq!(
+ classify_perform("AXPress", kAXErrorActionUnsupported).unwrap(),
+ PerformSignal::ReportedUnsupported
+ );
+ assert_eq!(
+ classify_perform("AXOpen", kAXErrorAttributeUnsupported).unwrap(),
+ PerformSignal::Uninformative
+ );
+ }
+
+ /// `tree::action_list` reads `kAXErrorFailure` as "this element implements
+ /// no such action". A perform must not read the same code as a failure, or
+ /// an element the reader called action-less becomes an error when acted on.
+ #[test]
+ fn perform_and_capability_reads_agree_on_the_appkit_absence_code() {
+ assert_eq!(
+ super::classify_perform("AXScrollToVisible", accessibility_sys::kAXErrorFailure)
+ .unwrap(),
+ super::PerformSignal::ReportedUnsupported
+ );
+ }
+
+ #[test]
+ fn perform_keeps_reporting_transport_failures_as_errors() {
+ let error = super::classify_perform("AXOpen", kAXErrorInvalidUIElement)
+ .expect_err("a stale element must still fail closed");
+ assert_eq!(error.code, ErrorCode::StaleRef);
+ }
+
#[test]
fn invalid_element_is_stale_and_safe_to_retry_with_a_fresh_ref() {
let error = classify("AXPress", "perform", kAXErrorInvalidUIElement)
diff --git a/crates/macos/src/actions/chain_defs.rs b/crates/macos/src/actions/chain_defs.rs
index d9396efe0..4e1a7b2fb 100644
--- a/crates/macos/src/actions/chain_defs.rs
+++ b/crates/macos/src/actions/chain_defs.rs
@@ -16,11 +16,25 @@ mod imp {
count: 1,
},
ChainStep::Action("AXPress"),
+ ChainStep::Action("AXOpen"),
+ ChainStep::CustomWithDeadline {
+ label: "activate_descendant",
+ func: crate::actions::activate_descendant::activate_descendant,
+ },
+ ChainStep::CustomWithDeadline {
+ label: "select_within_container",
+ func: crate::actions::container_select::select_within_container,
+ },
+ ChainStep::Action("AXConfirm"),
],
suggestion: "Target an element that advertises Click or use an explicit point click.",
continue_after_unverified_delivery: false,
};
+ /// Continues past an unverified delivery because an `AXShowMenu` that
+ /// reports success without opening a menu must not consume the fallbacks
+ /// behind it. Each step re-checks for an open menu first, so continuing
+ /// cannot raise a second one.
pub(crate) static RIGHT_CLICK_CHAIN: ChainDef = ChainDef {
steps: &[
ChainStep::CGClick {
@@ -49,7 +63,7 @@ mod imp {
},
],
suggestion: "Try 'mouse-click --button right --xy X,Y'.",
- continue_after_unverified_delivery: false,
+ continue_after_unverified_delivery: true,
};
pub(crate) static EXPAND_CHAIN: ChainDef = ChainDef {
@@ -89,7 +103,19 @@ mod imp {
};
pub(crate) static SEMANTIC_CLICK_CHAIN: ChainDef = ChainDef {
- steps: &[ChainStep::Action("AXPress")],
+ steps: &[
+ ChainStep::Action("AXPress"),
+ ChainStep::Action("AXOpen"),
+ ChainStep::CustomWithDeadline {
+ label: "activate_descendant",
+ func: crate::actions::activate_descendant::activate_descendant,
+ },
+ ChainStep::CustomWithDeadline {
+ label: "select_within_container",
+ func: crate::actions::container_select::select_within_container,
+ },
+ ChainStep::Action("AXConfirm"),
+ ],
suggestion: "Target an element that advertises Click.",
continue_after_unverified_delivery: false,
};
diff --git a/crates/macos/src/actions/chain_menu_steps.rs b/crates/macos/src/actions/chain_menu_steps.rs
index 62f5a4ad2..cb1f3865e 100644
--- a/crates/macos/src/actions/chain_menu_steps.rs
+++ b/crates/macos/src/actions/chain_menu_steps.rs
@@ -80,7 +80,7 @@ fn show_menu_on_element(
let Some(pid) = crate::system::app_ops::pid_from_element(element, deadline) else {
return Ok(DeliveryOutcome::NotDelivered);
};
- if menu_is_open(pid, deadline)? {
+ if menu_probe(pid, deadline) {
return Ok(DeliveryOutcome::NotDelivered);
}
prepare(element, deadline)?;
@@ -102,7 +102,7 @@ fn show_menu_or_press(
let Some(pid) = crate::system::app_ops::pid_from_element(element, deadline) else {
return Ok(DeliveryOutcome::NotDelivered);
};
- if menu_is_open(pid, deadline)? {
+ if menu_probe(pid, deadline) {
return Ok(DeliveryOutcome::NotDelivered);
}
for action in ["AXShowMenu", "AXPress"] {
@@ -120,7 +120,7 @@ fn show_menu_or_press(
fn wait_for_new_menu(pid: i32, deadline: Deadline) -> Result<bool, AdapterError> {
let local_end = std::time::Instant::now() + std::time::Duration::from_millis(600);
loop {
- if menu_is_open(pid, deadline)? {
+ if menu_probe(pid, deadline) {
return Ok(true);
}
if deadline.is_expired() || std::time::Instant::now() >= local_end {
@@ -131,8 +131,13 @@ fn wait_for_new_menu(pid: i32, deadline: Deadline) -> Result<bool, AdapterError>
}
}
-fn menu_is_open(pid: i32, deadline: Deadline) -> Result<bool, AdapterError> {
- crate::tree::surfaces::is_menu_open(pid, instant(deadline)?)
+/// An application in menu tracking stops answering child reads, so a failed
+/// probe is the expected shape of "a menu is up" rather than an application
+/// fault. Verification must never turn a delivered action into an error.
+fn menu_probe(pid: i32, deadline: Deadline) -> bool {
+ instant(deadline)
+ .and_then(|instant| crate::tree::surfaces::is_menu_open(pid, instant))
+ .unwrap_or(false)
}
fn select_containing_item(element: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {
diff --git a/crates/macos/src/actions/chain_step_exec.rs b/crates/macos/src/actions/chain_step_exec.rs
index 7a1d4a013..7e3435f3f 100644
--- a/crates/macos/src/actions/chain_step_exec.rs
+++ b/crates/macos/src/actions/chain_step_exec.rs
@@ -22,10 +22,7 @@ mod imp {
match step {
ChainStep::Action(name) => {
prepare(el, ctx.deadline)?;
- Ok(DeliveryOutcome::from_delivery(
- ax_helpers::try_ax_action_or_err(el, name, ctx.deadline)?,
- false,
- ))
+ ax_helpers::perform_observed_action(el, name, ctx.deadline)
}
ChainStep::SetBool { attr, value } => {
diff --git a/crates/macos/src/actions/container_select.rs b/crates/macos/src/actions/container_select.rs
new file mode 100644
index 000000000..df42b9561
--- /dev/null
+++ b/crates/macos/src/actions/container_select.rs
@@ -0,0 +1,145 @@
+pub(crate) const SELECTED: &str = "AXSelected";
+
+/// Kept narrow so the settability probe never runs on generic containers.
+pub(crate) fn role_activates_by_selection(role: &str) -> bool {
+ matches!(
+ role,
+ "row" | "treeitem" | "cell" | "listitem" | "option" | "tab"
+ )
+}
+
+#[cfg(target_os = "macos")]
+mod imp {
+ use agent_desktop_core::{AdapterError, Deadline};
+ use core_foundation::{array::CFArray, base::TCFType};
+
+ use crate::actions::chain_delivery::DeliveryOutcome;
+ use crate::tree::AXElement;
+
+ use super::SELECTED;
+
+ /// `AXOutline` and `AXTable` make `AXSelectedRows` writable; `AXList` and
+ /// `AXBrowser` columns make `AXSelectedChildren` writable. Most elements
+ /// publish both names and accept writes to only one.
+ const SELECTION_ATTRIBUTES: [&str; 2] = ["AXSelectedRows", "AXSelectedChildren"];
+ const MAX_ANCESTOR_WALK: usize = 6;
+ const MAX_SELECTION_READBACK: usize = 64;
+
+ /// Climbs from the target because the clickable label is usually a
+ /// descendant of the selectable row. Every write is verified by readback.
+ pub(crate) fn select_within_container(
+ element: &AXElement,
+ deadline: Deadline,
+ ) -> Result<DeliveryOutcome, AdapterError> {
+ let mut member = element.clone();
+ for _ in 0..MAX_ANCESTOR_WALK {
+ if select_member_directly(&member, deadline)? {
+ return Ok(DeliveryOutcome::DeliveredVerified);
+ }
+ let Some(parent) = parent_of(&member, deadline) else {
+ return Ok(DeliveryOutcome::NotDelivered);
+ };
+ if select_member_in_container(&parent, &member, deadline)? {
+ return Ok(DeliveryOutcome::DeliveredVerified);
+ }
+ member = parent;
+ }
+ Ok(DeliveryOutcome::NotDelivered)
+ }
+
+ fn select_member_directly(
+ member: &AXElement,
+ deadline: Deadline,
+ ) -> Result<bool, AdapterError> {
+ if !crate::actions::ax_helpers::is_attr_settable(member, SELECTED, deadline)? {
+ return Ok(false);
+ }
+ crate::actions::ax_helpers::set_ax_bool_or_err(member, SELECTED, true, deadline)?;
+ Ok(crate::tree::attributes::copy_bool_attr(member, SELECTED, deadline) == Some(true))
+ }
+
+ fn select_member_in_container(
+ container: &AXElement,
+ member: &AXElement,
+ deadline: Deadline,
+ ) -> Result<bool, AdapterError> {
+ for attribute in SELECTION_ATTRIBUTES {
+ if !crate::actions::ax_helpers::is_attr_settable(container, attribute, deadline)? {
+ continue;
+ }
+ let members = selection_array(member);
+ let cf_attr = core_foundation::string::CFString::new(attribute);
+ let error = crate::tree::ax_ipc::set_attribute_value(
+ container,
+ cf_attr.as_concrete_TypeRef(),
+ members.as_CFTypeRef(),
+ deadline,
+ )?;
+ if error == accessibility_sys::kAXErrorSuccess
+ && holds_selection(container, member, attribute, deadline)
+ {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+ }
+
+ /// `AXElement` does not implement `TCFType`, so the array is built through
+ /// the CoreFoundation C API.
+ fn selection_array(member: &AXElement) -> CFArray {
+ let values = [member.0 as *const std::ffi::c_void];
+ unsafe {
+ let raw = core_foundation_sys::array::CFArrayCreate(
+ std::ptr::null(),
+ values.as_ptr(),
+ 1,
+ &core_foundation_sys::array::kCFTypeArrayCallBacks,
+ );
+ CFArray::wrap_under_create_rule(raw)
+ }
+ }
+
+ fn parent_of(element: &AXElement, deadline: Deadline) -> Option<AXElement> {
+ crate::tree::attributes::copy_element_attr_result(element, "AXParent", deadline)
+ .ok()
+ .flatten()
+ }
+
+ fn holds_selection(
+ container: &AXElement,
+ member: &AXElement,
+ attribute: &str,
+ deadline: Deadline,
+ ) -> bool {
+ crate::tree::attributes::copy_ax_array_prefix_result(
+ container,
+ attribute,
+ MAX_SELECTION_READBACK,
+ deadline,
+ )
+ .ok()
+ .flatten()
+ .is_some_and(|selected| {
+ selected
+ .iter()
+ .any(|entry| crate::tree::capabilities::same_element(entry, member))
+ })
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+mod imp {
+ use agent_desktop_core::{AdapterError, Deadline};
+
+ use crate::actions::chain_delivery::DeliveryOutcome;
+ use crate::tree::AXElement;
+
+ pub(crate) fn select_within_container(
+ _element: &AXElement,
+ _deadline: Deadline,
+ ) -> Result<DeliveryOutcome, AdapterError> {
+ Ok(DeliveryOutcome::NotDelivered)
+ }
+}
+
+pub(crate) use imp::select_within_container;
diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs
index 4618e2c09..a1dd509d4 100644
--- a/crates/macos/src/actions/mod.rs
+++ b/crates/macos/src/actions/mod.rs
@@ -1,3 +1,5 @@
+pub(crate) mod activate_descendant;
+pub(crate) mod activation_effect;
mod adapter;
pub(crate) mod ax_helpers;
#[cfg(target_os = "macos")]
@@ -13,6 +15,7 @@ mod chain_step;
pub(crate) mod chain_step_exec;
pub(crate) mod chain_value_write;
pub(crate) mod chain_verify;
+pub(crate) mod container_select;
pub(crate) mod delivery_tracker;
pub(crate) mod dispatch;
pub(crate) mod extras;
diff --git a/crates/macos/src/actions/physical_keyboard.rs b/crates/macos/src/actions/physical_keyboard.rs
index 64bc7e199..9ddc68910 100644
--- a/crates/macos/src/actions/physical_keyboard.rs
+++ b/crates/macos/src/actions/physical_keyboard.rs
@@ -158,17 +158,13 @@ fn focused_element_matches(
pid: i32,
deadline: Deadline,
) -> Result<bool, AdapterError> {
- use core_foundation::base::{CFEqual, CFTypeRef};
-
let app = crate::tree::element_for_pid(pid);
prepare(&app, deadline)?;
let result =
crate::tree::attributes::copy_element_attr_result(&app, "AXFocusedUIElement", deadline);
ensure_budget(deadline)?;
let focused = result.map_err(|error| read_error("AXFocusedUIElement", error))?;
- Ok(focused.is_some_and(|focused| unsafe {
- CFEqual(focused.0 as CFTypeRef, expected.0 as CFTypeRef) != 0
- }))
+ Ok(focused.is_some_and(|focused| crate::tree::same_element(&focused, expected)))
}
fn prepare(element: &AXElement, deadline: Deadline) -> Result<(), AdapterError> {
diff --git a/crates/macos/src/actions/post_state.rs b/crates/macos/src/actions/post_state.rs
index 261d32456..1b093c5ce 100644
--- a/crates/macos/src/actions/post_state.rs
+++ b/crates/macos/src/actions/post_state.rs
@@ -1,6 +1,6 @@
use agent_desktop_core::{
Action, AdapterError, Deadline, ElementState, ErrorCode, EvidenceRequirements, LiveElement,
- LiveIdentity, LocatorField, ObservationBudget, Rect,
+ LiveIdentity, LocatorField, Rect,
};
use std::time::{Duration, Instant};
@@ -138,7 +138,7 @@ fn essential_live_evidence_complete(evidence: &agent_desktop_core::LocatorEviden
}
fn new_usage() -> crate::tree::observation_usage::ObservationUsage {
- crate::tree::observation_usage::ObservationUsage::new(ObservationBudget::default())
+ crate::tree::observation_usage::ObservationUsage::with_defaults()
}
fn owning_window_bounds(
@@ -159,17 +159,14 @@ fn owning_window_bounds(
crate::tree::element_bounds::read_bounds_with_deadline(&window, deadline_instant(deadline)?)
}
+/// The viewport an element is clipped by. `AXTopLevelUIElement` is not a
+/// substitute: for menu content it resolves to the menu bar, a 29-point strip
+/// that reports every open menu item as offscreen. An element with no window is
+/// drawn on its own surface, so its clipping viewport is simply unknown.
fn first_owning_container(
mut read: impl FnMut(&'static str) -> Result<Option<AXElement>, i32>,
) -> Result<Option<AXElement>, (&'static str, i32)> {
- for attribute in ["AXWindow", "AXTopLevelUIElement"] {
- match read(attribute) {
- Ok(Some(element)) => return Ok(Some(element)),
- Ok(None) => {}
- Err(error) => return Err((attribute, error)),
- }
- }
- Ok(None)
+ read("AXWindow").map_err(|error| ("AXWindow", error))
}
fn known_role(role: &LocatorField<String>) -> Result<String, AdapterError> {
@@ -212,7 +209,7 @@ fn element_state_from_attrs(
let states = crate::tree::state_reader::states_from_element(element, &attrs, &role, &context);
let enabled = Some(attrs.states.enabled);
let hidden = hidden_state(attrs.states.semantic.hidden);
- let offscreen = offscreen(attrs.bounds, window_bounds);
+ let offscreen = crate::tree::state_reader::offscreen(attrs.bounds, window_bounds);
Ok(ElementState {
role,
states,
@@ -227,16 +224,6 @@ fn hidden_state(reported: Option<bool>) -> Option<bool> {
reported
}
-fn offscreen(bounds: Option<Rect>, window: Option<Rect>) -> Option<bool> {
- let (bounds, window) = bounds.zip(window)?;
- Some(
- bounds.x + bounds.width <= window.x
- || bounds.x >= window.x + window.width
- || bounds.y + bounds.height <= window.y
- || bounds.y >= window.y + window.height,
- )
-}
-
#[cfg(test)]
fn normalized_role(ax_role: Option<&str>, ax_subrole: Option<&str>) -> String {
ax_role
diff --git a/crates/macos/src/actions/post_state_tests.rs b/crates/macos/src/actions/post_state_tests.rs
index 400110447..f9d71207d 100644
--- a/crates/macos/src/actions/post_state_tests.rs
+++ b/crates/macos/src/actions/post_state_tests.rs
@@ -111,18 +111,20 @@ fn element_visibility_preserves_live_hidden_evidence_for_every_role() {
assert_eq!(hidden_state(Some(true)), Some(true));
}
+/// A menu item's `AXTopLevelUIElement` is the menu bar, whose 29-point height
+/// clips every open menu item. A window-less element therefore reports no
+/// clipping viewport rather than a wrong one.
#[test]
-fn top_level_container_is_used_only_when_window_is_authoritatively_absent() {
+fn a_window_less_element_reports_no_clipping_viewport() {
let mut attributes = Vec::new();
let container = first_owning_container(|attribute| {
attributes.push(attribute);
- Ok((attribute == "AXTopLevelUIElement")
- .then(|| crate::tree::AXElement(std::ptr::null_mut())))
+ Ok(None)
})
.unwrap();
- assert!(container.is_some());
- assert_eq!(attributes, ["AXWindow", "AXTopLevelUIElement"]);
+ assert!(container.is_none());
+ assert_eq!(attributes, ["AXWindow"]);
}
#[test]
diff --git a/crates/macos/src/actions/scroll.rs b/crates/macos/src/actions/scroll.rs
index 6a923e3a7..de39ff0da 100644
--- a/crates/macos/src/actions/scroll.rs
+++ b/crates/macos/src/actions/scroll.rs
@@ -6,6 +6,47 @@ use crate::tree::AXElement;
const MAX_SCROLL_AMOUNT: u32 = 1_000;
+/// A responder can serve a page action while answering an uninformative code
+/// for it, which leaves the return value unable to prove anything. The content
+/// position is the observable that can, so the scroll is judged by whether the
+/// first child actually moved.
+fn paged_scroll_moved_content(
+ target: &AXElement,
+ direction: &Direction,
+ amount: u32,
+ deadline: Deadline,
+) -> Result<bool, AdapterError> {
+ let Some(before) = first_child_origin(target, deadline)? else {
+ return Ok(false);
+ };
+ for _ in 0..amount.max(1) {
+ try_action(target, page_action(direction), deadline)?;
+ }
+ let Some(after) = first_child_origin(target, deadline)? else {
+ return Ok(false);
+ };
+ Ok((before.0 - after.0).abs() > f64::EPSILON || (before.1 - after.1).abs() > f64::EPSILON)
+}
+
+fn first_child_origin(
+ target: &AXElement,
+ deadline: Deadline,
+) -> Result<Option<(f64, f64)>, AdapterError> {
+ let instant = crate::tree::locator_deadline::from_operation(deadline)?;
+ let Some(child) =
+ crate::tree::attributes::copy_ax_array_prefix_result(target, "AXChildren", 1, instant)
+ .ok()
+ .flatten()
+ .and_then(|children| children.into_iter().next())
+ else {
+ return Ok(None);
+ };
+ Ok(
+ crate::tree::element_bounds::read_bounds_with_deadline(&child, instant)?
+ .map(|bounds| (bounds.x, bounds.y)),
+ )
+}
+
pub(crate) fn ax_scroll(
element: &AXElement,
direction: &Direction,
@@ -37,11 +78,20 @@ pub(crate) fn ax_scroll(
if perform_repeated_action(target, page_action(direction), amount, deadline)? {
return Ok((StepMechanism::SemanticApi, false));
}
+ if paged_scroll_moved_content(target, direction, amount, deadline)? {
+ return Ok((StepMechanism::SemanticApi, true));
+ }
Err(AdapterError::new(
ErrorCode::ActionNotSupported,
- "No scroll mechanism found on element",
+ "Element advertises Scroll but no scroll mechanism moved its content",
)
- .with_suggestion("Element may not be scrollable, or try the parent container."))
+ .with_details(serde_json::json!({
+ "kind": "scroll_advertised_but_inert",
+ }))
+ .with_suggestion(
+ "The application publishes the scroll actions without implementing them. \
+ Try the parent container, or use '--headed' for a physical wheel scroll.",
+ ))
}
fn accept_optional_visibility_result(
diff --git a/crates/macos/src/actions/scroll_into_view.rs b/crates/macos/src/actions/scroll_into_view.rs
index 15f73cb43..96689972e 100644
--- a/crates/macos/src/actions/scroll_into_view.rs
+++ b/crates/macos/src/actions/scroll_into_view.rs
@@ -66,8 +66,9 @@ mod imp {
let instant = crate::tree::locator_deadline::from_operation(deadline)?;
let bounds = crate::tree::element_bounds::read_bounds_with_deadline(element, instant)?
.ok_or_else(|| AdapterError::new(ErrorCode::ActionFailed, "Target has no bounds"))?;
- let window = crate::tree::surface_read::element(element, "AXWindow", instant)?
- .ok_or_else(|| AdapterError::new(ErrorCode::ActionFailed, "Target has no window"))?;
+ let Some(window) = crate::tree::surface_read::element(element, "AXWindow", instant)? else {
+ return Ok(None);
+ };
let window_bounds = crate::tree::element_bounds::read_bounds_with_deadline(
&window, instant,
)?
diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs
index f3156f57f..3388791c4 100644
--- a/crates/macos/src/system/adapter.rs
+++ b/crates/macos/src/system/adapter.rs
@@ -69,7 +69,7 @@ impl SystemOps for MacOSAdapter {
id: &str,
options: &agent_desktop_core::launch_options::LaunchOptions,
lease: &InteractionLease,
- ) -> Result<WindowInfo, AdapterError> {
+ ) -> Result<agent_desktop_core::launch_result::LaunchResult, AdapterError> {
crate::system::launch::launch_app_impl(id, options, lease.deadline())
}
diff --git a/crates/macos/src/system/app_inventory_tests.rs b/crates/macos/src/system/app_inventory_tests.rs
index 9ee08bd4a..60dc50fab 100644
--- a/crates/macos/src/system/app_inventory_tests.rs
+++ b/crates/macos/src/system/app_inventory_tests.rs
@@ -6,6 +6,7 @@ fn app(name: &str, pid: u32) -> AppInfo {
pid: agent_desktop_core::ProcessId::new(pid),
bundle_id: None,
process_instance: Some(format!("instance-{pid}")),
+ presentation: None,
}
}
@@ -15,6 +16,7 @@ fn app_with_bundle(name: &str, pid: u32, bundle_id: &str) -> AppInfo {
pid: agent_desktop_core::ProcessId::new(pid),
bundle_id: Some(bundle_id.to_string()),
process_instance: Some(format!("instance-{pid}")),
+ presentation: None,
}
}
diff --git a/crates/macos/src/system/appkit_bridge.m b/crates/macos/src/system/appkit_bridge.m
index 5b532a26e..1594cf01c 100644
--- a/crates/macos/src/system/appkit_bridge.m
+++ b/crates/macos/src/system/appkit_bridge.m
@@ -17,6 +17,24 @@ typedef struct {
size_t length;
} AgentDesktopBytesResult;
+// Reports whether a running application has finished starting up.
+// -1 no such process, 0 still starting, 1 finished.
+int32_t agent_desktop_app_finished_launching(int32_t pid) {
+ @try {
+ @autoreleasepool {
+ NSRunningApplication *app =
+ [NSRunningApplication runningApplicationWithProcessIdentifier:pid];
+ if (app == nil) {
+ return -1;
+ }
+ return app.isFinishedLaunching ? 1 : 0;
+ }
+ } @catch (NSException *exception) {
+ (void)exception;
+ return -1;
+ }
+}
+
AgentDesktopTerminateResult agent_desktop_terminate_application(
int32_t pid,
double expectedLaunchTime,
diff --git a/crates/macos/src/system/appkit_bridge.rs b/crates/macos/src/system/appkit_bridge.rs
index b8e981730..9b82f04b3 100644
--- a/crates/macos/src/system/appkit_bridge.rs
+++ b/crates/macos/src/system/appkit_bridge.rs
@@ -107,6 +107,33 @@ fn bridge_error(operation: &str, status: u8, delivery_started: bool) -> AdapterE
.with_disposition(disposition)
}
+/// Where a process is in its startup. `NoRecord` covers both a process that
+/// exited and one that has not registered with the window server yet, so it
+/// answers neither question on its own and the caller has to ask libproc which
+/// of the two it is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum StartupState {
+ Starting,
+ Finished,
+ NoRecord,
+}
+
+/// An application that finished starting up has already created whatever
+/// windows its launch produces.
+#[cfg(target_os = "macos")]
+pub(crate) fn startup_state(pid: i32) -> StartupState {
+ match unsafe { agent_desktop_app_finished_launching(pid) } {
+ 0 => StartupState::Starting,
+ 1 => StartupState::Finished,
+ _ => StartupState::NoRecord,
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+pub(crate) fn startup_state(_pid: i32) -> StartupState {
+ StartupState::NoRecord
+}
+
#[cfg(target_os = "macos")]
unsafe extern "C" {
fn agent_desktop_terminate_application(
@@ -114,6 +141,7 @@ unsafe extern "C" {
expected_launch_time: f64,
force: u8,
) -> TerminateResult;
+ fn agent_desktop_app_finished_launching(pid: i32) -> i32;
fn agent_desktop_ensure_cocoa_multithreaded() -> u8;
fn agent_desktop_copy_workspace_snapshot_json() -> BytesResult;
fn agent_desktop_free_bridge_bytes(bytes: *mut u8);
diff --git a/crates/macos/src/system/launch.rs b/crates/macos/src/system/launch.rs
index 4a4256849..39297df85 100644
--- a/crates/macos/src/system/launch.rs
+++ b/crates/macos/src/system/launch.rs
@@ -1,12 +1,13 @@
use agent_desktop_core::{
AdapterError, AppInfo, Deadline, DeliverySemantics, ErrorCode, WindowInfo,
- launch_options::LaunchOptions,
+ launch_options::LaunchOptions, launch_result::LaunchResult,
};
use std::time::{Duration, Instant};
const MAX_ARGUMENT_COUNT: usize = 256;
const MAX_ENVIRONMENT_COUNT: usize = 256;
const MAX_LAUNCH_TEXT_BYTES: usize = 1024 * 1024;
+const STARTUP_GRACE: Duration = Duration::from_millis(1500);
enum LaunchTarget {
Existing { pid: i32, process_instance: String },
@@ -18,7 +19,7 @@ pub(crate) fn launch_app_impl(
id: &str,
options: &LaunchOptions,
parent_deadline: Deadline,
-) -> Result<WindowInfo, AdapterError> {
+) -> Result<LaunchResult, AdapterError> {
validate_app_identifier(id).map_err(before_launch)?;
validate_launch_options(options).map_err(before_launch)?;
let deadline = if options.timeout_ms == 0 {
@@ -27,45 +28,140 @@ pub(crate) fn launch_app_impl(
parent_deadline.capped(Duration::from_millis(options.timeout_ms))
};
ensure_launch_budget(deadline, id).map_err(before_launch)?;
- let timeout_ms = options.timeout_ms;
let initial = matching_apps(id, deadline).map_err(before_launch)?;
- if options.attach_if_running && initial.len() == 1 {
- let app = &initial[0];
- let instance = required_instance(app).map_err(before_launch)?;
+ if options.attach_if_running && initial.len() == 1 && !options.activate {
+ let app = initial[0].clone();
+ let instance = required_instance(&app).map_err(before_launch)?;
let pid = crate::system::process_identity::to_pid_t(app.pid).map_err(before_launch)?;
- if let Some(window) = exact_window(pid, &instance, deadline).map_err(before_launch)? {
- return Ok(window);
- }
+ let window = exact_window(pid, &instance, deadline).map_err(before_launch)?;
+ return Ok(result_from_app(&app, window));
}
let target = launch_target(options, initial).map_err(before_launch)?;
let launched = crate::system::launch_workspace::open(id, options, deadline)?;
validate_launched_target(&target, &launched).map_err(after_launch)?;
- let mut poll_interval = Duration::from_millis(50);
+ let window =
+ settled_window(launched.0, &launched.1, options, deadline).map_err(after_launch)?;
+ result_from_launched(&launched, window, id).map_err(after_launch)
+}
+
+/// Waits only for the windows the launch itself produces. Starting up is what
+/// creates them, so once the application reports that it finished starting up,
+/// every window it was going to open on its own already exists and further
+/// polling can only run out the deadline. An application that opens its first
+/// window in response to being brought forward — TextEdit, Preview, any
+/// document-based application — reports no window here, and `activate` is how a
+/// caller asks for one instead of waiting for one it never requested.
+#[cfg(target_os = "macos")]
+fn settled_window(
+ pid: i32,
+ process_instance: &str,
+ options: &LaunchOptions,
+ deadline: Deadline,
+) -> Result<Option<WindowInfo>, AdapterError> {
+ let mut poll_interval = Duration::from_millis(25);
+ let mut grace_ends_at = None;
loop {
- if let Some(window) =
- exact_window(launched.0, &launched.1, deadline).map_err(after_launch)?
+ if let Some(window) = exact_window(pid, process_instance, deadline)? {
+ return Ok(Some(window));
+ }
+ if options.timeout_ms == 0
+ || (!options.activate && grace_over(grace_ends_at, Instant::now()))
{
- return Ok(window);
+ return Ok(None);
}
- if !should_poll_after_first_observation(options.timeout_ms) {
- return Err(launch_no_window_error(id, timeout_ms, &launched));
+ if grace_ends_at.is_none() && startup_finished(pid, process_instance)? {
+ grace_ends_at = Instant::now().checked_add(STARTUP_GRACE);
}
let remaining = deadline.remaining();
if remaining.is_zero() {
- return Err(launch_no_window_error(id, timeout_ms, &launched));
+ return Ok(None);
}
std::thread::sleep(poll_interval.min(remaining));
poll_interval = (poll_interval * 3 / 2).min(Duration::from_millis(250));
}
}
+/// Ends the wait when the application has created whatever windows its launch
+/// produces. The window server keeps no record of a process that exited, and
+/// none of one that has not registered yet, so libproc decides which happened:
+/// a process that is gone ends the launch with an error rather than an answer
+/// about windows it will never open.
+#[cfg(target_os = "macos")]
+fn startup_finished(pid: i32, process_instance: &str) -> Result<bool, AdapterError> {
+ use crate::system::appkit_bridge::StartupState;
+ match crate::system::appkit_bridge::startup_state(pid) {
+ StartupState::Starting => Ok(false),
+ StartupState::Finished => Ok(true),
+ StartupState::NoRecord => {
+ if crate::system::process_identity::matches_instance(pid, process_instance)? {
+ Ok(true)
+ } else {
+ Err(launch_target_gone(pid))
+ }
+ }
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn launch_target_gone(pid: i32) -> AdapterError {
+ AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Launched application exited before it presented a window",
+ )
+ .with_details(serde_json::json!({ "pid": pid, "complete": false }))
+ .with_suggestion("Check the application's own launch requirements, then retry.")
+}
+
+/// The grace covers the gap between an application reporting that it started
+/// and its first window reaching the window server. Waiting starts running out
+/// only once there is a completed startup to measure from.
+#[cfg(target_os = "macos")]
+fn grace_over(grace_ends_at: Option<Instant>, now: Instant) -> bool {
+ grace_ends_at.is_some_and(|end| now >= end)
+}
+
+/// The attaching path reports the display name, so the launching path has to
+/// report the same thing for the same field. A window already carries it; the
+/// requested identifier is the fallback when there is no window to ask.
+#[cfg(target_os = "macos")]
+fn launched_display_name(window: Option<&WindowInfo>, id: &str) -> String {
+ window
+ .map(|window| window.app.clone())
+ .unwrap_or_else(|| id.to_owned())
+}
+
+#[cfg(target_os = "macos")]
+fn result_from_app(app: &AppInfo, window: Option<WindowInfo>) -> LaunchResult {
+ LaunchResult {
+ app: app.name.clone(),
+ pid: app.pid,
+ process_instance: app.process_instance.clone(),
+ window,
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn result_from_launched(
+ launched: &(i32, String),
+ window: Option<WindowInfo>,
+ id: &str,
+) -> Result<LaunchResult, AdapterError> {
+ Ok(LaunchResult {
+ app: launched_display_name(window.as_ref(), id),
+ pid: agent_desktop_core::ProcessId::try_from(launched.0)
+ .map_err(|_| AdapterError::internal("Launched process identifier is out of range"))?,
+ process_instance: Some(launched.1.clone()),
+ window,
+ })
+}
+
#[cfg(not(target_os = "macos"))]
pub(crate) fn launch_app_impl(
_id: &str,
_options: &LaunchOptions,
_deadline: Deadline,
-) -> Result<WindowInfo, AdapterError> {
+) -> Result<LaunchResult, AdapterError> {
Err(AdapterError::not_supported("launch_app"))
}
@@ -209,11 +305,6 @@ fn before_launch(error: AdapterError) -> AdapterError {
error.with_disposition(DeliverySemantics::not_delivered())
}
-#[cfg(target_os = "macos")]
-fn should_poll_after_first_observation(timeout_ms: u64) -> bool {
- timeout_ms > 0
-}
-
#[cfg(target_os = "macos")]
fn validate_app_identifier(id: &str) -> Result<(), AdapterError> {
let safe_bundle_id = !looks_like_bundle_id(id)
@@ -277,26 +368,6 @@ pub(crate) fn looks_like_bundle_id(id: &str) -> bool {
id.contains('.') && !id.ends_with(".app") && !id.contains(' ')
}
-#[cfg(target_os = "macos")]
-fn launch_no_window_error(id: &str, timeout_ms: u64, launched: &(i32, String)) -> AdapterError {
- AdapterError::new(
- ErrorCode::WindowNotFound,
- format!(
- "Application started, but no exact accessible window appeared within {timeout_ms} ms"
- ),
- )
- .with_details(serde_json::json!({
- "app_name": id,
- "pid": launched.0,
- "process_instance": launched.1,
- "retry_safe": false,
- }))
- .with_disposition(DeliverySemantics::delivered_unverified())
- .with_suggestion(
- "Inspect list-apps and list-windows for the returned process; do not repeat the launch blindly.",
- )
-}
-
#[cfg(target_os = "macos")]
fn after_launch(error: AdapterError) -> AdapterError {
error.with_disposition(DeliverySemantics::delivered_unverified())
diff --git a/crates/macos/src/system/launch_completion.rs b/crates/macos/src/system/launch_completion.rs
index 583748698..2c5222a00 100644
--- a/crates/macos/src/system/launch_completion.rs
+++ b/crates/macos/src/system/launch_completion.rs
@@ -147,7 +147,7 @@ fn validate_result(
)
})
})?;
- if !identity.matches_launch_time(result.launch_time) {
+ if identity.conflicts_with_launch_time(result.launch_time) {
return Err(callback_error(
result,
AdapterError::new(
diff --git a/crates/macos/src/system/launch_tests.rs b/crates/macos/src/system/launch_tests.rs
index 19189fbdc..4dc5860ab 100644
--- a/crates/macos/src/system/launch_tests.rs
+++ b/crates/macos/src/system/launch_tests.rs
@@ -45,9 +45,12 @@ fn rejects_paths_and_unsafe_bundle_identifiers() {
}
#[test]
-fn zero_wait_still_launches_but_never_polls_after_first_observation() {
- assert!(!should_poll_after_first_observation(0));
- assert!(should_poll_after_first_observation(1));
+fn waiting_ends_only_after_a_completed_startup_plus_its_grace() {
+ let now = std::time::Instant::now();
+
+ assert!(!grace_over(None, now));
+ assert!(!grace_over(now.checked_add(STARTUP_GRACE), now));
+ assert!(grace_over(Some(now), now));
}
#[test]
@@ -87,16 +90,3 @@ fn launch_options_enforce_a_bounded_text_budget() {
assert_eq!(error.code, ErrorCode::InvalidArgs);
}
-
-#[test]
-fn launch_no_window_error_keeps_identifier_in_details_only() {
- let marker = "MARKER_APP_ID_9f31c4";
- let error = launch_no_window_error(marker, 5000, &(77, "generation".into()));
-
- assert!(!error.message.contains(marker));
- assert!(error.message.contains("5000"));
- let details = error.details.expect("details");
- assert_eq!(details["app_name"], marker);
- assert_eq!(details["pid"], 77);
- assert_eq!(details["retry_safe"], false);
-}
diff --git a/crates/macos/src/system/launch_workspace.rs b/crates/macos/src/system/launch_workspace.rs
index 8e846350e..dedce0cba 100644
--- a/crates/macos/src/system/launch_workspace.rs
+++ b/crates/macos/src/system/launch_workspace.rs
@@ -18,7 +18,7 @@ pub(crate) fn open(
"bundle_id": super::launch::looks_like_bundle_id(id),
"arguments": options.args,
"environment": options.env,
- "activates": false,
+ "activates": options.activate,
"prompts": false,
"substitution": false,
"new_instance": creates_new_instance(options),
diff --git a/crates/macos/src/system/process_apps.rs b/crates/macos/src/system/process_apps.rs
index 3f6f2a955..8b46e6467 100644
--- a/crates/macos/src/system/process_apps.rs
+++ b/crates/macos/src/system/process_apps.rs
@@ -107,6 +107,7 @@ fn parse_apps(text: &str) -> Result<Vec<AppInfo>, AdapterError> {
pid: crate::system::process_identity::from_pid_t(pid)?,
bundle_id: None,
process_instance: None,
+ presentation: None,
});
}
}
diff --git a/crates/macos/src/system/process_identity.rs b/crates/macos/src/system/process_identity.rs
index 2cb9e5cc6..5202c48a2 100644
--- a/crates/macos/src/system/process_identity.rs
+++ b/crates/macos/src/system/process_identity.rs
@@ -92,6 +92,18 @@ impl ProcessIdentity {
(self.launch_time_seconds() - launch_time).abs() <= MAX_LAUNCH_TIME_DELTA_SECONDS
}
+ /// Absent evidence is not conflicting evidence. NSWorkspace reports no
+ /// launch date for a process it did not start — a system application
+ /// already running at login answers zero — so there is nothing to
+ /// reconcile against libproc and the caller must rely on its other
+ /// identity checks instead of failing.
+ pub(crate) fn conflicts_with_launch_time(self, launch_time: f64) -> bool {
+ if !launch_time.is_finite() || launch_time <= 0.0 {
+ return false;
+ }
+ !self.matches_launch_time(launch_time)
+ }
+
pub(crate) fn still_matches(self) -> Result<bool, AdapterError> {
Ok(Self::capture(self.pid)?.is_some_and(|current| current == self))
}
@@ -279,6 +291,10 @@ mod tests {
assert!(identity.matches_launch_time(1_700_000_000.25));
assert!(!identity.matches_launch_time(1_700_000_006.0));
assert!(!identity.matches_launch_time(0.0));
+ assert!(identity.conflicts_with_launch_time(1_700_000_006.0));
+ assert!(!identity.conflicts_with_launch_time(1_700_000_000.25));
+ assert!(!identity.conflicts_with_launch_time(0.0));
+ assert!(!identity.conflicts_with_launch_time(f64::NAN));
}
#[test]
diff --git a/crates/macos/src/system/signals_tests.rs b/crates/macos/src/system/signals_tests.rs
index f41496c04..f6c4785fe 100644
--- a/crates/macos/src/system/signals_tests.rs
+++ b/crates/macos/src/system/signals_tests.rs
@@ -43,12 +43,14 @@ fn matching_apps_filters_by_name_case_insensitively() {
pid: agent_desktop_core::ProcessId::new(42),
bundle_id: None,
process_instance: None,
+ presentation: None,
},
AppInfo {
name: "Finder".into(),
pid: agent_desktop_core::ProcessId::new(7),
bundle_id: None,
process_instance: None,
+ presentation: None,
},
],
);
@@ -65,6 +67,7 @@ fn app_filter_with_no_constraints_preserves_the_complete_inventory() {
pid: agent_desktop_core::ProcessId::new(7),
bundle_id: None,
process_instance: None,
+ presentation: None,
}];
let filtered = filter_apps(&filter, apps);
@@ -82,6 +85,7 @@ fn surfaces_for_apps_is_empty_without_an_app_or_pid_filter() {
pid: agent_desktop_core::ProcessId::new(1),
bundle_id: None,
process_instance: None,
+ presentation: None,
}];
let deadline = Instant::now() + Duration::from_secs(5);
let surfaces =
diff --git a/crates/macos/src/system/window_ax_state.rs b/crates/macos/src/system/window_ax_state.rs
index 7cc6e795e..652b191ac 100644
--- a/crates/macos/src/system/window_ax_state.rs
+++ b/crates/macos/src/system/window_ax_state.rs
@@ -52,12 +52,24 @@ pub(crate) fn read_frontmost_until(
})
}
+/// Frontmost-ness only selects whether a focused window is reported, and a busy
+/// application answering "unknown" is not a reason to fail the command that
+/// asked. Permission and API failures still propagate, because those describe
+/// the caller's access rather than the application's state.
+fn is_frontmost(app: &crate::tree::AXElement, deadline: Instant) -> Result<bool, AdapterError> {
+ match crate::tree::surface_read::boolean(app, "AXFrontmost", deadline) {
+ Ok(frontmost) => Ok(frontmost == Some(true)),
+ Err(error) if error.code == ErrorCode::PermDenied => Err(error),
+ Err(_) => Ok(false),
+ }
+}
+
fn focused_identity(
app: &crate::tree::AXElement,
pid: i32,
deadline: Instant,
) -> Result<Option<AxWindowIdentity>, AdapterError> {
- if crate::tree::surface_read::boolean(app, "AXFrontmost", deadline)? != Some(true) {
+ if !is_frontmost(app, deadline)? {
return Ok(None);
}
let Some(focused) = crate::tree::surface_read::element(app, "AXFocusedWindow", deadline)?
diff --git a/crates/macos/src/system/window_inventory.rs b/crates/macos/src/system/window_inventory.rs
index a483e289e..3fdb294e7 100644
--- a/crates/macos/src/system/window_inventory.rs
+++ b/crates/macos/src/system/window_inventory.rs
@@ -20,6 +20,7 @@ fn apps_from_window_records(
.expect("fixture pid must be positive"),
bundle_id: None,
process_instance: record.process_instance.clone(),
+ presentation: None,
});
}
@@ -48,6 +49,46 @@ pub(crate) fn list_windows_until(
)
}
+/// The window server already knows which windows exist; accessibility is only
+/// asked which one holds focus and which are minimized. An application too busy
+/// to answer that — a freshly launched one, or one sitting in a modal panel —
+/// must not hide its windows from the inventory, or a caller waits out its whole
+/// deadline for windows the window server listed immediately. Selecting *the
+/// focused* window is the one case that genuinely needs the answer.
+fn focus_state(
+ ax_state: &mut impl FnMut(
+ i32,
+ )
+ -> Result<crate::system::window_ax_state::WindowAxState, AdapterError>,
+ pid: i32,
+ focused_only: bool,
+) -> Result<crate::system::window_ax_state::WindowAxState, AdapterError> {
+ match ax_state(pid) {
+ Ok(state) => Ok(state),
+ Err(error) if focused_only => Err(error),
+ Err(_) => Ok(crate::system::window_ax_state::WindowAxState {
+ focused: None,
+ minimized_by_id: rustc_hash::FxHashMap::default(),
+ }),
+ }
+}
+
+/// An application carries offscreen bookkeeping windows alongside the one the
+/// user sees — TextEdit answers with four menu-bar-sized panels plus a save
+/// accessory view before its first document appears. Counting those makes the
+/// only real window look ambiguous, and reports an application that has not
+/// drawn anything yet as having several windows to choose between.
+///
+/// A minimized window is the user's window and is kept: it is offscreen for a
+/// reason the caller cares about, unlike a panel that was never meant to be
+/// seen. Dropping it would report an application as having no window while its
+/// window sits in the Dock.
+fn narrow_to_real_windows(windows: &mut Vec<WindowInfo>) {
+ windows.retain(|window| {
+ window.state.visible == Some(true) || window.state.minimized == Some(true)
+ });
+}
+
pub(crate) fn exact_window_for_pid_until(
pid: i32,
deadline: Instant,
@@ -62,6 +103,7 @@ pub(crate) fn exact_window_for_pid_until(
crate::system::process_identity::matches_instance(owner_pid, instance)
},
)?;
+ narrow_to_real_windows(&mut windows);
if windows.len() == 1 {
return Ok(windows.remove(0));
}
@@ -128,7 +170,9 @@ fn windows_from_records_with_focus(
.unwrap_or(0);
let state = match state_cache.entry(record.pid) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
- std::collections::hash_map::Entry::Vacant(entry) => entry.insert(ax_state(record.pid)?),
+ std::collections::hash_map::Entry::Vacant(entry) => {
+ entry.insert(focus_state(&mut ax_state, record.pid, focused_only)?)
+ }
};
if !verify_instance(record.pid, process_instance)? {
return Err(identity_race_error(
diff --git a/crates/macos/src/system/window_inventory_tests.rs b/crates/macos/src/system/window_inventory_tests.rs
index 45c358386..448309282 100644
--- a/crates/macos/src/system/window_inventory_tests.rs
+++ b/crates/macos/src/system/window_inventory_tests.rs
@@ -174,3 +174,43 @@ fn record(app_name: &str, pid: i32, title: &str, window_number: i64) -> WindowRe
process_instance: Some(format!("instance-{pid}")),
}
}
+
+fn window_with_state(id: &str, visible: Option<bool>, minimized: Option<bool>) -> WindowInfo {
+ WindowInfo {
+ id: id.to_owned(),
+ title: "w".into(),
+ app: "Fixture".into(),
+ pid: agent_desktop_core::ProcessId::new(42),
+ process_instance: Some("fixture-42".into()),
+ bounds: None,
+ state: agent_desktop_core::WindowState {
+ is_focused: false,
+ minimized,
+ visible,
+ },
+ }
+}
+
+#[test]
+fn narrowing_drops_bookkeeping_panels_but_keeps_a_minimized_window() {
+ let mut windows = vec![
+ window_with_state("panel", Some(false), Some(false)),
+ window_with_state("never-drawn", Some(false), None),
+ window_with_state("minimized", Some(false), Some(true)),
+ window_with_state("onscreen", Some(true), Some(false)),
+ ];
+
+ narrow_to_real_windows(&mut windows);
+
+ let kept = windows.iter().map(|w| w.id.as_str()).collect::<Vec<_>>();
+ assert_eq!(kept, vec!["minimized", "onscreen"]);
+}
+
+#[test]
+fn narrowing_leaves_nothing_when_an_application_has_only_panels() {
+ let mut windows = vec![window_with_state("panel", Some(false), Some(false))];
+
+ narrow_to_real_windows(&mut windows);
+
+ assert!(windows.is_empty());
+}
diff --git a/crates/macos/src/system/window_resolve.rs b/crates/macos/src/system/window_resolve.rs
index 127653c7c..f2e9e8a98 100644
--- a/crates/macos/src/system/window_resolve.rs
+++ b/crates/macos/src/system/window_resolve.rs
@@ -130,7 +130,7 @@ fn resolve_window_element_strict(
crate::tree::locator_deadline::remaining(deadline)?;
let pid = crate::system::process_identity::to_pid_t(win.pid)?;
ax_window_element_for_number(pid, window_number, record.title.as_deref(), deadline)?
- .ok_or_else(|| window_not_found(&win.id))
+ .ok_or_else(|| window_not_accessible(&win.id))
}
pub(crate) fn parse_window_number(id: &str) -> Option<i64> {
@@ -344,6 +344,26 @@ fn invalid_window_id(id: &str) -> AdapterError {
.with_suggestion("Window ids come from 'list-windows' (format w-<number>).")
}
+/// The window exists in the CoreGraphics inventory but the owning application
+/// does not publish it through accessibility. Reporting it as missing
+/// contradicts `list-windows`, which correctly still lists it: screenshots and
+/// coordinate input address CoreGraphics windows, only the semantic path needs
+/// an accessibility element.
+fn window_not_accessible(id: &str) -> AdapterError {
+ AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ format!("Window '{id}' exists but is not exposed through accessibility"),
+ )
+ .with_details(serde_json::json!({
+ "kind": "window_without_accessibility_element",
+ "window_id": id,
+ }))
+ .with_suggestion(
+ "This window supports screenshots and coordinate input only. Bring it on screen, \
+ or target another window from 'list-windows'.",
+ )
+}
+
fn window_not_found(id: &str) -> AdapterError {
AdapterError::new(
ErrorCode::WindowNotFound,
diff --git a/crates/macos/src/system/window_resolve_tests.rs b/crates/macos/src/system/window_resolve_tests.rs
index 6f205c6c0..a399391bc 100644
--- a/crates/macos/src/system/window_resolve_tests.rs
+++ b/crates/macos/src/system/window_resolve_tests.rs
@@ -186,3 +186,18 @@ fn verify_skips_title_when_request_title_empty() {
let live = record("TextEdit", pid, "Any Title", 100);
assert!(verify_window_record(&requested, &live).is_ok());
}
+
+/// `list-windows` reports the CoreGraphics inventory, which includes windows an
+/// application never publishes through accessibility. Calling those missing
+/// contradicts the inventory that just handed out the id.
+#[test]
+fn a_window_without_an_accessibility_element_is_not_reported_as_missing() {
+ let error = super::window_not_accessible("w-82");
+
+ assert_eq!(
+ error.code,
+ agent_desktop_core::ErrorCode::ActionNotSupported
+ );
+ assert!(error.message.contains("exists"));
+ assert_ne!(error.code, agent_desktop_core::ErrorCode::WindowNotFound);
+}
diff --git a/crates/macos/src/system/workspace_apps.rs b/crates/macos/src/system/workspace_apps.rs
index 71e731380..e49dc3148 100644
--- a/crates/macos/src/system/workspace_apps.rs
+++ b/crates/macos/src/system/workspace_apps.rs
@@ -144,7 +144,7 @@ fn apps_from_json_with(
for app in bridged
.applications
.into_iter()
- .filter(|app| app.activation_policy == ActivationPolicy::Regular)
+ .filter(|app| app.activation_policy != ActivationPolicy::Prohibited)
.filter(include)
{
ensure_before_deadline(deadline)?;
@@ -160,12 +160,22 @@ fn apps_from_json_with(
pid: crate::system::process_identity::from_pid_t(app.pid)?,
bundle_id: app.bundle_id,
process_instance: Some(process_instance),
+ presentation: Some(presentation_of(app.activation_policy)),
});
}
ensure_before_deadline(deadline)?;
Ok(apps)
}
+fn presentation_of(policy: ActivationPolicy) -> agent_desktop_core::AppPresentation {
+ match policy {
+ ActivationPolicy::Regular => agent_desktop_core::AppPresentation::Foreground,
+ ActivationPolicy::Accessory | ActivationPolicy::Prohibited => {
+ agent_desktop_core::AppPresentation::Background
+ }
+ }
+}
+
fn window_owner_snapshot_from_json(
bytes: &[u8],
deadline: Instant,
diff --git a/crates/macos/src/system/workspace_apps_tests.rs b/crates/macos/src/system/workspace_apps_tests.rs
index 36fda35ba..3ef6d5829 100644
--- a/crates/macos/src/system/workspace_apps_tests.rs
+++ b/crates/macos/src/system/workspace_apps_tests.rs
@@ -184,7 +184,7 @@ fn owner_snapshot_equality_detects_generation_and_frontmost_changes() {
}
#[test]
-fn app_inventory_keeps_only_regular_activation_policy() {
+fn app_inventory_labels_menu_bar_apps_and_drops_headless_services() {
let bytes = br#"{
"applications":[
{"name":"Mail","pid":10,"launch_time":100.25,"activation_policy":"regular"},
@@ -206,9 +206,18 @@ fn app_inventory_keeps_only_regular_activation_policy() {
)
.unwrap();
- assert_eq!(probed, [10]);
- assert_eq!(apps.len(), 1);
+ assert_eq!(probed, [10, 11]);
+ assert_eq!(apps.len(), 2);
assert_eq!(apps[0].name, "Mail");
+ assert_eq!(
+ apps[0].presentation,
+ Some(agent_desktop_core::AppPresentation::Foreground)
+ );
+ assert_eq!(apps[1].name, "Palette");
+ assert_eq!(
+ apps[1].presentation,
+ Some(agent_desktop_core::AppPresentation::Background)
+ );
}
#[test]
diff --git a/crates/macos/src/tree/action_list.rs b/crates/macos/src/tree/action_list.rs
index 7679aaaeb..81c2d9e87 100644
--- a/crates/macos/src/tree/action_list.rs
+++ b/crates/macos/src/tree/action_list.rs
@@ -5,6 +5,10 @@ use agent_desktop_core::capability;
#[cfg(target_os = "macos")]
use accessibility_sys::{kAXFocusedAttribute, kAXValueAttribute};
+/// AppKit controls publish `AXPress`; document-shell rows publish `AXOpen` or
+/// `AXConfirm` instead and never publish `AXPress`.
+pub(crate) const PRIMARY_ACTIVATION_ACTIONS: [&str; 3] = ["AXPress", "AXOpen", "AXConfirm"];
+
pub(crate) struct AvailableActionsRead {
pub(crate) actions: Vec<String>,
pub(crate) complete: bool,
@@ -50,11 +54,22 @@ pub(crate) fn read_platform_available_actions(
let ax_actions = native_actions.value.unwrap_or_default();
let has = |name: &str| ax_actions.iter().any(|a| a == name);
- if has("AXPress") {
+ let publishes_activation = PRIMARY_ACTIVATION_ACTIONS.iter().any(|name| has(name));
+ if publishes_activation {
push_unique(&mut read.actions, capability::CLICK);
if crate::tree::roles::is_toggleable_role(role) {
push_unique(&mut read.actions, capability::TOGGLE);
}
+ } else if crate::actions::container_select::role_activates_by_selection(role)
+ && read_settable(
+ el,
+ crate::actions::container_select::SELECTED,
+ deadline,
+ &mut read,
+ )
+ .unwrap_or(false)
+ {
+ push_unique(&mut read.actions, capability::CLICK);
}
if has("AXShowMenu") && role_allows_context_menu_action(role) {
push_unique(&mut read.actions, capability::RIGHT_CLICK);
@@ -125,21 +140,9 @@ fn record_error(read: &mut AvailableActionsRead, error: i32) {
read.api_disabled |= error == accessibility_sys::kAXErrorAPIDisabled;
}
-/// AppKit's NSAccessibility bridge answers these codes when an element simply
-/// does not implement the probed attribute or action list — including
-/// `kAXErrorFailure`, which it returns for synthetic `NSAccessibilityElement`s
-/// with no action support. They are complete "none present" answers, not
-/// transport failures, so they must not mark the read incomplete.
#[cfg(target_os = "macos")]
fn is_definitive_absence(error: i32) -> bool {
- matches!(
- error,
- accessibility_sys::kAXErrorAttributeUnsupported
- | accessibility_sys::kAXErrorNoValue
- | accessibility_sys::kAXErrorNotImplemented
- | accessibility_sys::kAXErrorActionUnsupported
- | accessibility_sys::kAXErrorFailure
- )
+ crate::tree::ax_absence::is_absent_action_error(error)
}
fn role_may_bear_value(role: &str) -> bool {
@@ -225,6 +228,14 @@ mod tests {
role_may_bear_value, role_may_insert_text, role_supports_collection_select,
};
+ #[test]
+ fn document_shell_activation_actions_are_recognised_alongside_press() {
+ assert_eq!(
+ super::PRIMARY_ACTIVATION_ACTIONS,
+ ["AXPress", "AXOpen", "AXConfirm"]
+ );
+ }
+
#[test]
fn canonical_handle_role_is_probed_for_settable_value() {
assert!(role_may_bear_value("handle"));
diff --git a/crates/macos/src/tree/attributes.rs b/crates/macos/src/tree/attributes.rs
index e8053ebfa..1904011ec 100644
--- a/crates/macos/src/tree/attributes.rs
+++ b/crates/macos/src/tree/attributes.rs
@@ -6,7 +6,7 @@ mod imp {
};
const MALFORMED_AX_VALUE: i32 = i32::MIN;
- use accessibility_sys::{kAXErrorAttributeUnsupported, kAXErrorNoValue, kAXErrorSuccess};
+ use accessibility_sys::kAXErrorSuccess;
use core_foundation::{
array::CFArray,
base::{CFType, CFTypeRef, TCFType},
@@ -131,7 +131,7 @@ mod imp {
}
fn is_absent_error(error: i32) -> bool {
- error == kAXErrorAttributeUnsupported || error == kAXErrorNoValue
+ crate::tree::ax_absence::is_absent_attribute_error(error)
}
}
diff --git a/crates/macos/src/tree/ax_absence.rs b/crates/macos/src/tree/ax_absence.rs
new file mode 100644
index 000000000..068d58d4c
--- /dev/null
+++ b/crates/macos/src/tree/ax_absence.rs
@@ -0,0 +1,46 @@
+/// AppKit's NSAccessibility bridge answers these codes when an element simply
+/// does not implement the probed attribute — including `kAXErrorFailure`, which
+/// it returns for synthetic `NSAccessibilityElement`s with no support at all.
+/// They are complete "none present" answers, not transport failures.
+///
+/// One definition, because a code that the capability reader calls absent and
+/// the attribute reader calls a failure makes the same element readable in one
+/// command and broken in another.
+pub(crate) fn is_absent_attribute_error(error: i32) -> bool {
+ matches!(
+ error,
+ accessibility_sys::kAXErrorAttributeUnsupported
+ | accessibility_sys::kAXErrorNoValue
+ | accessibility_sys::kAXErrorNotImplemented
+ | accessibility_sys::kAXErrorFailure
+ )
+}
+
+pub(crate) fn is_absent_action_error(error: i32) -> bool {
+ error == accessibility_sys::kAXErrorActionUnsupported || is_absent_attribute_error(error)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{is_absent_action_error, is_absent_attribute_error};
+
+ #[test]
+ fn appkit_failure_code_reads_as_absence_everywhere() {
+ assert!(is_absent_attribute_error(
+ accessibility_sys::kAXErrorFailure
+ ));
+ assert!(is_absent_action_error(accessibility_sys::kAXErrorFailure));
+ }
+
+ #[test]
+ fn transport_failures_are_never_absence() {
+ for error in [
+ accessibility_sys::kAXErrorCannotComplete,
+ accessibility_sys::kAXErrorInvalidUIElement,
+ accessibility_sys::kAXErrorAPIDisabled,
+ ] {
+ assert!(!is_absent_attribute_error(error));
+ assert!(!is_absent_action_error(error));
+ }
+ }
+}
diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rs
index 73b57cbe0..2ee11f268 100644
--- a/crates/macos/src/tree/mod.rs
+++ b/crates/macos/src/tree/mod.rs
@@ -1,6 +1,7 @@
pub(crate) mod action_list;
mod adapter;
pub(crate) mod attributes;
+pub(crate) mod ax_absence;
pub(crate) mod ax_element;
pub(crate) mod ax_ipc;
pub(crate) mod ax_value;
diff --git a/crates/macos/src/tree/observation_usage.rs b/crates/macos/src/tree/observation_usage.rs
index ede1522a5..75112f2ea 100644
--- a/crates/macos/src/tree/observation_usage.rs
+++ b/crates/macos/src/tree/observation_usage.rs
@@ -8,6 +8,10 @@ pub(crate) struct ObservationUsage {
}
impl ObservationUsage {
+ pub(crate) fn with_defaults() -> Self {
+ Self::new(ObservationBudget::default())
+ }
+
pub(crate) fn new(limits: ObservationBudget) -> Self {
Self {
limits,
diff --git a/crates/macos/src/tree/query/child_read.rs b/crates/macos/src/tree/query/child_read.rs
index 329b5c0b1..37f4757d9 100644
--- a/crates/macos/src/tree/query/child_read.rs
+++ b/crates/macos/src/tree/query/child_read.rs
@@ -30,6 +30,17 @@ impl ChildRead {
}
}
+ fn failed(status: ChildReadStatus) -> Self {
+ Self {
+ elements: Vec::new(),
+ total_count: 0,
+ complete: false,
+ source_availability: ChildSourceAvailability::Unknown,
+ prefix_certain: false,
+ status,
+ }
+ }
+
fn unavailable(status: ChildReadStatus) -> Self {
Self {
elements: Vec::new(),
@@ -88,17 +99,10 @@ mod imp {
deadline: std::time::Instant,
) -> ChildRead {
let count_deadline =
- super::super::child_read_budget::boundary_count_deadline(max_elements, deadline);
+ super::super::child_read_budget::count_deadline(max_elements, deadline);
let mut status = ChildReadStatus::default();
if prepare(element, deadline, &mut status).is_err() {
- return ChildRead {
- elements: Vec::new(),
- total_count: 0,
- complete: false,
- source_availability: ChildSourceAvailability::Unknown,
- prefix_certain: false,
- status,
- };
+ return ChildRead::failed(status);
}
status.attempts += 1;
let count = match child_count(element, attribute, count_deadline) {
@@ -108,14 +112,7 @@ mod imp {
}
Err(error) => {
telemetry::record(&mut status, attribute, "initial_count", error, None);
- return ChildRead {
- elements: Vec::new(),
- total_count: 0,
- complete: false,
- source_availability: ChildSourceAvailability::Unknown,
- prefix_certain: false,
- status,
- };
+ return read_without_count(element, attribute, max_elements, deadline, status);
}
};
let requested = count.min(max_elements);
@@ -160,14 +157,7 @@ mod imp {
) -> ChildRead {
let mut status = ChildReadStatus::default();
if prepare(element, deadline, &mut status).is_err() {
- return ChildRead {
- elements: Vec::new(),
- total_count: 0,
- complete: false,
- source_availability: ChildSourceAvailability::Unknown,
- prefix_certain: false,
- status,
- };
+ return ChildRead::failed(status);
}
status.attempts += 1;
let initial_count = match child_count(element, attribute, deadline) {
@@ -175,14 +165,7 @@ mod imp {
Err(error) if is_absent_error(error) => return ChildRead::unavailable(status),
Err(error) => {
telemetry::record(&mut status, attribute, "initial_count", error, None);
- return ChildRead {
- elements: Vec::new(),
- total_count: 0,
- complete: false,
- source_availability: ChildSourceAvailability::Unknown,
- prefix_certain: false,
- status,
- };
+ return ChildRead::failed(status);
}
};
let mut elements = if index < initial_count {
@@ -240,6 +223,32 @@ mod imp {
}
}
+ /// A responder can serve the values of an attribute while failing to answer
+ /// its count inside the count budget — Xcode does this for `AXWindows`. The
+ /// count is only an optimisation, so a short read still proves the elements
+ /// it returned; only a full page leaves the tail unknown.
+ fn read_without_count(
+ element: &AXElement,
+ attribute: &str,
+ max_elements: usize,
+ deadline: std::time::Instant,
+ mut status: ChildReadStatus,
+ ) -> ChildRead {
+ let Ok(elements) = read_prefix(element, attribute, max_elements, deadline, &mut status)
+ else {
+ return ChildRead::failed(status);
+ };
+ let saturated = max_elements > 0 && elements.len() == max_elements;
+ ChildRead {
+ total_count: elements.len() + usize::from(saturated),
+ elements,
+ complete: !saturated,
+ source_availability: ChildSourceAvailability::Available,
+ prefix_certain: !saturated,
+ status,
+ }
+ }
+
fn child_count(
element: &AXElement,
attribute: &str,
diff --git a/crates/macos/src/tree/query/child_read_budget.rs b/crates/macos/src/tree/query/child_read_budget.rs
index c98ffaeb9..b3053945e 100644
--- a/crates/macos/src/tree/query/child_read_budget.rs
+++ b/crates/macos/src/tree/query/child_read_budget.rs
@@ -6,15 +6,20 @@
/// that cannot afford one is still reported as truncated, just without a number.
const BOUNDARY_COUNT_BUDGET: std::time::Duration = std::time::Duration::from_millis(25);
-pub(super) fn boundary_count_deadline(
+/// The same reasoning applies when the children are about to be read: a count
+/// that consumes the whole deadline starves the read it was meant to size, so
+/// it never gets more than half of what is left.
+pub(super) fn count_deadline(
max_elements: usize,
deadline: std::time::Instant,
) -> std::time::Instant {
- if max_elements == 0 {
- deadline.min(std::time::Instant::now() + BOUNDARY_COUNT_BUDGET)
+ let now = std::time::Instant::now();
+ let budget = if max_elements == 0 {
+ BOUNDARY_COUNT_BUDGET
} else {
- deadline
- }
+ deadline.saturating_duration_since(now) / 2
+ };
+ deadline.min(now + budget)
}
#[cfg(test)]
@@ -26,7 +31,7 @@ mod tests {
fn a_boundary_count_gets_only_a_slice_of_a_long_deadline() {
let far = Instant::now() + Duration::from_secs(3);
- let bounded = boundary_count_deadline(0, far);
+ let bounded = count_deadline(0, far);
assert!(
bounded < far,
@@ -36,17 +41,22 @@ mod tests {
assert!(bounded <= Instant::now() + Duration::from_millis(60));
}
+ /// A slow responder that cannot answer a count must still leave the caller
+ /// enough budget to read the values themselves.
#[test]
- fn a_real_child_read_keeps_the_callers_deadline() {
+ fn a_real_child_read_leaves_half_its_deadline_for_the_values() {
let far = Instant::now() + Duration::from_secs(3);
- assert_eq!(boundary_count_deadline(128, far), far);
+ let bounded = count_deadline(128, far);
+
+ assert!(bounded < far);
+ assert!(far.saturating_duration_since(bounded) >= Duration::from_millis(1400));
}
#[test]
fn the_bound_never_extends_a_deadline_that_is_already_shorter() {
let near = Instant::now() + Duration::from_millis(5);
- assert_eq!(boundary_count_deadline(0, near), near);
+ assert!(count_deadline(0, near) <= near);
}
}
diff --git a/crates/macos/src/tree/query/mod.rs b/crates/macos/src/tree/query/mod.rs
index 4580b635a..0415db495 100644
--- a/crates/macos/src/tree/query/mod.rs
+++ b/crates/macos/src/tree/query/mod.rs
@@ -89,7 +89,7 @@ fn resolve_root(
request: &ObservationRequest,
deadline: std::time::Instant,
) -> Result<ResolvedRoot, AdapterError> {
- let source = ObservationSource::from_root(&root);
+ let source = ObservationSource::from_root(&root, request.surface);
match root {
ObservationRoot::Window(window) => {
let pid = crate::system::process_identity::to_pid_t(window.pid)?;
diff --git a/crates/macos/src/tree/state_reader.rs b/crates/macos/src/tree/state_reader.rs
index 8a3f463d2..48ebb5ccd 100644
--- a/crates/macos/src/tree/state_reader.rs
+++ b/crates/macos/src/tree/state_reader.rs
@@ -60,7 +60,7 @@ pub(crate) fn states_from_element(
if attrs.states.control.readonly == Some(true) {
states.push(state::READONLY.into());
}
- if is_offscreen(attrs.bounds, ctx.window_bounds) {
+ if offscreen(attrs.bounds, ctx.window_bounds).unwrap_or(false) {
states.push(state::OFFSCREEN.into());
}
states
@@ -83,15 +83,17 @@ fn value_is_indeterminate(value: Option<&str>) -> bool {
matches!(value, Some("2" | "mixed"))
}
-fn is_offscreen(bounds: Option<Rect>, window_bounds: Option<Rect>) -> bool {
- let (Some(el), Some(win)) = (bounds, window_bounds) else {
- return false;
- };
- let el_right = el.x + el.width;
- let el_bottom = el.y + el.height;
- let win_right = win.x + win.width;
- let win_bottom = win.y + win.height;
- el_right <= win.x || el.x >= win_right || el_bottom <= win.y || el.y >= win_bottom
+/// `None` when either rectangle is unknown. No macOS element publishes
+/// `AXOffscreen`, so this geometry test is the only source of the state and
+/// both the canonical state list and the live element read must share it.
+pub(crate) fn offscreen(bounds: Option<Rect>, window_bounds: Option<Rect>) -> Option<bool> {
+ let (el, win) = bounds.zip(window_bounds)?;
+ Some(
+ el.x + el.width <= win.x
+ || el.x >= win.x + win.width
+ || el.y + el.height <= win.y
+ || el.y >= win.y + win.height,
+ )
}
#[cfg(test)]
diff --git a/crates/macos/src/tree/text_attributes.rs b/crates/macos/src/tree/text_attributes.rs
index 2404596b9..5034b7120 100644
--- a/crates/macos/src/tree/text_attributes.rs
+++ b/crates/macos/src/tree/text_attributes.rs
@@ -1,9 +1,7 @@
#[cfg(target_os = "macos")]
mod imp {
use crate::tree::{AXElement, bounded_string::BoundedString};
- use accessibility_sys::{
- kAXErrorAttributeUnsupported, kAXErrorNoValue, kAXErrorSuccess, kAXValueAttribute,
- };
+ use accessibility_sys::{kAXErrorSuccess, kAXValueAttribute};
use core_foundation::{
base::{CFType, CFTypeRef, TCFType},
boolean::CFBoolean,
@@ -123,7 +121,7 @@ mod imp {
}
fn is_absent_error(error: i32) -> bool {
- error == kAXErrorAttributeUnsupported || error == kAXErrorNoValue
+ crate::tree::ax_absence::is_absent_attribute_error(error)
}
fn release_if_present(value: CFTypeRef) {
diff --git a/docs/json-output.md b/docs/json-output.md
index 7eafa7194..ca2b802c7 100644
--- a/docs/json-output.md
+++ b/docs/json-output.md
@@ -4,7 +4,7 @@ Every command returns structured JSON:
```json
{
- "version": "2.2",
+ "version": "2.3",
"ok": true,
"command": "click",
"data": { "action": "click" }
@@ -15,7 +15,7 @@ Errors include machine-readable codes and recovery hints:
```json
{
- "version": "2.2",
+ "version": "2.3",
"ok": false,
"command": "click",
"error": {
diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md
index f359426cb..728a5b230 100644
--- a/skills/agent-desktop/SKILL.md
+++ b/skills/agent-desktop/SKILL.md
@@ -102,8 +102,8 @@ Use **progressive skeleton traversal** as the default approach. It reduces token
Every command returns a JSON envelope on stdout:
-**Success:** `{ "version": "2.2", "ok": true, "command": "snapshot", "data": { ... } }`
-**Error:** `{ "version": "2.2", "ok": false, "command": "click", "error": { "code": "STALE_REF", "message": "...", "suggestion": "..." } }`
+**Success:** `{ "version": "2.3", "ok": true, "command": "snapshot", "data": { ... } }`
+**Error:** `{ "version": "2.3", "ok": false, "command": "click", "error": { "code": "STALE_REF", "message": "...", "suggestion": "..." } }`
The `error` object may also carry an optional `details` object (e.g. the actionability report on an actionability failure, candidate summaries on `AMBIGUOUS_TARGET`, or the last observed state on a `wait` `TIMEOUT`). Parse errors leniently — `details` and future fields are additive, so do not reject responses with unknown keys.
@@ -144,6 +144,8 @@ agent-desktop snapshot --app "App" -i # Full tree (simple
agent-desktop snapshot --app "App" --surface menu -i # Surface snapshot
agent-desktop screenshot --app "App" out.png # PNG screenshot
agent-desktop find --app "App" --role button # Search elements
+agent-desktop find --root @s8f3k2p9:e3 --role button # Search one region only
+agent-desktop find --app "App" --surface menubar --name "Save" --first # Search a menu
agent-desktop get @e1 --snapshot <snapshot_id> --property text # Read element property
agent-desktop is @e1 --snapshot <snapshot_id> --property enabled # Check element state
agent-desktop list-surfaces --app "App" # Available surfaces
@@ -184,7 +186,8 @@ agent-desktop --headed mouse-move --xy 100,200 # Move cursor
### App & Window
```
-agent-desktop launch "System Settings" # Launch and wait
+agent-desktop launch "System Settings" # Launch; returns once running
+agent-desktop launch "TextEdit" --activate # Also bring it forward and wait for a window
agent-desktop close-app "TextEdit" # Quit gracefully
agent-desktop close-app "TextEdit" --force # Force quit; SIGKILL if SIGTERM does not exit
agent-desktop list-windows --app "Finder" # List windows
@@ -260,9 +263,10 @@ agent-desktop skills get desktop --full # Load this skill + all referenc
5. **Use `wait` for async UI.** After launch/dialog triggers, wait for expected state.
6. **Check permissions first.** Run `permissions` on first use; screenshots also need Screen Recording.
7. **Handle errors.** Branch on `error.code` only — `error.message` and `error.suggestion` text is informational and may change between versions.
-8. **Use `find` for targeted searches.** Faster than any snapshot when you know role/name.
-9. **Use surfaces for overlays.** `snapshot --surface menu` for menus, `--surface sheet` for dialogs. Never `--skeleton` for surfaces — they're already focused.
-10. **Batch for performance.** Multiple commands in one invocation.
-11. **Headless by default.** Ref actions use semantic AX paths and block silent focus stealing, cursor movement, keyboard synthesis, and pasteboard insertion. Use `--headed` only when exact-window focus or physical delivery is intended; raw coordinates never imply focus.
-12. **Start a session once per run.** `session start` creates the manifest; pass its returned ID through `AGENT_DESKTOP_SESSION` for the run or `--session <id>` for one command. It does not activate later processes implicitly.
-13. **Trace hard failures.** With an active trace-enabled session, segments are written automatically. Add `--trace /tmp/agent-desktop.jsonl` only when you need a single override file (CI, one-offs). Check `status` when unsure whether tracing is active.
+8. **Use `find` for targeted searches, and scope it.** Faster than any snapshot when you know role/name. Narrow it with `--root @ref` for one region or `--surface menubar` for a menu — an unscoped find on a dense tree returns hundreds of refs and can exhaust its budget.
+9. **Use surfaces for overlays.** `snapshot --surface menu` for menus, `--surface sheet` for dialogs. Never `--skeleton` for surfaces — they're already focused. Reach one item inside an overlay with `find --surface`, not a full surface snapshot.
+10. **Read `data.surfaces` after acting.** An action that opens a sheet, menu, or alert reports it there. Target that overlay next instead of searching windows for what changed.
+11. **Batch for performance.** Multiple commands in one invocation.
+12. **Headless by default.** Ref actions use semantic AX paths and block silent focus stealing, cursor movement, keyboard synthesis, and pasteboard insertion. Use `--headed` only when exact-window focus or physical delivery is intended; raw coordinates never imply focus.
+13. **Start a session once per run.** `session start` creates the manifest; pass its returned ID through `AGENT_DESKTOP_SESSION` for the run or `--session <id>` for one command. It does not activate later processes implicitly.
+14. **Trace hard failures.** With an active trace-enabled session, segments are written automatically. Add `--trace /tmp/agent-desktop.jsonl` only when you need a single override file (CI, one-offs). Check `status` when unsure whether tracing is active.
diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.md
index 98f04992c..c5e180848 100644
--- a/skills/agent-desktop/references/commands-interaction.md
+++ b/skills/agent-desktop/references/commands-interaction.md
@@ -13,6 +13,30 @@ Ref-based actions run in two modes, Playwright-style:
`--headed` is a global flag and also applies to every `batch` entry.
+### Reading the result of an action
+
+A successful action reports what happened, not just that it ran:
+
+| Field | Meaning |
+|-------|---------|
+| `data.steps` | Each mechanism attempted, in order, with `outcome` (`succeeded`/`skipped`) and `verified` |
+| `data.disposition.delivery` | `delivered_verified` when the effect was observed, `delivered_unverified` when the application claimed success without an observable change |
+| `data.post_state` | The target element's state after the action, when the action has one |
+| `data.surfaces` | Overlays the application had open once the action settled |
+
+Check `data.surfaces` before assuming an action finished the job. An action that
+opens a sheet, menu, or alert leaves the application waiting on that overlay, and
+the next command must target it:
+
+```json
+{ "ok": true, "command": "set-value",
+ "data": { "action": "set-value", "surfaces": [{ "id": "focused-window", "type": "sheet" }] } }
+```
+
+Reach into that overlay with `find --surface sheet` rather than searching the
+window. A `delivered_unverified` result with a surface still open usually means
+the application is waiting for a confirmation the action did not deliver.
+
### `--wait-for` / `--wait-for-gone` (global)
Three global flags poll the accessibility tree until a compact selector matches (or, with `--wait-for-gone`, until it no longer matches), then return a snapshot envelope:
@@ -76,7 +100,7 @@ Click commands use semantic AX activation in strict headless mode. Pass `--heade
agent-desktop click @s8f3k2p9:e5
agent-desktop click @e5 --snapshot <snapshot_id>
```
-Primary activation. Headless uses `AXPress`; `--headed` performs a physical click first and reports `physical_synthetic` in `data.steps`.
+Primary activation. Headless tries the activation the element actually publishes — `AXPress`, `AXOpen`, or `AXConfirm` — and, for a row whose activation is selection, writes the container's selection instead. `--headed` performs a physical click first and reports `physical_synthetic` in `data.steps`. Delivery is judged by observing the application, not by the accessibility return code, so `data.steps` reports each attempt and `disposition.delivery` distinguishes `delivered_verified` from `delivered_unverified`.
### double-click
```bash
diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.md
index e20da3eca..a4169b7d4 100644
--- a/skills/agent-desktop/references/commands-observation.md
+++ b/skills/agent-desktop/references/commands-observation.md
@@ -37,7 +37,7 @@ agent-desktop snapshot --root @e12 --snapshot <snapshot_id> -i
**Output structure:**
```json
{
- "version": "2.2",
+ "version": "2.3",
"ok": true,
"command": "snapshot",
"data": {
@@ -122,11 +122,20 @@ agent-desktop find --app "App" --role button --name "OK" --exact
agent-desktop find --app "App" --description "Closes the dialog"
agent-desktop find --app "App" --native-id "submitButton"
agent-desktop find --app "App" --state enabled --state focused=false
+agent-desktop find --root @s8f3k2p9:e4 --role textfield --value "README.md" --first
+agent-desktop find --app "Finder" --surface menubar --name "Go to Folder…" --exact --first
```
+Scope the search before widening the query. `--root` searches one ref's subtree
+and `--surface` searches an overlay; both return a single ref instead of the
+whole tree, which is the difference between a few hundred bytes and a full
+menu-bar dump.
+
| Flag | Description |
|------|-------------|
| `--app` | Application name |
+| `--root REF` | Search only inside this ref's subtree instead of the whole window. Pair with `--snapshot` for a legacy bare `@eN` ref |
+| `--surface` | Search an overlay instead of the window (`menubar`, `menu`, `sheet`, `alert`, `popover`, ...). A menu bar belongs to the application, so several open windows are not ambiguous here. Cannot be combined with `--root`, which already carries its own surface |
| `--role` | Role to match against the live tree (button, textfield, checkbox, scrollarea, window, ...). Case-insensitive; `textarea`/`textbox`/`searchfield` fold to `textfield`. When a role filter matches nothing, the response carries `roles_present` — the roles actually in the searched tree — so you can tell "none on screen" from a wrong role name and retry |
| `--name` | Accessible name or label |
| `--value` | Current value |
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index 526b72cfc..e307848af 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -11,18 +11,38 @@ agent-desktop launch "com.apple.Safari" --timeout 10000
agent-desktop launch "TextEdit" --arg /tmp/notes.txt
agent-desktop launch "MyTool" --arg --flag --arg value --env KEY=VALUE --cwd /tmp
agent-desktop launch "MyTool" --no-attach
+agent-desktop launch "TextEdit" --activate
```
-Launches an application by name or bundle ID and waits until its window is visible.
+Launches an application by name or bundle ID and returns once the process is running.
| Flag | Default | Description |
|------|---------|-------------|
-| `--timeout` | 30000 | Max wait time in ms for window to appear |
+| `--timeout` | 30000 | Upper bound in ms for the whole launch |
| `--arg` | | Command-line argument passed to the launched app; repeatable, order preserved |
| `--env` | | `KEY=VALUE` environment variable for the launched process; repeatable |
| `--cwd` | | Working directory for the launched process |
| `--no-attach` | false | Require a fresh launch instead of the default attach-if-running behavior |
+| `--activate` | false | Bring the app forward so it presents a window, and wait for that window |
-By default, `launch` attaches to an already-running instance and returns its visible window. `--no-attach` rejects an already-running app with `ACTION_FAILED`; otherwise it starts a fresh instance and still waits for a real visible window. Windowless, menu-bar-only, or background apps return `WINDOW_NOT_FOUND` rather than a fabricated empty window response; use `list-apps` to observe those processes.
+The process starting and the app presenting a window are separate outcomes, so the response reports them separately:
+
+```json
+{ "app": "TextEdit", "pid": 611, "process_instance": "macos-proc-v1:...",
+ "window": { "id": "w-110407", "title": "Open", "visible": true } }
+```
+
+`window` is present when the app already has one and **omitted when it does not**. Its absence is a fact, not a failure — `launch` still returns `ok: true`.
+
+A launch waits only for the windows the launch itself causes. It polls until the app reports that it finished starting up, plus a short grace for the first window to reach the window server. Most apps therefore return their window in one step. An app that opens its first window only when brought forward — any document-based app — returns without one instead of waiting out `--timeout`.
+
+A launch that finds its process gone before any window appears fails with `APP_UNRESPONSIVE` rather than reporting a windowless success.
+
+When you need the window:
+
+- `--activate` asks the app to present one and waits for it up to `--timeout`, because activation is what causes the window. This brings the app forward, so it is not headless. Pair it with a small `--timeout` for an app that may have no window at all.
+- `wait --event window-opened` waits on your terms after you trigger the window some other way.
+
+Windowless, menu-bar-only, and background apps simply report no `window`; use `list-apps` to observe those processes and read their `presentation`. `--no-attach` rejects an already-running app with `ACTION_FAILED` and starts a fresh instance.
### close-app
```bash
@@ -39,7 +59,17 @@ Requests an application quit. A graceful quit is asynchronous — the app may sh
agent-desktop list-apps
agent-desktop list-apps --app "Text"
```
-Lists running GUI applications, optionally filtered by a case-insensitive name substring. Returns array of `{ name, pid, bundle_id }`.
+Lists running GUI applications, optionally filtered by a case-insensitive name substring. Returns array of `{ name, pid, bundle_id, presentation }`.
+
+`presentation` tells a foreground app from one that only appears on a hotkey or lives in the menu bar:
+
+| Value | Meaning |
+|-------|---------|
+| `foreground` | Owns ordinary windows and appears in the Dock |
+| `background` | No Dock entry — menu-bar and tray items, and overlays summoned by a hotkey. Their windows may exist only while shown |
+| omitted | Not registered as an application (helper processes and daemons found through the process table) |
+
+Applications with no user interface at all are excluded.
## Window Management
@@ -50,6 +80,12 @@ agent-desktop list-windows --app "Finder"
```
Lists all visible windows, optionally filtered by app. Returns array of `{ id, title, app_name, pid, bounds, is_focused }`. Focus is detected through the platform's frontmost/focused-window APIs, not window stacking order.
+The inventory comes from the window server, which knows more windows than the
+accessibility layer exposes. Targeting one an application never published
+returns `ACTION_NOT_SUPPORTED` with `kind: "window_without_accessibility_element"`
+— the window exists and still accepts screenshots and coordinate input, but no
+semantic command can reach it. Choose another window from this list.
+
### focus-window
```bash
agent-desktop focus-window --app "Finder"
@@ -326,7 +362,7 @@ Each entry may include `"session": "id"` beside `command` and `args`. If omitted
**Per-entry failure shape:**
```json
{
- "version": "2.2",
+ "version": "2.3",
"ok": false,
"command": "click",
"error": {
diff --git a/skills/agent-desktop/references/macos.md b/skills/agent-desktop/references/macos.md
index 4ab398fce..deb1c1b71 100644
--- a/skills/agent-desktop/references/macos.md
+++ b/skills/agent-desktop/references/macos.md
@@ -56,7 +56,8 @@ agent-desktop uses the macOS Accessibility API (`AXUIElement`) to read and manip
Core resolves and validates a ref, applies its headed focus/cursor requirement, and then asks the macOS adapter to execute an action-specific chain. The chain records each attempted mechanism and never invents a generic fallback ladder:
-- Headless `click` uses `AXPress`; headed `click` uses a verified-point `CGClick` first, then `AXPress` only if physical delivery was not attempted.
+- Headless `click` performs whichever activation the element publishes — `AXPress`, `AXOpen`, or `AXConfirm` — and falls back to writing the owning container's selection (`AXSelected`, `AXSelectedRows`, or `AXSelectedChildren`) for rows that publish no activation action. Only advertised actions are performed, because a responder can answer success to an action it never published. Headed `click` uses a verified-point `CGClick` first, then the same semantic chain if physical delivery was not attempted.
+- Return codes do not decide delivery. Finder answers `kAXErrorAttributeUnsupported` from an `AXOpen` that navigates and `kAXErrorSuccess` from an `AXConfirm` that does nothing, so a performed action is judged by observing the application.
- Headed `right-click` uses physical right-click first; headless uses the bounded `AXShowMenu` family.
- Headed `type`, `clear`, and `scroll` use PID-targeted keyboard, keyboard clear, and wheel delivery respectively; their headless paths use AX semantics.
- `expand` and `collapse` use a verified semantic disclosure mutation in both modes.
diff --git a/skills/agent-desktop/references/workflows.md b/skills/agent-desktop/references/workflows.md
index 8cc536f1b..8fd09f0e1 100644
--- a/skills/agent-desktop/references/workflows.md
+++ b/skills/agent-desktop/references/workflows.md
@@ -243,6 +243,8 @@ agent-desktop wait --element @e10 --snapshot <snapshot_id> --timeout 10000
```bash
# Full lifecycle
agent-desktop launch "Calculator"
+# Read data.window: present means the app already drew one. If it is absent and
+# you need a window, launch --activate or wait --event window-opened.
# Simple app → full snapshot is fine
agent-desktop snapshot --app "Calculator" -i
diff --git a/src/batch/baseline_tests.rs b/src/batch/baseline_tests.rs
index dfe6c528e..7e763fc41 100644
--- a/src/batch/baseline_tests.rs
+++ b/src/batch/baseline_tests.rs
@@ -21,6 +21,7 @@ impl agent_desktop_core::ObservationOps for AtomicEventAdapter {
pid: agent_desktop_core::ProcessId::new(42),
bundle_id: Some("com.example.fixture".into()),
process_instance: Some("fixture-42".into()),
+ presentation: None,
}])
}
}
diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rs
index b0a6dc2e5..b842481e8 100644
--- a/src/cli/contract_tests.rs
+++ b/src/cli/contract_tests.rs
@@ -16,6 +16,8 @@ const NON_COMMAND_MODULES: &[&str] = &[
"point_resolve",
"pointer_action",
"query",
+ "find_live_test_support",
+ "surface_scope",
"stale_retry_test_support",
"wait_element",
"wait_latest_ref_cache",
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index feb0a430c..b195a0bc1 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -94,7 +94,9 @@ pub(crate) enum Commands {
MouseUp(MousePointArgs),
#[command(about = "Scroll the mouse wheel at absolute coordinates (requires --headed)")]
MouseWheel(MouseWheelArgs),
- #[command(about = "Launch application and wait until its window is visible")]
+ #[command(
+ about = "Launch application and return once its process is running; --activate waits for a window"
+ )]
Launch(LaunchArgs),
#[command(about = "Quit an application gracefully (--force to terminate)")]
CloseApp(CloseAppArgs),
diff --git a/src/cli_args/mod.rs b/src/cli_args/mod.rs
index 3a9f419a0..16ce6a3e6 100644
--- a/src/cli_args/mod.rs
+++ b/src/cli_args/mod.rs
@@ -175,6 +175,25 @@ pub(crate) struct FindArgs {
#[command(flatten)]
#[serde(flatten)]
pub filter: FindFilterArgs,
+ #[arg(
+ long,
+ help = "Search only inside this ref's subtree, not the whole window"
+ )]
+ pub root: Option<String>,
+ #[arg(
+ long,
+ value_name = "SNAPSHOT_ID",
+ help = "Snapshot ID to use when resolving --root"
+ )]
+ pub snapshot: Option<String>,
+ #[arg(
+ long,
+ value_enum,
+ default_value_t = Surface::Window,
+ help = "Surface to search (menubar, menu, sheet ...) instead of the window"
+ )]
+ #[serde(default)]
+ pub surface: Surface,
#[arg(
long = "state",
value_name = "TOKEN[=BOOL]",
diff --git a/src/cli_args/mod_tests.rs b/src/cli_args/mod_tests.rs
index a0e589db5..97f3ff219 100644
--- a/src/cli_args/mod_tests.rs
+++ b/src/cli_args/mod_tests.rs
@@ -104,6 +104,16 @@ fn find_args_cli_flags_still_resolve_through_flattened_groups() {
assert!(args.selection.first);
}
+#[test]
+fn find_accepts_a_drill_down_root_and_leaves_it_unset_by_default() {
+ let scoped =
+ FindArgs::try_parse_from(["find", "--root", "@s1:e4", "--role", "button"]).unwrap();
+ assert_eq!(scoped.root.as_deref(), Some("@s1:e4"));
+
+ let unscoped = FindArgs::try_parse_from(["find", "--role", "button"]).unwrap();
+ assert!(unscoped.root.is_none());
+}
+
#[test]
fn find_args_selection_conflicts_still_enforced_across_the_flatten_boundary() {
let err = FindArgs::try_parse_from(["find", "--first", "--last"]).unwrap_err();
diff --git a/src/cli_args/system.rs b/src/cli_args/system.rs
index dd512b9ae..4d770b366 100644
--- a/src/cli_args/system.rs
+++ b/src/cli_args/system.rs
@@ -19,7 +19,7 @@ pub(crate) struct LaunchArgs {
#[arg(
long,
default_value = "30000",
- help = "Max time in ms to wait for the window to appear"
+ help = "Upper bound in ms for the whole launch"
)]
#[serde(default = "default_launch_timeout")]
pub timeout: u64,
@@ -44,6 +44,12 @@ pub(crate) struct LaunchArgs {
)]
#[serde(default)]
pub no_attach: bool,
+ #[arg(
+ long,
+ help = "Bring the app forward so it presents a window, and wait for one"
+ )]
+ #[serde(default)]
+ pub activate: bool,
}
#[derive(Parser, Debug, Deserialize)]
diff --git a/src/dispatch/app_window.rs b/src/dispatch/app_window.rs
index f52a48da9..736e9efd8 100644
--- a/src/dispatch/app_window.rs
+++ b/src/dispatch/app_window.rs
@@ -23,14 +23,8 @@ use crate::dispatch::parse::build_launch_options;
pub(super) fn launch(args: LaunchArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
launch_command::execute(
launch_command::LaunchArgs {
- app: args.app,
- options: build_launch_options(
- &args.args,
- &args.env,
- args.cwd,
- args.timeout,
- args.no_attach,
- )?,
+ app: args.app.clone(),
+ options: build_launch_options(&args)?,
},
adapter,
)
diff --git a/src/dispatch/observation.rs b/src/dispatch/observation.rs
index e02b40c20..d0d6e0950 100644
--- a/src/dispatch/observation.rs
+++ b/src/dispatch/observation.rs
@@ -48,6 +48,9 @@ pub(super) fn find(
find_command::FindArgs {
app: args.scope.app,
window_id: args.scope.window_id,
+ root: args.root,
+ snapshot: args.snapshot,
+ surface: args.surface.to_core(),
filter: find_command::FindFilterArgs {
role: args.filter.role,
name: args.filter.name,
diff --git a/src/dispatch/parse.rs b/src/dispatch/parse.rs
index 4042d27f3..b0ed5361e 100644
--- a/src/dispatch/parse.rs
+++ b/src/dispatch/parse.rs
@@ -126,12 +126,9 @@ pub(crate) fn parse_modifier(s: &str) -> Result<Modifier, AppError> {
}
pub(crate) fn build_launch_options(
- args: &[String],
- env: &[String],
- cwd: Option<std::path::PathBuf>,
- timeout_ms: u64,
- no_attach: bool,
+ launch: &crate::cli_args::system::LaunchArgs,
) -> Result<LaunchOptions, AppError> {
+ let (args, env) = (launch.args.as_slice(), launch.env.as_slice());
if let Some(index) = args.iter().position(|argument| argument.contains('\0')) {
return Err(AppError::invalid_input(format!(
"Invalid --arg entry #{index}: argument contains a NUL byte"
@@ -149,9 +146,10 @@ pub(crate) fn build_launch_options(
Ok(LaunchOptions {
args: args.to_vec(),
env: env_map,
- cwd,
- timeout_ms,
- attach_if_running: !no_attach,
+ cwd: launch.cwd.clone(),
+ timeout_ms: launch.timeout,
+ attach_if_running: !launch.no_attach,
+ activate: launch.activate,
})
}
diff --git a/src/dispatch/parse_tests.rs b/src/dispatch/parse_tests.rs
index 4ae90706f..3b668c13f 100644
--- a/src/dispatch/parse_tests.rs
+++ b/src/dispatch/parse_tests.rs
@@ -88,14 +88,26 @@ fn modifier_aliases_map_to_portable_meta() {
#[test]
fn launch_options_reject_ambiguous_or_nonportable_environment() {
- let duplicate = build_launch_options(&[], &["A=1".into(), "A=2".into()], None, 100, false)
+ let duplicate = build_launch_options(&launch_args(&[], &["A=1".into(), "A=2".into()]))
.expect_err("duplicate keys must not silently overwrite");
assert_eq!(duplicate.code(), "INVALID_ARGS");
for entry in ["9KEY=value", "BAD-KEY=value", "KEY=bad\0value"] {
assert_eq!(parse_env_pair(entry, 0).unwrap_err().code(), "INVALID_ARGS");
}
- let nul_arg = build_launch_options(&["bad\0arg".into()], &[], None, 100, false)
+ let nul_arg = build_launch_options(&launch_args(&["bad\0arg".into()], &[]))
.expect_err("NUL arguments must fail before platform spawn");
assert_eq!(nul_arg.code(), "INVALID_ARGS");
}
+
+fn launch_args(args: &[String], env: &[String]) -> crate::cli_args::system::LaunchArgs {
+ crate::cli_args::system::LaunchArgs {
+ app: "Fixture".into(),
+ timeout: 100,
+ args: args.to_vec(),
+ env: env.to_vec(),
+ cwd: None,
+ no_attach: false,
+ activate: false,
+ }
+}