Skip to content

Computer use CLI for AI agents

feat: add --wait-for selector polling flags (#86)

Lahfirce232787b502
diff --git a/crates/core/src/commands/find.rs b/crates/core/src/commands/find.rs
index 90ffe91eb..e4036b1f6 100644
--- a/crates/core/src/commands/find.rs
+++ b/crates/core/src/commands/find.rs
@@ -1,12 +1,14 @@
use crate::{
- adapter::PlatformAdapter, context::CommandContext, error::AppError, node::AccessibilityNode,
- roles, search_text, snapshot,
+ adapter::PlatformAdapter, commands::query, context::CommandContext, error::AppError,
+ node::AccessibilityNode, roles, search_text, snapshot,
};
use serde_json::{Value, json};
use std::collections::BTreeSet;
const DEFAULT_LIMIT: usize = 50;
+pub use query::FindQuery;
+
pub struct FindArgs {
pub app: Option<String>,
pub role: Option<String>,
@@ -149,14 +151,6 @@ fn validate_find_mode(args: &FindArgs) -> Result<(), AppError> {
Ok(())
}
-#[derive(Debug)]
-struct FindQuery {
- role: Option<String>,
- name: Option<String>,
- value: Option<String>,
- text: Option<String>,
-}
-
impl FindQuery {
fn from_args(args: &FindArgs) -> Self {
Self {
@@ -178,7 +172,7 @@ fn search_tree(
if max_matches.is_some_and(|limit| matches.len() >= limit) {
return true;
}
- if node_matches(node, query) {
+ if query::node_matches(node, query) {
let interactive = node.ref_id.is_some();
let display_name = node
.name
@@ -221,7 +215,7 @@ fn search_tree(
}
fn count_matches(node: &AccessibilityNode, query: &FindQuery) -> usize {
- usize::from(node_matches(node, query))
+ usize::from(query::node_matches(node, query))
+ node
.children
.iter()
@@ -229,25 +223,6 @@ fn count_matches(node: &AccessibilityNode, query: &FindQuery) -> usize {
.sum::<usize>()
}
-fn node_matches(node: &AccessibilityNode, query: &FindQuery) -> bool {
- let role_match = query.role.as_deref().is_none_or(|r| node.role == r);
- let name_match = query.name.as_deref().is_none_or(|n| {
- node.name
- .as_deref()
- .is_some_and(|text| search_text::contains(text, n))
- });
- let value_match = query.value.as_deref().is_none_or(|v| {
- node.value
- .as_deref()
- .is_some_and(|val| search_text::contains(val, v))
- });
- let text_match = query
- .text
- .as_deref()
- .is_none_or(|t| search_text::node_contains(node, t));
- role_match && name_match && value_match && text_match
-}
-
#[cfg(test)]
#[path = "find_tests.rs"]
mod tests;
diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs
index aba02ca47..45a7e5c15 100644
--- a/crates/core/src/commands/helpers.rs
+++ b/crates/core/src/commands/helpers.rs
@@ -2,7 +2,8 @@ use crate::{
action::WindowOp,
action_request::ActionRequest,
action_result::ActionResult,
- adapter::{PlatformAdapter, WindowFilter},
+ adapter::{PlatformAdapter, TreeOptions, WindowFilter},
+ commands::{wait_selector, wait_selector::WaitSelectorInput},
context::CommandContext,
error::AppError,
node::WindowInfo,
@@ -119,14 +120,65 @@ pub(crate) fn execute_ref_action_with_context(
request: ActionRequest,
context: &CommandContext,
) -> Result<Value, AppError> {
- let (_entry, result) = execute_ref_action_result_with_context(
+ let (entry, result) = execute_ref_action_result_with_context(
&args.ref_id,
args.snapshot_id.as_deref(),
adapter,
request,
context,
)?;
- Ok(serde_json::to_value(result)?)
+ apply_post_action_wait(serde_json::to_value(result)?, &entry, adapter, context)
+}
+
+/// Resolves the app name a ref belongs to for post-action polling. Normal
+/// refmaps always carry `source_app`; the pid lookup is a fallback for legacy
+/// or partially-populated entries so the wait never silently polls the focused
+/// window instead of the acted-on app.
+pub(crate) fn probe_app_name(adapter: &dyn PlatformAdapter, entry: &RefEntry) -> Option<String> {
+ if entry.source_app.is_some() {
+ return entry.source_app.clone();
+ }
+ window_lookup::find_window_for_pid(entry.pid, adapter)
+ .ok()
+ .map(|window| window.app)
+}
+
+pub(crate) fn apply_post_action_wait(
+ result: Value,
+ entry: &RefEntry,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+) -> Result<Value, AppError> {
+ let Some(wait) = context.wait_selector() else {
+ return Ok(result);
+ };
+ match wait_selector::execute(
+ WaitSelectorInput {
+ query_raw: wait.query_raw.clone(),
+ gone: wait.gone,
+ app: probe_app_name(adapter, entry),
+ window_id: entry.source_window_id.clone(),
+ opts: TreeOptions::default(),
+ timeout_ms: wait.timeout_ms,
+ },
+ adapter,
+ context,
+ ) {
+ Ok(mut snapshot) => {
+ if let Some(body) = snapshot.as_object_mut() {
+ body.insert("after_action".into(), result);
+ }
+ Ok(snapshot)
+ }
+ Err(AppError::Adapter(mut adapter_err)) => {
+ let mut details = adapter_err.details.take().unwrap_or_else(|| json!({}));
+ if let Some(obj) = details.as_object_mut() {
+ obj.insert("after_action".into(), result);
+ }
+ Err(AppError::Adapter(adapter_err.with_details(details)))
+ }
+ Err(err) => Err(err),
+ }
}
pub(crate) fn execute_ref_action_result_with_context(
diff --git a/crates/core/src/commands/helpers_ref_action_tests.rs b/crates/core/src/commands/helpers_ref_action_tests.rs
index bf8041140..31c3267dd 100644
--- a/crates/core/src/commands/helpers_ref_action_tests.rs
+++ b/crates/core/src/commands/helpers_ref_action_tests.rs
@@ -1,7 +1,9 @@
use super::test_support::{entry, text_entry};
use super::*;
-use crate::adapter::NativeHandle;
+use crate::adapter::{NativeHandle, WindowFilter};
+use crate::context::WaitSelector;
use crate::error::AdapterError;
+use crate::node::{AccessibilityNode, WindowInfo};
use crate::refs::RefMap;
use crate::refs_test_support::HomeGuard;
use crate::{
@@ -191,3 +193,262 @@ fn ref_action_trace_does_not_include_typed_text_payload() {
assert!(!trace.contains("super-secret"));
let _ = std::fs::remove_file(trace_path);
}
+
+struct ScopedWaitAdapter {
+ request: Mutex<Option<ActionRequest>>,
+ polled_app: Mutex<Option<String>>,
+}
+
+impl PlatformAdapter for ScopedWaitAdapter {
+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ request: ActionRequest,
+ ) -> Result<ActionResult, AdapterError> {
+ *self.request.lock().unwrap() = Some(request);
+ Ok(ActionResult::new("ok"))
+ }
+
+ fn list_windows(&self, filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
+ *self.polled_app.lock().unwrap() = filter.app.clone();
+ Ok(vec![WindowInfo {
+ id: "w-1".into(),
+ title: "Doc".into(),
+ app: filter.app.clone().unwrap_or_else(|| "TargetApp".into()),
+ pid: 1,
+ bounds: None,
+ is_focused: true,
+ }])
+ }
+
+ fn get_tree(
+ &self,
+ _win: &WindowInfo,
+ _opts: &crate::adapter::TreeOptions,
+ ) -> Result<AccessibilityNode, AdapterError> {
+ Ok(AccessibilityNode {
+ ref_id: None,
+ role: "window".into(),
+ name: Some("Saved!".into()),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children: vec![],
+ })
+ }
+}
+
+#[test]
+fn post_action_wait_scopes_to_source_app_and_merges_action_result() {
+ let _guard = HomeGuard::new();
+ let mut refmap = RefMap::new();
+ let mut entry = entry();
+ entry.source_app = Some("TargetApp".into());
+ refmap.allocate(entry);
+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
+ let adapter = ScopedWaitAdapter {
+ request: Mutex::new(None),
+ polled_app: Mutex::new(None),
+ };
+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: ":saved!".into(),
+ gone: false,
+ timeout_ms: 5_000,
+ }));
+ let args = RefArgs {
+ ref_id: "@e1".into(),
+ snapshot_id: Some(snapshot_id),
+ };
+
+ let value = execute_ref_action_with_context(
+ args,
+ &adapter,
+ ActionRequest::headless(Action::Click),
+ &context,
+ )
+ .unwrap();
+
+ assert_eq!(
+ adapter.polled_app.lock().unwrap().as_deref(),
+ Some("TargetApp")
+ );
+ assert_eq!(value["after_action"]["action"], "ok");
+ assert_eq!(value["matched_selector"], ":saved!");
+}
+
+struct MultiWindowAdapter;
+
+impl PlatformAdapter for MultiWindowAdapter {
+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ _request: ActionRequest,
+ ) -> Result<ActionResult, AdapterError> {
+ Ok(ActionResult::new("ok"))
+ }
+
+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
+ Ok(vec![
+ WindowInfo {
+ id: "w-other".into(),
+ title: "Other".into(),
+ app: "App".into(),
+ pid: 1,
+ bounds: None,
+ is_focused: true,
+ },
+ WindowInfo {
+ id: "w-target".into(),
+ title: "Target".into(),
+ app: "App".into(),
+ pid: 1,
+ bounds: None,
+ is_focused: false,
+ },
+ ])
+ }
+
+ fn get_tree(
+ &self,
+ win: &WindowInfo,
+ _opts: &crate::adapter::TreeOptions,
+ ) -> Result<AccessibilityNode, AdapterError> {
+ let children = if win.id == "w-target" {
+ vec![AccessibilityNode {
+ ref_id: None,
+ role: "button".into(),
+ name: Some("Saved!".into()),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children: vec![],
+ }]
+ } else {
+ vec![]
+ };
+ Ok(AccessibilityNode {
+ ref_id: None,
+ role: "window".into(),
+ name: Some(win.title.clone()),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children,
+ })
+ }
+}
+
+#[test]
+fn post_action_wait_polls_acted_on_window_not_focused_window() {
+ let _guard = HomeGuard::new();
+ let mut refmap = RefMap::new();
+ let mut entry = entry();
+ entry.source_app = Some("App".into());
+ entry.source_window_id = Some("w-target".into());
+ refmap.allocate(entry);
+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: ":saved!".into(),
+ gone: false,
+ timeout_ms: 500,
+ }));
+ let args = RefArgs {
+ ref_id: "@e1".into(),
+ snapshot_id: Some(snapshot_id),
+ };
+
+ let value = execute_ref_action_with_context(
+ args,
+ &MultiWindowAdapter,
+ ActionRequest::headless(Action::Click),
+ &context,
+ )
+ .expect("wait must match in the acted-on window, not the focused empty window");
+ assert_eq!(value["matched_selector"], ":saved!");
+ assert_eq!(value["window"]["id"], "w-target");
+}
+
+#[test]
+fn post_action_wait_without_flag_returns_action_only() {
+ let _guard = HomeGuard::new();
+ let mut refmap = RefMap::new();
+ refmap.allocate(entry());
+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
+ let adapter = RecordingAdapter {
+ request: Mutex::new(None),
+ };
+ let args = RefArgs {
+ ref_id: "@e1".into(),
+ snapshot_id: Some(snapshot_id),
+ };
+
+ let value = execute_ref_action_with_context(
+ args,
+ &adapter,
+ ActionRequest::headless(Action::Click),
+ &CommandContext::default(),
+ )
+ .unwrap();
+
+ assert_eq!(value["action"], "ok");
+ assert!(value.get("after_action").is_none());
+}
+
+#[test]
+fn post_action_wait_timeout_embeds_action_result_in_details() {
+ let _guard = HomeGuard::new();
+ let mut refmap = RefMap::new();
+ let mut entry = entry();
+ entry.source_app = Some("TargetApp".into());
+ refmap.allocate(entry);
+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
+ let adapter = ScopedWaitAdapter {
+ request: Mutex::new(None),
+ polled_app: Mutex::new(None),
+ };
+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: ":never-appears".into(),
+ gone: false,
+ timeout_ms: 50,
+ }));
+ let args = RefArgs {
+ ref_id: "@e1".into(),
+ snapshot_id: Some(snapshot_id),
+ };
+
+ let err = execute_ref_action_with_context(
+ args,
+ &adapter,
+ ActionRequest::headless(Action::Click),
+ &context,
+ )
+ .unwrap_err();
+
+ assert_eq!(err.code(), "TIMEOUT");
+ let details = match err {
+ crate::error::AppError::Adapter(adapter_err) => adapter_err.details.expect("details"),
+ other => panic!("expected adapter timeout, got {other:?}"),
+ };
+ assert_eq!(details["kind"], "wait_timeout");
+ assert_eq!(details["after_action"]["action"], "ok");
+}
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index 55fe992b0..bff3080e9 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -39,6 +39,7 @@ pub mod notification_action;
pub mod permissions;
pub(crate) mod point_resolve;
pub mod press;
+pub mod query;
pub mod resize_window;
pub mod restore;
pub mod right_click;
@@ -60,6 +61,7 @@ pub(crate) mod wait_element;
pub(crate) mod wait_latest_ref_cache;
pub(crate) mod wait_mode;
pub(crate) mod wait_predicate;
+pub mod wait_selector;
pub(crate) mod wait_text_match;
pub(crate) mod wait_timeout;
diff --git a/crates/core/src/commands/query.rs b/crates/core/src/commands/query.rs
new file mode 100644
index 000000000..af1d29df2
--- /dev/null
+++ b/crates/core/src/commands/query.rs
@@ -0,0 +1,79 @@
+use crate::{error::AppError, node::AccessibilityNode, roles, search_text};
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FindQuery {
+ pub role: Option<String>,
+ pub name: Option<String>,
+ pub value: Option<String>,
+ pub text: Option<String>,
+}
+
+impl FindQuery {
+ pub fn is_match_everything(&self) -> bool {
+ self.role.is_none() && self.name.is_none() && self.value.is_none() && self.text.is_none()
+ }
+}
+
+pub fn validate_selector(raw: &str) -> Result<FindQuery, AppError> {
+ let query = parse_selector(raw);
+ if query.is_match_everything() {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Selector must constrain at least role or text",
+ "Use forms like \"button:Submit\", \"button\", or \":Saved!\".",
+ ));
+ }
+ Ok(query)
+}
+
+pub fn parse_selector(raw: &str) -> FindQuery {
+ let (role_part, text_part) = match raw.split_once(':') {
+ Some((left, right)) => (Some(left.trim()), Some(right.trim())),
+ None => (Some(raw.trim()), None),
+ };
+
+ let role = role_part
+ .filter(|part| !part.is_empty())
+ .map(roles::normalize_role_query);
+ let text = text_part
+ .filter(|part| !part.is_empty())
+ .map(search_text::normalize);
+
+ FindQuery {
+ role,
+ name: None,
+ value: None,
+ text,
+ }
+}
+
+pub fn node_matches(node: &AccessibilityNode, query: &FindQuery) -> bool {
+ let role_match = query.role.as_deref().is_none_or(|r| node.role == r);
+ let name_match = query.name.as_deref().is_none_or(|n| {
+ node.name
+ .as_deref()
+ .is_some_and(|text| search_text::contains(text, n))
+ });
+ let value_match = query.value.as_deref().is_none_or(|v| {
+ node.value
+ .as_deref()
+ .is_some_and(|val| search_text::contains(val, v))
+ });
+ let text_match = query
+ .text
+ .as_deref()
+ .is_none_or(|t| search_text::node_contains(node, t));
+ role_match && name_match && value_match && text_match
+}
+
+pub fn tree_has_match(tree: &AccessibilityNode, query: &FindQuery) -> bool {
+ if node_matches(tree, query) {
+ return true;
+ }
+ tree.children
+ .iter()
+ .any(|child| tree_has_match(child, query))
+}
+
+#[cfg(test)]
+#[path = "query_tests.rs"]
+mod tests;
diff --git a/crates/core/src/commands/query_tests.rs b/crates/core/src/commands/query_tests.rs
new file mode 100644
index 000000000..075ded46f
--- /dev/null
+++ b/crates/core/src/commands/query_tests.rs
@@ -0,0 +1,96 @@
+use super::*;
+use crate::{node::AccessibilityNode, search_text};
+
+fn node(role: &str, name: Option<&str>, value: Option<&str>) -> AccessibilityNode {
+ AccessibilityNode {
+ ref_id: None,
+ role: role.into(),
+ name: name.map(String::from),
+ value: value.map(String::from),
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children: vec![],
+ }
+}
+
+#[test]
+fn parse_selector_role_and_text() {
+ let query = parse_selector("button:Submit");
+ assert_eq!(query.role.as_deref(), Some("button"));
+ assert_eq!(query.text.as_deref(), Some("submit"));
+}
+
+#[test]
+fn parse_selector_role_only() {
+ let query = parse_selector("button");
+ assert_eq!(query.role.as_deref(), Some("button"));
+ assert!(query.text.is_none());
+}
+
+#[test]
+fn parse_selector_text_only() {
+ let query = parse_selector(":Saved!");
+ assert!(query.role.is_none());
+ assert_eq!(query.text.as_deref(), Some("saved!"));
+}
+
+#[test]
+fn parse_selector_match_everything_variants() {
+ for raw in ["", ":", " : "] {
+ let query = parse_selector(raw);
+ assert!(
+ query.is_match_everything(),
+ "expected match-everything for {raw:?}"
+ );
+ }
+}
+
+#[test]
+fn parse_selector_empty_text_side_becomes_none() {
+ let query = parse_selector("button:");
+ assert_eq!(query.role.as_deref(), Some("button"));
+ assert!(query.text.is_none());
+}
+
+#[test]
+fn parse_selector_trims_whitespace() {
+ let query = parse_selector(" button : Submit ");
+ assert_eq!(query.role.as_deref(), Some("button"));
+ assert_eq!(query.text.as_deref(), Some("submit"));
+}
+
+#[test]
+fn parse_selector_splits_on_first_colon_only() {
+ let query = parse_selector("textfield:a:b");
+ assert_eq!(query.role.as_deref(), Some("textfield"));
+ assert_eq!(query.text.as_deref(), Some("a:b"));
+}
+
+#[test]
+fn find_query_without_text_never_calls_contains_with_empty_needle() {
+ let root = node("button", Some("Save"), None);
+ let query = FindQuery {
+ role: Some("button".into()),
+ name: None,
+ value: None,
+ text: None,
+ };
+ assert!(tree_has_match(&root, &query));
+}
+
+#[test]
+fn tree_has_match_finds_nested_node() {
+ let mut root = node("window", None, None);
+ root.children.push(node("button", Some("Submit"), None));
+ let query = FindQuery {
+ role: Some("button".into()),
+ name: None,
+ value: None,
+ text: Some(search_text::normalize("submit")),
+ };
+ assert!(tree_has_match(&root, &query));
+}
diff --git a/crates/core/src/commands/right_click.rs b/crates/core/src/commands/right_click.rs
index d58f6108f..fee94093e 100644
--- a/crates/core/src/commands/right_click.rs
+++ b/crates/core/src/commands/right_click.rs
@@ -1,10 +1,11 @@
use crate::{
action::Action,
adapter::{PlatformAdapter, SnapshotSurface, TreeOptions},
- commands::helpers::{RefArgs, execute_ref_action_result_with_context},
+ commands::helpers::{
+ RefArgs, apply_post_action_wait, execute_ref_action_result_with_context, probe_app_name,
+ },
context::CommandContext,
error::AppError,
- refs::RefEntry,
snapshot,
};
use serde_json::{Value, json};
@@ -53,16 +54,7 @@ pub fn execute(
Err(err) => response["menu_probe"] = probe_error_json(&err),
}
- Ok(response)
-}
-
-fn probe_app_name(adapter: &dyn PlatformAdapter, entry: &RefEntry) -> Option<String> {
- if entry.source_app.is_some() {
- return entry.source_app.clone();
- }
- crate::window_lookup::find_window_for_pid(entry.pid, adapter)
- .ok()
- .map(|window| window.app)
+ apply_post_action_wait(response, &entry, adapter, context)
}
fn probe_error_json(err: &AppError) -> Value {
diff --git a/crates/core/src/commands/scroll.rs b/crates/core/src/commands/scroll.rs
index a30d45fe4..33b6c5b40 100644
--- a/crates/core/src/commands/scroll.rs
+++ b/crates/core/src/commands/scroll.rs
@@ -1,7 +1,7 @@
use crate::{
action::{Action, Direction},
adapter::PlatformAdapter,
- commands::helpers::execute_ref_action_result_with_context,
+ commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
};
@@ -20,12 +20,13 @@ pub fn execute(
context: &CommandContext,
) -> Result<Value, AppError> {
let request = context.request_base(Action::Scroll(args.direction, args.amount));
- let (_entry, result) = execute_ref_action_result_with_context(
- &args.ref_id,
- args.snapshot_id.as_deref(),
+ execute_ref_action_with_context(
+ RefArgs {
+ ref_id: args.ref_id,
+ snapshot_id: args.snapshot_id,
+ },
adapter,
request,
context,
- )?;
- Ok(serde_json::to_value(result)?)
+ )
}
diff --git a/crates/core/src/commands/select.rs b/crates/core/src/commands/select.rs
index eeeb53b3a..75f22d81e 100644
--- a/crates/core/src/commands/select.rs
+++ b/crates/core/src/commands/select.rs
@@ -1,6 +1,8 @@
use crate::{
- action::Action, adapter::PlatformAdapter,
- commands::helpers::execute_ref_action_result_with_context, context::CommandContext,
+ action::Action,
+ adapter::PlatformAdapter,
+ commands::helpers::{RefArgs, execute_ref_action_with_context},
+ context::CommandContext,
error::AppError,
};
use serde_json::Value;
@@ -17,12 +19,13 @@ pub fn execute(
context: &CommandContext,
) -> Result<Value, AppError> {
let request = context.request_base(Action::Select(args.value));
- let (_entry, result) = execute_ref_action_result_with_context(
- &args.ref_id,
- args.snapshot_id.as_deref(),
+ execute_ref_action_with_context(
+ RefArgs {
+ ref_id: args.ref_id,
+ snapshot_id: args.snapshot_id,
+ },
adapter,
request,
context,
- )?;
- Ok(serde_json::to_value(result)?)
+ )
}
diff --git a/crates/core/src/commands/set_value.rs b/crates/core/src/commands/set_value.rs
index 6fef056c8..4ab94a365 100644
--- a/crates/core/src/commands/set_value.rs
+++ b/crates/core/src/commands/set_value.rs
@@ -1,6 +1,8 @@
use crate::{
- action::Action, adapter::PlatformAdapter,
- commands::helpers::execute_ref_action_result_with_context, context::CommandContext,
+ action::Action,
+ adapter::PlatformAdapter,
+ commands::helpers::{RefArgs, execute_ref_action_with_context},
+ context::CommandContext,
error::AppError,
};
use serde_json::Value;
@@ -17,12 +19,13 @@ pub fn execute(
context: &CommandContext,
) -> Result<Value, AppError> {
let request = context.request_base(Action::SetValue(args.value));
- let (_entry, result) = execute_ref_action_result_with_context(
- &args.ref_id,
- args.snapshot_id.as_deref(),
+ execute_ref_action_with_context(
+ RefArgs {
+ ref_id: args.ref_id,
+ snapshot_id: args.snapshot_id,
+ },
adapter,
request,
context,
- )?;
- Ok(serde_json::to_value(result)?)
+ )
}
diff --git a/crates/core/src/commands/snapshot.rs b/crates/core/src/commands/snapshot.rs
index ffb0b30e3..d6b021e3f 100644
--- a/crates/core/src/commands/snapshot.rs
+++ b/crates/core/src/commands/snapshot.rs
@@ -1,5 +1,6 @@
use crate::{
adapter::{PlatformAdapter, SnapshotSurface},
+ commands::{wait_selector, wait_selector::WaitSelectorInput},
context::CommandContext,
error::AppError,
refs::validate_ref_id,
@@ -54,22 +55,43 @@ pub fn execute(
let opts = tree_options(&args);
- if let Some(ref root) = args.root_ref {
+ if let Some(root) = args.root_ref {
+ if context.wait_selector().is_some() {
+ return Err(AppError::invalid_input_with_suggestion(
+ "--root cannot be combined with --wait-for or --wait-for-gone",
+ "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",
));
}
- validate_ref_id(root)?;
+ validate_ref_id(&root)?;
return format_result(snapshot_ref::run_from_ref_with_context(
adapter,
&opts,
- root,
+ &root,
args.snapshot_id.as_deref(),
context,
)?);
}
+ if let Some(wait) = context.wait_selector() {
+ return wait_selector::execute(
+ WaitSelectorInput {
+ query_raw: wait.query_raw.clone(),
+ gone: wait.gone,
+ app: args.app.clone(),
+ window_id: args.window_id.clone(),
+ opts,
+ timeout_ms: wait.timeout_ms,
+ },
+ adapter,
+ context,
+ );
+ }
+
let result = snapshot::run_with_context(
adapter,
&opts,
@@ -82,6 +104,14 @@ pub fn execute(
}
fn format_result(result: snapshot::SnapshotResult) -> Result<Value, AppError> {
+ format_snapshot_fields(&result, None, None)
+}
+
+pub(crate) fn format_snapshot_fields(
+ result: &snapshot::SnapshotResult,
+ elapsed_ms: Option<u128>,
+ matched_selector: Option<&str>,
+) -> Result<Value, AppError> {
let ref_count = result.refmap.len();
let tree = serde_json::to_value(&result.tree)?;
let win = &result.window;
@@ -93,7 +123,7 @@ fn format_result(result: snapshot::SnapshotResult) -> Result<Value, AppError> {
ref_count
);
- Ok(json!({
+ let mut body = json!({
"app": win.app,
"window": {
"id": win.id,
@@ -102,7 +132,14 @@ fn format_result(result: snapshot::SnapshotResult) -> Result<Value, AppError> {
"ref_count": ref_count,
"snapshot_id": result.snapshot_id,
"tree": tree
- }))
+ });
+ if let Some(ms) = elapsed_ms {
+ body["elapsed_ms"] = json!(ms);
+ }
+ if let Some(selector) = matched_selector {
+ body["matched_selector"] = json!(selector);
+ }
+ Ok(body)
}
#[cfg(test)]
diff --git a/crates/core/src/commands/snapshot_tests.rs b/crates/core/src/commands/snapshot_tests.rs
index 24972e79c..7c9df0d87 100644
--- a/crates/core/src/commands/snapshot_tests.rs
+++ b/crates/core/src/commands/snapshot_tests.rs
@@ -1,9 +1,60 @@
use super::*;
-use crate::error::ErrorCode;
+use crate::adapter::{PlatformAdapter, WindowFilter};
+use crate::context::{CommandContext, WaitSelector};
+use crate::error::{AdapterError, ErrorCode};
+use crate::node::{AccessibilityNode, WindowInfo};
+use crate::refs_test_support::HomeGuard;
struct NoopAdapter;
impl PlatformAdapter for NoopAdapter {}
+struct WaitSnapshotAdapter;
+
+impl PlatformAdapter for WaitSnapshotAdapter {
+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
+ Ok(vec![WindowInfo {
+ id: "w-1".into(),
+ title: "Doc".into(),
+ app: "FixtureApp".into(),
+ pid: 1,
+ bounds: None,
+ is_focused: true,
+ }])
+ }
+
+ fn get_tree(
+ &self,
+ _win: &WindowInfo,
+ _opts: &crate::adapter::TreeOptions,
+ ) -> Result<AccessibilityNode, AdapterError> {
+ Ok(AccessibilityNode {
+ ref_id: None,
+ role: "window".into(),
+ name: Some("Doc".into()),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children: vec![AccessibilityNode {
+ ref_id: None,
+ role: "button".into(),
+ name: Some("Submit".into()),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children: vec![],
+ }],
+ })
+ }
+}
+
fn base_args() -> SnapshotArgs {
SnapshotArgs {
app: None,
@@ -131,3 +182,36 @@ fn test_valid_root_ref_format_does_not_trigger_invalid_args() {
);
}
}
+
+#[test]
+fn wait_for_selector_returns_matched_snapshot() {
+ let _guard = HomeGuard::new();
+ let mut args = base_args();
+ args.app = Some("FixtureApp".into());
+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: "button:Submit".into(),
+ gone: false,
+ timeout_ms: 5_000,
+ }));
+ let value = execute(args, &WaitSnapshotAdapter, &context).unwrap();
+ assert_eq!(value["matched_selector"], "button:Submit");
+ assert!(value["snapshot_id"].as_str().is_some());
+}
+
+#[test]
+fn root_and_wait_for_are_mutually_exclusive() {
+ let mut args = base_args();
+ args.root_ref = Some("@e1".into());
+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: "button:Submit".into(),
+ gone: false,
+ timeout_ms: 5_000,
+ }));
+ let err = execute(args, &NoopAdapter, &context).expect_err("root + wait must fail");
+ match err {
+ AppError::Adapter(adapter_err) => {
+ assert_eq!(adapter_err.code, ErrorCode::InvalidArgs);
+ }
+ other => panic!("expected InvalidArgs, got {other:?}"),
+ }
+}
diff --git a/crates/core/src/commands/type_text.rs b/crates/core/src/commands/type_text.rs
index 192f58d70..51a9484cf 100644
--- a/crates/core/src/commands/type_text.rs
+++ b/crates/core/src/commands/type_text.rs
@@ -1,6 +1,8 @@
use crate::{
- action::Action, adapter::PlatformAdapter,
- commands::helpers::execute_ref_action_result_with_context, context::CommandContext,
+ action::Action,
+ adapter::PlatformAdapter,
+ commands::helpers::{RefArgs, execute_ref_action_with_context},
+ context::CommandContext,
error::AppError,
};
use serde_json::Value;
@@ -25,12 +27,13 @@ pub fn execute(
}
let request = context.request_base(Action::TypeText(args.text));
- let (_entry, result) = execute_ref_action_result_with_context(
- &args.ref_id,
- args.snapshot_id.as_deref(),
+ execute_ref_action_with_context(
+ RefArgs {
+ ref_id: args.ref_id,
+ snapshot_id: args.snapshot_id,
+ },
adapter,
request,
context,
- )?;
- Ok(serde_json::to_value(result)?)
+ )
}
diff --git a/crates/core/src/commands/wait_selector.rs b/crates/core/src/commands/wait_selector.rs
new file mode 100644
index 000000000..85f0da0dd
--- /dev/null
+++ b/crates/core/src/commands/wait_selector.rs
@@ -0,0 +1,132 @@
+use crate::{
+ adapter::{PlatformAdapter, TreeOptions},
+ commands::{query, snapshot as snapshot_cmd, wait_timeout},
+ context::CommandContext,
+ error::{AppError, ErrorCode},
+ refs_store::RefStore,
+ snapshot,
+};
+use serde_json::{Value, json};
+use std::time::{Duration, Instant};
+
+pub struct WaitSelectorInput {
+ pub query_raw: String,
+ pub gone: bool,
+ pub app: Option<String>,
+ pub window_id: Option<String>,
+ pub opts: TreeOptions,
+ pub timeout_ms: u64,
+}
+
+pub fn execute(
+ input: WaitSelectorInput,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+) -> Result<Value, AppError> {
+ let query = query::validate_selector(&input.query_raw)?;
+
+ let start = Instant::now();
+ let timeout = Duration::from_millis(input.timeout_ms);
+ let mut interval = Duration::from_millis(200);
+ let mut last_error = None;
+ let mut last_built = None;
+
+ loop {
+ match snapshot::build(
+ adapter,
+ &input.opts,
+ input.app.as_deref(),
+ input.window_id.as_deref(),
+ ) {
+ Ok(mut result) => {
+ let present = query::tree_has_match(&result.tree, &query);
+ let matched = if input.gone { !present } else { present };
+ if matched {
+ let snapshot_id = RefStore::for_session(context.session_id())?
+ .save_new_snapshot(&result.refmap)?;
+ result.snapshot_id = Some(snapshot_id);
+ let elapsed = start.elapsed().as_millis();
+ return snapshot_cmd::format_snapshot_fields(
+ &result,
+ Some(elapsed),
+ Some(&input.query_raw),
+ );
+ }
+ last_built = Some(result);
+ }
+ Err(err) if is_target_gone_error(&err) => {
+ if input.gone {
+ return Ok(target_absent_response(
+ &input.query_raw,
+ start.elapsed().as_millis(),
+ ));
+ }
+ last_error = Some(poll_error_json(&err));
+ }
+ Err(err) if is_transient_poll_error(&err) => {
+ last_error = Some(poll_error_json(&err));
+ }
+ Err(err) => return Err(err),
+ }
+
+ let remaining = timeout.saturating_sub(start.elapsed());
+ if remaining.is_zero() {
+ let last_snapshot_id = persist_last_built(context, last_built.as_ref())?;
+ return wait_timeout::selector(
+ &input.query_raw,
+ input.gone,
+ input.timeout_ms,
+ last_error,
+ last_snapshot_id,
+ );
+ }
+
+ std::thread::sleep(remaining.min(interval));
+ interval = (interval * 2).min(Duration::from_millis(1000));
+ }
+}
+
+fn target_absent_response(query_raw: &str, elapsed_ms: u128) -> Value {
+ json!({
+ "matched_selector": query_raw,
+ "gone": true,
+ "target_absent": true,
+ "elapsed_ms": elapsed_ms,
+ })
+}
+
+fn poll_error_json(err: &AppError) -> Value {
+ json!({ "code": err.code(), "message": err.to_string() })
+}
+
+fn persist_last_built(
+ context: &CommandContext,
+ last_built: Option<&snapshot::SnapshotResult>,
+) -> Result<Option<String>, AppError> {
+ let Some(result) = last_built else {
+ return Ok(None);
+ };
+ let snapshot_id =
+ RefStore::for_session(context.session_id())?.save_new_snapshot(&result.refmap)?;
+ Ok(Some(snapshot_id))
+}
+
+fn is_target_gone_error(err: &AppError) -> bool {
+ matches!(
+ err,
+ AppError::Adapter(e)
+ if matches!(e.code, ErrorCode::AppNotFound | ErrorCode::WindowNotFound)
+ )
+}
+
+fn is_transient_poll_error(err: &AppError) -> bool {
+ matches!(
+ err,
+ AppError::Adapter(e)
+ if matches!(e.code, ErrorCode::Timeout | ErrorCode::ElementNotFound)
+ )
+}
+
+#[cfg(test)]
+#[path = "wait_selector_tests.rs"]
+mod tests;
diff --git a/crates/core/src/commands/wait_selector_tests.rs b/crates/core/src/commands/wait_selector_tests.rs
new file mode 100644
index 000000000..78ac5e0d6
--- /dev/null
+++ b/crates/core/src/commands/wait_selector_tests.rs
@@ -0,0 +1,353 @@
+use super::*;
+use crate::{
+ adapter::{PlatformAdapter, WindowFilter},
+ context::CommandContext,
+ error::{AdapterError, ErrorCode},
+ node::{AccessibilityNode, WindowInfo},
+ refs_store::RefStore,
+ refs_test_support::HomeGuard,
+};
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+fn window_node(children: Vec<AccessibilityNode>) -> AccessibilityNode {
+ AccessibilityNode {
+ ref_id: None,
+ role: "window".into(),
+ name: Some("Doc".into()),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children,
+ }
+}
+
+fn button_node(label: &str) -> AccessibilityNode {
+ AccessibilityNode {
+ ref_id: None,
+ role: "button".into(),
+ name: Some(label.into()),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ available_actions: vec![],
+ bounds: None,
+ children_count: None,
+ children: vec![],
+ }
+}
+
+struct StaticTreeAdapter {
+ tree: AccessibilityNode,
+}
+
+impl PlatformAdapter for StaticTreeAdapter {
+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
+ Ok(vec![WindowInfo {
+ id: "w-1".into(),
+ title: "Doc".into(),
+ app: "TestApp".into(),
+ pid: 1,
+ bounds: None,
+ is_focused: true,
+ }])
+ }
+
+ fn get_tree(
+ &self,
+ _win: &WindowInfo,
+ _opts: &crate::adapter::TreeOptions,
+ ) -> Result<AccessibilityNode, AdapterError> {
+ Ok(self.tree.clone())
+ }
+}
+
+struct FlippingTreeAdapter {
+ calls: AtomicUsize,
+ before: AccessibilityNode,
+ after: AccessibilityNode,
+}
+
+impl PlatformAdapter for FlippingTreeAdapter {
+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
+ Ok(vec![WindowInfo {
+ id: "w-1".into(),
+ title: "Doc".into(),
+ app: "TestApp".into(),
+ pid: 1,
+ bounds: None,
+ is_focused: true,
+ }])
+ }
+
+ fn get_tree(
+ &self,
+ _win: &WindowInfo,
+ _opts: &crate::adapter::TreeOptions,
+ ) -> Result<AccessibilityNode, AdapterError> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst);
+ if call == 0 {
+ Ok(self.before.clone())
+ } else {
+ Ok(self.after.clone())
+ }
+ }
+}
+
+struct ErrorThenTreeAdapter;
+
+impl PlatformAdapter for ErrorThenTreeAdapter {
+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
+ Err(AdapterError::new(ErrorCode::AppNotFound, "app missing"))
+ }
+}
+
+struct CodeErrorAdapter {
+ code: ErrorCode,
+}
+
+impl PlatformAdapter for CodeErrorAdapter {
+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
+ Err(AdapterError::new(self.code.clone(), "poll error"))
+ }
+}
+
+fn base_input(query_raw: &str, gone: bool) -> WaitSelectorInput {
+ WaitSelectorInput {
+ query_raw: query_raw.into(),
+ gone,
+ app: Some("TestApp".into()),
+ window_id: None,
+ opts: crate::adapter::TreeOptions::default(),
+ timeout_ms: 500,
+ }
+}
+
+#[test]
+fn match_everything_selector_rejected() {
+ let _guard = HomeGuard::new();
+ let err = execute(
+ WaitSelectorInput {
+ query_raw: String::new(),
+ gone: false,
+ app: None,
+ window_id: None,
+ opts: crate::adapter::TreeOptions::default(),
+ timeout_ms: 500,
+ },
+ &StaticTreeAdapter {
+ tree: window_node(vec![]),
+ },
+ &CommandContext::default(),
+ )
+ .unwrap_err();
+ assert_eq!(err.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn present_on_first_poll_returns_snapshot_envelope() {
+ let _guard = HomeGuard::new();
+ let adapter = StaticTreeAdapter {
+ tree: window_node(vec![button_node("saved")]),
+ };
+ let value = execute(
+ base_input("button:saved", false),
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ assert_eq!(value["matched_selector"], "button:saved");
+ assert!(value["elapsed_ms"].as_u64().is_some());
+ assert!(value["snapshot_id"].as_str().is_some());
+ assert_eq!(value["ref_count"].as_u64(), Some(1));
+}
+
+#[test]
+fn absent_then_present_on_second_poll() {
+ let _guard = HomeGuard::new();
+ let adapter = FlippingTreeAdapter {
+ calls: AtomicUsize::new(0),
+ before: window_node(vec![]),
+ after: window_node(vec![button_node("saved")]),
+ };
+ let value = execute(
+ base_input("button:saved", false),
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ assert_eq!(value["matched_selector"], "button:saved");
+ assert!(adapter.calls.load(Ordering::SeqCst) >= 2);
+}
+
+#[test]
+fn gone_true_returns_when_element_disappears() {
+ let _guard = HomeGuard::new();
+ let adapter = FlippingTreeAdapter {
+ calls: AtomicUsize::new(0),
+ before: window_node(vec![button_node("spinner")]),
+ after: window_node(vec![]),
+ };
+ let value = execute(
+ base_input("button:spinner", true),
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ assert_eq!(value["matched_selector"], "button:spinner");
+ assert!(adapter.calls.load(Ordering::SeqCst) >= 2);
+}
+
+#[test]
+fn gone_true_when_never_present_returns_immediately() {
+ let _guard = HomeGuard::new();
+ let adapter = StaticTreeAdapter {
+ tree: window_node(vec![]),
+ };
+ let value = execute(
+ base_input(":missing", true),
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ assert_eq!(value["matched_selector"], ":missing");
+}
+
+#[test]
+fn timeout_includes_last_snapshot_id() {
+ let _guard = HomeGuard::new();
+ let adapter = StaticTreeAdapter {
+ tree: window_node(vec![button_node("other")]),
+ };
+ let err = execute(
+ WaitSelectorInput {
+ timeout_ms: 50,
+ ..base_input(":missing", false)
+ },
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap_err();
+ assert_eq!(err.code(), "TIMEOUT");
+ let details = match err {
+ AppError::Adapter(adapter_err) => adapter_err.details.expect("timeout details"),
+ other => panic!("expected adapter timeout, got {other:?}"),
+ };
+ assert_eq!(details["kind"], "wait_timeout");
+ assert_eq!(details["predicate"], "selector");
+ assert!(details["snapshot_id"].as_str().is_some());
+ assert!(
+ details.get("last_error").is_none(),
+ "last_error must be omitted when no poll error occurred, got {details}"
+ );
+}
+
+#[test]
+fn retryable_app_not_found_swallowed_until_timeout() {
+ let _guard = HomeGuard::new();
+ let err = execute(
+ WaitSelectorInput {
+ timeout_ms: 50,
+ ..base_input("button:saved", false)
+ },
+ &ErrorThenTreeAdapter,
+ &CommandContext::default(),
+ )
+ .unwrap_err();
+ assert_eq!(err.code(), "TIMEOUT");
+ let details = match err {
+ AppError::Adapter(adapter_err) => adapter_err.details.expect("timeout details"),
+ other => panic!("expected adapter timeout, got {other:?}"),
+ };
+ assert_eq!(details["last_error"]["code"], "APP_NOT_FOUND");
+}
+
+#[test]
+fn gone_true_with_app_not_found_returns_immediately() {
+ let _guard = HomeGuard::new();
+ let value = execute(
+ WaitSelectorInput {
+ timeout_ms: 30_000,
+ ..base_input("button:spinner", true)
+ },
+ &ErrorThenTreeAdapter,
+ &CommandContext::default(),
+ )
+ .expect("app gone satisfies a wait-for-gone");
+ assert_eq!(value["gone"], true);
+ assert_eq!(value["target_absent"], true);
+ assert_eq!(value["matched_selector"], "button:spinner");
+}
+
+#[test]
+fn gone_true_with_window_not_found_returns_immediately() {
+ let _guard = HomeGuard::new();
+ let value = execute(
+ WaitSelectorInput {
+ timeout_ms: 30_000,
+ ..base_input("button:spinner", true)
+ },
+ &CodeErrorAdapter {
+ code: ErrorCode::WindowNotFound,
+ },
+ &CommandContext::default(),
+ )
+ .expect("window gone satisfies a wait-for-gone");
+ assert_eq!(value["target_absent"], true);
+}
+
+#[test]
+fn appearance_window_not_found_swallowed_until_timeout() {
+ let _guard = HomeGuard::new();
+ let err = execute(
+ WaitSelectorInput {
+ timeout_ms: 50,
+ ..base_input("button:saved", false)
+ },
+ &CodeErrorAdapter {
+ code: ErrorCode::WindowNotFound,
+ },
+ &CommandContext::default(),
+ )
+ .unwrap_err();
+ assert_eq!(err.code(), "TIMEOUT");
+}
+
+#[test]
+fn appearance_element_not_found_swallowed_until_timeout() {
+ let _guard = HomeGuard::new();
+ let err = execute(
+ WaitSelectorInput {
+ timeout_ms: 50,
+ ..base_input("button:saved", false)
+ },
+ &CodeErrorAdapter {
+ code: ErrorCode::ElementNotFound,
+ },
+ &CommandContext::default(),
+ )
+ .unwrap_err();
+ assert_eq!(err.code(), "TIMEOUT");
+}
+
+#[test]
+fn persisted_snapshot_is_loadable() {
+ let _guard = HomeGuard::new();
+ let adapter = StaticTreeAdapter {
+ tree: window_node(vec![button_node("saved")]),
+ };
+ let value = execute(
+ base_input("button:saved", false),
+ &adapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ let snapshot_id = value["snapshot_id"].as_str().unwrap();
+ let store = RefStore::new().unwrap();
+ let refmap = store.load(Some(snapshot_id)).unwrap();
+ assert!(!refmap.is_empty());
+}
diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rs
index 3b48255ff..f68b7521e 100644
--- a/crates/core/src/commands/wait_timeout.rs
+++ b/crates/core/src/commands/wait_timeout.rs
@@ -35,6 +35,13 @@ pub(crate) fn element(
)
}
+fn with_last_error(mut details: Value, last_error: Option<Value>) -> Value {
+ if let Some(err) = last_error {
+ details["last_error"] = err;
+ }
+ details
+}
+
pub(crate) fn window(
title: &str,
timeout_ms: u64,
@@ -42,12 +49,14 @@ pub(crate) fn window(
) -> Result<Value, AppError> {
timeout_err(
format!("Window with title '{title}' not found within {timeout_ms}ms"),
- json!({
- "predicate": "window",
- "title": title,
- "timeout_ms": timeout_ms,
- "last_error": last_error
- }),
+ with_last_error(
+ json!({
+ "predicate": "window",
+ "title": title,
+ "timeout_ms": timeout_ms,
+ }),
+ last_error,
+ ),
)
}
@@ -59,13 +68,15 @@ pub(crate) fn text(
) -> Result<Value, AppError> {
timeout_err(
format!("Text '{text}' did not match within {timeout_ms}ms"),
- json!({
- "predicate": "text",
- "text_chars": text.chars().count(),
- "timeout_ms": timeout_ms,
- "expected_count": expected_count,
- "last_error": last_error
- }),
+ with_last_error(
+ json!({
+ "predicate": "text",
+ "text_chars": text.chars().count(),
+ "timeout_ms": timeout_ms,
+ "expected_count": expected_count,
+ }),
+ last_error,
+ ),
)
}
@@ -77,12 +88,42 @@ pub(crate) fn notification(
) -> Result<Value, AppError> {
timeout_err(
format!("No new notification within {timeout_ms}ms"),
+ with_last_error(
+ json!({
+ "predicate": "notification",
+ "timeout_ms": timeout_ms,
+ "app": app,
+ "text_chars": text.map(|text| text.chars().count()),
+ }),
+ last_error,
+ ),
+ )
+}
+
+pub(crate) fn selector(
+ selector: &str,
+ gone: bool,
+ timeout_ms: u64,
+ last_error: Option<Value>,
+ last_snapshot_id: Option<String>,
+) -> Result<Value, AppError> {
+ let mut details = with_last_error(
json!({
- "predicate": "notification",
+ "predicate": "selector",
+ "selector": selector,
+ "gone": gone,
"timeout_ms": timeout_ms,
- "app": app,
- "text_chars": text.map(|text| text.chars().count()),
- "last_error": last_error
}),
+ last_error,
+ );
+ if let Some(snapshot_id) = last_snapshot_id {
+ details["snapshot_id"] = json!(snapshot_id);
+ }
+ timeout_err(
+ format!(
+ "Selector '{selector}' did not {} within {timeout_ms}ms",
+ if gone { "disappear" } else { "appear" }
+ ),
+ details,
)
}
diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs
index 21af67ab3..bcaa37348 100644
--- a/crates/core/src/context.rs
+++ b/crates/core/src/context.rs
@@ -5,11 +5,19 @@ use crate::{
use serde_json::Value;
use std::path::PathBuf;
+#[derive(Debug, Clone)]
+pub struct WaitSelector {
+ pub query_raw: String,
+ pub gone: bool,
+ pub timeout_ms: u64,
+}
+
#[derive(Debug, Clone, Default)]
pub struct CommandContext {
session_id: Option<String>,
trace: TraceConfig,
headed: bool,
+ wait_selector: Option<WaitSelector>,
}
impl CommandContext {
@@ -25,6 +33,7 @@ impl CommandContext {
session_id,
trace: TraceConfig::new(trace_path, trace_strict)?,
headed: false,
+ wait_selector: None,
})
}
@@ -37,6 +46,15 @@ impl CommandContext {
self
}
+ pub fn with_wait_selector(mut self, wait_selector: Option<WaitSelector>) -> Self {
+ self.wait_selector = wait_selector;
+ self
+ }
+
+ pub fn wait_selector(&self) -> Option<&WaitSelector> {
+ self.wait_selector.as_ref()
+ }
+
/// Builds the action request for a ref command. Headless (default) uses the
/// command's own `base` policy — its minimum viable policy with no cursor
/// movement (most commands are pure-AX `headless`; `type` is `focus_fallback`
@@ -82,6 +100,7 @@ impl CommandContext {
session_id,
trace: self.trace.clone(),
headed: self.headed,
+ wait_selector: None,
})
}
@@ -317,6 +336,17 @@ mod tests {
assert_eq!(err.code(), "INVALID_ARGS");
}
+ #[test]
+ fn batch_item_clears_wait_selector() {
+ let parent = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: "button:OK".into(),
+ gone: false,
+ timeout_ms: 5_000,
+ }));
+ let child = parent.for_batch_item(None).unwrap();
+ assert!(child.wait_selector().is_none());
+ }
+
#[test]
fn batch_item_inherits_or_overrides_session_without_trace_loss() {
let path = std::env::temp_dir().join("agent-desktop-context-test.jsonl");
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 3036fe58e..3ef05bd9c 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -45,7 +45,7 @@ pub use adapter::{
ImageBuffer, ImageFormat, NativeHandle, PlatformAdapter, ScreenshotTarget, TreeOptions,
WindowFilter,
};
-pub use context::CommandContext;
+pub use context::{CommandContext, WaitSelector};
pub use element_state::ElementState;
pub use error::{AdapterError, AppError, ErrorCode};
pub use interaction_policy::InteractionPolicy;
diff --git a/crates/core/src/search_text.rs b/crates/core/src/search_text.rs
index 00a71665b..12bb56c13 100644
--- a/crates/core/src/search_text.rs
+++ b/crates/core/src/search_text.rs
@@ -7,6 +7,9 @@ pub(crate) fn normalize(value: &str) -> String {
}
pub(crate) fn contains(haystack: &str, normalized_needle: &str) -> bool {
+ if normalized_needle.is_empty() {
+ return true;
+ }
if haystack.is_ascii() && normalized_needle.is_ascii() {
return haystack
.as_bytes()
diff --git a/crates/core/src/search_text_tests.rs b/crates/core/src/search_text_tests.rs
index ca5e2d202..10ab4eede 100644
--- a/crates/core/src/search_text_tests.rs
+++ b/crates/core/src/search_text_tests.rs
@@ -29,6 +29,12 @@ fn contains_handles_non_ascii_text() {
assert!(contains("Résumé", &normalize("rés")));
}
+#[test]
+fn contains_empty_needle_is_true_not_panic() {
+ assert!(contains("anything", ""));
+ assert!(contains("", ""));
+}
+
#[test]
fn node_contains_searches_name_value_and_description() {
assert!(node_contains(
diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs
index 4efb54762..803b96466 100644
--- a/crates/core/src/snapshot.rs
+++ b/crates/core/src/snapshot.rs
@@ -8,6 +8,7 @@ use crate::{
refs_store::RefStore,
};
+#[derive(Clone)]
pub struct SnapshotResult {
pub tree: AccessibilityNode,
pub refmap: RefMap,
diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.md
index cb861844b..a71a0d96c 100644
--- a/skills/agent-desktop/references/commands-interaction.md
+++ b/skills/agent-desktop/references/commands-interaction.md
@@ -13,6 +13,34 @@ Raw-input commands (`press`, `hover`, `drag`, `mouse-*`, `key-down`, `key-up`) a
`--headed` is a global flag and also applies to every `batch` entry.
+### `--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:
+
+```bash
+agent-desktop snapshot --app Finder -w "button:OK"
+agent-desktop click @e5 -w ":Saved!"
+agent-desktop click @e5 --wait-for-gone "progressindicator" --wait-timeout 5000
+```
+
+| Flag | Short | Default | Meaning |
+|------|-------|---------|---------|
+| `--wait-for <SELECTOR>` | `-w` | — | Block until an element matching `<SELECTOR>` is present |
+| `--wait-for-gone <SELECTOR>` | — | — | Block until no element matches (mutually exclusive with `--wait-for`) |
+| `--wait-timeout <MS>` | — | `30000` | Poll budget; on expiry exit `1` with `kind: "wait_timeout"`, `predicate: "selector"` |
+
+**Selector grammar:** one `role:text` string split on the first `:`. Examples: `"button:Submit"` (role + text), `"button"` (role only), `":Saved!"` (text only). Matching uses the same `find` matcher (`node_matches`); text searches name, value, and description.
+
+**Supported commands:** `snapshot` plus the 16 ref-resolving actions (`click`, `type`, `set-value`, `scroll`, …) — 17 commands total. Other commands (`find`, `launch`, …) return `INVALID_ARGS`. Workaround: `snapshot --app Foo -w "button:Login"`.
+
+**Post-action waits** poll the **acted-on ref's own window** (`entry.source_window_id`, scoped to `entry.source_app`), not the frontmost window — critical in headless and multi-window apps where the terminal or a sibling window has focus. The action result is preserved under `after_action` in the returned envelope.
+
+**Success shape:** a match returns the full snapshot envelope (`app`, `window`, `ref_count`, `snapshot_id`, `tree`) plus `elapsed_ms` and `matched_selector`. The one exception is `--wait-for-gone` when the target **app or window has itself closed**: there is no tree left to capture, so the success payload is the compact `{ "matched_selector", "gone": true, "target_absent": true, "elapsed_ms" }`. On timeout the `wait_timeout` error `details` carry `last_error` (when a poll errored) and the `snapshot_id` of the last tree built.
+
+**Snapshot constraints:** `--root` and `--wait-for`/`--wait-for-gone` are mutually exclusive (`INVALID_ARGS`). Batch items never inherit an outer `-w` (use per-item flows or run `snapshot -w` separately).
+
+**Timeout envelope:** exit `1`, `error.code` `TIMEOUT`, `error.details.kind` `"wait_timeout"`, `error.details.snapshot_id` holds the last built tree for inspection. Post-action timeouts also embed `error.details.after_action`.
+
#### Which gestures have a headless path
The command surface is platform-agnostic: every ref action builds an `Action` and calls the platform adapter, which owns the headless-vs-physical implementation. The table below is the **macOS (Phase 1) adapter's** behavior — a gesture is headless-capable there only when macOS exposes an accessibility action for it. If a future Windows (UIA) or Linux (AT-SPI) adapter exposes a headless path for `double-click`/`triple-click`, that command lights up headlessly on that platform with **no change to the command or core** — only the adapter changes (`hover`/`drag` are modeled as raw cursor gestures, so they stay physical everywhere by design).
diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.md
index 6d42a1e24..ab2b1e1ca 100644
--- a/skills/agent-desktop/references/commands-observation.md
+++ b/skills/agent-desktop/references/commands-observation.md
@@ -13,6 +13,7 @@ agent-desktop snapshot --app "App" --surface menu
agent-desktop snapshot --app "App" --window-id "w-1234"
agent-desktop snapshot --app "App" -i --compact
agent-desktop snapshot --app "App" --skeleton -i
+agent-desktop snapshot --app "App" -w "button:Submit"
agent-desktop snapshot --root @e12 --snapshot <snapshot_id> -i
```
diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rs
index 4a620baae..a706f7e43 100644
--- a/src/cli/contract_tests.rs
+++ b/src/cli/contract_tests.rs
@@ -10,6 +10,7 @@ const NON_COMMAND_MODULES: &[&str] = &[
"helpers_test_support",
"mod",
"point_resolve",
+ "query",
"wait_element",
"wait_latest_ref_cache",
"wait_mode",
@@ -17,6 +18,7 @@ const NON_COMMAND_MODULES: &[&str] = &[
"wait_test_support",
"wait_text_match",
"wait_timeout",
+ "wait_selector",
];
const COMMAND_SPECIFIC_TESTS: &[&str] = &[
diff --git a/src/cli/help_after.txt b/src/cli/help_after.txt
index 98d504825..ee3c28204 100644
--- a/src/cli/help_after.txt
+++ b/src/cli/help_after.txt
@@ -118,6 +118,8 @@ EXAMPLES
agent-desktop --headed mouse-click --xy 500,300
agent-desktop wait --text "Loading complete" --app Safari --timeout 5000
agent-desktop wait --element @e5 --predicate actionable --timeout 5000
+ agent-desktop snapshot --app Finder -w "button:OK"
+ agent-desktop click @e5 -w ":Saved!"
agent-desktop --session run-a --trace /tmp/ad.jsonl click @e5
agent-desktop batch '[{"command":"click","args":{"ref_id":"@e1","snapshot":"<snapshot_id>"}}]'
agent-desktop --session run-a batch '[{"command":"status","session":"run-b","args":{}}]'
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 3a35854da..37af62162 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -67,6 +67,31 @@ pub(crate) struct Cli {
)]
pub headed: bool,
+ #[arg(
+ long,
+ short = 'w',
+ global = true,
+ conflicts_with = "wait_for_gone",
+ help = "Poll until an element matching the role:text selector appears, then return the snapshot"
+ )]
+ pub wait_for: Option<String>,
+
+ #[arg(
+ long,
+ global = true,
+ conflicts_with = "wait_for",
+ help = "Poll until no element matches the role:text selector, then return the snapshot"
+ )]
+ pub wait_for_gone: Option<String>,
+
+ #[arg(
+ long,
+ global = true,
+ default_value_t = 30_000,
+ help = "Maximum wait time in milliseconds for --wait-for / --wait-for-gone (default: 30000)"
+ )]
+ pub wait_timeout: u64,
+
#[command(subcommand)]
pub command: Option<Commands>,
}
@@ -248,6 +273,10 @@ impl Commands {
}
}
+#[cfg(test)]
+#[path = "wait_for_cli_tests.rs"]
+mod wait_for_cli_tests;
+
#[cfg(test)]
#[path = "contract_tests.rs"]
mod contract_tests;
diff --git a/src/cli/wait_for_cli_tests.rs b/src/cli/wait_for_cli_tests.rs
new file mode 100644
index 000000000..16b80493a
--- /dev/null
+++ b/src/cli/wait_for_cli_tests.rs
@@ -0,0 +1,101 @@
+use super::Cli;
+use agent_desktop_core::context::WaitSelector;
+use clap::{CommandFactory, Parser};
+
+fn selector(query_raw: &str) -> WaitSelector {
+ WaitSelector {
+ query_raw: query_raw.into(),
+ gone: false,
+ timeout_ms: 30_000,
+ }
+}
+
+#[test]
+fn help_lists_global_wait_for_flags() {
+ let help = Cli::command().render_help();
+ let help = help.to_string();
+ assert!(help.contains("--wait-for"));
+ assert!(help.contains("--wait-for-gone"));
+ assert!(help.contains("--wait-timeout"));
+}
+
+#[test]
+fn wait_for_and_wait_for_gone_conflict() {
+ let err = Cli::try_parse_from([
+ "agent-desktop",
+ "--wait-for",
+ "button:OK",
+ "--wait-for-gone",
+ "button:Spinner",
+ "snapshot",
+ "--app",
+ "Finder",
+ ])
+ .expect_err("mutually exclusive wait flags must fail parse");
+ assert_eq!(err.exit_code(), 2);
+}
+
+#[test]
+fn short_w_flag_maps_to_wait_for() {
+ let cli = Cli::try_parse_from([
+ "agent-desktop",
+ "-w",
+ "button:Submit",
+ "snapshot",
+ "--app",
+ "Finder",
+ ])
+ .expect("short -w should parse");
+ assert_eq!(cli.wait_for.as_deref(), Some("button:Submit"));
+ assert_eq!(cli.wait_timeout, 30_000);
+}
+
+#[test]
+fn wait_timeout_parses_custom_value() {
+ let cli = Cli::try_parse_from([
+ "agent-desktop",
+ "--wait-for",
+ "button:OK",
+ "--wait-timeout",
+ "5000",
+ "snapshot",
+ ])
+ .expect("custom wait timeout should parse");
+ assert_eq!(cli.wait_timeout, 5_000);
+}
+
+#[test]
+fn validate_rejects_unsupported_command() {
+ let err = crate::validate_wait_for_command("find", &selector("button:OK"))
+ .expect_err("find must not accept --wait-for");
+ assert_eq!(err.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn validate_rejects_match_everything_selector_before_dispatch() {
+ let err = crate::validate_wait_for_command("click", &selector(""))
+ .expect_err("empty selector must be rejected before the action runs");
+ assert_eq!(err.code(), "INVALID_ARGS");
+ assert!(crate::validate_wait_for_command("click", &selector(":")).is_err());
+}
+
+#[test]
+fn validate_accepts_supported_command_with_constraining_selector() {
+ assert!(crate::validate_wait_for_command("click", &selector(":Saved!")).is_ok());
+ assert!(crate::validate_wait_for_command("snapshot", &selector("button")).is_ok());
+}
+
+#[test]
+fn wait_supported_names_are_real_subcommands() {
+ let cmd = Cli::command();
+ let subcommands: Vec<String> = cmd
+ .get_subcommands()
+ .map(|sub| sub.get_name().to_string())
+ .collect();
+ for name in crate::WAIT_SUPPORTED {
+ assert!(
+ subcommands.iter().any(|sub| sub == name),
+ "WAIT_SUPPORTED entry '{name}' is not a real subcommand"
+ );
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 9f8bcac37..21d903087 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,7 +6,8 @@ mod dispatch;
use agent_desktop_core::{
adapter::PlatformAdapter,
- context::CommandContext,
+ context::{CommandContext, WaitSelector},
+ error::AppError,
output::{ENVELOPE_VERSION, ErrorPayload, Response},
};
use clap::{CommandFactory, Parser};
@@ -14,6 +15,26 @@ use cli::{Cli, Commands};
use cli_args::skills::SkillsAction;
use std::io::{BufWriter, Write};
+const WAIT_SUPPORTED: &[&str] = &[
+ "snapshot",
+ "click",
+ "double-click",
+ "triple-click",
+ "right-click",
+ "clear",
+ "focus",
+ "toggle",
+ "check",
+ "uncheck",
+ "expand",
+ "collapse",
+ "scroll-to",
+ "type",
+ "set-value",
+ "select",
+ "scroll",
+];
+
fn main() {
let cli = match Cli::try_parse() {
Ok(c) => c,
@@ -35,8 +56,11 @@ fn main() {
};
init_tracing(cli.verbose);
+ let wait_selector = build_wait_selector(&cli);
let context = match CommandContext::new(cli.session, cli.trace, cli.trace_strict) {
- Ok(context) => context.with_headed(cli.headed),
+ Ok(context) => context
+ .with_headed(cli.headed)
+ .with_wait_selector(wait_selector.clone()),
Err(err) => {
finish("unknown", Err(err));
return;
@@ -53,6 +77,13 @@ fn main() {
let cmd_name = cmd.name();
+ if let Some(wait) = wait_selector.as_ref() {
+ if let Err(err) = validate_wait_for_command(cmd_name, wait) {
+ finish(cmd_name, Err(err));
+ return;
+ }
+ }
+
match cmd {
Commands::Version => {
let result = agent_desktop_core::commands::version::execute();
@@ -76,6 +107,30 @@ fn main() {
}
}
+fn build_wait_selector(cli: &Cli) -> Option<WaitSelector> {
+ let (query_raw, gone) = cli
+ .wait_for
+ .as_ref()
+ .map(|raw| (raw, false))
+ .or_else(|| cli.wait_for_gone.as_ref().map(|raw| (raw, true)))?;
+ Some(WaitSelector {
+ query_raw: query_raw.clone(),
+ gone,
+ timeout_ms: cli.wait_timeout,
+ })
+}
+
+fn validate_wait_for_command(cmd_name: &str, wait: &WaitSelector) -> Result<(), AppError> {
+ if !WAIT_SUPPORTED.contains(&cmd_name) {
+ return Err(AppError::invalid_input_with_suggestion(
+ format!("Command '{cmd_name}' does not support --wait-for or --wait-for-gone"),
+ "Use snapshot --wait-for \"<selector>\" or a supported ref action (click, type, …).",
+ ));
+ }
+ agent_desktop_core::commands::query::validate_selector(&wait.query_raw)?;
+ Ok(())
+}
+
fn run_with_adapter(cmd: Commands, cmd_name: &str, context: &CommandContext) {
let adapter = build_adapter();
let report = adapter.permission_report();
diff --git a/tests/e2e/run.sh b/tests/e2e/run.sh
index 00d6874a7..dbe7fbefd 100755
--- a/tests/e2e/run.sh
+++ b/tests/e2e/run.sh
@@ -250,6 +250,33 @@ wt="$("$bin" wait --text appeared-text --app "$app" --timeout 5000 2>/dev/null)"
assert "wait text resolved" "$([ "$(echo "$wt" | field "['data']['found']")" = "True" ] && echo 1 || echo 0)" \
"found=$(echo "$wt" | field "['data']['found']") elapsed_ms=$(echo "$wt" | field "['data']['elapsed_ms']")"
+note "wait-for selector (global -w / --wait-for-gone)"
+"$bin" focus-window --app "$app" >/dev/null 2>&1
+wf_out="$("$bin" click "$(resolve button appear-later)" -w ":appeared-text" --wait-timeout 8000 2>&1)"
+wf_ok="$(echo "$wf_out" | field "['ok']")"
+wf_sel="$(echo "$wf_out" | field "['data']['matched_selector']")"
+wf_after="$(echo "$wf_out" | field "['data']['after_action']['action']")"
+assert "post-action -w waits for async text" \
+ "$([ "$wf_ok" = "True" ] && [ "$wf_sel" = ":appeared-text" ] && [ "$wf_after" = "click" ] && echo 1 || echo 0)" \
+ "ok=$wf_ok matched=$wf_sel after_action=$wf_after"
+wg_out="$("$bin" click "$(resolve button remove-row)" --wait-for-gone ":removable-row" --wait-timeout 5000 2>&1)"
+wg_ok="$(echo "$wg_out" | field "['ok']")"
+wg_gone="$(echo "$wg_out" | field "['data']['matched_selector']")"
+assert "--wait-for-gone after remove-row" \
+ "$([ "$wg_ok" = "True" ] && [ "$wg_gone" = ":removable-row" ] && echo 1 || echo 0)" \
+ "ok=$wg_ok matched=$wg_gone"
+to_out="$("$bin" snapshot --app "$app" -w ":does-not-exist-xyz" --wait-timeout 400 2>&1)"; to_ec=$?
+to_kind="$(echo "$to_out" | field "['error']['details']['kind']")"
+to_pred="$(echo "$to_out" | field "['error']['details']['predicate']")"
+to_sid="$(echo "$to_out" | field "['error']['details']['snapshot_id']")"
+assert "wait-for timeout envelope" \
+ "$([ "$to_ec" -ne 0 ] && [ "$to_kind" = "wait_timeout" ] && [ "$to_pred" = "selector" ] && [ -n "$to_sid" ] && echo 1 || echo 0)" \
+ "exit=$to_ec kind=$to_kind predicate=$to_pred snapshot_id=${to_sid:0:12}..."
+find_wf="$("$bin" find --app "$app" -w "button:OK" 2>&1)"
+find_wf_code="$(echo "$find_wf" | field "['error']['code']")"
+assert "unsupported command rejects -w" "$([ "$find_wf_code" = "INVALID_ARGS" ] && echo 1 || echo 0)" \
+ "find -w code=$find_wf_code"
+
note "skeleton traversal + scoped drill-down"
sk="$("$bin" snapshot --app "$app" --skeleton 2>/dev/null)"; sk_id="$(echo "$sk" | field "['data']['snapshot_id']")"
sk_refs="$(echo "$sk" | field "['data']['ref_count']")"