Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): verify a raised window on its display, not global order (#3785)

Will Bogusz0a91a118675b
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index f32bda3eb5..7cc8781391 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -200,7 +200,7 @@ Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; taskkill
### `bring_to_front`
-Persistently activate an app and leave it in the foreground. Most input does not need this; use it only for a focus-proxy surface that must remain foreground across interactions. With window_id, success means the exact ordinary macOS window was independently verified as the focused window and first in WindowServer layer-0 order. Request acceptance alone is reported as a partial result, never as activation. This DOES steal foreground.
+Persistently activate an app and leave it in the foreground. Most input does not need this; use it only for a focus-proxy surface that must remain foreground across interactions. With window_id, success means the exact ordinary macOS window was independently verified as the frontmost process's focused window and the front window of that process on the display it sits on. `exact_window_effect.frontmost_ordinary` additionally reports whether it is first in the global WindowServer layer-0 order; another application (an always-raised utility window, another display's front window) can hold that spot without the requested window losing keyboard focus, so it is reported and not required. Request acceptance alone is reported as a partial result, never as activation. This DOES steal foreground and does NOT restore the previously frontmost application.
**Arguments:**
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs
index ca3e7c992d..09b78b7ca9 100644
--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs
@@ -26,7 +26,7 @@
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
-use std::time::Duration;
+use std::time::{Duration, Instant};
use cua_driver_testkit::ax::{element_index_by_id, element_index_containing, has_id, looks_empty};
use cua_driver_testkit::e2e::{
@@ -131,6 +131,58 @@ fn snapshot_elements(driver: &mut McpDriver, pid: u32, window_id: u64) -> ToolRe
)
}
+struct FrontWindow {
+ window_id: u64,
+ z_index: i64,
+ app_name: String,
+ title: String,
+}
+
+impl std::fmt::Display for FrontWindow {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "window {} (z_index {}, {} {:?})",
+ self.window_id, self.z_index, self.app_name, self.title
+ )
+ }
+}
+
+/// The window WindowServer ranks first in the global layer-0 order, read from
+/// `list_windows` (`z_index`: higher values are closer to the front) so the
+/// observation does not depend on the tool under test.
+fn front_layer_zero_window(driver: &mut McpDriver) -> Option<FrontWindow> {
+ let response = driver.call("list_windows", serde_json::json!({"on_screen_only": true}));
+ response.structured()["windows"]
+ .as_array()?
+ .iter()
+ .filter(|window| window["layer"].as_i64() == Some(0))
+ .filter_map(|window| {
+ Some(FrontWindow {
+ window_id: window["window_id"].as_u64()?,
+ z_index: window["z_index"].as_i64()?,
+ app_name: window["app_name"].as_str().unwrap_or_default().to_owned(),
+ title: window["title"].as_str().unwrap_or_default().to_owned(),
+ })
+ })
+ .max_by_key(|window| window.z_index)
+}
+
+/// Poll the global layer-0 order until `window_id` leads it, up to 3s, and
+/// return the last observation so a caller can name whatever leads instead.
+fn await_front_layer_zero_window(driver: &mut McpDriver, window_id: u64) -> Option<FrontWindow> {
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ let front = front_layer_zero_window(driver);
+ if front.as_ref().map(|window| window.window_id) == Some(window_id)
+ || Instant::now() >= deadline
+ {
+ return front;
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
fn element_token_by_id(snapshot: &ToolResponse, identifier: &str) -> String {
let index = element_index_by_id(snapshot.tree_text(), identifier)
.unwrap_or_else(|| panic!("{identifier} element_index not found"));
@@ -333,20 +385,20 @@ fn harness_appkit_exact_activation_with_agent_cursor() {
#[test]
#[ignore]
-fn harness_appkit_exact_activation_refuses_competing_window() {
+fn harness_appkit_exact_activation_ignores_competing_application_window() {
let mut case = native_foreground_case(
"appkit",
"exact_activation_competing_window",
Targeting::NotApplicable,
DriverRoute::WindowState,
- )
- .expecting_refusal(vec![RefusalCode::BringToFrontExactWindowUnverified]);
+ );
case.oracles.push(OracleKind::Cursor);
run_case(case, |pid, wid, driver| {
let competitor = Harness::launch_with_options(None, None, true);
let (competing_wid, _) = driver
.find_window(competitor.pid as i64, "CuaTestHarness AppKit")
.expect("find competing ordinary window");
+ assert_ne!(competing_wid, u64::from(wid));
let snapshot = snapshot_elements(driver, pid, wid);
assert!(!snapshot.is_error(), "target snapshot: {}", snapshot.text());
let observer = NativeObserver::new();
@@ -355,38 +407,47 @@ fn harness_appkit_exact_activation_refuses_competing_window() {
native_id: wid,
};
let before = observer.snapshot(target).expect("observe competing window");
+ let front = await_front_layer_zero_window(driver, competing_wid);
+ let leader = front
+ .as_ref()
+ .map(FrontWindow::to_string)
+ .unwrap_or_else(|| "no on-screen layer-0 window".to_owned());
+ assert_eq!(
+ front.map(|window| window.window_id),
+ Some(competing_wid),
+ "competing window {competing_wid} must lead the global layer-0 order before \
+ bring_to_front; list_windows ranks {leader} first"
+ );
let response = driver.call(
"bring_to_front",
serde_json::json!({"pid": pid, "window_id": wid}),
);
assert!(
- response.is_error(),
- "competing window must prevent verification"
+ !response.is_error(),
+ "another application ordering its window front must not unverify activation: {}",
+ response.raw
);
assert_eq!(
response.structured()["code"],
- "bring_to_front_exact_window_unverified"
+ "bring_to_front_exact_window_verified"
);
- assert_eq!(response.structured()["activated"], false);
+ assert_eq!(response.structured()["activated"], true);
assert_eq!(response.structured()["process_activated"], true);
assert_eq!(
response.structured()["exact_window_effect"]["focused"],
true
);
assert_eq!(
- response.structured()["observed"]["frontmost_ordinary_window_id"].as_u64(),
- Some(competing_wid)
+ response.structured()["exact_window_effect"]["front_in_process_on_display"],
+ true
+ );
+ assert_eq!(
+ response.structured()["observed"]["focused_window_id"].as_u64(),
+ Some(u64::from(wid))
);
- let after = observer
- .snapshot(target)
- .expect("observe refused activation");
+ let after = observer.snapshot(target).expect("observe activated target");
assert_eq!(after.cursor_pos, before.cursor_pos, "real pointer moved");
- Observation::refused(
- RefusalCode::BringToFrontExactWindowUnverified,
- vec![OracleKind::FixtureState, OracleKind::Cursor],
- response.text(),
- Evidence::default(),
- )
+ Observation::delivered_with_fixture_state(vec![OracleKind::Cursor])
});
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs
index 1a1f2614ff..aa01ed4f06 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs
@@ -3,13 +3,14 @@
//! This is the explicit persistent-foreground escape hatch for focus-proxy
//! applications. A successful native request is only a request receipt: when
//! an exact `window_id` is supplied, the tool independently verifies the
-//! process, semantic key window, and WindowServer layer-0 order before it says
-//! `activated: true`.
+//! process, semantic key window, and per-display front position before it
+//! says `activated: true`.
use std::time::{Duration, Instant};
use async_trait::async_trait;
use core_foundation::base::{CFRelease, CFTypeRef};
+use core_graphics::display::CGDisplay;
use cua_driver_core::{
protocol::ToolResult,
tool::{Tool, ToolDef},
@@ -21,6 +22,7 @@ use crate::ax::bindings::{
ax_get_window_id, copy_ax_windows, perform_action, set_bool_attr_true,
AXUIElementCreateApplication,
};
+use crate::windows::{WindowBounds, WindowInfo};
pub struct BringToFrontTool;
@@ -36,9 +38,15 @@ fn def() -> &'static ToolDef {
description: "Persistently activate an app and leave it in the foreground. Most input \
does not need this; use it only for a focus-proxy surface that must remain \
foreground across interactions. With window_id, success means the exact ordinary \
- macOS window was independently verified as the focused window and first in \
- WindowServer layer-0 order. Request acceptance alone is reported as a partial \
- result, never as activation. This DOES steal foreground."
+ macOS window was independently verified as the frontmost process's focused window \
+ and the front window of that process on the display it sits on. \
+ `exact_window_effect.frontmost_ordinary` additionally reports whether it is first \
+ in the global WindowServer layer-0 order; another application (an always-raised \
+ utility window, another display's front window) can hold that spot without the \
+ requested window losing keyboard focus, so it is reported and not required. \
+ Request acceptance alone is reported as a partial \
+ result, never as activation. This DOES steal foreground and does NOT restore the \
+ previously frontmost application."
.into(),
input_schema: json!({
"type": "object",
@@ -62,6 +70,7 @@ struct ExactWindowObservation {
front_process_matches_target: Option<bool>,
focused_window_id: Option<u32>,
frontmost_ordinary_window_id: Option<u32>,
+ process_front_window_on_display: Option<u32>,
target_visible_ordinary: bool,
}
@@ -82,6 +91,10 @@ impl ExactWindowObservation {
self.focused_window_id == Some(window_id)
}
+ fn exact_window_front_in_process_on_display(self, window_id: u32) -> bool {
+ self.target_visible_ordinary && self.process_front_window_on_display == Some(window_id)
+ }
+
fn exact_window_frontmost_ordinary(self, window_id: u32) -> bool {
self.target_visible_ordinary && self.frontmost_ordinary_window_id == Some(window_id)
}
@@ -89,7 +102,7 @@ impl ExactWindowObservation {
fn exact_postcondition(self, pid: i32, window_id: u32) -> bool {
self.process_activated(pid)
&& self.exact_window_focused(window_id)
- && self.exact_window_frontmost_ordinary(window_id)
+ && self.exact_window_front_in_process_on_display(window_id)
}
}
@@ -111,7 +124,7 @@ fn classify_exact_outcome(
} else if request_accepted
|| observation.process_activated(pid)
|| observation.exact_window_focused(window_id)
- || observation.exact_window_frontmost_ordinary(window_id)
+ || observation.exact_window_front_in_process_on_display(window_id)
{
ExactOutcome::Partial
} else {
@@ -119,6 +132,61 @@ fn classify_exact_outcome(
}
}
+fn active_display_bounds() -> Vec<WindowBounds> {
+ let Ok(displays) = CGDisplay::active_displays() else {
+ return Vec::new();
+ };
+ displays
+ .into_iter()
+ .map(|display| {
+ let bounds = CGDisplay::new(display).bounds();
+ WindowBounds {
+ x: bounds.origin.x,
+ y: bounds.origin.y,
+ width: bounds.size.width,
+ height: bounds.size.height,
+ }
+ })
+ .collect()
+}
+
+fn overlap_area(left: &WindowBounds, right: &WindowBounds) -> f64 {
+ let width = (left.x + left.width).min(right.x + right.width) - left.x.max(right.x);
+ let height = (left.y + left.height).min(right.y + right.height) - left.y.max(right.y);
+ if width > 0.0 && height > 0.0 {
+ width * height
+ } else {
+ 0.0
+ }
+}
+
+fn display_holding(bounds: &WindowBounds, displays: &[WindowBounds]) -> Option<usize> {
+ displays
+ .iter()
+ .enumerate()
+ .map(|(index, display)| (index, overlap_area(bounds, display)))
+ .filter(|(_, area)| *area > 0.0)
+ .max_by(|(_, left), (_, right)| left.total_cmp(right))
+ .map(|(index, _)| index)
+}
+
+fn front_window_of_process_on_target_display(
+ windows: &[WindowInfo],
+ displays: &[WindowBounds],
+ pid: i32,
+ window_id: u32,
+) -> Option<u32> {
+ let target = windows.iter().find(|w| w.window_id == window_id)?;
+ let target_display = display_holding(&target.bounds, displays);
+ windows
+ .iter()
+ .filter(|window| {
+ window.pid == pid && display_holding(&window.bounds, displays) == target_display
+ })
+ .max_by_key(|window| window.z_index)
+ .map(|window| window.window_id)
+}
+
fn observe_exact_window(pid: i32, window_id: u32) -> ExactWindowObservation {
let mut windows = crate::windows::visible_windows();
windows.retain(|window| !crate::cursor::overlay::is_overlay_window(window.window_id));
@@ -129,11 +197,18 @@ fn observe_exact_window(pid: i32, window_id: u32) -> ExactWindowObservation {
.iter()
.max_by_key(|window| window.z_index)
.map(|window| window.window_id);
+ let process_front_window_on_display = front_window_of_process_on_target_display(
+ &windows,
+ &active_display_bounds(),
+ pid,
+ window_id,
+ );
ExactWindowObservation {
workspace_frontmost_pid: crate::apps::frontmost_pid(),
front_process_matches_target: crate::input::skylight::front_process_matches(pid, window_id),
focused_window_id: crate::ax::bindings::focused_window_id_of_pid(pid),
frontmost_ordinary_window_id,
+ process_front_window_on_display,
target_visible_ordinary,
}
}
@@ -200,6 +275,8 @@ fn exact_result(
let process_activated = observation.process_activated(pid);
let frontmost_pid = observation.frontmost_pid(pid);
let exact_window_focused = observation.exact_window_focused(window_id);
+ let exact_window_front_on_display =
+ observation.exact_window_front_in_process_on_display(window_id);
let exact_window_frontmost_ordinary = observation.exact_window_frontmost_ordinary(window_id);
let status = match outcome {
ExactOutcome::Activated => "activated",
@@ -218,6 +295,7 @@ fn exact_result(
"exact_window_effect": {
"verified": activated,
"focused": exact_window_focused,
+ "front_in_process_on_display": exact_window_front_on_display,
"frontmost_ordinary": exact_window_frontmost_ordinary,
"target_visible_ordinary": observation.target_visible_ordinary,
},
@@ -227,6 +305,7 @@ fn exact_result(
"front_process_matches_target": observation.front_process_matches_target,
"focused_window_id": observation.focused_window_id,
"frontmost_ordinary_window_id": observation.frontmost_ordinary_window_id,
+ "process_front_window_on_display": observation.process_front_window_on_display,
}
});
if activated {
@@ -237,9 +316,10 @@ fn exact_result(
} else {
ToolResult::error(format!(
"bring_to_front: exact window {window_id} for pid {pid} was not verified \
- as frontmost and focused (request_accepted={request_accepted}, \
+ as the frontmost process's focused window and the front window of that process \
+ on its display (request_accepted={request_accepted}, \
process_activated={process_activated}, focused={exact_window_focused}, \
- frontmost_ordinary={exact_window_frontmost_ordinary})."
+ front_in_process_on_display={exact_window_front_on_display})."
))
.with_structured(structured)
}
@@ -437,12 +517,138 @@ mod tests {
front_process_matches_target,
focused_window_id,
frontmost_ordinary_window_id,
+ process_front_window_on_display: frontmost_ordinary_window_id,
target_visible_ordinary,
}
}
+ fn contested_observation(
+ focused_window_id: Option<u32>,
+ global_front_window_id: Option<u32>,
+ process_front_window_on_display: Option<u32>,
+ ) -> ExactWindowObservation {
+ ExactWindowObservation {
+ workspace_frontmost_pid: Some(42),
+ front_process_matches_target: Some(true),
+ focused_window_id,
+ frontmost_ordinary_window_id: global_front_window_id,
+ process_front_window_on_display,
+ target_visible_ordinary: true,
+ }
+ }
+
+ fn side_by_side_displays() -> Vec<WindowBounds> {
+ vec![
+ WindowBounds {
+ x: 0.0,
+ y: 0.0,
+ width: 1920.0,
+ height: 1080.0,
+ },
+ WindowBounds {
+ x: 1920.0,
+ y: 0.0,
+ width: 1920.0,
+ height: 1080.0,
+ },
+ ]
+ }
+
+ fn window(window_id: u32, pid: i32, z_index: usize, x: f64) -> WindowInfo {
+ WindowInfo {
+ window_id,
+ pid,
+ app_name: "Target".into(),
+ title: format!("window {window_id}"),
+ bounds: WindowBounds {
+ x,
+ y: 100.0,
+ width: 800.0,
+ height: 600.0,
+ },
+ layer: 0,
+ z_index,
+ is_on_screen: true,
+ current_space_id: None,
+ on_current_space: Some(true),
+ space_ids: None,
+ }
+ }
+
+ #[test]
+ fn another_applications_window_on_top_does_not_unverify_the_reveal() {
+ let contested = contested_observation(Some(7), Some(900), Some(7));
+ assert_eq!(
+ classify_exact_outcome(true, 42, 7, contested),
+ ExactOutcome::Activated
+ );
+ let structured = exact_result(42, 7, "skylight_process_exact_cocoa_ax", true, contested)
+ .structured_content
+ .expect("structured result");
+ assert_eq!(structured["activated"], true);
+ assert_eq!(
+ structured["exact_window_effect"]["front_in_process_on_display"],
+ true
+ );
+ assert_eq!(
+ structured["exact_window_effect"]["frontmost_ordinary"],
+ false
+ );
+ assert_eq!(structured["observed"]["process_front_window_on_display"], 7);
+ assert_eq!(structured["observed"]["frontmost_ordinary_window_id"], 900);
+ }
+
+ #[test]
+ fn a_sibling_window_of_the_same_application_in_front_is_only_partial() {
+ assert_eq!(
+ classify_exact_outcome(
+ true,
+ 42,
+ 7,
+ contested_observation(Some(7), Some(8), Some(8))
+ ),
+ ExactOutcome::Partial
+ );
+ }
+
+ #[test]
+ fn a_sibling_in_front_on_another_display_leaves_the_target_front_where_it_sits() {
+ let windows = vec![window(7, 42, 10, 100.0), window(8, 42, 30, 2000.0)];
+ let displays = side_by_side_displays();
+ assert_eq!(
+ front_window_of_process_on_target_display(&windows, &displays, 42, 7),
+ Some(7)
+ );
+ assert_eq!(
+ front_window_of_process_on_target_display(&windows, &displays, 42, 8),
+ Some(8)
+ );
+ }
+
+ #[test]
+ fn a_sibling_in_front_on_the_same_display_takes_the_front_position() {
+ let windows = vec![
+ window(7, 42, 10, 100.0),
+ window(8, 42, 30, 500.0),
+ window(9, 99, 40, 200.0),
+ ];
+ assert_eq!(
+ front_window_of_process_on_target_display(&windows, &side_by_side_displays(), 42, 7),
+ Some(8)
+ );
+ }
+
+ #[test]
+ fn without_display_bounds_every_window_of_the_process_competes() {
+ let windows = vec![window(7, 42, 10, 100.0), window(8, 42, 30, 2000.0)];
+ assert_eq!(
+ front_window_of_process_on_target_display(&windows, &[], 42, 7),
+ Some(8)
+ );
+ }
+
#[test]
- fn exact_success_requires_process_focus_and_layer_zero_order() {
+ fn exact_success_requires_process_focus_and_front_position_on_its_display() {
assert_eq!(
classify_exact_outcome(
true,
diff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.sh
index 19006f5c33..2e895411f8 100755
--- a/scripts/ci/macos/run-rust-e2e.sh
+++ b/scripts/ci/macos/run-rust-e2e.sh
@@ -359,7 +359,7 @@ if [[ "${SUITE}" == native || "${SUITE}" == all ]]; then
harness_appkit_counter_px_background \
harness_appkit_px_background_press_key_reports_honest_delivery_truth \
harness_appkit_exact_activation_with_agent_cursor \
- harness_appkit_exact_activation_refuses_competing_window \
+ harness_appkit_exact_activation_ignores_competing_application_window \
harness_appkit_foreground_single_click_has_one_ordered_native_pair \
harness_appkit_right_click_px_foreground \
harness_appkit_right_click_px_background \