Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
fix(drag): scope --wait-for to the drop target by default with --wait-for-scope from|to
detail-app[bot]cefc80a89c95
diff --git a/crates/core/src/commands/drag.rs b/crates/core/src/commands/drag.rsindex 9b3eb4631..fc61c6237 100644--- a/crates/core/src/commands/drag.rs+++ b/crates/core/src/commands/drag.rs@@ -18,6 +18,20 @@ pub struct DragEndpoint {pub xy: Option<(f64, f64)>,}+/// Selects which drag endpoint's window scopes the post-action `--wait-for` /+/// `--wait-for-gone` verification. A drag has two endpoints, only one of which+/// `apply_post_action_wait` can poll, so the caller must be able to target the+/// window where the confirmation (or its absence) appears rather than always+/// the pickup window. Defaults to the drop target (`To`), since a drag's+/// defining effect is the drop; falls back to the other endpoint when the+/// chosen one carries no `source_entry` (e.g. an `--from-xy` pickup).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum WaitForScope {+ From,+ #[default]+ To,+}+pub struct DragArgs {pub from: DragEndpoint,pub to: DragEndpoint,@@ -25,6 +39,7 @@ pub struct DragArgs {pub duration_ms: Option<u64>,pub drop_delay_ms: Option<u64>,pub timeout_ms: Option<u64>,+ pub wait_for_scope: WaitForScope,}pub fn execute(@@ -132,7 +147,11 @@ pub fn execute(response["focused"] = json!(true);}drop(lease);- apply_post_action_wait(response, from.source_entry.as_ref(), adapter, context)+ let wait_entry = match args.wait_for_scope {+ WaitForScope::To => to.source_entry.as_ref().or(from.source_entry.as_ref()),+ WaitForScope::From => from.source_entry.as_ref().or(to.source_entry.as_ref()),+ };+ apply_post_action_wait(response, wait_entry, adapter, context)}#[cfg(test)]diff --git a/crates/core/src/commands/drag_retry_tests.rs b/crates/core/src/commands/drag_retry_tests.rsindex 05283b1d8..96bfea1d5 100644--- a/crates/core/src/commands/drag_retry_tests.rs+++ b/crates/core/src/commands/drag_retry_tests.rs@@ -112,6 +112,7 @@ fn transient_stale_ref_retries_then_succeeds_when_timeout_wired() {duration_ms: None,drop_delay_ms: None,timeout_ms: Some(5_000),+ wait_for_scope: WaitForScope::default(),},&adapter,&CommandContext::default().with_headed(true),@@ -345,6 +346,7 @@ fn timeout_none_is_single_shot() {duration_ms: None,drop_delay_ms: None,timeout_ms: None,+ wait_for_scope: WaitForScope::default(),},&adapter,&CommandContext::default().with_headed(true),diff --git a/crates/core/src/commands/drag_tests.rs b/crates/core/src/commands/drag_tests.rsindex dc2900518..a171ab9a4 100644--- a/crates/core/src/commands/drag_tests.rs+++ b/crates/core/src/commands/drag_tests.rs@@ -122,6 +122,7 @@ fn xy_args(drop_delay_ms: Option<u64>) -> DragArgs {duration_ms: None,drop_delay_ms,timeout_ms: None,+ wait_for_scope: WaitForScope::default(),}}@@ -218,6 +219,7 @@ fn cross_app_args(snapshot_id: String) -> DragArgs {duration_ms: None,drop_delay_ms: None,timeout_ms: None,+ wait_for_scope: WaitForScope::default(),}}@@ -304,3 +306,6 @@ mod retry_tests;#[path = "drag_occlusion_retry_tests.rs"]mod occlusion_retry_tests;++#[path = "drag_wait_scope_tests.rs"]+mod wait_scope_tests;diff --git a/crates/core/src/commands/drag_wait_scope_tests.rs b/crates/core/src/commands/drag_wait_scope_tests.rsnew file mode 100644index 000000000..a20ee609d--- /dev/null+++ b/crates/core/src/commands/drag_wait_scope_tests.rs@@ -0,0 +1,312 @@+//! Fixes the cross-window `drag --wait-for` scoping defect: the post-action+//! wait must be able to observe the drop-target window, not only the pickup+//! window. See `crates/core/src/commands/drag.rs` (`WaitForScope`).+use super::*;+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps, TreeOptions};+use crate::commands::wait_selector::{self, WaitSelectorInput};+use crate::context::WaitSelector;+use crate::refs_test_support::HomeGuard;+use crate::{+ AccessibilityNode, AdapterError, CommandContext, DragParams, InteractionLease, ProcessId,+ WindowInfo, WindowState, window_filter::WindowFilter,+};+use serde_json::json;+use std::sync::Mutex;++/// Models a cross-window drag whose confirmation ("Dropped") surfaces only in+/// the destination window. Exposes two windows in distinct apps so+/// `resolve_window` pins `from` to `w-1` and `to` to `w-2`, and records every+/// window id the wait observes via `observe_tree` so a test can prove which+/// window was polled.+struct CrossAppWaitAdapter {+ captured: Mutex<Option<DragParams>>,+ observed: Mutex<Vec<String>>,+}++impl CrossAppWaitAdapter {+ fn new() -> Self {+ Self {+ captured: Mutex::new(None),+ observed: Mutex::new(Vec::new()),+ }+ }++ fn windows() -> Vec<WindowInfo> {+ vec![+ WindowInfo {+ id: "w-1".into(),+ title: "Source".into(),+ app: "App 1".into(),+ pid: ProcessId::new(1),+ process_instance: Some("test-instance".into()),+ bounds: None,+ state: WindowState {+ is_focused: true,+ ..Default::default()+ },+ },+ WindowInfo {+ id: "w-2".into(),+ title: "Destination".into(),+ app: "App 2".into(),+ pid: ProcessId::new(2),+ process_instance: Some("test-instance".into()),+ bounds: None,+ state: WindowState::default(),+ },+ ]+ }++ fn dropped_confirmation() -> AccessibilityNode {+ AccessibilityNode {+ ref_id: None,+ role: "button".into(),+ identity: crate::NodeIdentity {+ name: Some("Dropped".into()),+ ..Default::default()+ },+ presentation: Default::default(),+ children_count: None,+ subtree_truncated: false,+ children: vec![],+ }+ }++ fn window_node(window: &WindowInfo) -> AccessibilityNode {+ let children = (window.id == "w-2")+ .then(Self::dropped_confirmation)+ .into_iter()+ .collect();+ AccessibilityNode {+ ref_id: None,+ role: "window".into(),+ identity: crate::NodeIdentity {+ name: Some(window.title.clone()),+ ..Default::default()+ },+ presentation: Default::default(),+ children_count: None,+ subtree_truncated: false,+ children,+ }+ }+}++impl ObservationOps for CrossAppWaitAdapter {+ fn observe_tree(+ &self,+ root: crate::live_locator::ObservationRoot<'_>,+ _request: &crate::live_locator::ObservationRequest,+ ) -> Result<crate::live_locator::ObservedTree, AdapterError> {+ let crate::live_locator::ObservationRoot::Window(window) = root else {+ return Err(AdapterError::internal("expected window root"));+ };+ self.observed.lock().unwrap().push(window.id.clone());+ let node = Self::window_node(window);+ crate::adapter::observed_tree(&crate::live_locator::ObservationRoot::Window(window), node)+ }++ fn resolve_element_strict(+ &self,+ _entry: &crate::refs::RefEntry,+ _deadline: crate::Deadline,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn list_windows(+ &self,+ filter: &WindowFilter,+ _deadline: crate::Deadline,+ ) -> Result<Vec<WindowInfo>, AdapterError> {+ Ok(Self::windows()+ .into_iter()+ .filter(|window| {+ filter+ .app+ .as_deref()+ .is_none_or(|app| window.app.as_str() == app)+ })+ .collect())+ }++ fn get_tree(+ &self,+ window: &WindowInfo,+ _opts: &TreeOptions,+ _deadline: crate::Deadline,+ ) -> Result<AccessibilityNode, AdapterError> {+ Ok(Self::window_node(window))+ }++ crate::adapter::complete_live_observation!("button", "Item", [crate::capability::CLICK]);+}++impl ActionOps for CrossAppWaitAdapter {}++impl InputOps for CrossAppWaitAdapter {+ fn drag(&self, params: DragParams, _lease: &InteractionLease) -> Result<(), AdapterError> {+ *self.captured.lock().unwrap() = Some(params);+ Ok(())+ }+}++impl SystemOps for CrossAppWaitAdapter {+ crate::adapter::guarded_interaction_lease!();+ crate::adapter::exact_window_focus!();+}++fn drag_args(snapshot_id: String, scope: WaitForScope) -> DragArgs {+ DragArgs {+ from: DragEndpoint {+ ref_id: Some("@e1".into()),+ xy: None,+ },+ to: DragEndpoint {+ ref_id: Some("@e2".into()),+ xy: None,+ },+ snapshot_id: Some(snapshot_id),+ duration_ms: None,+ drop_delay_ms: None,+ timeout_ms: None,+ wait_for_scope: scope,+ }+}++fn wait_context(timeout_ms: u64) -> CommandContext {+ CommandContext::default()+ .with_headed(true)+ .with_wait_selector(Some(WaitSelector {+ query_raw: ":dropped".into(),+ gone: false,+ timeout_ms,+ }))+}++/// A same-window fixture: both endpoints resolve to `App 2` / `w-2`, so the+/// `from` and `to` `source_entry`s are identical and the scope choice is+/// invisible. The destination carries the "Dropped" confirmation.+fn same_window_snapshot() -> String {+ let store = crate::refs_store::RefStore::new().unwrap();+ let mut refmap = crate::refs::RefMap::new();+ refmap.allocate(ref_entry(2));+ refmap.allocate(ref_entry(2));+ store.save_new_snapshot(&refmap).unwrap()+}++/// The default scope resolves a cross-window drag's `--wait-for` to the drop+/// target, so a destination-only confirmation is observed instead of timing+/// out against the source window.+#[test]+fn drag_wait_defaults_to_destination_window_and_finds_confirmation() {+ let _guard = HomeGuard::new();+ let snapshot_id = cross_app_snapshot();+ let adapter = CrossAppWaitAdapter::new();++ let value = execute(+ drag_args(snapshot_id, WaitForScope::default()),+ &adapter,+ &wait_context(2_000),+ )+ .expect("destination carries the confirmation; default scope must poll it");++ assert_eq!(value["matched_selector"], ":dropped");+ assert_eq!(value["after_action"]["dragged"], json!(true));+ let observed = adapter.observed.lock().unwrap();+ assert!(+ observed.iter().any(|id| id == "w-2"),+ "the destination window must be polled: {observed:?}",+ );+ assert!(adapter.captured.lock().unwrap().is_some());+}++/// Escaping the default (destination) scope to the pickup window must still be+/// possible via `--wait-for-scope from`, and a destination-only confirmation+/// remains unreachable from the source window: the drag is delivered but the+/// wait times out polling only `w-1`.+#[test]+fn drag_wait_scoped_to_source_window_misses_destination_confirmation() {+ let _guard = HomeGuard::new();+ let snapshot_id = cross_app_snapshot();+ let adapter = CrossAppWaitAdapter::new();++ let error = execute(+ drag_args(snapshot_id, WaitForScope::From),+ &adapter,+ &wait_context(300),+ )+ .expect_err("source window cannot observe a destination-only confirmation");++ assert_eq!(error.code(), "TIMEOUT");+ let details = match &error {+ crate::AppError::Adapter(err) => {+ err.details.as_ref().expect("wait timeout carries details")+ }+ other => panic!("expected adapter TIMEOUT, got {other:?}"),+ };+ assert_eq!(details["kind"], json!("wait_timeout"));+ assert_eq!(details["after_action"]["dragged"], json!(true));+ let observed = adapter.observed.lock().unwrap();+ assert!(+ observed.iter().all(|id| id == "w-1"),+ "wait must only inspect the from window: {observed:?}",+ );+ assert!(+ !observed.iter().any(|id| id == "w-2"),+ "the drop-target window must never be inspected under from scope: {observed:?}",+ );+ assert!(adapter.captured.lock().unwrap().is_some());+}++/// The confirmation is observable in the destination window, proving the only+/// defect is the scoping choice: scoping `wait_selector` to `App 2` / `w-2`+/// matches immediately.+#[test]+fn wait_selector_scoped_to_destination_window_finds_the_confirmation() {+ let _guard = HomeGuard::new();+ let adapter = CrossAppWaitAdapter::new();++ let value = wait_selector::execute(+ WaitSelectorInput {+ query_raw: ":dropped".into(),+ gone: false,+ app: Some("App 2".into()),+ window_id: Some("w-2".into()),+ opts: TreeOptions::default(),+ timeout_ms: 1_000,+ },+ &adapter,+ &CommandContext::default(),+ )+ .expect("destination carries the confirmation");++ assert_eq!(value["matched_selector"], ":dropped");+}++/// A same-window drag has identical `from`/`to` endpoints, so the default+/// scope change is a no-op there: the shared window is polled and the+/// confirmation matches, guarding the previously-correct same-window path+/// against a regression from the destination default.+#[test]+fn drag_wait_same_window_drag_polls_the_shared_window_and_matches() {+ let _guard = HomeGuard::new();+ let snapshot_id = same_window_snapshot();+ let adapter = CrossAppWaitAdapter::new();++ let value = execute(+ drag_args(snapshot_id, WaitForScope::default()),+ &adapter,+ &wait_context(2_000),+ )+ .expect("the shared window carries the confirmation");++ assert_eq!(value["matched_selector"], ":dropped");+ assert_eq!(value["after_action"]["dragged"], json!(true));+ let observed = adapter.observed.lock().unwrap();+ assert!(+ observed.iter().any(|id| id == "w-2") && !observed.iter().any(|id| id == "w-1"),+ "same-window drag must poll the shared destination window: {observed:?}",+ );+ assert!(adapter.captured.lock().unwrap().is_some());+}diff --git a/crates/core/src/commands/pointer_single_shot_tests.rs b/crates/core/src/commands/pointer_single_shot_tests.rsindex df04e271a..5928a9260 100644--- a/crates/core/src/commands/pointer_single_shot_tests.rs+++ b/crates/core/src/commands/pointer_single_shot_tests.rs@@ -218,6 +218,7 @@ fn drag_none_scrolls_once_then_dispatches_revalidated_endpoints_once() {duration_ms: None,drop_delay_ms: None,timeout_ms: None,+ wait_for_scope: drag::WaitForScope::default(),},&adapter,&CommandContext::default().with_headed(true),diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex 39a0aabf5..374f9736f 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -267,11 +267,14 @@ agent-desktop --headed drag --from @s8f3k2p9:e1 --to @s8f3k2p9:e5 --drop-delay 8| `--duration` | Drag duration in milliseconds (movement from source to destination) || `--drop-delay` | Milliseconds to hold over the destination before releasing; default 500 || `--timeout-ms` | Actionability wait budget in ms before failing with `TIMEOUT`; default 5000 |+| `--wait-for-scope` | Window a `--wait-for`/`--wait-for-gone` verification polls: `to` (drop target, default) or `from` (pickup). Needed when the confirmation appears only in the destination window of a cross-window drag |Can mix ref and coordinate sources (e.g., `--from @s8f3k2p9:e1 --to-xy 400,500`).With `--headed`, a ref-addressed `--from` must focus the source's exact window before mouse-down and fails before delivery if focus cannot be confirmed. The destination app is never pre-focused because raising it could cover the source point. Coordinate-only drags never attempt focus. For cross-app two-ref drags, keep the destination window visible; both endpoints still undergo live visibility, stability, and hit-test checks.+A drag's `--wait-for`/`--wait-for-gone` verification observes one endpoint's window. The default scope is `to` (the drop target, where the drop's effect usually appears); use `--wait-for-scope from` when the confirmation is source-side (e.g. the dragged row leaving the source list). When the chosen endpoint is coordinate-only (`--from-xy`/`--to-xy`, which carry no window identity), the wait falls back to the other endpoint's window, then to the focused window.+macOS drop targets often need the dragged item to dwell over them before they register as the drop destination — too short and the gesture lands as a drag with no drop. The default 500ms dwell suits most targets; raise `--drop-delay` (e.g. 800–1200) for sluggish destinations like list reorders or cross-window drops. The dwell posts continuous drag events over the destination so it stays highlighted, rather than a dead pause.### mouse-movediff --git a/src/cli/wait_for_cli_tests.rs b/src/cli/wait_for_cli_tests.rsindex 55358c74b..af0b28734 100644--- a/src/cli/wait_for_cli_tests.rs+++ b/src/cli/wait_for_cli_tests.rs@@ -153,3 +153,66 @@ fn mutation_metadata_distinguishes_read_only_and_file_writing_forms() {assert!(!command(&["trace", "show"]).is_mutating());assert!(command(&["trace", "export"]).is_mutating());}++fn drag_args(arguments: &[&str]) -> crate::cli_args::drag::DragCliArgs {+ let command = command(arguments);+ let crate::cli::Commands::Drag(args) = command else {+ panic!("expected a drag command, got {:?}", command.name());+ };+ args+}++#[test]+fn wait_for_scope_defaults_absent_and_dispatch_applies_the_destination_default() {+ let args = drag_args(&["drag", "--from", "@e1", "--to", "@e2"]);+ assert_eq!(+ args.wait_for_scope, None,+ "the flag is optional; the destination default is applied in the dispatch layer",+ );+}++#[test]+fn wait_for_scope_to_and_from_parse_to_the_named_scope() {+ assert_eq!(+ drag_args(&[+ "drag",+ "--from",+ "@e1",+ "--to",+ "@e2",+ "--wait-for-scope",+ "to"+ ])+ .wait_for_scope,+ Some(crate::cli_args::drag::WaitForScopeArg::To),+ );+ assert_eq!(+ drag_args(&[+ "drag",+ "--from",+ "@e1",+ "--to",+ "@e2",+ "--wait-for-scope",+ "from"+ ])+ .wait_for_scope,+ Some(crate::cli_args::drag::WaitForScopeArg::From),+ );+}++#[test]+fn wait_for_scope_rejects_unknown_values() {+ let err = Cli::try_parse_from([+ "agent-desktop",+ "drag",+ "--from",+ "@e1",+ "--to",+ "@e2",+ "--wait-for-scope",+ "destination",+ ])+ .expect_err("an unknown scope value must fail parse");+ assert_eq!(err.exit_code(), 2);+}diff --git a/src/cli_args/drag.rs b/src/cli_args/drag.rsindex cd8cfde1a..ffd42ea4e 100644--- a/src/cli_args/drag.rs+++ b/src/cli_args/drag.rs@@ -1,4 +1,4 @@-use clap::Parser;+use clap::{Parser, ValueEnum};use serde::Deserialize;use super::drag_target::DragTargetArgs;@@ -7,6 +7,18 @@ fn default_ref_timeout_ms() -> u64 {5000}+/// Selects which drag endpoint's window scopes the post-action+/// `--wait-for` / `--wait-for-gone` verification. Maps 1:1 to+/// [`agent_desktop_core::commands::drag::WaitForScope`]; the conversion lives+/// in the dispatch layer so the core enum stays free of `clap`.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum, Deserialize)]+#[serde(rename_all = "lowercase")]+pub(crate) enum WaitForScopeArg {+ From,+ #[default]+ To,+}+#[derive(Parser, Debug, Deserialize)]#[serde(deny_unknown_fields)]pub(crate) struct DragCliArgs {@@ -34,4 +46,12 @@ pub(crate) struct DragCliArgs {)]#[serde(default = "default_ref_timeout_ms")]pub timeout_ms: u64,+ #[arg(+ long = "wait-for-scope",+ value_name = "SCOPE",+ value_enum,+ help = "Window a drag's --wait-for/--wait-for-gone verification polls: 'to' (drop target, default) or 'from' (pickup). Needed when the confirmation appears only in the destination window of a cross-window drag"+ )]+ #[serde(default)]+ pub wait_for_scope: Option<WaitForScopeArg>,}diff --git a/src/dispatch/keyboard_mouse.rs b/src/dispatch/keyboard_mouse.rsindex 8918753ca..f49fb674a 100644--- a/src/dispatch/keyboard_mouse.rs+++ b/src/dispatch/keyboard_mouse.rs@@ -93,6 +93,13 @@ pub(super) fn drag(duration_ms: args.duration,drop_delay_ms: args.drop_delay,timeout_ms: helpers::normalize_action_timeout_ms(args.timeout_ms),+ wait_for_scope: match args.wait_for_scope {+ Some(crate::cli_args::drag::WaitForScopeArg::From) => {+ drag_command::WaitForScope::From+ }+ Some(crate::cli_args::drag::WaitForScopeArg::To) => drag_command::WaitForScope::To,+ None => drag_command::WaitForScope::default(),+ },},adapter,context,