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): exclude cursor overlay from foreground verification (#3704)

injaneity44c9d1f6d5c9
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
index 2ef1c2787f..d789a97894 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
@@ -299,6 +299,7 @@ pub enum OracleKind {
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RefusalCode {
+ BringToFrontExactWindowUnverified,
BackgroundUnavailable,
BackgroundOccluded,
BackgroundUipiBlocked,
@@ -321,6 +322,9 @@ pub enum RefusalCode {
impl RefusalCode {
pub fn from_driver_code(code: &str) -> Option<Self> {
match code {
+ "bring_to_front_exact_window_unverified" => {
+ Some(Self::BringToFrontExactWindowUnverified)
+ }
"background_unavailable" => Some(Self::BackgroundUnavailable),
"background_occluded" => Some(Self::BackgroundOccluded),
"background_uipi_blocked" => Some(Self::BackgroundUipiBlocked),
@@ -572,21 +576,30 @@ impl CaseSpec {
return Err(format!("{}: no external oracle declared", self.cell_id));
}
if let ContractExpectation::Refuse { allowed_codes } = &self.expected_behavior {
- if self.delivery != Delivery::Background {
+ let exact_activation_refusal = self.delivery == Delivery::Foreground
+ && self.scope == Scope::Window
+ && self.driver_route == DriverRoute::WindowState
+ && allowed_codes == &[RefusalCode::BringToFrontExactWindowUnverified];
+ if self.delivery != Delivery::Background && !exact_activation_refusal {
return Err(format!(
- "{}: only background delivery may declare refusal",
+ "{}: only background delivery or exact-window activation may declare refusal",
self.cell_id
));
}
if allowed_codes.is_empty() {
return Err(format!("{}: refusal has no allowed code", self.cell_id));
}
- for required in [
- OracleKind::Focus,
- OracleKind::ZOrder,
- OracleKind::NoLeakedInput,
- ] {
- if !self.oracles.contains(&required) {
+ let required_oracles: &[OracleKind] = if exact_activation_refusal {
+ &[OracleKind::FixtureState]
+ } else {
+ &[
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ]
+ };
+ for required in required_oracles {
+ if !self.oracles.contains(required) {
return Err(format!(
"{}: refusal is missing {:?} oracle",
self.cell_id, required
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs
index 2a2092bf16..610c0d833d 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs
@@ -33,7 +33,7 @@ use cua_driver_testkit::e2e::{
execute_case, native_background_case, native_foreground_case, native_readonly_case,
recording_evidence, DriverRoute, Evidence, Observation, OracleKind, RefusalCode, Targeting,
};
-use cua_driver_testkit::observer::TargetWindow;
+use cua_driver_testkit::observer::{NativeObserver, ObserverBackend, TargetWindow};
use cua_driver_testkit::sentinel::run_with_background_oracles;
use cua_driver_testkit::{Driver, McpDriver, ToolResponse};
@@ -70,6 +70,14 @@ impl Harness {
}
fn launch_with_oracles(command_oracle: Option<&Path>, pointer_oracle: Option<&Path>) -> Self {
+ Self::launch_with_options(command_oracle, pointer_oracle, false)
+ }
+
+ fn launch_with_options(
+ command_oracle: Option<&Path>,
+ pointer_oracle: Option<&Path>,
+ keep_ordered_front: bool,
+ ) -> Self {
let exe = harness_exe();
assert!(
exe.exists(),
@@ -86,6 +94,9 @@ impl Harness {
if let Some(path) = pointer_oracle {
command.env("CUA_APPKIT_POINTER_ORACLE", path);
}
+ if keep_ordered_front {
+ command.env("CUA_APPKIT_KEEP_ORDERED_FRONT", "1");
+ }
let app = command
.spawn()
.unwrap_or_else(|error| panic!("launch AppKit harness {exe:?}: {error}"));
@@ -216,6 +227,166 @@ fn run_background_case_targeting(
// ── tests ────────────────────────────────────────────────────────────────────
+#[test]
+#[ignore]
+fn harness_appkit_exact_activation_with_agent_cursor() {
+ let mut case = native_foreground_case(
+ "appkit",
+ "exact_activation_with_agent_cursor",
+ Targeting::NotApplicable,
+ DriverRoute::WindowState,
+ );
+ case.oracles.extend([OracleKind::Focus, OracleKind::Cursor]);
+ run_case(case, |pid, wid, driver| {
+ let snapshot = snapshot_elements(driver, pid, wid);
+ assert!(!snapshot.is_error(), "snapshot: {}", snapshot.text());
+ let target = TargetWindow {
+ pid,
+ native_id: wid,
+ };
+ let observer = NativeObserver::new();
+ let before = observer.snapshot(target).expect("observe native desktop");
+ let socket = std::env::var("CUA_E2E_MACOS_DAEMON_SOCKET")
+ .expect("canonical installed daemon socket");
+ let mut peer = McpDriver::spawn_daemon_proxy_unrecorded(&socket)
+ .expect("start concurrent cursor session");
+ let verifies_target = |response: &ToolResponse| {
+ let state = response.structured();
+ !response.is_error()
+ && state["activated"] == true
+ && state["observed"]["focused_window_id"].as_u64() == Some(wid)
+ && state["observed"]["frontmost_ordinary_window_id"].as_u64() == Some(wid)
+ && state["observed"]["frontmost_pid"].as_u64() == Some(u64::from(pid))
+ };
+ let stopped = std::sync::atomic::AtomicBool::new(false);
+ let (ready, started) = std::sync::mpsc::sync_channel(1);
+ let activated = std::thread::scope(|scope| {
+ let moving = scope.spawn(|| {
+ let snapshot = snapshot_elements(&mut peer, pid, wid);
+ assert!(!snapshot.is_error(), "peer snapshot: {}", snapshot.text());
+ let motion = peer.call(
+ "set_agent_cursor_motion",
+ serde_json::json!({"idle_hide_ms": 0, "glide_duration_ms": 0}),
+ );
+ assert!(!motion.is_error(), "cursor motion: {}", motion.text());
+ let deadline = std::time::Instant::now() + Duration::from_secs(60);
+ let mut first = true;
+ let mut x = 120;
+ while !stopped.load(std::sync::atomic::Ordering::Relaxed)
+ && std::time::Instant::now() < deadline
+ {
+ let moved = peer.call(
+ "move_cursor",
+ serde_json::json!({
+ "target": {"kind": "window", "pid": pid, "window_id": wid},
+ "x": x,
+ "y": 100
+ }),
+ );
+ assert!(!moved.is_error(), "agent cursor: {}", moved.text());
+ if first {
+ ready.send(()).expect("cursor readiness");
+ first = false;
+ }
+ x = if x == 120 { 121 } else { 120 };
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ assert!(
+ stopped.load(std::sync::atomic::Ordering::Relaxed),
+ "cursor producer expired before the activation interval completed"
+ );
+ });
+ started
+ .recv_timeout(Duration::from_secs(15))
+ .expect("live cursor ready");
+ let mut result = driver.call(
+ "bring_to_front",
+ serde_json::json!({"pid": pid, "window_id": wid}),
+ );
+ for _ in 1..20 {
+ if !verifies_target(&result) {
+ break;
+ }
+ result = driver.call(
+ "bring_to_front",
+ serde_json::json!({"pid": pid, "window_id": wid}),
+ );
+ }
+ stopped.store(true, std::sync::atomic::Ordering::Relaxed);
+ moving.join().expect("concurrent cursor transport");
+ result
+ });
+ assert!(
+ verifies_target(&activated),
+ "active agent cursor must not invalidate exact activation: {}",
+ activated.raw
+ );
+ let after = observer.snapshot(target).expect("observe activated target");
+ assert_eq!(after.foreground, Some(u64::from(pid)));
+ assert_eq!(after.cursor_pos, before.cursor_pos, "real pointer moved");
+ Observation::delivered_with_fixture_state(vec![OracleKind::Focus, OracleKind::Cursor])
+ });
+}
+
+#[test]
+#[ignore]
+fn harness_appkit_exact_activation_refuses_competing_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");
+ let snapshot = snapshot_elements(driver, pid, wid);
+ assert!(!snapshot.is_error(), "target snapshot: {}", snapshot.text());
+ let observer = NativeObserver::new();
+ let target = TargetWindow {
+ pid,
+ native_id: wid,
+ };
+ let before = observer.snapshot(target).expect("observe competing window");
+ let response = driver.call(
+ "bring_to_front",
+ serde_json::json!({"pid": pid, "window_id": wid}),
+ );
+ assert!(
+ response.is_error(),
+ "competing window must prevent verification"
+ );
+ assert_eq!(
+ response.structured()["code"],
+ "bring_to_front_exact_window_unverified"
+ );
+ assert_eq!(response.structured()["activated"], false);
+ 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)
+ );
+ let after = observer
+ .snapshot(target)
+ .expect("observe refused activation");
+ assert_eq!(after.cursor_pos, before.cursor_pos, "real pointer moved");
+ Observation::refused(
+ RefusalCode::BringToFrontExactWindowUnverified,
+ vec![OracleKind::FixtureState, OracleKind::Cursor],
+ response.text(),
+ Evidence::default(),
+ )
+ });
+}
+
#[test]
#[ignore]
fn harness_appkit_foreground_single_click_has_one_ordered_native_pair() {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
index 21f036745a..abc10c7fe6 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
@@ -31,6 +31,7 @@
use std::collections::HashMap;
use std::ffi::c_void;
+use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -74,6 +75,11 @@ static CMD_TX: OnceLock<std::sync::mpsc::SyncSender<OverlayMsg>> = OnceLock::new
// Single-consumer slot; receiver is moved into run_on_main_thread().
static CMD_RX_CELL: Mutex<Option<std::sync::mpsc::Receiver<OverlayMsg>>> = Mutex::new(None);
static RENDER: Mutex<Option<RenderMap>> = Mutex::new(None);
+static OVERLAY_WINDOW_ID: AtomicU32 = AtomicU32::new(0);
+
+pub(crate) fn is_overlay_window(window_id: u32) -> bool {
+ window_id != 0 && OVERLAY_WINDOW_ID.load(Ordering::Acquire) == window_id
+}
/// The keyed, insertion-ordered collection of owned cursors that the render
/// loop composites every frame. Insertion order = stable z-order (later keys
@@ -676,6 +682,9 @@ unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMs
}
}
+ let window_number: isize = msg_send![win, windowNumber];
+ OVERLAY_WINDOW_ID.store(u32::try_from(window_number).unwrap_or(0), Ordering::Release);
+
// ---- Show the window ----
let _: () = msg_send![win, orderFrontRegardless];
@@ -688,6 +697,7 @@ unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMs
// ---- NSApplication run loop (blocks until process exits) ----
let _: () = msg_send![app, run];
+ OVERLAY_WINDOW_ID.store(0, Ordering::Release);
}
fn render_loop(
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 3c5b4167ca..1a1f2614ff 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
@@ -120,7 +120,8 @@ fn classify_exact_outcome(
}
fn observe_exact_window(pid: i32, window_id: u32) -> ExactWindowObservation {
- let windows = crate::windows::visible_windows();
+ let mut windows = crate::windows::visible_windows();
+ windows.retain(|window| !crate::cursor::overlay::is_overlay_window(window.window_id));
let target_visible_ordinary = windows
.iter()
.any(|window| window.pid == pid && window.window_id == window_id && window.layer == 0);
diff --git a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift
index ab10e42424..973ba7b372 100644
--- a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift
+++ b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift
@@ -651,6 +651,11 @@ struct CuaAppKitHarness {
let controller = HarnessWindowController()
installMenuBar(target: controller)
controller.show()
+ if ProcessInfo.processInfo.environment["CUA_APPKIT_KEEP_ORDERED_FRONT"] == "1" {
+ _ = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { [weak window = controller.window] _ in
+ window?.orderFrontRegardless()
+ }
+ }
if let path = ProcessInfo.processInfo.environment["CUA_APPKIT_POINTER_ORACLE"] {
let receiver = SingleClickReceiver(
frame: controller.window.contentView!.bounds,
diff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.sh
index 0bd1a3a021..c475731813 100755
--- a/scripts/ci/macos/run-rust-e2e.sh
+++ b/scripts/ci/macos/run-rust-e2e.sh
@@ -354,6 +354,8 @@ if [[ "${SUITE}" == native || "${SUITE}" == all ]]; then
harness_appkit_scroll_background \
harness_appkit_counter \
harness_appkit_counter_px_background \
+ harness_appkit_exact_activation_with_agent_cursor \
+ harness_appkit_exact_activation_refuses_competing_window \
harness_appkit_foreground_single_click_has_one_ordered_native_pair \
harness_appkit_right_click_px_foreground \
harness_appkit_right_click_px_background \