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.

test(cua-driver): prune redundant macOS adapter tests (#4116)

Francesco Bonacci2baa2ac45361
diff --git a/.github/workflows/ci-rust-macos.yml b/.github/workflows/ci-rust-macos.yml
index c5e5c128b0..83f8423ab6 100644
--- a/.github/workflows/ci-rust-macos.yml
+++ b/.github/workflows/ci-rust-macos.yml
@@ -54,6 +54,10 @@ jobs:
# harness (libs/cua-driver/tests/runners/macos-lume/run-all.sh).
- name: Run platform-macos unit tests
working-directory: libs/cua-driver/rust
+ env:
+ # The hosted runner's pasteboard is disposable; opt in to the native
+ # clipboard round trip that would clobber a developer's clipboard.
+ CUA_TEST_ALLOW_CLIPBOARD: "1"
run: cargo test --locked -p platform-macos --lib
- name: Run cua-driver-core unit tests on macOS
working-directory: libs/cua-driver/rust
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs b/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs
index b94288ace6..a271397a30 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs
@@ -141,59 +141,3 @@ where
let prior = apps::frontmost_pid();
with_focus_suppressed(target_pid, prior, origin, f).await
}
-
-// ── Tests ────────────────────────────────────────────────────────────────────
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- /// `with_focus_suppressed` runs the closure and returns its value.
- /// Skip-arming path (no prior frontmost) still executes f.
- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
- async fn runs_closure_without_prior_frontmost() {
- let n = with_focus_suppressed(
- Some(42),
- None, // no prior → no lease armed
- "test.no_prior",
- || async { 7 },
- )
- .await;
- assert_eq!(n, 7);
- }
-
- /// Skip-arming path: target == prior_frontmost (self → self).
- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
- async fn runs_closure_when_target_is_prior_frontmost() {
- let n = with_focus_suppressed(
- Some(42),
- Some(42), // self → self → skip
- "test.self_to_self",
- || async { 11 },
- )
- .await;
- assert_eq!(n, 11);
- }
-
- /// Arming path: target != prior_frontmost. The lease is armed,
- /// closure runs, lease drops on the way out (we can't directly
- /// observe the dispatcher state through the public API here —
- /// the focus_steal module's own tests cover the lease lifecycle —
- /// but we exercise the codepath to make sure it compiles and the
- /// 50ms sleep doesn't deadlock.
- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
- async fn arms_lease_when_target_differs_from_prior() {
- let n = with_focus_suppressed(Some(123), Some(456), "test.armed", || async { 99 }).await;
- assert_eq!(n, 99);
- }
-
- /// `with_focus_suppressed_now` resolves prior_frontmost via the
- /// live NSWorkspace query — exercise the codepath end-to-end.
- /// In a unit-test context (no NSApp main thread) the query may
- /// return None; the closure must still run.
- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
- async fn now_variant_runs_even_when_frontmost_is_none() {
- let n = with_focus_suppressed_now(Some(7), "test.now", || async { 5 }).await;
- assert_eq!(n, 5);
- }
-}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs b/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs
index 759684116f..682a6ff86d 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs
@@ -649,30 +649,6 @@ mod tests {
assert_eq!(d.len(), 0, "snapshot_matches should purge expired");
}
- /// Janitor lifecycle: starts on first add, stops when empty,
- /// restarts on next add. Spin up a tokio runtime to host the task.
- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
- async fn janitor_starts_stops_restarts() {
- let d = Arc::new(Dispatcher::new());
- // First add → janitor starts.
- let h1 = d.add(Some(1), 2, "test.j1");
- d.kick_janitor();
- // Give the janitor task time to spin up.
- tokio::time::sleep(Duration::from_millis(50)).await;
- // The dispatcher should still hold the entry.
- assert_eq!(d.len(), 1);
- // Now remove → janitor goes idle.
- d.remove(h1);
- tokio::time::sleep(Duration::from_millis(50)).await;
- assert_eq!(d.len(), 0);
- // Add again — same kick, same lifecycle. (start_janitor is
- // idempotent — already-started task picks up new adds via watch.)
- let _h2 = d.add(Some(3), 4, "test.j2");
- d.kick_janitor();
- tokio::time::sleep(Duration::from_millis(50)).await;
- assert_eq!(d.len(), 1);
- }
-
/// Verifies the CodeRabbit #2 fix: `add()` always calls
/// `kick_janitor()`, regardless of whether the map was empty.
///
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs
index ceaa7d42ba..f79faf9765 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs
@@ -1816,11 +1816,6 @@ mod tests {
);
}
- #[test]
- fn hid_only_post_mode_is_distinct_from_routed_background() {
- assert_ne!(MousePostMode::Both, MousePostMode::HidOnly);
- }
-
#[test]
fn foreground_drag_plan_keeps_a_drag_sample_for_zero_steps() {
let events = foreground_drag_events(1.0, 2.0, 3.0, 4.0, 0);
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs b/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs
index d67d317588..4768a1f712 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs
@@ -769,15 +769,6 @@ mod tests {
}
}
- #[test]
- fn env_var_disables_gate() {
- let _guard = env_lock();
- std::env::set_var("CUA_DRIVER_RS_PERMISSIONS_GATE", "0");
- let opts = GateOpts::from_env_and_flag(false);
- assert!(opts.opt_out, "env=0 must opt out");
- std::env::remove_var("CUA_DRIVER_RS_PERMISSIONS_GATE");
- }
-
#[test]
fn flag_disables_gate() {
let _guard = env_lock();
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/terminal.rs b/libs/cua-driver/rust/crates/platform-macos/src/terminal.rs
index a2b35055d7..a14db61886 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/terminal.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/terminal.rs
@@ -13,8 +13,7 @@
//! call is cheap (one Objective-C method) and we only run it when
//! `type_text` is about to issue an AX value-set.
//!
-//! Adding a new terminal: append the bundle id to [`TERMINAL_BUNDLE_IDS`]
-//! and add a coverage line in the unit tests below.
+//! Adding a new terminal: append the bundle id to [`TERMINAL_BUNDLE_IDS`].
/// Bundle identifiers of macOS terminal emulators where AX value-set is
/// known to be silently dropped — `type_text` skips the AX path and
@@ -57,16 +56,6 @@ pub fn is_terminal_pid(pid: i32) -> bool {
mod tests {
use super::*;
- #[test]
- fn matches_documented_terminals() {
- for bid in TERMINAL_BUNDLE_IDS {
- assert!(
- is_terminal_bundle_id(bid),
- "documented terminal {bid:?} must match"
- );
- }
- }
-
#[test]
fn rejects_non_terminal_bundles() {
for bid in [
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/background_input_regression_tests.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/background_input_regression_tests.rs
deleted file mode 100644
index 2b39f35333..0000000000
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/background_input_regression_tests.rs
+++ /dev/null
@@ -1,150 +0,0 @@
-use super::*;
-use async_trait::async_trait;
-use cua_driver_core::{
- protocol::ToolResult,
- tool::{Tool, ToolDef},
-};
-use serde_json::Value;
-use std::sync::{
- atomic::{AtomicUsize, Ordering},
- Arc, Mutex,
-};
-use std::time::Duration;
-
-#[tokio::test]
-async fn same_pid_lease_covers_proof_dispatch_restoration_and_verification() {
- const PID: i32 = -92_101;
- let events = Arc::new(Mutex::new(Vec::new()));
- let (first_started_tx, first_started_rx) = tokio::sync::oneshot::channel();
- let (finish_first_tx, finish_first_rx) = tokio::sync::oneshot::channel();
-
- let first_events = events.clone();
- let first = tokio::spawn(async move {
- let _lease = acquire_background_mutation(PID).await;
- first_events
- .lock()
- .unwrap()
- .extend(["first:proof", "first:dispatch"]);
- first_started_tx.send(()).unwrap();
- finish_first_rx.await.unwrap();
- first_events
- .lock()
- .unwrap()
- .extend(["first:restore", "first:verify"]);
- });
- first_started_rx.await.unwrap();
-
- let second_events = events.clone();
- let mut second = tokio::spawn(async move {
- let _lease = acquire_background_mutation(PID).await;
- second_events.lock().unwrap().push("second:proof");
- });
-
- assert!(
- tokio::time::timeout(Duration::from_millis(50), &mut second)
- .await
- .is_err(),
- "the sibling-window mutation must wait through restoration and verification"
- );
- finish_first_tx.send(()).unwrap();
- first.await.unwrap();
- tokio::time::timeout(Duration::from_secs(1), second)
- .await
- .expect("same-pid mutation should proceed after the full lifecycle")
- .unwrap();
-
- assert_eq!(
- *events.lock().unwrap(),
- [
- "first:proof",
- "first:dispatch",
- "first:restore",
- "first:verify",
- "second:proof",
- ]
- );
-}
-
-#[tokio::test]
-async fn different_pid_lease_enters_while_first_mutation_is_in_flight() {
- const FIRST_PID: i32 = -92_102;
- const SECOND_PID: i32 = -92_103;
- let first = acquire_background_mutation(FIRST_PID).await;
- let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
-
- let second = tokio::spawn(async move {
- let _lease = acquire_background_mutation(SECOND_PID).await;
- entered_tx.send(()).unwrap();
- });
-
- tokio::time::timeout(Duration::from_secs(1), entered_rx)
- .await
- .expect("a different pid must not wait for the in-flight mutation")
- .unwrap();
- drop(first);
- second.await.unwrap();
-}
-
-struct KeyboardProbe {
- calls: Arc<AtomicUsize>,
-}
-
-static KEYBOARD_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
-
-#[async_trait]
-impl Tool for KeyboardProbe {
- fn def(&self) -> &ToolDef {
- KEYBOARD_DEF.get_or_init(|| ToolDef {
- name: "press_key".into(),
- description: "keyboard ambiguity regression probe".into(),
- input_schema: serde_json::json!({"type": "object"}),
- read_only: false,
- destructive: true,
- idempotent: false,
- open_world: false,
- })
- }
-
- async fn invoke(&self, _args: Value) -> ToolResult {
- self.calls.fetch_add(1, Ordering::SeqCst);
- ToolResult::text("keyboard actuator invoked")
- }
-}
-
-fn candidate(window_id: u64) -> WindowTargetCandidate {
- WindowTargetCandidate {
- window_id,
- transient_for: None,
- title: format!("Document {window_id}"),
- app_name: Some("Editor".into()),
- is_on_screen: true,
- }
-}
-
-#[tokio::test]
-async fn pid_only_keyboard_refuses_same_pid_multi_window_ambiguity_before_dispatch() {
- let calls = Arc::new(AtomicUsize::new(0));
- let candidates: WindowTargetCandidates = Arc::new(|pid| {
- (pid == 42)
- .then(|| vec![candidate(7), candidate(8)])
- .unwrap_or_default()
- });
- let keyboard = pid_window_guarded(
- KeyboardProbe {
- calls: calls.clone(),
- },
- &candidates,
- );
-
- let result = keyboard
- .invoke(serde_json::json!({"pid": 42, "key": "return"}))
- .await;
-
- assert_eq!(calls.load(Ordering::SeqCst), 0, "no key may be posted");
- assert_eq!(result.is_error, Some(true));
- let refusal = result.structured_content.unwrap();
- assert_eq!(refusal["code"], "ambiguous_window_target");
- assert_eq!(refusal["effect"], "refused");
- assert_eq!(refusal["candidates"][0]["window_id"], 7);
- assert_eq!(refusal["candidates"][1]["window_id"], 8);
-}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
index 7ce3c2679c..e9c300ad83 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
@@ -1653,36 +1653,6 @@ mod tests {
);
}
- /// Existing default behaviour preserved: no `button` field on the call →
- /// resolves to "left" inside invoke. We can't drive the AX path without a
- /// live macOS Window Server, but we CAN check the same arg-parsing logic
- /// the invoke uses produces "left" for empty / absent input.
- #[test]
- fn button_defaults_to_left_when_absent() {
- use cua_driver_core::tool_args::ArgsExt;
- let args = serde_json::json!({ "pid": 1234 });
- let button_str_raw = args.str_or("button", "left").to_lowercase();
- let resolved = if button_str_raw.is_empty() {
- "left".to_string()
- } else {
- button_str_raw
- };
- assert_eq!(resolved, "left");
- }
-
- /// Round-trip the three canonical values through the same parse the invoke
- /// uses, so any future refactor that changes str_or semantics breaks here
- /// before it breaks consumers.
- #[test]
- fn button_round_trips_right_and_middle() {
- use cua_driver_core::tool_args::ArgsExt;
- for v in ["left", "right", "middle"] {
- let args = serde_json::json!({ "pid": 1234, "button": v });
- let s = args.str_or("button", "left").to_lowercase();
- assert_eq!(s, v);
- }
- }
-
/// Regression for the Swift→Rust port gap: only a raw background left
/// click with an exact window may intentionally activate the target
/// without raising it. Other background buttons retain strict suppression,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/clipboard.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/clipboard.rs
index 1d48a87cb9..601a620f2d 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/clipboard.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/clipboard.rs
@@ -89,8 +89,12 @@ mod tests {
}
#[test]
- fn native_clipboard_round_trips_text_png_and_file_url_in_ci() {
- if std::env::var_os("CI").is_none() {
+ fn native_clipboard_round_trips_text_png_and_file_url_when_opted_in() {
+ // Overwrites the general pasteboard, so it runs only where a job opts
+ // in explicitly. `CI` alone is not enough: developers export it too.
+ if std::env::var_os("CUA_TEST_ALLOW_CLIPBOARD").as_deref()
+ != Some(std::ffi::OsStr::new("1"))
+ {
return;
}
let backend = MacosClipboard::new();
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
index 72c3d105f1..b2f7fa86e8 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
@@ -1162,7 +1162,6 @@ mod window_scope_contract_tests {
mod tests {
use super::*;
use crate::ax::tree::AXNode;
- use cua_driver_core::element_query::project_elements_for_query;
use serde_json::json;
fn node(
@@ -1247,95 +1246,6 @@ mod tests {
);
}
- #[test]
- fn query_projection_keeps_only_rendered_actionable_rows() {
- let nodes = vec![
- node(Some(0), "AXWindow", Some("Document"), 0, None, None, vec![]),
- node(
- Some(1),
- "AXMenuItem",
- Some("Window"),
- 1,
- Some(0),
- None,
- vec![],
- ),
- node(
- Some(2),
- "AXMenuItem",
- Some("Move & Resize"),
- 2,
- Some(1),
- None,
- vec![],
- ),
- node(
- Some(3),
- "AXMenuItem",
- Some("Left"),
- 3,
- Some(2),
- None,
- vec![],
- ),
- node(
- Some(4),
- "AXButton",
- Some("Unrelated"),
- 1,
- Some(0),
- None,
- vec![],
- ),
- ];
- let elements = build_elements_array_with_token(&nodes, None);
- let filtered_markdown = concat!(
- "- [0] AXWindow \"Document\"\n",
- " - [1] AXMenuItem \"Window\"\n",
- " - [2] AXMenuItem \"Move & Resize\"\n",
- " - [3] AXMenuItem \"Left\"\n",
- );
-
- let projected = project_elements_for_query(elements, Some("Left"), filtered_markdown);
- let indices: Vec<u64> = projected
- .iter()
- .map(|entry| entry["element_index"].as_u64().unwrap())
- .collect();
-
- assert_eq!(indices, vec![0, 1, 2, 3]);
- }
-
- #[test]
- fn query_projection_returns_no_elements_when_markdown_has_no_match() {
- let nodes = vec![node(
- Some(0),
- "AXButton",
- Some("Unrelated"),
- 0,
- None,
- None,
- vec![],
- )];
- let elements = build_elements_array_with_token(&nodes, None);
-
- let projected = project_elements_for_query(elements, Some("zoomLeft"), "");
-
- assert!(projected.is_empty());
- }
-
- #[test]
- fn unfiltered_projection_preserves_every_element() {
- let nodes = vec![
- node(Some(0), "AXButton", Some("One"), 0, None, None, vec![]),
- node(Some(1), "AXButton", Some("Two"), 0, None, None, vec![]),
- ];
- let elements = build_elements_array_with_token(&nodes, None);
-
- let projected = project_elements_for_query(elements, None, "");
-
- assert_eq!(projected.len(), 2);
- }
-
#[test]
fn elements_shape_carries_role_label_frame_parent_depth() {
let nodes = vec![node(
@@ -1613,33 +1523,4 @@ mod tests {
entries[0]
);
}
-
- #[test]
- fn walk_tree_bounded_signature_accepts_caps_no_panic() {
- // Regression guard for #22865: the bounded variant must accept
- // arbitrary cap values without panicking, even against a pid that
- // has no AX tree to walk. Returns a TreeWalkResult either way.
- // Use pid that won't be a real process. Don't assume tree is empty
- // (CI may have process re-use) — only assert that the call returns
- // and the result struct shape is intact.
- let r1 = crate::ax::tree::walk_tree_bounded(i32::MAX, None, None, 5, 2);
- // Cap of 5 is the contract test from the task: when this many
- // visible nodes existed, the walker must stop early. The dead pid
- // exercises the early-return path; the assertion is that the call
- // honors the cap without overflowing or panicking.
- assert!(r1.nodes.len() <= 5, "max_elements=5 must cap nodes ≤ 5");
- assert!(
- r1.nodes.iter().all(|n| n.depth <= 2),
- "max_depth=2 must cap depth ≤ 2"
- );
- // And the uncapped variant — same dead-pid path, just validating
- // walk_tree(...) (which delegates to walk_tree_bounded with
- // DEFAULT_MAX_*) returns the same empty/safe shape.
- let r2 = crate::ax::tree::walk_tree(i32::MAX, None, None);
- assert_eq!(
- r1.nodes.len(),
- r2.nodes.len(),
- "no-pid case: both bounded and unbounded must agree on the empty result"
- );
- }
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index 99a32faba3..7896fd9ca8 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -131,9 +131,6 @@ mod pid_window_target_tests {
}
}
-#[cfg(test)]
-mod background_input_regression_tests;
-
fn pid_window_guarded<T: Tool + 'static>(
tool: T,
candidates: &WindowTargetCandidates,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs
index 76ecd2778e..a4826ed3ef 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs
@@ -34,14 +34,6 @@ struct WheelTarget {
wid: Option<u32>,
}
-fn after_exact_target_gate<T>(
- gate: Result<(), ToolResult>,
- action: impl FnOnce() -> T,
-) -> Result<T, ToolResult> {
- gate?;
- Ok(action())
-}
-
pub struct ScrollTool {
state: Arc<ToolState>,
}
@@ -382,12 +374,13 @@ impl Tool for ScrollTool {
// reveal the target before taking the screen-space center;
// otherwise the wheel is posted outside the rendered window
// and nested overflow regions never receive it.
- after_exact_target_gate(semantic_gate, || unsafe {
+ semantic_gate?;
+ unsafe {
crate::ax::bindings::perform_action(
element_ptr as AXUIElementRef,
"AXScrollToVisible",
- )
- })?;
+ );
+ }
std::thread::sleep(std::time::Duration::from_millis(40));
let center = unsafe { element_screen_center(element_ptr as AXUIElementRef) };
Ok(center.map(|(cx, cy)| {
@@ -740,43 +733,3 @@ unsafe fn collect_ax_buttons(
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use cua_driver_core::background_input::{
- decide_background_input, BackgroundAction, BackgroundInputDecision, BackgroundTargetFacts,
- ElementAncestry, ExactWindowTarget, WindowServerOwnership,
- };
- use std::sync::atomic::{AtomicBool, Ordering};
-
- #[test]
- fn exact_target_refusal_prevents_ax_reveal() {
- let action_ran = AtomicBool::new(false);
- let target = ExactWindowTarget {
- pid: 42,
- window_id: 7,
- };
- let facts = BackgroundTargetFacts {
- window_server: WindowServerOwnership::SamePid,
- ax_window_present: true,
- target_minimized: Some(false),
- app_hidden: Some(false),
- competing_keyboard_destinations: 0,
- element: ElementAncestry::OutsideTargetWindow,
- };
- let refusal = match decide_background_input(target, &facts, BackgroundAction::AxSemantic) {
- BackgroundInputDecision::Refuse(refusal) => Err(
- super::super::background_refusal_result(target.pid, target.window_id, &refusal),
- ),
- BackgroundInputDecision::Execute { .. } => panic!("exact-target facts must refuse"),
- };
-
- let result = after_exact_target_gate(refusal, || {
- action_ran.store(true, Ordering::SeqCst);
- });
-
- assert!(result.is_err());
- assert!(!action_ran.load(Ordering::SeqCst));
- }
-}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs
index 6555a5a6a4..8d7e2aa238 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs
@@ -885,23 +885,18 @@ fn foreground_settle_ms(pid: i32, frontmost_pid: Option<i32>) -> u64 {
/// Read-back verification for a keystroke rung: did the typed text actually land?
///
/// `before`/`after` are `AXValue` read from the target field before and after
-/// the keystrokes. Returns whether we can *positively confirm* the text landed:
-/// - unreadable `after` (`None`) → unverifiable → `false` (Catalyst case; the
-/// agent must confirm via screenshot).
-/// - `after` contains the complete text → `true`.
-/// - empty input text → trivially `true`.
+/// the keystrokes. Only `Complete` positively confirms the text landed:
+/// - unreadable `after` (`None`) → `Unverifiable` (Catalyst case; the agent
+/// must confirm via screenshot).
+/// - `after` contains the complete text → `Complete`.
+/// - empty input text → trivially `Complete`.
///
-/// Apps that normalize input (smart quotes, autocomplete) may fail the
-/// substring/length test even though something landed — we report `false`
-/// (unverified) rather than erroring, so the agent can still confirm.
-#[cfg(test)]
-fn verify_typed(before: Option<&str>, after: Option<&str>, text: &str) -> bool {
- matches!(typed_progress(before, after, text), TypedProgress::Complete)
-}
-
-/// Classify an observable insertion without mistaking a prefix for complete
-/// delivery. A positive length delta is an exact delivered-character count for
-/// insert-at-cursor typing; it is capped at the request size defensively.
+/// Otherwise classify an observable insertion without mistaking a prefix for
+/// complete delivery. A positive length delta is an exact delivered-character
+/// count for insert-at-cursor typing; it is capped at the request size
+/// defensively. Apps that normalize input (smart quotes, autocomplete) may fail
+/// the substring/length test even though something landed — we report it as
+/// unverified rather than erroring, so the agent can still confirm.
fn typed_progress(before: Option<&str>, after: Option<&str>, text: &str) -> TypedProgress {
if text.is_empty() {
return TypedProgress::Complete;
@@ -1436,40 +1431,6 @@ fn type_text_blocking(
mod tests {
use super::*;
- /// Sanity-check that the terminal short-circuit can be expressed as a
- /// pure function of `is_terminal_target`: when true, the code goes
- /// to key-event synthesis without consulting AX. This test stands
- /// in for an integration test (which would need a running terminal)
- /// — it exercises the branch by injecting `is_terminal_target=true`
- /// with a non-existent pid and checking we get the expected error
- /// shape from the CGEvent path (not from the AX path).
- ///
- /// The CGEvent post will fail for pid 0 / -1, so we only assert
- /// that `type_text_blocking` returns `Err` *after* deciding to
- /// take the key-events path — i.e. it doesn't hit the AX branches
- /// where `set_string_attr(0)` would crash.
- #[test]
- fn terminal_flag_routes_past_ax_path() {
- // Pid -1 is invalid; the AX path would unconditionally call
- // focused_element_of_pid which is safe but it would never reach
- // CGEvent. The fact that this returns an Err (without crashing)
- // proves we routed through CGEvent-only and never touched AX.
- let r = type_text_blocking(
- -1,
- "x",
- None,
- 0,
- /*is_terminal_target=*/ true,
- super::super::DeliveryMode::Background,
- None,
- BackgroundKeyboardPolicy::Allowed,
- );
- // We don't care whether r is Ok or Err — what matters is that
- // calling it with is_terminal_target=true is safe and never
- // dereferences null AX pointers.
- let _ = r;
- }
-
/// A semantic-only policy must refuse the terminal short-circuit before
/// any CGEvent is posted: terminals have no semantic AX rung, so nothing
/// safe remains and the carried refusal comes back unchanged.
@@ -1567,29 +1528,31 @@ mod tests {
}
#[test]
- fn verify_typed_unreadable_after_is_unverified() {
- // Catalyst: can't read AXValue back → cannot confirm → false.
- assert!(!verify_typed(None, None, "hi"));
- assert!(!verify_typed(Some(""), None, "hi"));
- }
-
- #[test]
- fn verify_typed_contains_full_request_is_verified() {
- assert!(verify_typed(Some(""), Some("hi"), "hi")); // contains
- assert!(verify_typed(Some("ab"), Some("ab hi"), "hi")); // contains, appended
- }
-
- #[test]
- fn observable_prefix_is_partial_not_verified() {
- assert_eq!(
- typed_progress(Some(""), Some("BEGINpayload"), "BEGINpayloadEND"),
- TypedProgress::Partial(12)
- );
- assert!(!verify_typed(
- Some(""),
- Some("BEGINpayload"),
- "BEGINpayloadEND"
- ));
+ fn typed_progress_classifies_readback() {
+ use TypedProgress::*;
+ for (before, after, text, expected) in [
+ // Catalyst: can't read AXValue back, so delivery cannot be confirmed.
+ (None, None, "hi", Unverifiable),
+ (Some(""), None, "hi", Unverifiable),
+ (None, Some("h"), "hi", Unverifiable),
+ (Some(""), Some("hi"), "hi", Complete),
+ (Some("ab"), Some("ab hi"), "hi", Complete),
+ // An observable prefix is partial delivery, never completion.
+ (
+ Some(""),
+ Some("BEGINpayload"),
+ "BEGINpayloadEND",
+ Partial(12),
+ ),
+ (Some("ab"), Some("ab"), "hi", Unchanged),
+ (None, None, "", Complete),
+ ] {
+ assert_eq!(
+ typed_progress(before, after, text),
+ expected,
+ "before={before:?} after={after:?} text={text:?}"
+ );
+ }
}
#[test]
@@ -1624,17 +1587,6 @@ mod tests {
assert_eq!(delivery, (false, Some(5)));
}
- #[test]
- fn verify_typed_unchanged_is_unverified() {
- // Readable but the field didn't change and doesn't contain the text.
- assert!(!verify_typed(Some("ab"), Some("ab"), "hi"));
- }
-
- #[test]
- fn verify_typed_empty_text_is_trivially_verified() {
- assert!(verify_typed(None, None, ""));
- }
-
#[test]
fn path_constants_are_stable_tokens() {
// These string constants are part of the structured-response
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs
index 198917a54b..dd5a1b19e7 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs
@@ -154,8 +154,7 @@ impl Tool for ZoomTool {
#[cfg(test)]
mod tests {
- use super::{def, ToolState};
- use crate::ax::cache::CachedSnapshot;
+ use super::def;
#[test]
fn schema_keeps_pid_optional_for_window_owned_zoom_lookup() {
@@ -163,33 +162,4 @@ mod tests {
assert!(!required.iter().any(|field| field == "pid"));
assert!(def().input_schema["properties"].get("pid").is_some());
}
-
- #[test]
- fn omitted_pid_resolves_owned_window_snapshot() {
- let state = ToolState::new(false, false, None);
- state.element_cache.publish_for_session(
- 42,
- 7,
- CachedSnapshot::from_nodes(&[]),
- Some("zoom-optional-pid-macos"),
- Some(2.0),
- );
- let (pid, context) = state
- .element_cache
- .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-macos"))
- .unwrap();
- assert_eq!(pid, 42);
- assert_eq!(context.window_id, 7);
- state.element_cache.publish_for_session(
- 43,
- 7,
- CachedSnapshot::from_nodes(&[]),
- Some("zoom-optional-pid-macos"),
- Some(1.0),
- );
- assert!(state
- .element_cache
- .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-macos"))
- .is_err());
- }
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs b/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs
index 4eb41e454c..57b44875ad 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs
@@ -54,16 +54,6 @@ pub struct WindowEvent {
pub title: String,
}
-/// Categorical diff entry. We mirror Swift which only emits
-/// `WindowEvent` rows for *new* windows — closed/changed never appear
-/// in the result suffix — but keep them as enum variants for future
-/// extensibility and so unit tests can pin down the diff semantics.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum WindowChange {
- Opened(WindowEvent),
- Closed { window_id: u32 },
-}
-
/// State captured immediately before the action fires.
///
/// Holds:
@@ -312,9 +302,8 @@ impl Snapshot {
.unwrap_or_else(|_| Changes::no_change())
}
- /// Same as `detect()` but with configurable timing — exposed for
- /// tests / callers that want a tighter or looser poll window.
- pub fn detect_with(self, timeout: Duration, poll_interval: Duration) -> Changes {
+ /// Same as `detect()` but with configurable timing.
+ fn detect_with(self, timeout: Duration, poll_interval: Duration) -> Changes {
let deadline = Instant::now() + timeout;
loop {
std::thread::sleep(poll_interval);
@@ -323,7 +312,6 @@ impl Snapshot {
.into_iter()
.filter(|w| w.layer == 0)
.collect();
- let current_ids: HashSet<u32> = current.iter().map(|w| w.window_id).collect();
let new_windows: Vec<WindowEvent> = current
.iter()
@@ -335,15 +323,6 @@ impl Snapshot {
title: w.title.clone(),
})
.collect();
- // Diff the other direction too — keeps unit tests honest
- // even though Swift's result_suffix only uses opened windows.
- let _closed: Vec<u32> = self
- .window_ids
- .iter()
- .copied()
- .filter(|id| !current_ids.contains(id))
- .collect();
-
let current_front = apps::frontmost_pid();
let foreground_changed = match (self.front_pid, current_front) {
(Some(orig), Some(cur)) => orig != cur,
@@ -361,44 +340,6 @@ impl Snapshot {
}
}
}
-
- // ── Internal helpers — also used by unit tests via the `pub(super)`
- // path so the diff logic can be exercised without driving the live
- // window enumerator. ────────────────────────────────────────────
-
- /// Pure-function diff: given the snapshot's window-id set + a
- /// list of currently-visible windows, return the (opened, closed)
- /// classification.
- ///
- /// `#[allow(dead_code)]`: today only the `#[cfg(test)]` block below
- /// constructs this — production callers `wait_for_window_change` /
- /// `wait_for_window_close` keep the (opened, closed) split inline.
- /// Kept `pub(crate)` because the doc comment near the top of this
- /// `impl` block calls it out as the entry point for unit-testing the
- /// diff logic without driving the live window enumerator.
- #[allow(dead_code)]
- pub(crate) fn diff(
- snapshot_ids: &HashSet<u32>,
- current: &[WindowInfo],
- ) -> (Vec<WindowEvent>, Vec<u32>) {
- let current_ids: HashSet<u32> = current.iter().map(|w| w.window_id).collect();
- let opened: Vec<WindowEvent> = current
- .iter()
- .filter(|w| !snapshot_ids.contains(&w.window_id))
- .map(|w| WindowEvent {
- window_id: w.window_id,
- pid: w.pid,
- app_name: w.app_name.clone(),
- title: w.title.clone(),
- })
- .collect();
- let closed: Vec<u32> = snapshot_ids
- .iter()
- .copied()
- .filter(|id| !current_ids.contains(id))
- .collect();
- (opened, closed)
- }
}
// ── Tests ────────────────────────────────────────────────────────────────────
@@ -406,65 +347,6 @@ impl Snapshot {
#[cfg(test)]
mod tests {
use super::*;
- use crate::windows::WindowBounds;
-
- fn win(id: u32, pid: i32, app: &str, title: &str) -> WindowInfo {
- WindowInfo {
- window_id: id,
- pid,
- app_name: app.into(),
- title: title.into(),
- bounds: WindowBounds {
- x: 0.,
- y: 0.,
- width: 100.,
- height: 100.,
- },
- layer: 0,
- z_index: 0,
- is_on_screen: true,
- current_space_id: None,
- on_current_space: None,
- space_ids: None,
- }
- }
-
- #[test]
- fn diff_finds_opened_window() {
- let snap: HashSet<u32> = [1, 2].into_iter().collect();
- let cur = vec![
- win(1, 100, "Safari", "Home"),
- win(2, 100, "Safari", "Tab2"),
- win(3, 101, "Mail", "Inbox"),
- ];
- let (opened, closed) = Snapshot::diff(&snap, &cur);
- assert_eq!(opened.len(), 1);
- assert_eq!(opened[0].window_id, 3);
- assert_eq!(opened[0].app_name, "Mail");
- assert_eq!(opened[0].title, "Inbox");
- assert!(closed.is_empty());
- }
-
- #[test]
- fn diff_finds_closed_window() {
- let snap: HashSet<u32> = [1, 2, 3].into_iter().collect();
- let cur = vec![win(1, 100, "Safari", "Home")];
- let (opened, closed) = Snapshot::diff(&snap, &cur);
- assert!(opened.is_empty());
- assert_eq!(closed.len(), 2);
- let closed_set: HashSet<u32> = closed.into_iter().collect();
- assert!(closed_set.contains(&2));
- assert!(closed_set.contains(&3));
- }
-
- #[test]
- fn diff_no_change() {
- let snap: HashSet<u32> = [1, 2].into_iter().collect();
- let cur = vec![win(1, 100, "Safari", "A"), win(2, 100, "Safari", "B")];
- let (opened, closed) = Snapshot::diff(&snap, &cur);
- assert!(opened.is_empty());
- assert!(closed.is_empty());
- }
#[test]
fn changes_result_suffix_no_change_is_empty() {