Skip to content

Computer use CLI for AI agents

chore: stack the reviewed open PRs onto main (#247)

Lahfirdd6c47397e32
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 56829ac0d..2bd5edcfa 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -31,12 +31,12 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Initialize CodeQL
- uses: github/codeql-action/init@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4.38.1
+ uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
languages: ${{ matrix.language }}
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4.38.1
+ uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
analyze-rust:
name: Analyze (rust)
@@ -50,10 +50,10 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Initialize CodeQL
- uses: github/codeql-action/init@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4.38.1
+ uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
languages: rust
build-mode: none
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4.38.1
+ uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
diff --git a/Cargo.lock b/Cargo.lock
index 3e0243f1d..05feeadd7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -456,9 +456,9 @@ dependencies = [
[[package]]
name = "smallvec"
-version = "1.16.1"
+version = "1.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
dependencies = [
"serde",
]
@@ -493,18 +493,18 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "2.0.20"
+version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "2.0.20"
+version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
diff --git a/crates/core/src/app_lookup.rs b/crates/core/src/app_lookup.rs
index cd73288a4..d871bc080 100644
--- a/crates/core/src/app_lookup.rs
+++ b/crates/core/src/app_lookup.rs
@@ -1,7 +1,7 @@
use serde_json::json;
use crate::{
- AdapterError, AppError, AppInfo, Deadline, ErrorCode, ProcessIdentity,
+ AdapterError, AppError, AppInfo, Deadline, ErrorCode, ProcessIdentity, WindowInfo,
adapter::{PlatformAdapter, WindowFilter},
};
@@ -38,6 +38,16 @@ pub(crate) fn resolve_app(
.into());
}
};
+ resolve_app_owning(window, adapter, deadline)
+}
+
+/// The application that owns `window`, narrowed to the window's exact process
+/// instance, so a second running copy of the same application is never chosen.
+pub(crate) fn resolve_app_owning(
+ window: &WindowInfo,
+ adapter: &dyn PlatformAdapter,
+ deadline: Deadline,
+) -> Result<AppInfo, AppError> {
let instance = window
.process_instance
.as_deref()
@@ -45,7 +55,7 @@ pub(crate) fn resolve_app(
.ok_or_else(|| {
AdapterError::new(
ErrorCode::ActionNotSupported,
- "Focused window has no process-instance identity",
+ "Window has no process-instance identity",
)
})?;
let same_pid = adapter
diff --git a/crates/core/src/commands/press.rs b/crates/core/src/commands/press.rs
index a09f1555e..bbea58339 100644
--- a/crates/core/src/commands/press.rs
+++ b/crates/core/src/commands/press.rs
@@ -10,6 +10,7 @@ use serde_json::Value;
pub struct PressArgs {
pub combo: String,
pub app: Option<String>,
+ pub window_id: Option<String>,
pub force: bool,
}
@@ -23,8 +24,7 @@ pub fn execute(
ensure_combo_allowed(&combo, &args.combo, args.force, adapter)?;
let deadline = crate::Deadline::standard()?;
- let result = if let Some(app_name) = &args.app {
- let expected = crate::commands::helpers::resolve_app(Some(app_name), adapter, deadline)?;
+ let result = if let Some((expected, window)) = target_app(&args, adapter, deadline)? {
let lease = adapter.acquire_interaction_lease(deadline)?;
let live = crate::commands::helpers::revalidate_app_for_mutation(
adapter,
@@ -33,7 +33,17 @@ pub fn execute(
)?;
let process = crate::commands::helpers::process_identity(&live)?;
if context.physical_input_policy().is_headed() {
- crate::headed_focus::focus_process_window(process.clone(), adapter, context, &lease)?;
+ match &window {
+ Some(window) => {
+ crate::headed_focus::focus_exact_window(window, adapter, context, &lease)?
+ }
+ None => crate::headed_focus::focus_process_window(
+ process.clone(),
+ adapter,
+ context,
+ &lease,
+ )?,
+ };
}
adapter.press_key_for_app(process, &combo, context.physical_input_policy(), &lease)?
} else {
@@ -48,12 +58,38 @@ pub fn execute(
super::helpers::apply_scoped_post_action_wait(
serde_json::to_value(result)?,
args.app,
- None,
+ args.window_id,
adapter,
context,
)
}
+fn target_app(
+ args: &PressArgs,
+ adapter: &dyn PlatformAdapter,
+ deadline: crate::Deadline,
+) -> Result<Option<(crate::AppInfo, Option<crate::WindowInfo>)>, AppError> {
+ if let Some(window_id) = &args.window_id {
+ let window = crate::snapshot::resolve_window(
+ adapter,
+ args.app.as_deref(),
+ Some(window_id),
+ deadline,
+ )?;
+ let app = crate::app_lookup::resolve_app_owning(&window, adapter, deadline)?;
+ return Ok(Some((app, Some(window))));
+ }
+ args.app
+ .as_deref()
+ .map(|app| crate::commands::helpers::resolve_app(Some(app), adapter, deadline))
+ .transpose()
+ .map(|app| app.map(|app| (app, None)))
+}
+
#[cfg(test)]
#[path = "press_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "press_window_tests.rs"]
+mod window_tests;
diff --git a/crates/core/src/commands/press_tests.rs b/crates/core/src/commands/press_tests.rs
index a9f2f0448..44fa245c1 100644
--- a/crates/core/src/commands/press_tests.rs
+++ b/crates/core/src/commands/press_tests.rs
@@ -149,6 +149,7 @@ fn args(combo: &str, force: bool) -> PressArgs {
PressArgs {
combo: combo.to_owned(),
app: None,
+ window_id: None,
force,
}
}
diff --git a/crates/core/src/commands/press_window_tests.rs b/crates/core/src/commands/press_window_tests.rs
new file mode 100644
index 000000000..550b35365
--- /dev/null
+++ b/crates/core/src/commands/press_window_tests.rs
@@ -0,0 +1,178 @@
+use super::{PressArgs, execute};
+use crate::action_request::ActionRequest;
+use crate::action_result::ActionResult;
+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps};
+use crate::context::CommandContext;
+use crate::{AdapterError, KeyCombo};
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct TwoInstancesAdapter {
+ pressed_pid: Mutex<Option<u32>>,
+ focused_window: Mutex<Option<String>>,
+}
+
+fn instance(pid: u32) -> crate::AppInfo {
+ crate::AppInfo {
+ name: "Electron".into(),
+ pid: crate::ProcessId::new(pid),
+ bundle_id: Some("com.github.Electron".into()),
+ process_instance: Some(format!("generation-{pid}")),
+ presentation: None,
+ }
+}
+
+fn window(pid: u32) -> crate::WindowInfo {
+ crate::WindowInfo {
+ id: format!("w-{pid}"),
+ title: format!("Instance {pid}"),
+ app: "Electron".into(),
+ pid: crate::ProcessId::new(pid),
+ process_instance: Some(format!("generation-{pid}")),
+ bounds: None,
+ state: crate::WindowState {
+ visible: Some(true),
+ ..Default::default()
+ },
+ }
+}
+
+impl ObservationOps for TwoInstancesAdapter {
+ fn list_apps(&self, _deadline: crate::Deadline) -> Result<Vec<crate::AppInfo>, AdapterError> {
+ Ok(vec![instance(41), instance(42)])
+ }
+
+ fn list_windows(
+ &self,
+ _filter: &crate::WindowFilter,
+ _deadline: crate::Deadline,
+ ) -> Result<Vec<crate::WindowInfo>, AdapterError> {
+ let mut second = window(42);
+ second.id = "w-42-prefs".into();
+ second.title = "Preferences".into();
+ Ok(vec![window(41), window(42), second])
+ }
+}
+
+impl ActionOps for TwoInstancesAdapter {
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ _request: ActionRequest,
+ _lease: &crate::InteractionLease,
+ ) -> Result<ActionResult, AdapterError> {
+ panic!("a targeted press must never fall back to global delivery")
+ }
+}
+
+impl InputOps for TwoInstancesAdapter {}
+
+impl SystemOps for TwoInstancesAdapter {
+ crate::adapter::guarded_interaction_lease!();
+
+ fn resolve_window_strict(
+ &self,
+ window: &crate::WindowInfo,
+ _deadline: crate::Deadline,
+ ) -> Result<crate::WindowInfo, AdapterError> {
+ Ok(window.clone())
+ }
+
+ fn focus_window(
+ &self,
+ window: &crate::WindowInfo,
+ _lease: &crate::InteractionLease,
+ ) -> Result<(), AdapterError> {
+ *self.focused_window.lock().unwrap() = Some(window.id.clone());
+ Ok(())
+ }
+
+ fn press_key_for_app(
+ &self,
+ process: crate::ProcessIdentity,
+ _combo: &KeyCombo,
+ _policy: crate::InteractionPolicy,
+ _lease: &crate::InteractionLease,
+ ) -> Result<ActionResult, AdapterError> {
+ *self.pressed_pid.lock().unwrap() = Some(process.pid.get());
+ Ok(ActionResult::delivered_unverified("PressKey"))
+ }
+}
+
+fn press(
+ app: Option<&str>,
+ window_id: Option<&str>,
+ adapter: &TwoInstancesAdapter,
+) -> Result<serde_json::Value, crate::AppError> {
+ press_with(app, window_id, adapter, &CommandContext::default())
+}
+
+fn press_with(
+ app: Option<&str>,
+ window_id: Option<&str>,
+ adapter: &TwoInstancesAdapter,
+ context: &CommandContext,
+) -> Result<serde_json::Value, crate::AppError> {
+ execute(
+ PressArgs {
+ combo: "cmd+k".into(),
+ app: app.map(str::to_owned),
+ window_id: window_id.map(str::to_owned),
+ force: false,
+ },
+ adapter,
+ context,
+ )
+}
+
+#[test]
+fn window_id_reaches_the_instance_that_owns_the_window() {
+ let adapter = TwoInstancesAdapter::default();
+
+ press(None, Some("w-42"), &adapter).unwrap();
+
+ assert_eq!(*adapter.pressed_pid.lock().unwrap(), Some(42));
+}
+
+#[test]
+fn window_id_narrows_an_app_name_shared_by_two_instances() {
+ let adapter = TwoInstancesAdapter::default();
+
+ press(Some("Electron"), Some("w-41"), &adapter).unwrap();
+
+ assert_eq!(*adapter.pressed_pid.lock().unwrap(), Some(41));
+}
+
+#[test]
+fn app_name_alone_stays_ambiguous_across_instances() {
+ let adapter = TwoInstancesAdapter::default();
+
+ let error = press(Some("Electron"), None, &adapter).unwrap_err();
+
+ assert_eq!(error.code(), "AMBIGUOUS_TARGET");
+ assert!(adapter.pressed_pid.lock().unwrap().is_none());
+}
+
+#[test]
+fn unknown_window_id_is_window_not_found() {
+ let adapter = TwoInstancesAdapter::default();
+
+ let error = press(None, Some("w-7"), &adapter).unwrap_err();
+
+ assert_eq!(error.code(), "WINDOW_NOT_FOUND");
+ assert!(adapter.pressed_pid.lock().unwrap().is_none());
+}
+
+#[test]
+fn headed_window_id_focuses_the_named_window_not_another_of_the_instance() {
+ let adapter = TwoInstancesAdapter::default();
+ let context = CommandContext::default().with_headed(true);
+
+ press_with(None, Some("w-42-prefs"), &adapter, &context).unwrap();
+
+ assert_eq!(
+ adapter.focused_window.lock().unwrap().as_deref(),
+ Some("w-42-prefs")
+ );
+ assert_eq!(*adapter.pressed_pid.lock().unwrap(), Some(42));
+}
diff --git a/crates/core/src/commands/wait_element.rs b/crates/core/src/commands/wait_element.rs
index 747cbb2f8..bacc182f2 100644
--- a/crates/core/src/commands/wait_element.rs
+++ b/crates/core/src/commands/wait_element.rs
@@ -74,7 +74,7 @@ pub(crate) fn wait_for_element(
}));
}
}
- Err(err) if is_retryable_wait_error(&err) => {
+ Err(err) if is_retryable_observe_error(&err) => {
last_observed = json!({
"error": err.code.as_str(),
"message": err.message,
@@ -101,6 +101,14 @@ pub(crate) fn wait_for_element(
}
}
+fn is_retryable_observe_error(error: &crate::AdapterError) -> bool {
+ error.is_explicitly_retryable()
+ || matches!(
+ error.code,
+ crate::ErrorCode::Timeout | crate::ErrorCode::ElementNotFound
+ )
+}
+
fn is_retryable_wait_error(error: &crate::AdapterError) -> bool {
error.is_explicitly_retryable()
}
diff --git a/crates/core/src/commands/wait_element_tests.rs b/crates/core/src/commands/wait_element_tests.rs
index 97e0adb18..dc6569298 100644
--- a/crates/core/src/commands/wait_element_tests.rs
+++ b/crates/core/src/commands/wait_element_tests.rs
@@ -208,6 +208,68 @@ fn element_wait_propagates_live_read_errors_after_dropping_handle() {
assert_eq!(adapter.drops.load(Ordering::SeqCst), 1);
}
+struct DeadlineTimeoutPredicateAdapter {
+ polls: Arc<AtomicU32>,
+}
+
+impl ObservationOps for DeadlineTimeoutPredicateAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ fn get_live_state(
+ &self,
+ _handle: &NativeHandle,
+ deadline: crate::Deadline,
+ ) -> Result<Option<ElementState>, AdapterError> {
+ self.polls.fetch_add(1, Ordering::SeqCst);
+ Err(deadline.timeout_error())
+ }
+}
+
+impl ActionOps for DeadlineTimeoutPredicateAdapter {}
+impl InputOps for DeadlineTimeoutPredicateAdapter {}
+impl SystemOps for DeadlineTimeoutPredicateAdapter {}
+
+#[test]
+fn element_wait_wraps_bare_live_read_timeout_in_the_documented_wait_timeout() {
+ let _guard = HomeGuard::new();
+ let snapshot_id = snapshot_with_one_ref();
+ let adapter = DeadlineTimeoutPredicateAdapter {
+ polls: Arc::new(AtomicU32::new(0)),
+ };
+
+ let err = wait_for_element_test(
+ "@e1".into(),
+ Some(snapshot_id),
+ wait_predicate::ElementPredicate::Enabled,
+ 400,
+ &adapter,
+ &crate::context::CommandContext::default(),
+ )
+ .unwrap_err();
+
+ assert_eq!(err.code(), "TIMEOUT");
+ assert!(adapter.polls.load(Ordering::SeqCst) > 1);
+
+ let AppError::Adapter(adapter_err) = err else {
+ panic!("expected adapter error");
+ };
+ let details = adapter_err
+ .details
+ .expect("wait timeout should carry details");
+ assert_eq!(details["kind"], "wait_timeout");
+ assert_eq!(details["ref"], "@e1");
+ assert_eq!(details["predicate"], "enabled");
+ assert_eq!(details["timeout_ms"], 400);
+ assert_eq!(details["last_observed"]["error"], "TIMEOUT");
+ assert_eq!(details["last_observed"]["details"]["kind"], "deadline");
+}
+
#[test]
fn zero_timeout_returns_timeout_before_any_resolution_attempt() {
let _guard = HomeGuard::new();
diff --git a/crates/core/src/headed_focus.rs b/crates/core/src/headed_focus.rs
index e932b4198..f0b9ff0ea 100644
--- a/crates/core/src/headed_focus.rs
+++ b/crates/core/src/headed_focus.rs
@@ -39,7 +39,7 @@ pub(crate) fn focus_process_window(
focus_exact_window(&expected, adapter, context, lease)
}
-fn focus_exact_window(
+pub(crate) fn focus_exact_window(
expected: &WindowInfo,
adapter: &dyn PlatformAdapter,
context: &crate::CommandContext,
diff --git a/crates/core/src/post_action.rs b/crates/core/src/post_action.rs
index 4a2effc9b..277d793b2 100644
--- a/crates/core/src/post_action.rs
+++ b/crates/core/src/post_action.rs
@@ -96,10 +96,7 @@ pub fn execute_verified_action(
return Err(verification_error(
&result,
Some(&observed),
- AdapterError::new(
- ErrorCode::ActionFailed,
- "Post-action state does not match the requested change",
- ),
+ mismatch_error(&action),
));
}
result.post_state = Some(observed.state);
@@ -115,6 +112,20 @@ pub fn execute_verified_action(
Ok(result)
}
+fn mismatch_error(action: &Action) -> AdapterError {
+ let error = AdapterError::new(
+ ErrorCode::ActionFailed,
+ "Post-action state does not match the requested change",
+ );
+ if matches!(action, Action::TypeText(_)) {
+ return error.with_suggestion(
+ "Some fields, often in Chromium and Electron apps, accept typed text without applying it. \
+ Read the field with 'get', then write the full intended value with 'set-value'.",
+ );
+ }
+ error
+}
+
fn secure_value_is_redacted(action: &Action, observed: &LiveElement) -> bool {
action.writes_element_value()
&& observed.state.value.is_none()
diff --git a/crates/core/src/post_action_tests.rs b/crates/core/src/post_action_tests.rs
index efe3e00d3..5b73509f3 100644
--- a/crates/core/src/post_action_tests.rs
+++ b/crates/core/src/post_action_tests.rs
@@ -130,7 +130,16 @@ fn adapter_success_cannot_override_contradictory_fresh_state() {
),
] {
let adapter = adapter(before, after);
+ let typed = matches!(action, Action::TypeText(_));
let error = execute(&adapter, action).unwrap_err();
+ assert_eq!(
+ error
+ .suggestion
+ .as_deref()
+ .unwrap_or("")
+ .contains("set-value"),
+ typed
+ );
assert_eq!(error.code, ErrorCode::ActionFailed);
assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());
assert!(error.details.unwrap()["post_state"].is_object());
diff --git a/crates/macos/src/system/window_ax_state.rs b/crates/macos/src/system/window_ax_state.rs
index 21902c715..07ac38d3a 100644
--- a/crates/macos/src/system/window_ax_state.rs
+++ b/crates/macos/src/system/window_ax_state.rs
@@ -120,25 +120,24 @@ fn focused_identity(
return Ok(None);
};
let role = crate::tree::surface_read::string(&focused, "AXRole", deadline)?;
- let window = if role.as_deref() == Some("AXWindow") {
- focused
- } else if role.as_deref().is_some_and(is_transient_surface_role) {
- let Some(window) = crate::tree::surface_read::element(&focused, "AXWindow", deadline)?
- else {
- return Ok(None);
- };
- if crate::tree::surface_read::string(&window, "AXRole", deadline)?.as_deref()
- != Some("AXWindow")
- {
+ let window = match focused_role_kind(role.as_deref()) {
+ FocusedRoleKind::Window => focused,
+ FocusedRoleKind::TransientSurface => {
+ let Some(window) = crate::tree::surface_read::element(&focused, "AXWindow", deadline)?
+ else {
+ return Ok(None);
+ };
+ if crate::tree::surface_read::string(&window, "AXRole", deadline)?.as_deref()
+ != Some("AXWindow")
+ {
+ return Ok(None);
+ }
+ window
+ }
+ FocusedRoleKind::NotAWindow => {
+ tracing::debug!(pid, ?role, "focused accessibility object is not a window");
return Ok(None);
}
- window
- } else {
- return Err(AdapterError::new(
- ErrorCode::AppUnresponsive,
- "Focused accessibility object was not a window",
- )
- .with_details(serde_json::json!({ "pid": pid, "complete": false, "role": role })));
};
let title = crate::tree::surface_read::string(&window, "AXTitle", deadline)?;
let number = match crate::system::window_resolve::ax_window_id_with_deadline(&window, deadline)
@@ -154,9 +153,26 @@ fn is_transient_surface_role(role: &str) -> bool {
matches!(role, "AXSheet" | "AXDialog" | "AXAlert" | "AXPopover")
}
+#[derive(Debug, PartialEq)]
+enum FocusedRoleKind {
+ Window,
+ TransientSurface,
+ NotAWindow,
+}
+
+fn focused_role_kind(role: Option<&str>) -> FocusedRoleKind {
+ match role {
+ Some("AXWindow") => FocusedRoleKind::Window,
+ Some(role) if is_transient_surface_role(role) => FocusedRoleKind::TransientSurface,
+ _ => FocusedRoleKind::NotAWindow,
+ }
+}
+
#[cfg(test)]
mod tests {
- use super::{is_transient_surface_role, label_accessibility};
+ use super::{
+ FocusedRoleKind, focused_role_kind, is_transient_surface_role, label_accessibility,
+ };
use agent_desktop_core::{ProcessId, WindowInfo, WindowState};
use rustc_hash::FxHashSet;
@@ -168,6 +184,20 @@ mod tests {
assert!(!is_transient_surface_role("AXButton"));
}
+ #[test]
+ fn a_focused_desktop_is_no_focused_window_rather_than_an_error() {
+ assert_eq!(focused_role_kind(Some("AXWindow")), FocusedRoleKind::Window);
+ assert_eq!(
+ focused_role_kind(Some("AXSheet")),
+ FocusedRoleKind::TransientSurface
+ );
+ assert_eq!(
+ focused_role_kind(Some("AXScrollArea")),
+ FocusedRoleKind::NotAWindow
+ );
+ assert_eq!(focused_role_kind(None), FocusedRoleKind::NotAWindow);
+ }
+
#[test]
fn failed_pid_probe_keeps_unknown_window_selectable() {
let mut windows = vec![window(10, "w-1"), window(20, "w-2")];
diff --git a/crates/macos/src/system/window_inventory_global.rs b/crates/macos/src/system/window_inventory_global.rs
index 642e0c764..93572ff66 100644
--- a/crates/macos/src/system/window_inventory_global.rs
+++ b/crates/macos/src/system/window_inventory_global.rs
@@ -134,11 +134,14 @@ pub(super) fn assemble_global_windows<S: OwnerSnapshotView>(
Some(pid) => Some(read_frontmost(pid).map_err(frontmost_read_error)?),
None => None,
};
+ let focus_reported = focus_state
+ .as_ref()
+ .is_some_and(|state| state.focused.is_some());
let focused_window = match matching_focus_windows(&records, frontmost_pid, focus_state.as_ref())
{
FocusJoin::TitleAmbiguous => None,
FocusJoin::Windows(windows) => {
- if frontmost_window_owner.is_some() && windows.len() != 1 {
+ if frontmost_window_owner.is_some() && focus_reported && windows.len() != 1 {
return Err(focus_join_error(frontmost_pid, windows.len()));
}
windows.first().copied()
diff --git a/crates/macos/src/system/window_inventory_global_focus_tests.rs b/crates/macos/src/system/window_inventory_global_focus_tests.rs
new file mode 100644
index 000000000..9d7b7d51b
--- /dev/null
+++ b/crates/macos/src/system/window_inventory_global_focus_tests.rs
@@ -0,0 +1,24 @@
+use super::*;
+
+#[test]
+fn frontmost_owner_reporting_no_focused_window_lists_windows_unfocused() {
+ let owners = owners(&[(10, 100.0), (20, 200.0)], Some(10));
+ let records = vec![record(10, 1, "Front"), record(20, 2, "Background")];
+
+ let windows = assemble_global_windows(records, &owners, false, |_| Ok(ax_state(None))).unwrap();
+
+ assert_eq!(windows.len(), 2);
+ assert!(windows.iter().all(|window| !window.state.is_focused));
+}
+
+#[test]
+fn focused_only_is_empty_when_the_frontmost_owner_reports_no_focused_window() {
+ let owners = owners(&[(10, 100.0)], Some(10));
+
+ let windows = assemble_global_windows(vec![record(10, 1, "Front")], &owners, true, |_| {
+ Ok(ax_state(None))
+ })
+ .unwrap();
+
+ assert!(windows.is_empty());
+}
diff --git a/crates/macos/src/system/window_inventory_global_tests.rs b/crates/macos/src/system/window_inventory_global_tests.rs
index 6706ababe..34a9da464 100644
--- a/crates/macos/src/system/window_inventory_global_tests.rs
+++ b/crates/macos/src/system/window_inventory_global_tests.rs
@@ -2,6 +2,9 @@ use super::*;
use agent_desktop_core::Rect;
use rustc_hash::FxHashMap;
+#[path = "window_inventory_global_focus_tests.rs"]
+mod focus;
+
#[derive(Clone)]
struct Owners {
launches: FxHashMap<i32, Option<f64>>,
diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.md
index eb813ab29..c4c10faa5 100644
--- a/skills/agent-desktop/references/commands-interaction.md
+++ b/skills/agent-desktop/references/commands-interaction.md
@@ -73,7 +73,7 @@ agent-desktop click @s8f3k2p9:e5 --wait-for-gone "progressindicator" --wait-time
**Supported commands:** `snapshot`, `press`, and all 18 ref-resolving actions (`click`, `type`, `set-value`, `scroll`, `hover`, `drag`, …). Other commands (`find`, `launch`, …) return `INVALID_ARGS`. Workaround: `snapshot --app Foo -w "button:Login"`.
-**Post-action waits** for ref actions poll the **acted-on ref's own window** (`entry.source_window_id`, scoped to `entry.source_app`). For `press`, `--app` scopes the observation to that app; without it, observation uses the frontmost app. The action result is preserved under `after_action` in the returned envelope.
+**Post-action waits** for ref actions poll the **acted-on ref's own window** (`entry.source_window_id`, scoped to `entry.source_app`). For `press`, `--app` scopes the observation to that app and `--window-id` to that window; without either, observation uses the frontmost app. 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.
@@ -243,11 +243,13 @@ agent-desktop press cmd+shift+z
agent-desktop press shift+tab
agent-desktop press f5
agent-desktop press cmd+a --app "TextEdit"
+agent-desktop --headed press cmd+k --window-id w-4521
```
| Flag | Description |
|------|-------------|
| `--app` | Target application; key delivery is PID-targeted without focusing the app, and `--headed` additionally focuses its exact window first |
+| `--window-id` | Target the application instance that owns this window (id from `list-windows`). Use it when several running instances share one name — two Electron dev builds, two copies of an app — where `--app` alone is `AMBIGUOUS_TARGET`. Combine with `--app` to scope the window lookup |
With `--app`, `press` sends the keystroke to the app's process; only `return` and `escape` use the focused element's advertised `AXConfirm` or `AXCancel` instead. Printable keys, including `space`, always arrive as keystrokes, and delivery requires the app to report a focused element. Under `--headed`, a modified combo that matches a menu item's shortcut performs that item with `AXPress`. Headless `press` never performs menu items: an inactive app runs a menu action without a focused window, and some apps, such as VS Code, open and activate a new window in response. To run a menu command without keyboard delivery, find it with `--surface menubar` and `click` its ref. `data.steps` reports which route delivered the key: `CGEventPostToPid`, `AXConfirm`, `AXCancel`, or `AXPress menu item`.
diff --git a/src/cli_args/actions.rs b/src/cli_args/actions.rs
index a60ca42a8..cb2ca66e2 100644
--- a/src/cli_args/actions.rs
+++ b/src/cli_args/actions.rs
@@ -146,6 +146,13 @@ pub(crate) struct PressArgs {
help = "Target application name; keys go to its process without focusing it (--headed focuses its window first)"
)]
pub app: Option<String>,
+ #[arg(
+ long = "window-id",
+ help = "Target the application instance that owns this window (from list-windows); \
+ use it when several instances share one name"
+ )]
+ #[serde(default)]
+ pub window_id: Option<String>,
#[arg(
long,
help = "Send the combo even if the adapter flags it as a dangerous shortcut"
diff --git a/src/dispatch/cursor_overlay_lifecycle_tests.rs b/src/dispatch/cursor_overlay_lifecycle_tests.rs
index 60356922e..99d81349e 100644
--- a/src/dispatch/cursor_overlay_lifecycle_tests.rs
+++ b/src/dispatch/cursor_overlay_lifecycle_tests.rs
@@ -180,6 +180,7 @@ fn mutating_keyboard_and_clipboard_commands_re_show_cursor_overlay() {
Commands::Press(PressArgs {
combo: "a".into(),
app: None,
+ window_id: None,
force: false,
}),
&adapter,
@@ -264,6 +265,7 @@ fn cursor_overlay_show_fires_even_when_the_mutating_command_errors() {
Commands::Press(PressArgs {
combo: "cmd+q".into(),
app: None,
+ window_id: None,
force: false,
}),
&adapter,
diff --git a/src/dispatch/keyboard_mouse.rs b/src/dispatch/keyboard_mouse.rs
index f49fb674a..fe5f339f1 100644
--- a/src/dispatch/keyboard_mouse.rs
+++ b/src/dispatch/keyboard_mouse.rs
@@ -26,6 +26,7 @@ pub(super) fn press(
press_command::PressArgs {
combo: args.combo,
app: args.app,
+ window_id: args.window_id,
force: args.force,
},
adapter,