Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
refactor(cua-driver): move misplaced tests and unify test layout (#4146)
Francesco Bonacci3c2c0cb5d2dd
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.ymlindex 11176396c8..281aff85b6 100644--- a/.github/workflows/ci-cua-driver-contract-clients.yml+++ b/.github/workflows/ci-cua-driver-contract-clients.yml@@ -394,8 +394,8 @@ jobs:run: |python -m py_compile \claude_agent.py codex_agent.py fixture_server.py \- native_driver.py native_tools.py test_fixture_server.py- python -m unittest test_fixture_server.py -v+ native_driver.py native_tools.py tests/test_fixture_server.py+ python -m unittest tests.test_fixture_server -vpython -c "import claude_agent_sdk, openai_codex, cua_driver"- name: Install agent SDK example dependenciesdiff --git a/libs/cua-driver/docs/linux-mpx-recovery.md b/libs/cua-driver/docs/linux-mpx-recovery.mdindex 868a42e9ed..57fc0871c4 100644--- a/libs/cua-driver/docs/linux-mpx-recovery.md+++ b/libs/cua-driver/docs/linux-mpx-recovery.md@@ -43,7 +43,7 @@ TigerVNC do not support the needed device hotplug path.```shcargo build --locked -p cua-driver --manifest-path libs/cua-driver/rust/Cargo.toml-python3 libs/cua-driver/tests/linux-mpx-recovery.py \+python3 scripts/ci/linux/run-mpx-recovery-e2e.py \--driver libs/cua-driver/rust/target/debug/cua-driver \--output /tmp/mpx-recovery-evidence \--source-sha "$(git rev-parse HEAD)"diff --git a/libs/cua-driver/docs/test-harnesses-guide.md b/libs/cua-driver/docs/test-harnesses-guide.mdindex 4cdf4a632b..9c2597c99c 100644--- a/libs/cua-driver/docs/test-harnesses-guide.md+++ b/libs/cua-driver/docs/test-harnesses-guide.md@@ -597,3 +597,40 @@ When adding a new scenario:The goal is one understandable Rust E2E model across platforms, withplatform-specific harnesses where the OS genuinely differs.++## Test Layout Conventions++Rust tests in the driver workspace use one layout:++| Test kind | Where it lives |+| --- | --- |+| Small unit suite | Inline `#[cfg(test)] mod tests { ... }` at the end of the module |+| Large unit suite | `src/<module>/tests.rs`, declared as `#[cfg(test)] mod tests;` in `src/<module>.rs` |+| Several suites for one large module | `src/<module>/<name>_tests.rs`, one `#[cfg(test)] mod <name>_tests;` each, for example `platform-{linux,windows}/src/tools/impl_/` |+| Crate-root suites | `src/tests/`, for example `cua-driver-sdk/src/tests/` |+| Integration test in `cua-driver` or its E2E suites | `tests/<subject>_test.rs`; shared helpers go in `tests/support/` |++Moving a suite into its own file keeps its module path, so test names and+CI filters stay the same. Prefer Rust's default module file lookup over+`#[path]`. Other crates' `tests/` directories keep their existing names.++Scripts and their tests live next to their owner:++- Desktop runners and focused native gates live in `scripts/ci/<os>/`, for+ example `scripts/ci/linux/run-mpx-recovery-e2e.py`.+- Example code keeps its tests in a `tests/` directory beside it, for example+ `libs/cua-driver/examples/agent-sdks/tests/`.+- `libs/cua-driver/rust/test-apps/` is the staging directory for built+ harness apps, not a test directory. The fixture build scripts `cd` into it,+ so its tracked README and `.gitignore` must stay.++Perception tests have three owners, and each tests different code:++| Directory | Owns | Run by |+| --- | --- | --- |+| `libs/cua-driver/rust/crates/cua-perception/{src,tests}` | Rust perception engine and extension protocol | `ci-cua-perception-release.yml`, `ci-cua-driver-quick.yml` |+| `libs/cua-driver/rust/crates/cua-perception/scripts/tests/` | Model artifact tooling and quality measurement scripts | `ci-cua-perception-release.yml` |+| `libs/cua-driver/tests/perception-demo/` | Visual demo evidence sanitizing, caching, and envelopes | `ci-test-scripts.yml` |+| `.github/scripts/tests/test_cua_perception_*.py`, `test_perception_release.py` | Perception release, review-trigger, and review-pipeline workflows and `.github/scripts` helpers | `ci-test-scripts.yml`, `ci-cua-perception-release.yml` |++Add a perception test to the directory that owns the code it exercises.diff --git a/libs/cua-driver/examples/agent-sdks/README.md b/libs/cua-driver/examples/agent-sdks/README.mdindex fc2f14d738..8c810b611c 100644--- a/libs/cua-driver/examples/agent-sdks/README.md+++ b/libs/cua-driver/examples/agent-sdks/README.md@@ -106,6 +106,6 @@ the same cleanup as an explicit `end_session`.```bashpython3.12 -m py_compile \claude_agent.py codex_agent.py fixture_server.py native_driver.py native_tools.py-python3.12 -m unittest test_fixture_server.py+python3.12 -m unittest tests.test_fixture_servernpm run typecheck```diff --git a/libs/cua-driver/examples/agent-sdks/tests/__init__.py b/libs/cua-driver/examples/agent-sdks/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/libs/cua-driver/examples/agent-sdks/test_fixture_server.py b/libs/cua-driver/examples/agent-sdks/tests/test_fixture_server.pysimilarity index 100%rename from libs/cua-driver/examples/agent-sdks/test_fixture_server.pyrename to libs/cua-driver/examples/agent-sdks/tests/test_fixture_server.pydiff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rsindex f84bab2fff..746df28e48 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs@@ -1995,6 +1995,7 @@ fn normalize_result(tool: &str, raw: Value) -> Result<ToolResult, DriverError> {uniffi::setup_scaffolding!("cua_driver_sdk");#[cfg(test)]+#[path = "tests/snapshot_lifecycle.rs"]mod snapshot_lifecycle_tests;#[cfg(test)]diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp.rsindex e8c696fddc..314075625e 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp.rs@@ -807,5 +807,4 @@ fn strict_json(text: &str) -> Result<Value, String> {}#[cfg(test)]-#[path = "remote_mcp_tests.rs"]mod tests;diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp_tests.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp/tests.rssimilarity index 100%rename from libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp_tests.rsrename to libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp/tests.rsdiff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver.rsindex 2a8a469ff7..1446b99097 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver.rs@@ -430,5 +430,4 @@ fn now_ms() -> u128 {}#[cfg(test)]-#[path = "remote_receiver_tests.rs"]mod tests;diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver_tests.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver/tests.rssimilarity index 100%rename from libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver_tests.rsrename to libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_receiver/tests.rsdiff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/snapshot_lifecycle_tests.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/tests/snapshot_lifecycle.rssimilarity index 100%rename from libs/cua-driver/rust/crates/cua-driver-sdk/src/snapshot_lifecycle_tests.rsrename to libs/cua-driver/rust/crates/cua-driver-sdk/src/tests/snapshot_lifecycle.rsdiff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 16917fc9b6..3fef85729a 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -107,103 +107,7 @@ fn pid_fallback_window_resolver() -> cua_driver_core::window_target::PidFallback}#[cfg(test)]-mod pid_window_resolver_tests {- use super::*;-- fn win(xid: u64, z: Option<usize>, on_screen: bool, w: u32, h: u32) -> crate::x11::WindowInfo {- crate::x11::WindowInfo {- xid,- pid: Some(7),- app_name: "gimp".into(),- title: format!("w{xid}"),- is_on_screen: on_screen,- z_index: z,- x: 0,- y: 0,- width: w,- height: h,- }- }-- #[test]- fn point_resolver_prefers_the_topmost_window_by_stacking_position() {- // Main window listed last (as `_NET_CLIENT_LIST_STACKING` bottom-up- // enumeration does when a dialog sits above it); the dialog wins.- let dialog = crate::x11::WindowInfo {- z_index: Some(5),- ..win(2, None, true, 400, 300)- };- let main = crate::x11::WindowInfo {- z_index: Some(3),- ..win(1, None, true, 1920, 1080)- };- assert_eq!(- topmost_window_at(&[main.clone(), dialog.clone()], 7, 100.0, 100.0),- Some(2)- );- assert_eq!(topmost_window_at(&[dialog, main], 7, 100.0, 100.0), Some(2));- }-- #[test]- fn point_resolver_ignores_windows_without_a_stacking_position_when_one_has_it() {- let ranked = win(2, Some(0), true, 400, 300);- let unranked = win(1, None, true, 1920, 1080);- assert_eq!(- topmost_window_at(&[ranked, unranked], 7, 10.0, 10.0),- Some(2)- );- }-- #[test]- fn pid_only_resolver_orders_focus_then_dialog_then_active_then_largest() {- let main = win(1, Some(1), true, 1920, 1080);- let dialog = win(2, Some(2), true, 400, 300);- let dock = win(3, Some(0), true, 200, 900);- let hidden = win(4, None, false, 3000, 3000);- let windows = vec![main, dialog, dock, hidden];- let transient = |xid: u64| (xid == 2).then_some(1u64);- // 1. core focus inside the pid wins outright (even over a dialog).- assert_eq!(- crate::x11::pick_pid_window(&windows, Some(3), transient, Some(1)),- Some(3)- );- // 2. no focus in the pid: its topmost transient dialog.- assert_eq!(- crate::x11::pick_pid_window(&windows, None, transient, Some(1)),- Some(2)- );- // 3. no dialog: the WM's active window when it is the pid's.- assert_eq!(- crate::x11::pick_pid_window(&windows, None, |_| None, Some(3)),- Some(3)- );- // 4. otherwise the largest mapped toplevel (never the unmapped one).- assert_eq!(- crate::x11::pick_pid_window(&windows, None, |_| None, None),- Some(1)- );- assert_eq!(- crate::x11::pick_pid_window(&windows, None, |_| None, Some(99)),- Some(1)- );- // A focused window that is not the pid's is ignored.- assert_eq!(- crate::x11::pick_pid_window(&windows, Some(42), |_| None, None),- Some(1)- );- }-- #[test]- fn pid_only_resolver_skips_unmapped_dialogs() {- let main = win(1, Some(1), true, 800, 600);- let unmapped_dialog = win(2, Some(2), false, 400, 300);- let windows = vec![main, unmapped_dialog];- assert_eq!(- crate::x11::pick_pid_window(&windows, None, |xid| (xid == 2).then_some(1u64), None),- Some(1)- );- }-}+mod pid_window_resolver_tests;type PidWindowGuardParts = (WindowTargetCandidates,@@ -716,74 +620,7 @@ fn window_record_json(w: &crate::x11::WindowInfo) -> Value {}#[cfg(test)]-mod list_windows_tests {- use super::*;-- #[test]- fn record_has_bounds_and_flat_legacy_fields() {- let w = crate::x11::WindowInfo {- xid: 42,- pid: Some(1234),- app_name: "example-app".to_owned(),- title: "Example".to_owned(),- is_on_screen: true,- z_index: Some(3),- x: 10,- y: 20,- width: 300,- height: 400,- };- let rec = window_record_json(&w);-- // Canonical cross-platform shape: nested `bounds` object.- let bounds = rec- .get("bounds")- .expect("record must carry a `bounds` object");- assert_eq!(bounds["x"], json!(10));- assert_eq!(bounds["y"], json!(20));- assert_eq!(bounds["width"], json!(300));- assert_eq!(bounds["height"], json!(400));-- // Legacy alias: flat fields must still be present.- assert_eq!(rec["x"], json!(10));- assert_eq!(rec["y"], json!(20));- assert_eq!(rec["width"], json!(300));- assert_eq!(rec["height"], json!(400));-- // Cross-platform companions.- assert_eq!(rec["app_name"], json!("example-app"));- assert_eq!(rec["is_on_screen"], json!(true));- assert_eq!(rec["z_index"], json!(3));- assert_eq!(rec["window_id"], json!(42));- assert_eq!(rec["title"], json!("Example"));- }-- #[test]- fn unavailable_wayland_order_serializes_as_null() {- let w = crate::x11::WindowInfo {- xid: 43,- pid: Some(1234),- app_name: "native-wayland-app".to_owned(),- title: "Example".to_owned(),- is_on_screen: true,- z_index: None,- x: 0,- y: 0,- width: 300,- height: 400,- };-- assert_eq!(window_record_json(&w)["z_index"], Value::Null);- }-- #[test]- fn chromium_launch_detection_uses_executable_basename() {- assert!(chromium_family_program("/usr/bin/google-chrome-stable"));- assert!(chromium_family_program("CuaTestHarness.Electron"));- assert!(chromium_family_program("chromium-browser"));- assert!(!chromium_family_program("/usr/bin/gnome-text-editor"));- }-}+mod list_windows_tests;// ── get_window_state ─────────────────────────────────────────────────────────@@ -817,34 +654,7 @@ fn megapixel_long_edge_cap(w: u32, h: u32, max_pixels: u64) -> Option<u32> {}#[cfg(test)]-mod megapixel_cap_tests {- use super::{megapixel_long_edge_cap, WINDOW_SCREENSHOT_MAX_PIXELS};-- #[test]- fn a_window_shot_above_the_api_threshold_is_capped_below_it() {- let edge =- megapixel_long_edge_cap(1568, 861, WINDOW_SCREENSHOT_MAX_PIXELS).expect("capped");- let scale = edge as f64 / 1568.0;- let (w, h) = (- (1568.0 * scale).round() as u64,- (861.0 * scale).round() as u64,- );- assert!(w * h <= WINDOW_SCREENSHOT_MAX_PIXELS, "{w}x{h}");- assert!(edge >= 1440 && edge < 1568, "{edge}");- }-- #[test]- fn a_shot_within_the_threshold_is_left_alone() {- assert_eq!(- megapixel_long_edge_cap(1280, 800, WINDOW_SCREENSHOT_MAX_PIXELS),- None- );- assert_eq!(- megapixel_long_edge_cap(0, 800, WINDOW_SCREENSHOT_MAX_PIXELS),- None- );- }-}+mod megapixel_cap_tests;/// Build a single structured element entry for `get_window_state`./// Returns `None` when the node has no `element_index` (non-actionable rows).@@ -1940,49 +1750,7 @@ fn surface_identity_unproven_error(xid: u64, reason: String) -> Value {// ── launch_app ───────────────────────────────────────────────────────────────#[cfg(test)]-mod get_window_state_actions_tests {- use super::*;- use crate::atspi::AtspiNode;-- fn node(actions: Vec<String>) -> AtspiNode {- AtspiNode {- element_index: Some(1),- role: "button".to_owned(),- name: Some("ok".to_owned()),- value: None,- checked: None,- enabled: Some(true),- selected: None,- description: None,- actions,- element_key: 1,- identity: None,- depth: 0,- parent_element_index: None,- in_web_content: false,- object_ref: None,- }- }-- #[test]- fn element_entry_omits_actions_when_empty() {- let n = node(Vec::new());- let entry = build_element_entry(&n, None, None).unwrap();- assert!(entry.get("actions").is_none());- }-- #[test]- fn element_entry_filters_blank_action_names() {- let n = node(vec![- "Press".to_owned(),- "".to_owned(),- " ".to_owned(),- "Open".to_owned(),- ]);- let entry = build_element_entry(&n, None, None).unwrap();- assert_eq!(entry["actions"], json!(["Press", "Open"]));- }-}+mod get_window_state_actions_tests;pub struct LaunchAppTool;static LAUNCH_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -2113,124 +1881,7 @@ fn xdg_open_failure(mut child: std::process::Child) -> Option<String> {}#[cfg(test)]-mod launch_app_tests {- use super::*;- use crate::installed_apps::InstalledApp;-- fn app(name: &str, bundle_id: &str, launch_path: &str) -> InstalledApp {- InstalledApp {- name: name.to_owned(),- bundle_id: bundle_id.to_owned(),- launch_path: launch_path.to_owned(),- last_used: None,- startup_wm_class: None,- }- }-- fn fixture() -> Vec<InstalledApp> {- vec![- app("Galculator", "galculator", "galculator"),- app(- "Google Chrome",- "google-chrome",- "/usr/bin/google-chrome-stable",- ),- app("File Manager", "thunar", "thunar"),- app(- "File Manager Settings",- "thunar-settings",- "thunar-settings",- ),- ]- }-- /// Process state letter from `/proc/<pid>/stat`, or `None` once the entry- /// is gone. `comm` may itself contain spaces and parentheses, so the state- /// is read after the final `)` rather than by splitting from the left.- fn proc_state(pid: u32) -> Option<char> {- let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;- let after_comm = stat.rsplit_once(')')?.1;- after_comm.split_whitespace().next()?.chars().next()- }-- #[test]- fn launched_children_are_reaped_instead_of_lingering_as_zombies() {- // A launched app that exits must not stay in the process table. The- // driver never waits on what it launches, so without an explicit- // reaper every launch leaked a pid slot for the daemon's lifetime and- // left "does this pid exist" liveness checks reporting a terminated- // app as still running.- // `/bin/sh` rather than a richer coreutils binary: it is the one- // executable POSIX and the Nix build sandbox both guarantee, and the- // sandbox has no `/bin/true`.- let pid = spawn_launch_command("/bin/sh -c exit", &[]).expect("/bin/sh should spawn");- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);- loop {- match proc_state(pid) {- None => break, // reaped, entry gone- Some(state) if state != 'Z' => {} // still running or exiting- Some(_) => {- assert!(- std::time::Instant::now() < deadline,- "pid {pid} was still a zombie after the reaper deadline"- );- }- }- assert!(- std::time::Instant::now() < deadline,- "pid {pid} was never reaped"- );- std::thread::sleep(std::time::Duration::from_millis(25));- }- }-- #[test]- fn matches_exact_display_name_case_insensitively() {- let apps = fixture();- let hit = match_installed_app(&apps, "google chrome").expect("should match");- assert_eq!(hit.bundle_id, "google-chrome");- }-- #[test]- fn matches_desktop_file_id_and_exec_basename() {- let apps = fixture();- assert_eq!(- match_installed_app(&apps, "galculator").unwrap().name,- "Galculator"- );- assert_eq!(- match_installed_app(&apps, "google-chrome-stable")- .unwrap()- .name,- "Google Chrome"- );- }-- #[test]- fn matches_unambiguous_display_name_substring() {- let apps = fixture();- assert_eq!(- match_installed_app(&apps, "chrome").unwrap().name,- "Google Chrome"- );- }-- #[test]- fn refuses_ambiguous_substring_and_unknown_names() {- let apps = fixture();- // "file manager" is a substring of two entries — refuse to guess.- // ("File Manager" itself still resolves via the exact-name rung.)- assert!(match_installed_app(&apps, "file man").is_none());- assert_eq!(- match_installed_app(&apps, "file manager")- .unwrap()- .bundle_id,- "thunar"- );- assert!(match_installed_app(&apps, "gnome-calculator").is_none());- assert!(match_installed_app(&apps, "").is_none());- }-}+mod launch_app_tests;#[async_trait]impl Tool for LaunchAppTool {@@ -2594,81 +2245,7 @@ fn resolve_launched_windows(}#[cfg(test)]-mod launch_resolution_tests {- use super::*;-- fn window(class: &str) -> crate::x11::WindowInfo {- crate::x11::WindowInfo {- xid: 1,- pid: Some(7),- app_name: class.into(),- title: "t".into(),- is_on_screen: true,- z_index: None,- x: 0,- y: 0,- width: 1,- height: 1,- }- }-- #[test]- fn launch_queries_match_window_classes() {- assert!(window_matches_launch(- &window("org.gnome.Nautilus"),- "nautilus"- ));- assert!(window_matches_launch(- &window("org.gnome.Nautilus"),- "org.gnome.Nautilus"- ));- assert!(window_matches_launch(- &window("Gnome-terminal"),- "gnome-terminal"- ));- assert!(window_matches_launch(- &window("Gnome-control-center"),- "gnome-control-center"- ));- assert!(window_matches_launch(- &window("Org.gnome.Nautilus"),- "org.gnome.Nautilus.desktop"- ));- assert!(window_matches_launch(- &window("Org.gnome.Nautilus"),- "Files\u{0}org.gnome.Nautilus\u{0}nautilus --new-window"- ));- assert!(window_matches_launch(- &window("Gnome-control-center"),- "Settings\u{0}Settings\u{0}gnome-control-center"- ));- assert!(!window_matches_launch(&window("Gedit"), "nautilus"));- assert!(!window_matches_launch(&window(""), "nautilus"));- }-- #[test]- fn a_missing_process_counts_as_exited() {- assert!(process_exited(u32::MAX - 1));- assert!(!process_exited(std::process::id()));- }-- #[test]- fn a_handoff_timeout_is_a_refusal_not_a_null_pid_success() {- let result = launch_handoff_timeout_result("Nautilus", 4242, 8);- assert_eq!(- result.is_error,- Some(true),- "a hand-off timeout must be reported as an error, not success"- );- let s = result.structured_content.unwrap();- assert_eq!(s["code"], "launch_handoff_timeout");- assert_eq!(s["effect"], "refused");- assert_eq!(s["pid"], Value::Null);- assert_eq!(s["running"], Value::Null);- assert_eq!(s["launcher_pid"], 4242);- assert_eq!(s["waited_secs"], 8);- }-}+mod launch_resolution_tests;fn chromium_family_program(program: &str) -> bool {let basename = std::path::Path::new(program)@@ -3015,65 +2592,7 @@ fn require_point_args(tool: &str, args: &Value) -> Option<ToolResult> {}#[cfg(test)]-mod pointer_argument_tests {- use super::*;-- #[test]- fn pid_only_pointer_call_is_refused_not_clicked_at_origin() {- let refusal = require_point_args("click", &json!({"target_id": "s1:147", "pid": 1867}))- .expect("refused");- assert_eq!(refusal.is_error, Some(true));- let structured = refusal.structured_content.expect("structured");- assert_eq!(structured["code"], "invalid_arguments");- assert_eq!(structured["effect"], "refused");- assert!(structured["accepted_forms"].as_array().unwrap().len() == 3);- }-- #[test]- fn complete_point_passes() {- assert!(require_point_args(- "click",- &json!({"pid": 1, "window_id": 2, "x": 3, "y": 4.5})- )- .is_none());- assert!(require_point_args("click", &json!({"x": 1, "y": null})).is_some());- assert!(require_point_args("click", &json!({"y": 1})).is_some());- }-- #[test]- fn foreground_report_becomes_evidence() {- let report = crate::input::ForegroundReport {- already_active: false,- retried_activation: false,- confirm_ms: 12,- focus_after: crate::input::FocusAfter::SamePid,- window_change: Some("appeared: window 9 \"Brightness-Contrast\"".into()),- };- let v = foreground_structured("x11_xtest_fg", report, serde_json::Map::new());- assert_eq!(v["effect"], "confirmed");- assert_eq!(v["focus_after"], "same_pid");- assert_eq!(v["evidence"][0]["kind"], "window_change");- let quiet = crate::input::ForegroundReport {- already_active: true,- retried_activation: false,- confirm_ms: 0,- focus_after: crate::input::FocusAfter::Target,- window_change: None,- };- let v = foreground_structured("x11_xtest_fg", quiet, serde_json::Map::new());- assert_eq!(v["effect"], "unverifiable");- assert_eq!(v["evidence"][0]["kind"], "native_api_result");- let lost = crate::input::ForegroundReport {- already_active: true,- retried_activation: false,- confirm_ms: 0,- focus_after: crate::input::FocusAfter::Elsewhere,- window_change: Some("closed: window 3".into()),- };- let v = foreground_structured("x11_xtest_fg", lost, serde_json::Map::new());- assert_eq!(v["effect"], "suspected_noop");- }-}+mod pointer_argument_tests;fn parse_mouse_button(name: &str) -> u8 {match name {@@ -3229,27 +2748,7 @@ fn type_text_readback_result(}#[cfg(test)]-mod type_text_readback_tests {- use super::*;-- #[test]- fn typed_text_is_confirmed_only_when_read_back() {- let confirmed =- type_text_readback_result(1, 3, "-40", "via targeted AT-SPI", Some("-40.0".into()));- let s = confirmed.structured_content.clone().unwrap();- assert_eq!(s["effect"], "confirmed");- assert_eq!(s["verified"], true);- assert_eq!(s["evidence"][0]["kind"], "value_readback");- let contained = type_text_readback_result(1, 3, "ab", "r", Some("xxabyy".into()));- assert_eq!(contained.structured_content.unwrap()["effect"], "confirmed");- let mismatch = type_text_readback_result(1, 3, "ab", "r", Some("zz".into()));- let s = mismatch.structured_content.unwrap();- assert_eq!(s["effect"], "unverifiable");- assert_eq!(s["readback"], "zz");- let blind = type_text_readback_result(1, 3, "ab", "r", None);- assert_eq!(blind.structured_content.unwrap()["effect"], "unverifiable");- }-}+mod type_text_readback_tests;/// Build the success `ToolResult` for an AT-SPI insert. The EditableText/// method's boolean is a delivery acknowledgement, not a fresh value readback,@@ -8478,26 +7977,7 @@ fn press_key_chord(mods: &[String], key: &str) -> Option<Vec<String>> {}#[cfg(test)]-mod press_key_tests {- use super::press_key_chord;-- #[test]- fn unmodified_press_stays_on_the_single_key_route() {- assert_eq!(press_key_chord(&[], "return"), None);- }-- #[test]- fn modifiers_are_promoted_to_a_chord_in_order() {- assert_eq!(- press_key_chord(&["ctrl".to_owned()], "s"),- Some(vec!["ctrl".to_owned(), "s".to_owned()])- );- assert_eq!(- press_key_chord(&["ctrl".to_owned(), "shift".to_owned()], "t"),- Some(vec!["ctrl".to_owned(), "shift".to_owned(), "t".to_owned()])- );- }-}+mod press_key_tests;#[async_trait]impl Tool for PressKeyTool {@@ -9625,56 +9105,7 @@ fn path_normalised_to_basename(value: &str, seen: &str) -> bool {}#[cfg(test)]-mod set_value_tests {- use super::*;-- #[test]- fn a_file_chooser_keeping_the_basename_counts_as_committed() {- assert!(path_normalised_to_basename(- "/home/user/Desktop/tone.wav",- "tone.wav"- ));- assert!(!path_normalised_to_basename(- "/home/user/Desktop/tone.wav",- "other.wav"- ));- assert!(!path_normalised_to_basename("tone.wav", "tone.wav"));- let ok = set_value_result(- 3,- "/home/user/Desktop/tone.wav",- "ax",- Some("tone.wav".into()),- None,- );- let s = ok.structured_content.unwrap();- assert_eq!(s["verified"], true);- assert_eq!(s["effect"], "confirmed");- }-- #[test]- fn readback_agreement_is_numeric_aware() {- assert!(values_agree("40", "40.0"));- assert!(values_agree("40", " 40 "));- assert!(values_agree("abc", "abc"));- assert!(!values_agree("40", "41"));- assert!(!values_agree("40", "forty"));- }-- #[test]- fn set_value_result_is_verified_only_on_matching_readback() {- let ok = set_value_result(3, "40", "click_type_mpx", Some("40.0".into()), None);- let s = ok.structured_content.unwrap();- assert_eq!(s["verified"], true);- assert_eq!(s["effect"], "confirmed");- let noop = set_value_result(3, "40", "ax", Some("10.0".into()), None);- let s = noop.structured_content.unwrap();- assert_eq!(s["verified"], false);- assert_eq!(s["effect"], "suspected_noop");- assert_eq!(s["readback"], "10.0");- let blind = set_value_result(3, "40", "ax", None, None);- assert_eq!(blind.structured_content.unwrap()["effect"], "unverifiable");- }-}+mod set_value_tests;// ── scroll ────────────────────────────────────────────────────────────────────@@ -14614,525 +14045,28 @@ pub fn build_registry_with_provider(}#[cfg(test)]-mod click_button_schema_tests {- use super::{chromium_background_must_refuse, maps_indicate_gtk, ClickTool};- use cua_driver_core::tool::Tool;-- /// Surface 5: schema must advertise the three canonical button values and- /// describe the back-compat default. Linux already routed button=middle/right- /// pre-Surface-5; this freezes the schema shape so the contract can't drift.- #[test]- fn schema_advertises_button_enum_and_description() {- let tool = ClickTool {- state: super::ToolState::new(),- };- let d = tool.def();- let props = d.input_schema.get("properties").expect("properties");- let button = props.get("button").expect("button field present");- assert_eq!(button.get("type").and_then(|v| v.as_str()), Some("string"));- let enum_vals: Vec<&str> = button- .get("enum")- .and_then(|v| v.as_array())- .expect("button.enum present")- .iter()- .filter_map(|v| v.as_str())- .collect();- for need in ["left", "right", "middle"] {- assert!(enum_vals.contains(&need), "missing {need} in button.enum");- }- let desc = button- .get("description")- .and_then(|v| v.as_str())- .expect("button.description present");- let lc = desc.to_ascii_lowercase();- assert!(lc.contains("left"), "description should mention default");- assert!(- lc.contains("wayland"),- "description should call out wayland fallback"- );- }-- #[test]- fn chromium_background_requires_focus_free_inject_mode() {- assert!(chromium_background_must_refuse(false, false, true));- assert!(!chromium_background_must_refuse(false, true, true));- assert!(!chromium_background_must_refuse(true, false, true));- assert!(!chromium_background_must_refuse(false, false, false));- }-- #[test]- fn gtk_process_maps_are_detected_without_matching_unrelated_libraries() {- assert!(maps_indicate_gtk(- "7f00-7f01 r-xp /usr/lib/x86_64-linux-gnu/libgtk-3.so.0.2404.32"- ));- assert!(maps_indicate_gtk(- "7f00-7f01 r-xp /nix/store/hash-gtk4/lib/libgtk-4.so.1"- ));- assert!(!maps_indicate_gtk(- "7f00-7f01 r-xp /usr/lib/x86_64-linux-gnu/libgdk_pixbuf-2.0.so"- ));- }-}+mod click_button_schema_tests;#[cfg(test)]-mod browser_launch_guard_tests {- use super::contains_remote_debugging_flag;-- #[test]- fn rejects_all_chromium_remote_debugging_spellings() {- assert!(contains_remote_debugging_flag("--remote-debugging-port=0"));- assert!(contains_remote_debugging_flag("--REMOTE-DEBUGGING-PIPE"));- assert!(contains_remote_debugging_flag(- "/usr/bin/chrome --remote-debugging-port 9222"- ));- assert!(!contains_remote_debugging_flag(- "--user-data-dir=/tmp/profile"- ));- }-}+mod browser_launch_guard_tests;#[cfg(test)]-mod pid_window_target_tests {- use super::*;- use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};-- fn window(xid: u64, pid: u32) -> crate::x11::WindowInfo {- crate::x11::WindowInfo {- xid,- pid: Some(pid),- app_name: "editor".into(),- title: format!("Document {xid}"),- is_on_screen: true,- z_index: Some(1),- x: 0,- y: 0,- width: 640,- height: 480,- }- }-- #[test]- fn same_pid_sibling_windows_are_ambiguous() {- let candidates =- window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);- assert!(matches!(- resolve_pid_window_target(candidates),- PidWindowTargetResolution::Ambiguous(windows)- if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]- ));- }-}+mod pid_window_target_tests;#[cfg(test)]-mod session_cursor_target_tests {- use super::{- choose_keyboard_cursor_target, cursor_control_scope, named_session_cursor_key,- reveal_pointer_action_for, CursorControlScope, ToolState,- };- use serde_json::json;-- #[test]- fn lifecycle_owned_sessions_opt_into_keyboard_cursor_positioning() {- assert_eq!(- named_session_cursor_key(&json!({"session": "editing-run"})).as_deref(),- Some("editing-run")- );- assert_eq!(- named_session_cursor_key(&json!({"cursor_id": "legacy"})),- None- );- assert_eq!(- named_session_cursor_key(&json!({"_session_id": "implicit"})).as_deref(),- Some("implicit")- );- assert_eq!(named_session_cursor_key(&json!({})), None);- }-- #[test]- fn keyboard_cursor_uses_explicit_then_remembered_then_safe_seed() {- let explicit = Some((10.0, 20.0));- let remembered = Some((30.0, 40.0));- let window_center = Some((50.0, 60.0));- let current_pointer = Some((70.0, 80.0));-- assert_eq!(- choose_keyboard_cursor_target(explicit, remembered, window_center, current_pointer),- explicit- );- assert_eq!(- choose_keyboard_cursor_target(None, remembered, window_center, current_pointer),- remembered- );- assert_eq!(- choose_keyboard_cursor_target(None, None, window_center, current_pointer),- window_center- );- assert_eq!(- choose_keyboard_cursor_target(None, None, None, current_pointer),- current_pointer- );- }-- #[test]- fn invalid_coordinates_do_not_poison_session_position_reuse() {- assert_eq!(- choose_keyboard_cursor_target(Some((f64::NAN, 1.0)), Some((12.0, 34.0)), None, None,),- Some((12.0, 34.0))- );- }-- #[test]- fn real_pointer_control_requires_explicit_desktop_scope() {- assert_eq!(cursor_control_scope(&json!({})), CursorControlScope::Agent);- assert_eq!(- cursor_control_scope(&json!({"scope": "window"})),- CursorControlScope::Agent- );- assert_eq!(- cursor_control_scope(&json!({"scope": "desktop"})),- CursorControlScope::Desktop- );- }-- #[tokio::test]- async fn pointer_position_survives_an_unavailable_overlay() {- let state = ToolState::new();- reveal_pointer_action_for(&state, "no-renderer", 123.0, 456.0, true).await;-- let cursor = state- .cursor_registry- .get("no-renderer")- .expect("pointer action records its position independently of rendering");- assert!(cursor.config.enabled, "input must revive its agent cursor");- assert_eq!(cursor.x.zip(cursor.y), Some((123.0, 456.0)));- }-}+mod session_cursor_target_tests;#[cfg(test)]-mod window_capture_dimension_tests {- use super::{GetWindowStateTool, ToolState};- use cua_driver_core::tool::Tool;-- #[test]- fn schema_exposes_zero_as_native_resolution() {- let tool = GetWindowStateTool {- state: ToolState::new(),- };- assert_eq!(- tool.def().input_schema["properties"]["max_image_dimension"]["minimum"],- 0- );- }-}+mod window_capture_dimension_tests;#[cfg(test)]-mod desktop_capture_frame_tests {- use super::{capture_admission_error, normalize_desktop_capture_for_action_frame};-- fn png(width: u32, height: u32) -> Vec<u8> {- let rgba = vec![0x7f; (width * height * 4) as usize];- cua_driver_core::image_utils::encode_rgba_to_png(&rgba, width, height)- .expect("encode fixture")- }-- #[test]- fn native_wayland_capture_is_resized_to_the_reported_action_frame() {- let (normalized, width, height, scale) =- normalize_desktop_capture_for_action_frame(png(3200, 2000), 1600, 1000)- .expect("normalize 2x capture");-- assert_eq!((width, height), (1600, 1000));- assert_eq!(- cua_driver_core::image_utils::png_dimensions(&normalized).unwrap(),- (1600, 1000)- );- assert_eq!(scale, 2.0);- }-- #[test]- fn nonuniform_capture_mapping_fails_instead_of_distorting_coordinates() {- let error = normalize_desktop_capture_for_action_frame(png(3200, 2000), 1600, 1200)- .expect_err("nonuniform mapping must fail closed");- assert!(error.to_string().contains("cannot be mapped uniformly"));- }-- #[test]- fn capture_refusal_exposes_specific_code_and_refused_effect() {- let refusal = capture_admission_error(anyhow::Error::new(- cua_driver_core::capture_runtime::CaptureActionError::NativeActionFrameMismatch,- ));- let structured = refusal.structured_content.unwrap();- assert_eq!(structured["code"], "capture_frame_mismatch");- assert_eq!(structured["effect"], "refused");- }-}+mod desktop_capture_frame_tests;#[cfg(test)]-mod background_budget_tests {- use super::*;-- #[test]- fn synthetic_pointer_drop_detection_covers_gtk_vcl_and_qt() {- assert!(maps_indicate_synthetic_pointer_dropped(- "7f /usr/lib/libgtk-3.so.0\n"- ));- assert!(maps_indicate_synthetic_pointer_dropped(- "7f /usr/lib/libgtk-4.so.1\n"- ));- assert!(maps_indicate_synthetic_pointer_dropped(- "7f /opt/libreoffice/program/libmergedlo.so\n"- ));- assert!(maps_indicate_synthetic_pointer_dropped(- "7f /usr/lib/libvcllo.so\n"- ));- assert!(maps_indicate_synthetic_pointer_dropped(- "7f /usr/lib/libQt5Gui.so.5\n"- ));- assert!(!maps_indicate_synthetic_pointer_dropped(- "7f /usr/lib/libgtk-x11-2.0.so.0\n"- ));- assert!(!maps_indicate_synthetic_pointer_dropped(- "7f /usr/lib/libX11.so.6\n"- ));- }-- #[test]- fn desktop_window_lines_expose_pid_and_window_id() {- let windows = vec![crate::x11::WindowInfo {- xid: 0x2e00003,- pid: Some(4321),- app_name: "libreoffice".into(),- title: "Untitled 1 - LibreOffice Calc".into(),- is_on_screen: true,- z_index: None,- x: 0,- y: 27,- width: 1920,- height: 1053,- }];- let text = desktop_window_lines(&windows, 1.0);- assert!(text.contains("pid=4321 window_id=48234499"));- assert!(text.contains("LibreOffice Calc"));- assert!(text.contains("app=libreoffice"));- assert!(text.contains("get_window_state(pid, window_id)"));- assert!(desktop_window_lines(&[], 1.0).contains("none"));- // A downsized desktop screenshot reports window rects in ITS pixels.- let scaled = desktop_window_lines(&windows, 1.5);- assert!(scaled.contains("1280x702 at (0,18)"), "{scaled}");- }-}+mod background_budget_tests;#[cfg(test)]-mod background_keyboard_route_tests {- use super::{element_needs_real_click, split_key_combo, wm_chord_kind, WmChord};-- #[test]- fn key_combos_split_into_modifiers_and_key() {- assert_eq!(- split_key_combo("alt+F4"),- (vec!["alt".to_owned()], "F4".to_owned())- );- assert_eq!(- split_key_combo("ctrl+shift+t"),- (vec!["ctrl".to_owned(), "shift".to_owned()], "t".to_owned())- );- assert_eq!(split_key_combo("+"), (vec![], "+".to_owned()));- assert_eq!(- split_key_combo("ctrl++"),- (vec!["ctrl".to_owned()], "+".to_owned())- );- assert_eq!(split_key_combo("Return"), (vec![], "Return".to_owned()));- // Not a modifier prefix: left untouched for the keysym resolver.- assert_eq!(split_key_combo("a+b"), (vec![], "a+b".to_owned()));- }-- #[test]- fn wm_chords_are_recognised() {- let m = |xs: &[&str]| xs.iter().map(|x| x.to_string()).collect::<Vec<_>>();- assert_eq!(- wm_chord_kind("F4", &m(&["alt"])),- Some(WmChord::CloseWindow)- );- assert_eq!(- wm_chord_kind("f4", &m(&["Alt_L"])),- Some(WmChord::CloseWindow)- );- assert_eq!(- wm_chord_kind("Tab", &m(&["alt"])),- Some(WmChord::Unavailable)- );- assert_eq!(- wm_chord_kind("Tab", &m(&["alt", "shift"])),- Some(WmChord::Unavailable)- );- assert_eq!(- wm_chord_kind("a", &m(&["super"])),- Some(WmChord::Unavailable)- );- assert_eq!(- wm_chord_kind("t", &m(&["ctrl", "alt"])),- Some(WmChord::Unavailable)- );- assert_eq!(- wm_chord_kind("F4", &m(&["ctrl", "alt"])),- Some(WmChord::Unavailable)- );- // Application chords stay with the application.- assert_eq!(wm_chord_kind("c", &m(&["ctrl"])), None);- assert_eq!(wm_chord_kind("F4", &m(&["ctrl"])), None);- assert_eq!(wm_chord_kind("f", &m(&["alt"])), None);- assert_eq!(wm_chord_kind("F4", &m(&[])), None);- assert_eq!(wm_chord_kind("s", &m(&["ctrl", "shift"])), None);- }-- #[test]- fn focus_taking_roles_need_a_real_click() {- for role in ["spin button", "Text", "entry", "slider", "combo box"] {- assert!(element_needs_real_click(role), "{role}");- }- for role in ["menu item", "push button", "menu", "check box", "page tab"] {- assert!(!element_needs_real_click(role), "{role}");- }- }-}+mod background_keyboard_route_tests;#[cfg(test)]-mod visibility_tests {- use super::*;-- #[test]- fn framed_elements_lead_and_keep_their_relative_order() {- let elements = vec![- json!({"element_index": 0, "role": "menu"}),- json!({"element_index": 1, "role": "push button", "frame": {"x": 1, "y": 1, "w": 2, "h": 2}}),- json!({"element_index": 2, "role": "menu"}),- json!({"element_index": 3, "role": "paragraph", "frame": {"x": 1, "y": 9, "w": 2, "h": 2}}),- ];- let ordered: Vec<u64> = framed_elements_first(elements)- .iter()- .map(|e| e["element_index"].as_u64().unwrap())- .collect();- assert_eq!(ordered, vec![1, 3, 0, 2]);- }-- #[test]- fn a_frameless_popup_returns_only_the_menu_entries_drawn_inside_it() {- let elements = vec![- json!({"element_index": 1, "role": "push button", "frame": {"x": 5, "y": 5, "w": 20, "h": 20}}),- json!({"element_index": 2, "role": "menu item", "label": "Paragraph...", "frame": {"x": 2, "y": 30, "w": 180, "h": 22}}),- json!({"element_index": 3, "role": "menu item", "label": "elsewhere", "frame": {"x": 400, "y": 30, "w": 180, "h": 22}}),- json!({"element_index": 4, "role": "menu", "label": "Format"}),- ];- let kept: Vec<u64> = popup_menu_elements(elements.clone(), (0, 0), 200, 400)- .iter()- .map(|e| e["element_index"].as_u64().unwrap())- .collect();- assert_eq!(kept, vec![2]);- assert_eq!(- popup_menu_elements(elements[..1].to_vec(), (0, 0), 200, 400).len(),- 1- );- }-- #[test]- fn a_combo_popup_returns_the_rows_of_the_list_that_fills_it() {- // Qt: the combo list lives under the combo box inside the dialog; the- // main window's menubar entries are elsewhere on the screen.- let elements = vec![- json!({"element_index": 1, "role": "menu", "label": "Audio", "frame": {"x": -600, "y": -300, "w": 50, "h": 20}}),- json!({"element_index": 7, "role": "list", "frame": {"x": 1, "y": 1, "w": 198, "h": 118}}),- json!({"element_index": 8, "role": "list item", "label": "Desktop", "parent_index": 7, "frame": {"x": 2, "y": 2, "w": 190, "h": 22}}),- json!({"element_index": 9, "role": "list item", "label": "user", "parent_index": 7, "frame": {"x": 2, "y": 26, "w": 190, "h": 22}}),- json!({"element_index": 12, "role": "push button", "label": "Open", "frame": {"x": 20, "y": 20, "w": 60, "h": 20}}),- ];- let kept: Vec<u64> = popup_menu_elements(elements, (0, 0), 200, 120)- .iter()- .map(|e| e["element_index"].as_u64().unwrap())- .collect();- assert_eq!(kept, vec![8, 9]);- }-- #[test]- fn a_list_popup_without_an_indexed_container_keeps_its_item_rows_only() {- let elements = vec![- json!({"element_index": 1, "role": "menu", "label": "Audio", "frame": {"x": 1, "y": 1, "w": 50, "h": 20}}),- json!({"element_index": 8, "role": "list item", "label": "Desktop", "frame": {"x": 2, "y": 2, "w": 190, "h": 22}}),- json!({"element_index": 9, "role": "tree item", "label": "user", "frame": {"x": 2, "y": 26, "w": 190, "h": 22}}),- json!({"element_index": 12, "role": "push button", "label": "Open", "frame": {"x": 20, "y": 20, "w": 60, "h": 20}}),- ];- let kept: Vec<u64> = popup_menu_elements(elements, (0, 0), 200, 120)- .iter()- .map(|e| e["element_index"].as_u64().unwrap())- .collect();- assert_eq!(kept, vec![8, 9]);- }-- #[test]- fn menu_roles_take_the_real_press() {- for role in ["menu", "Menu Item", "check menu item", "radio menu item"] {- assert!(element_is_menu_role(role), "{role}");- }- for role in ["menu bar", "push button", "text"] {- assert!(!element_is_menu_role(role), "{role}");- }- }-- #[test]- fn overlays_name_the_follow_up_call_per_dialog_and_popup() {- let overlays = WindowOverlays {- dialogs: vec![json!({- "window_id": 71, "title": "Position and Size", "transient_for": 3, "modal": true,- "bounds": {"x": 100, "y": 100, "width": 400, "height": 300}- })],- popups: vec![json!({- "window_id": 72, "title": "", "pid": 5,- "bounds": {"x": 10, "y": 30, "width": 200, "height": 400}- })],- covers_window: true,- window_rect: Some((0, 0, 800, 600)),- };- let note = overlays.follow_up(5).unwrap();- assert!(- note.contains(- "dialog \"Position and Size\" (window_id 71, transient of window 3, modal)"- ),- "{note}"- );- assert!(- note.contains("get_window_state(pid=5, window_id=71)"),- "{note}"- );- assert!(- note.contains("popup (window_id 72, bounds x=10 y=30 200x400)"),- "{note}"- );- assert!(rects_intersect((0, 0, 800, 600), (100, 100, 400, 300)));- assert!(!rects_intersect((0, 0, 800, 600), (800, 0, 10, 10)));- }-- #[test]- fn a_cross_process_dialog_names_its_real_owning_pid_in_the_follow_up() {- // GIMP's "Export Image as JPEG" dialog spawned as a separate process- // (owning_pid 999) but is transient-for the target pid (5)'s window.- let overlays = WindowOverlays {- dialogs: vec![json!({- "window_id": 90, "title": "Export Image as JPEG", "transient_for": 10,- "modal": false,- "bounds": {"x": 0, "y": 0, "width": 300, "height": 200},- "owning_pid": 999,- })],- popups: vec![],- covers_window: false,- window_rect: Some((0, 0, 800, 600)),- };- let note = overlays.follow_up(5).unwrap();- assert!(- note.contains("owned by a different process pid 999, not pid 5"),- "{note}"- );- assert!(- note.contains("get_window_state(pid=5, window_id=90)"),- "{note}"- );- }-}+mod visibility_tests;diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/background_budget_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/background_budget_tests.rsnew file mode 100644index 0000000000..edcb78ed06--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/background_budget_tests.rs@@ -0,0 +1,51 @@+use super::*;++#[test]+fn synthetic_pointer_drop_detection_covers_gtk_vcl_and_qt() {+ assert!(maps_indicate_synthetic_pointer_dropped(+ "7f /usr/lib/libgtk-3.so.0\n"+ ));+ assert!(maps_indicate_synthetic_pointer_dropped(+ "7f /usr/lib/libgtk-4.so.1\n"+ ));+ assert!(maps_indicate_synthetic_pointer_dropped(+ "7f /opt/libreoffice/program/libmergedlo.so\n"+ ));+ assert!(maps_indicate_synthetic_pointer_dropped(+ "7f /usr/lib/libvcllo.so\n"+ ));+ assert!(maps_indicate_synthetic_pointer_dropped(+ "7f /usr/lib/libQt5Gui.so.5\n"+ ));+ assert!(!maps_indicate_synthetic_pointer_dropped(+ "7f /usr/lib/libgtk-x11-2.0.so.0\n"+ ));+ assert!(!maps_indicate_synthetic_pointer_dropped(+ "7f /usr/lib/libX11.so.6\n"+ ));+}++#[test]+fn desktop_window_lines_expose_pid_and_window_id() {+ let windows = vec![crate::x11::WindowInfo {+ xid: 0x2e00003,+ pid: Some(4321),+ app_name: "libreoffice".into(),+ title: "Untitled 1 - LibreOffice Calc".into(),+ is_on_screen: true,+ z_index: None,+ x: 0,+ y: 27,+ width: 1920,+ height: 1053,+ }];+ let text = desktop_window_lines(&windows, 1.0);+ assert!(text.contains("pid=4321 window_id=48234499"));+ assert!(text.contains("LibreOffice Calc"));+ assert!(text.contains("app=libreoffice"));+ assert!(text.contains("get_window_state(pid, window_id)"));+ assert!(desktop_window_lines(&[], 1.0).contains("none"));+ // A downsized desktop screenshot reports window rects in ITS pixels.+ let scaled = desktop_window_lines(&windows, 1.5);+ assert!(scaled.contains("1280x702 at (0,18)"), "{scaled}");+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/background_keyboard_route_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/background_keyboard_route_tests.rsnew file mode 100644index 0000000000..3e11a11fc2--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/background_keyboard_route_tests.rs@@ -0,0 +1,70 @@+use super::{element_needs_real_click, split_key_combo, wm_chord_kind, WmChord};++#[test]+fn key_combos_split_into_modifiers_and_key() {+ assert_eq!(+ split_key_combo("alt+F4"),+ (vec!["alt".to_owned()], "F4".to_owned())+ );+ assert_eq!(+ split_key_combo("ctrl+shift+t"),+ (vec!["ctrl".to_owned(), "shift".to_owned()], "t".to_owned())+ );+ assert_eq!(split_key_combo("+"), (vec![], "+".to_owned()));+ assert_eq!(+ split_key_combo("ctrl++"),+ (vec!["ctrl".to_owned()], "+".to_owned())+ );+ assert_eq!(split_key_combo("Return"), (vec![], "Return".to_owned()));+ // Not a modifier prefix: left untouched for the keysym resolver.+ assert_eq!(split_key_combo("a+b"), (vec![], "a+b".to_owned()));+}++#[test]+fn wm_chords_are_recognised() {+ let m = |xs: &[&str]| xs.iter().map(|x| x.to_string()).collect::<Vec<_>>();+ assert_eq!(+ wm_chord_kind("F4", &m(&["alt"])),+ Some(WmChord::CloseWindow)+ );+ assert_eq!(+ wm_chord_kind("f4", &m(&["Alt_L"])),+ Some(WmChord::CloseWindow)+ );+ assert_eq!(+ wm_chord_kind("Tab", &m(&["alt"])),+ Some(WmChord::Unavailable)+ );+ assert_eq!(+ wm_chord_kind("Tab", &m(&["alt", "shift"])),+ Some(WmChord::Unavailable)+ );+ assert_eq!(+ wm_chord_kind("a", &m(&["super"])),+ Some(WmChord::Unavailable)+ );+ assert_eq!(+ wm_chord_kind("t", &m(&["ctrl", "alt"])),+ Some(WmChord::Unavailable)+ );+ assert_eq!(+ wm_chord_kind("F4", &m(&["ctrl", "alt"])),+ Some(WmChord::Unavailable)+ );+ // Application chords stay with the application.+ assert_eq!(wm_chord_kind("c", &m(&["ctrl"])), None);+ assert_eq!(wm_chord_kind("F4", &m(&["ctrl"])), None);+ assert_eq!(wm_chord_kind("f", &m(&["alt"])), None);+ assert_eq!(wm_chord_kind("F4", &m(&[])), None);+ assert_eq!(wm_chord_kind("s", &m(&["ctrl", "shift"])), None);+}++#[test]+fn focus_taking_roles_need_a_real_click() {+ for role in ["spin button", "Text", "entry", "slider", "combo box"] {+ assert!(element_needs_real_click(role), "{role}");+ }+ for role in ["menu item", "push button", "menu", "check box", "page tab"] {+ assert!(!element_needs_real_click(role), "{role}");+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/browser_launch_guard_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/browser_launch_guard_tests.rsnew file mode 100644index 0000000000..f9fefecaa6--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/browser_launch_guard_tests.rs@@ -0,0 +1,13 @@+use super::contains_remote_debugging_flag;++#[test]+fn rejects_all_chromium_remote_debugging_spellings() {+ assert!(contains_remote_debugging_flag("--remote-debugging-port=0"));+ assert!(contains_remote_debugging_flag("--REMOTE-DEBUGGING-PIPE"));+ assert!(contains_remote_debugging_flag(+ "/usr/bin/chrome --remote-debugging-port 9222"+ ));+ assert!(!contains_remote_debugging_flag(+ "--user-data-dir=/tmp/profile"+ ));+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/click_button_schema_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/click_button_schema_tests.rsnew file mode 100644index 0000000000..3d13735e85--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/click_button_schema_tests.rs@@ -0,0 +1,57 @@+use super::{chromium_background_must_refuse, maps_indicate_gtk, ClickTool};+use cua_driver_core::tool::Tool;++/// Surface 5: schema must advertise the three canonical button values and+/// describe the back-compat default. Linux already routed button=middle/right+/// pre-Surface-5; this freezes the schema shape so the contract can't drift.+#[test]+fn schema_advertises_button_enum_and_description() {+ let tool = ClickTool {+ state: super::ToolState::new(),+ };+ let d = tool.def();+ let props = d.input_schema.get("properties").expect("properties");+ let button = props.get("button").expect("button field present");+ assert_eq!(button.get("type").and_then(|v| v.as_str()), Some("string"));+ let enum_vals: Vec<&str> = button+ .get("enum")+ .and_then(|v| v.as_array())+ .expect("button.enum present")+ .iter()+ .filter_map(|v| v.as_str())+ .collect();+ for need in ["left", "right", "middle"] {+ assert!(enum_vals.contains(&need), "missing {need} in button.enum");+ }+ let desc = button+ .get("description")+ .and_then(|v| v.as_str())+ .expect("button.description present");+ let lc = desc.to_ascii_lowercase();+ assert!(lc.contains("left"), "description should mention default");+ assert!(+ lc.contains("wayland"),+ "description should call out wayland fallback"+ );+}++#[test]+fn chromium_background_requires_focus_free_inject_mode() {+ assert!(chromium_background_must_refuse(false, false, true));+ assert!(!chromium_background_must_refuse(false, true, true));+ assert!(!chromium_background_must_refuse(true, false, true));+ assert!(!chromium_background_must_refuse(false, false, false));+}++#[test]+fn gtk_process_maps_are_detected_without_matching_unrelated_libraries() {+ assert!(maps_indicate_gtk(+ "7f00-7f01 r-xp /usr/lib/x86_64-linux-gnu/libgtk-3.so.0.2404.32"+ ));+ assert!(maps_indicate_gtk(+ "7f00-7f01 r-xp /nix/store/hash-gtk4/lib/libgtk-4.so.1"+ ));+ assert!(!maps_indicate_gtk(+ "7f00-7f01 r-xp /usr/lib/x86_64-linux-gnu/libgdk_pixbuf-2.0.so"+ ));+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/desktop_capture_frame_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/desktop_capture_frame_tests.rsnew file mode 100644index 0000000000..82baf3fc4d--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/desktop_capture_frame_tests.rs@@ -0,0 +1,37 @@+use super::{capture_admission_error, normalize_desktop_capture_for_action_frame};++fn png(width: u32, height: u32) -> Vec<u8> {+ let rgba = vec![0x7f; (width * height * 4) as usize];+ cua_driver_core::image_utils::encode_rgba_to_png(&rgba, width, height).expect("encode fixture")+}++#[test]+fn native_wayland_capture_is_resized_to_the_reported_action_frame() {+ let (normalized, width, height, scale) =+ normalize_desktop_capture_for_action_frame(png(3200, 2000), 1600, 1000)+ .expect("normalize 2x capture");++ assert_eq!((width, height), (1600, 1000));+ assert_eq!(+ cua_driver_core::image_utils::png_dimensions(&normalized).unwrap(),+ (1600, 1000)+ );+ assert_eq!(scale, 2.0);+}++#[test]+fn nonuniform_capture_mapping_fails_instead_of_distorting_coordinates() {+ let error = normalize_desktop_capture_for_action_frame(png(3200, 2000), 1600, 1200)+ .expect_err("nonuniform mapping must fail closed");+ assert!(error.to_string().contains("cannot be mapped uniformly"));+}++#[test]+fn capture_refusal_exposes_specific_code_and_refused_effect() {+ let refusal = capture_admission_error(anyhow::Error::new(+ cua_driver_core::capture_runtime::CaptureActionError::NativeActionFrameMismatch,+ ));+ let structured = refusal.structured_content.unwrap();+ assert_eq!(structured["code"], "capture_frame_mismatch");+ assert_eq!(structured["effect"], "refused");+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/get_window_state_actions_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/get_window_state_actions_tests.rsnew file mode 100644index 0000000000..fddb546a42--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/get_window_state_actions_tests.rs@@ -0,0 +1,41 @@+use super::*;+use crate::atspi::AtspiNode;++fn node(actions: Vec<String>) -> AtspiNode {+ AtspiNode {+ element_index: Some(1),+ role: "button".to_owned(),+ name: Some("ok".to_owned()),+ value: None,+ checked: None,+ enabled: Some(true),+ selected: None,+ description: None,+ actions,+ element_key: 1,+ identity: None,+ depth: 0,+ parent_element_index: None,+ in_web_content: false,+ object_ref: None,+ }+}++#[test]+fn element_entry_omits_actions_when_empty() {+ let n = node(Vec::new());+ let entry = build_element_entry(&n, None, None).unwrap();+ assert!(entry.get("actions").is_none());+}++#[test]+fn element_entry_filters_blank_action_names() {+ let n = node(vec![+ "Press".to_owned(),+ "".to_owned(),+ " ".to_owned(),+ "Open".to_owned(),+ ]);+ let entry = build_element_entry(&n, None, None).unwrap();+ assert_eq!(entry["actions"], json!(["Press", "Open"]));+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/launch_app_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/launch_app_tests.rsnew file mode 100644index 0000000000..9adec8731e--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/launch_app_tests.rs@@ -0,0 +1,116 @@+use super::*;+use crate::installed_apps::InstalledApp;++fn app(name: &str, bundle_id: &str, launch_path: &str) -> InstalledApp {+ InstalledApp {+ name: name.to_owned(),+ bundle_id: bundle_id.to_owned(),+ launch_path: launch_path.to_owned(),+ last_used: None,+ startup_wm_class: None,+ }+}++fn fixture() -> Vec<InstalledApp> {+ vec![+ app("Galculator", "galculator", "galculator"),+ app(+ "Google Chrome",+ "google-chrome",+ "/usr/bin/google-chrome-stable",+ ),+ app("File Manager", "thunar", "thunar"),+ app(+ "File Manager Settings",+ "thunar-settings",+ "thunar-settings",+ ),+ ]+}++/// Process state letter from `/proc/<pid>/stat`, or `None` once the entry+/// is gone. `comm` may itself contain spaces and parentheses, so the state+/// is read after the final `)` rather than by splitting from the left.+fn proc_state(pid: u32) -> Option<char> {+ let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;+ let after_comm = stat.rsplit_once(')')?.1;+ after_comm.split_whitespace().next()?.chars().next()+}++#[test]+fn launched_children_are_reaped_instead_of_lingering_as_zombies() {+ // A launched app that exits must not stay in the process table. The+ // driver never waits on what it launches, so without an explicit+ // reaper every launch leaked a pid slot for the daemon's lifetime and+ // left "does this pid exist" liveness checks reporting a terminated+ // app as still running.+ // `/bin/sh` rather than a richer coreutils binary: it is the one+ // executable POSIX and the Nix build sandbox both guarantee, and the+ // sandbox has no `/bin/true`.+ let pid = spawn_launch_command("/bin/sh -c exit", &[]).expect("/bin/sh should spawn");+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);+ loop {+ match proc_state(pid) {+ None => break, // reaped, entry gone+ Some(state) if state != 'Z' => {} // still running or exiting+ Some(_) => {+ assert!(+ std::time::Instant::now() < deadline,+ "pid {pid} was still a zombie after the reaper deadline"+ );+ }+ }+ assert!(+ std::time::Instant::now() < deadline,+ "pid {pid} was never reaped"+ );+ std::thread::sleep(std::time::Duration::from_millis(25));+ }+}++#[test]+fn matches_exact_display_name_case_insensitively() {+ let apps = fixture();+ let hit = match_installed_app(&apps, "google chrome").expect("should match");+ assert_eq!(hit.bundle_id, "google-chrome");+}++#[test]+fn matches_desktop_file_id_and_exec_basename() {+ let apps = fixture();+ assert_eq!(+ match_installed_app(&apps, "galculator").unwrap().name,+ "Galculator"+ );+ assert_eq!(+ match_installed_app(&apps, "google-chrome-stable")+ .unwrap()+ .name,+ "Google Chrome"+ );+}++#[test]+fn matches_unambiguous_display_name_substring() {+ let apps = fixture();+ assert_eq!(+ match_installed_app(&apps, "chrome").unwrap().name,+ "Google Chrome"+ );+}++#[test]+fn refuses_ambiguous_substring_and_unknown_names() {+ let apps = fixture();+ // "file manager" is a substring of two entries — refuse to guess.+ // ("File Manager" itself still resolves via the exact-name rung.)+ assert!(match_installed_app(&apps, "file man").is_none());+ assert_eq!(+ match_installed_app(&apps, "file manager")+ .unwrap()+ .bundle_id,+ "thunar"+ );+ assert!(match_installed_app(&apps, "gnome-calculator").is_none());+ assert!(match_installed_app(&apps, "").is_none());+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/launch_resolution_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/launch_resolution_tests.rsnew file mode 100644index 0000000000..472e922f8f--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/launch_resolution_tests.rs@@ -0,0 +1,73 @@+use super::*;++fn window(class: &str) -> crate::x11::WindowInfo {+ crate::x11::WindowInfo {+ xid: 1,+ pid: Some(7),+ app_name: class.into(),+ title: "t".into(),+ is_on_screen: true,+ z_index: None,+ x: 0,+ y: 0,+ width: 1,+ height: 1,+ }+}++#[test]+fn launch_queries_match_window_classes() {+ assert!(window_matches_launch(+ &window("org.gnome.Nautilus"),+ "nautilus"+ ));+ assert!(window_matches_launch(+ &window("org.gnome.Nautilus"),+ "org.gnome.Nautilus"+ ));+ assert!(window_matches_launch(+ &window("Gnome-terminal"),+ "gnome-terminal"+ ));+ assert!(window_matches_launch(+ &window("Gnome-control-center"),+ "gnome-control-center"+ ));+ assert!(window_matches_launch(+ &window("Org.gnome.Nautilus"),+ "org.gnome.Nautilus.desktop"+ ));+ assert!(window_matches_launch(+ &window("Org.gnome.Nautilus"),+ "Files\u{0}org.gnome.Nautilus\u{0}nautilus --new-window"+ ));+ assert!(window_matches_launch(+ &window("Gnome-control-center"),+ "Settings\u{0}Settings\u{0}gnome-control-center"+ ));+ assert!(!window_matches_launch(&window("Gedit"), "nautilus"));+ assert!(!window_matches_launch(&window(""), "nautilus"));+}++#[test]+fn a_missing_process_counts_as_exited() {+ assert!(process_exited(u32::MAX - 1));+ assert!(!process_exited(std::process::id()));+}++#[test]+fn a_handoff_timeout_is_a_refusal_not_a_null_pid_success() {+ let result = launch_handoff_timeout_result("Nautilus", 4242, 8);+ assert_eq!(+ result.is_error,+ Some(true),+ "a hand-off timeout must be reported as an error, not success"+ );+ let s = result.structured_content.unwrap();+ assert_eq!(s["code"], "launch_handoff_timeout");+ assert_eq!(s["effect"], "refused");+ assert_eq!(s["pid"], Value::Null);+ assert_eq!(s["running"], Value::Null);+ assert_eq!(s["launcher_pid"], 4242);+ assert_eq!(s["waited_secs"], 8);+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/list_windows_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/list_windows_tests.rsnew file mode 100644index 0000000000..d0f9b01cf1--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/list_windows_tests.rs@@ -0,0 +1,66 @@+use super::*;++#[test]+fn record_has_bounds_and_flat_legacy_fields() {+ let w = crate::x11::WindowInfo {+ xid: 42,+ pid: Some(1234),+ app_name: "example-app".to_owned(),+ title: "Example".to_owned(),+ is_on_screen: true,+ z_index: Some(3),+ x: 10,+ y: 20,+ width: 300,+ height: 400,+ };+ let rec = window_record_json(&w);++ // Canonical cross-platform shape: nested `bounds` object.+ let bounds = rec+ .get("bounds")+ .expect("record must carry a `bounds` object");+ assert_eq!(bounds["x"], json!(10));+ assert_eq!(bounds["y"], json!(20));+ assert_eq!(bounds["width"], json!(300));+ assert_eq!(bounds["height"], json!(400));++ // Legacy alias: flat fields must still be present.+ assert_eq!(rec["x"], json!(10));+ assert_eq!(rec["y"], json!(20));+ assert_eq!(rec["width"], json!(300));+ assert_eq!(rec["height"], json!(400));++ // Cross-platform companions.+ assert_eq!(rec["app_name"], json!("example-app"));+ assert_eq!(rec["is_on_screen"], json!(true));+ assert_eq!(rec["z_index"], json!(3));+ assert_eq!(rec["window_id"], json!(42));+ assert_eq!(rec["title"], json!("Example"));+}++#[test]+fn unavailable_wayland_order_serializes_as_null() {+ let w = crate::x11::WindowInfo {+ xid: 43,+ pid: Some(1234),+ app_name: "native-wayland-app".to_owned(),+ title: "Example".to_owned(),+ is_on_screen: true,+ z_index: None,+ x: 0,+ y: 0,+ width: 300,+ height: 400,+ };++ assert_eq!(window_record_json(&w)["z_index"], Value::Null);+}++#[test]+fn chromium_launch_detection_uses_executable_basename() {+ assert!(chromium_family_program("/usr/bin/google-chrome-stable"));+ assert!(chromium_family_program("CuaTestHarness.Electron"));+ assert!(chromium_family_program("chromium-browser"));+ assert!(!chromium_family_program("/usr/bin/gnome-text-editor"));+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/megapixel_cap_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/megapixel_cap_tests.rsnew file mode 100644index 0000000000..2a1f9c77c0--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/megapixel_cap_tests.rs@@ -0,0 +1,25 @@+use super::{megapixel_long_edge_cap, WINDOW_SCREENSHOT_MAX_PIXELS};++#[test]+fn a_window_shot_above_the_api_threshold_is_capped_below_it() {+ let edge = megapixel_long_edge_cap(1568, 861, WINDOW_SCREENSHOT_MAX_PIXELS).expect("capped");+ let scale = edge as f64 / 1568.0;+ let (w, h) = (+ (1568.0 * scale).round() as u64,+ (861.0 * scale).round() as u64,+ );+ assert!(w * h <= WINDOW_SCREENSHOT_MAX_PIXELS, "{w}x{h}");+ assert!(edge >= 1440 && edge < 1568, "{edge}");+}++#[test]+fn a_shot_within_the_threshold_is_left_alone() {+ assert_eq!(+ megapixel_long_edge_cap(1280, 800, WINDOW_SCREENSHOT_MAX_PIXELS),+ None+ );+ assert_eq!(+ megapixel_long_edge_cap(0, 800, WINDOW_SCREENSHOT_MAX_PIXELS),+ None+ );+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pid_window_resolver_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pid_window_resolver_tests.rsnew file mode 100644index 0000000000..687cb50eb5--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pid_window_resolver_tests.rs@@ -0,0 +1,95 @@+use super::*;++fn win(xid: u64, z: Option<usize>, on_screen: bool, w: u32, h: u32) -> crate::x11::WindowInfo {+ crate::x11::WindowInfo {+ xid,+ pid: Some(7),+ app_name: "gimp".into(),+ title: format!("w{xid}"),+ is_on_screen: on_screen,+ z_index: z,+ x: 0,+ y: 0,+ width: w,+ height: h,+ }+}++#[test]+fn point_resolver_prefers_the_topmost_window_by_stacking_position() {+ // Main window listed last (as `_NET_CLIENT_LIST_STACKING` bottom-up+ // enumeration does when a dialog sits above it); the dialog wins.+ let dialog = crate::x11::WindowInfo {+ z_index: Some(5),+ ..win(2, None, true, 400, 300)+ };+ let main = crate::x11::WindowInfo {+ z_index: Some(3),+ ..win(1, None, true, 1920, 1080)+ };+ assert_eq!(+ topmost_window_at(&[main.clone(), dialog.clone()], 7, 100.0, 100.0),+ Some(2)+ );+ assert_eq!(topmost_window_at(&[dialog, main], 7, 100.0, 100.0), Some(2));+}++#[test]+fn point_resolver_ignores_windows_without_a_stacking_position_when_one_has_it() {+ let ranked = win(2, Some(0), true, 400, 300);+ let unranked = win(1, None, true, 1920, 1080);+ assert_eq!(+ topmost_window_at(&[ranked, unranked], 7, 10.0, 10.0),+ Some(2)+ );+}++#[test]+fn pid_only_resolver_orders_focus_then_dialog_then_active_then_largest() {+ let main = win(1, Some(1), true, 1920, 1080);+ let dialog = win(2, Some(2), true, 400, 300);+ let dock = win(3, Some(0), true, 200, 900);+ let hidden = win(4, None, false, 3000, 3000);+ let windows = vec![main, dialog, dock, hidden];+ let transient = |xid: u64| (xid == 2).then_some(1u64);+ // 1. core focus inside the pid wins outright (even over a dialog).+ assert_eq!(+ crate::x11::pick_pid_window(&windows, Some(3), transient, Some(1)),+ Some(3)+ );+ // 2. no focus in the pid: its topmost transient dialog.+ assert_eq!(+ crate::x11::pick_pid_window(&windows, None, transient, Some(1)),+ Some(2)+ );+ // 3. no dialog: the WM's active window when it is the pid's.+ assert_eq!(+ crate::x11::pick_pid_window(&windows, None, |_| None, Some(3)),+ Some(3)+ );+ // 4. otherwise the largest mapped toplevel (never the unmapped one).+ assert_eq!(+ crate::x11::pick_pid_window(&windows, None, |_| None, None),+ Some(1)+ );+ assert_eq!(+ crate::x11::pick_pid_window(&windows, None, |_| None, Some(99)),+ Some(1)+ );+ // A focused window that is not the pid's is ignored.+ assert_eq!(+ crate::x11::pick_pid_window(&windows, Some(42), |_| None, None),+ Some(1)+ );+}++#[test]+fn pid_only_resolver_skips_unmapped_dialogs() {+ let main = win(1, Some(1), true, 800, 600);+ let unmapped_dialog = win(2, Some(2), false, 400, 300);+ let windows = vec![main, unmapped_dialog];+ assert_eq!(+ crate::x11::pick_pid_window(&windows, None, |xid| (xid == 2).then_some(1u64), None),+ Some(1)+ );+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pid_window_target_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pid_window_target_tests.rsnew file mode 100644index 0000000000..dcf3a31f27--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pid_window_target_tests.rs@@ -0,0 +1,28 @@+use super::*;+use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};++fn window(xid: u64, pid: u32) -> crate::x11::WindowInfo {+ crate::x11::WindowInfo {+ xid,+ pid: Some(pid),+ app_name: "editor".into(),+ title: format!("Document {xid}"),+ is_on_screen: true,+ z_index: Some(1),+ x: 0,+ y: 0,+ width: 640,+ height: 480,+ }+}++#[test]+fn same_pid_sibling_windows_are_ambiguous() {+ let candidates =+ window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);+ assert!(matches!(+ resolve_pid_window_target(candidates),+ PidWindowTargetResolution::Ambiguous(windows)+ if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]+ ));+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pointer_argument_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pointer_argument_tests.rsnew file mode 100644index 0000000000..d4f42dddc1--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/pointer_argument_tests.rs@@ -0,0 +1,57 @@+use super::*;++#[test]+fn pid_only_pointer_call_is_refused_not_clicked_at_origin() {+ let refusal =+ require_point_args("click", &json!({"target_id": "s1:147", "pid": 1867})).expect("refused");+ assert_eq!(refusal.is_error, Some(true));+ let structured = refusal.structured_content.expect("structured");+ assert_eq!(structured["code"], "invalid_arguments");+ assert_eq!(structured["effect"], "refused");+ assert!(structured["accepted_forms"].as_array().unwrap().len() == 3);+}++#[test]+fn complete_point_passes() {+ assert!(require_point_args(+ "click",+ &json!({"pid": 1, "window_id": 2, "x": 3, "y": 4.5})+ )+ .is_none());+ assert!(require_point_args("click", &json!({"x": 1, "y": null})).is_some());+ assert!(require_point_args("click", &json!({"y": 1})).is_some());+}++#[test]+fn foreground_report_becomes_evidence() {+ let report = crate::input::ForegroundReport {+ already_active: false,+ retried_activation: false,+ confirm_ms: 12,+ focus_after: crate::input::FocusAfter::SamePid,+ window_change: Some("appeared: window 9 \"Brightness-Contrast\"".into()),+ };+ let v = foreground_structured("x11_xtest_fg", report, serde_json::Map::new());+ assert_eq!(v["effect"], "confirmed");+ assert_eq!(v["focus_after"], "same_pid");+ assert_eq!(v["evidence"][0]["kind"], "window_change");+ let quiet = crate::input::ForegroundReport {+ already_active: true,+ retried_activation: false,+ confirm_ms: 0,+ focus_after: crate::input::FocusAfter::Target,+ window_change: None,+ };+ let v = foreground_structured("x11_xtest_fg", quiet, serde_json::Map::new());+ assert_eq!(v["effect"], "unverifiable");+ assert_eq!(v["evidence"][0]["kind"], "native_api_result");+ let lost = crate::input::ForegroundReport {+ already_active: true,+ retried_activation: false,+ confirm_ms: 0,+ focus_after: crate::input::FocusAfter::Elsewhere,+ window_change: Some("closed: window 3".into()),+ };+ let v = foreground_structured("x11_xtest_fg", lost, serde_json::Map::new());+ assert_eq!(v["effect"], "suspected_noop");+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/press_key_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/press_key_tests.rsnew file mode 100644index 0000000000..88f4576fda--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/press_key_tests.rs@@ -0,0 +1,18 @@+use super::press_key_chord;++#[test]+fn unmodified_press_stays_on_the_single_key_route() {+ assert_eq!(press_key_chord(&[], "return"), None);+}++#[test]+fn modifiers_are_promoted_to_a_chord_in_order() {+ assert_eq!(+ press_key_chord(&["ctrl".to_owned()], "s"),+ Some(vec!["ctrl".to_owned(), "s".to_owned()])+ );+ assert_eq!(+ press_key_chord(&["ctrl".to_owned(), "shift".to_owned()], "t"),+ Some(vec!["ctrl".to_owned(), "shift".to_owned(), "t".to_owned()])+ );+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/session_cursor_target_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/session_cursor_target_tests.rsnew file mode 100644index 0000000000..7860153cc5--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/session_cursor_target_tests.rs@@ -0,0 +1,81 @@+use super::{+ choose_keyboard_cursor_target, cursor_control_scope, named_session_cursor_key,+ reveal_pointer_action_for, CursorControlScope, ToolState,+};+use serde_json::json;++#[test]+fn lifecycle_owned_sessions_opt_into_keyboard_cursor_positioning() {+ assert_eq!(+ named_session_cursor_key(&json!({"session": "editing-run"})).as_deref(),+ Some("editing-run")+ );+ assert_eq!(+ named_session_cursor_key(&json!({"cursor_id": "legacy"})),+ None+ );+ assert_eq!(+ named_session_cursor_key(&json!({"_session_id": "implicit"})).as_deref(),+ Some("implicit")+ );+ assert_eq!(named_session_cursor_key(&json!({})), None);+}++#[test]+fn keyboard_cursor_uses_explicit_then_remembered_then_safe_seed() {+ let explicit = Some((10.0, 20.0));+ let remembered = Some((30.0, 40.0));+ let window_center = Some((50.0, 60.0));+ let current_pointer = Some((70.0, 80.0));++ assert_eq!(+ choose_keyboard_cursor_target(explicit, remembered, window_center, current_pointer),+ explicit+ );+ assert_eq!(+ choose_keyboard_cursor_target(None, remembered, window_center, current_pointer),+ remembered+ );+ assert_eq!(+ choose_keyboard_cursor_target(None, None, window_center, current_pointer),+ window_center+ );+ assert_eq!(+ choose_keyboard_cursor_target(None, None, None, current_pointer),+ current_pointer+ );+}++#[test]+fn invalid_coordinates_do_not_poison_session_position_reuse() {+ assert_eq!(+ choose_keyboard_cursor_target(Some((f64::NAN, 1.0)), Some((12.0, 34.0)), None, None,),+ Some((12.0, 34.0))+ );+}++#[test]+fn real_pointer_control_requires_explicit_desktop_scope() {+ assert_eq!(cursor_control_scope(&json!({})), CursorControlScope::Agent);+ assert_eq!(+ cursor_control_scope(&json!({"scope": "window"})),+ CursorControlScope::Agent+ );+ assert_eq!(+ cursor_control_scope(&json!({"scope": "desktop"})),+ CursorControlScope::Desktop+ );+}++#[tokio::test]+async fn pointer_position_survives_an_unavailable_overlay() {+ let state = ToolState::new();+ reveal_pointer_action_for(&state, "no-renderer", 123.0, 456.0, true).await;++ let cursor = state+ .cursor_registry+ .get("no-renderer")+ .expect("pointer action records its position independently of rendering");+ assert!(cursor.config.enabled, "input must revive its agent cursor");+ assert_eq!(cursor.x.zip(cursor.y), Some((123.0, 456.0)));+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/set_value_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/set_value_tests.rsnew file mode 100644index 0000000000..c4a909c92e--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/set_value_tests.rs@@ -0,0 +1,48 @@+use super::*;++#[test]+fn a_file_chooser_keeping_the_basename_counts_as_committed() {+ assert!(path_normalised_to_basename(+ "/home/user/Desktop/tone.wav",+ "tone.wav"+ ));+ assert!(!path_normalised_to_basename(+ "/home/user/Desktop/tone.wav",+ "other.wav"+ ));+ assert!(!path_normalised_to_basename("tone.wav", "tone.wav"));+ let ok = set_value_result(+ 3,+ "/home/user/Desktop/tone.wav",+ "ax",+ Some("tone.wav".into()),+ None,+ );+ let s = ok.structured_content.unwrap();+ assert_eq!(s["verified"], true);+ assert_eq!(s["effect"], "confirmed");+}++#[test]+fn readback_agreement_is_numeric_aware() {+ assert!(values_agree("40", "40.0"));+ assert!(values_agree("40", " 40 "));+ assert!(values_agree("abc", "abc"));+ assert!(!values_agree("40", "41"));+ assert!(!values_agree("40", "forty"));+}++#[test]+fn set_value_result_is_verified_only_on_matching_readback() {+ let ok = set_value_result(3, "40", "click_type_mpx", Some("40.0".into()), None);+ let s = ok.structured_content.unwrap();+ assert_eq!(s["verified"], true);+ assert_eq!(s["effect"], "confirmed");+ let noop = set_value_result(3, "40", "ax", Some("10.0".into()), None);+ let s = noop.structured_content.unwrap();+ assert_eq!(s["verified"], false);+ assert_eq!(s["effect"], "suspected_noop");+ assert_eq!(s["readback"], "10.0");+ let blind = set_value_result(3, "40", "ax", None, None);+ assert_eq!(blind.structured_content.unwrap()["effect"], "unverifiable");+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/type_text_readback_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/type_text_readback_tests.rsnew file mode 100644index 0000000000..edff46a7aa--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/type_text_readback_tests.rs@@ -0,0 +1,19 @@+use super::*;++#[test]+fn typed_text_is_confirmed_only_when_read_back() {+ let confirmed =+ type_text_readback_result(1, 3, "-40", "via targeted AT-SPI", Some("-40.0".into()));+ let s = confirmed.structured_content.clone().unwrap();+ assert_eq!(s["effect"], "confirmed");+ assert_eq!(s["verified"], true);+ assert_eq!(s["evidence"][0]["kind"], "value_readback");+ let contained = type_text_readback_result(1, 3, "ab", "r", Some("xxabyy".into()));+ assert_eq!(contained.structured_content.unwrap()["effect"], "confirmed");+ let mismatch = type_text_readback_result(1, 3, "ab", "r", Some("zz".into()));+ let s = mismatch.structured_content.unwrap();+ assert_eq!(s["effect"], "unverifiable");+ assert_eq!(s["readback"], "zz");+ let blind = type_text_readback_result(1, 3, "ab", "r", None);+ assert_eq!(blind.structured_content.unwrap()["effect"], "unverifiable");+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/visibility_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/visibility_tests.rsnew file mode 100644index 0000000000..f961be5caf--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/visibility_tests.rs@@ -0,0 +1,135 @@+use super::*;++#[test]+fn framed_elements_lead_and_keep_their_relative_order() {+ let elements = vec![+ json!({"element_index": 0, "role": "menu"}),+ json!({"element_index": 1, "role": "push button", "frame": {"x": 1, "y": 1, "w": 2, "h": 2}}),+ json!({"element_index": 2, "role": "menu"}),+ json!({"element_index": 3, "role": "paragraph", "frame": {"x": 1, "y": 9, "w": 2, "h": 2}}),+ ];+ let ordered: Vec<u64> = framed_elements_first(elements)+ .iter()+ .map(|e| e["element_index"].as_u64().unwrap())+ .collect();+ assert_eq!(ordered, vec![1, 3, 0, 2]);+}++#[test]+fn a_frameless_popup_returns_only_the_menu_entries_drawn_inside_it() {+ let elements = vec![+ json!({"element_index": 1, "role": "push button", "frame": {"x": 5, "y": 5, "w": 20, "h": 20}}),+ json!({"element_index": 2, "role": "menu item", "label": "Paragraph...", "frame": {"x": 2, "y": 30, "w": 180, "h": 22}}),+ json!({"element_index": 3, "role": "menu item", "label": "elsewhere", "frame": {"x": 400, "y": 30, "w": 180, "h": 22}}),+ json!({"element_index": 4, "role": "menu", "label": "Format"}),+ ];+ let kept: Vec<u64> = popup_menu_elements(elements.clone(), (0, 0), 200, 400)+ .iter()+ .map(|e| e["element_index"].as_u64().unwrap())+ .collect();+ assert_eq!(kept, vec![2]);+ assert_eq!(+ popup_menu_elements(elements[..1].to_vec(), (0, 0), 200, 400).len(),+ 1+ );+}++#[test]+fn a_combo_popup_returns_the_rows_of_the_list_that_fills_it() {+ // Qt: the combo list lives under the combo box inside the dialog; the+ // main window's menubar entries are elsewhere on the screen.+ let elements = vec![+ json!({"element_index": 1, "role": "menu", "label": "Audio", "frame": {"x": -600, "y": -300, "w": 50, "h": 20}}),+ json!({"element_index": 7, "role": "list", "frame": {"x": 1, "y": 1, "w": 198, "h": 118}}),+ json!({"element_index": 8, "role": "list item", "label": "Desktop", "parent_index": 7, "frame": {"x": 2, "y": 2, "w": 190, "h": 22}}),+ json!({"element_index": 9, "role": "list item", "label": "user", "parent_index": 7, "frame": {"x": 2, "y": 26, "w": 190, "h": 22}}),+ json!({"element_index": 12, "role": "push button", "label": "Open", "frame": {"x": 20, "y": 20, "w": 60, "h": 20}}),+ ];+ let kept: Vec<u64> = popup_menu_elements(elements, (0, 0), 200, 120)+ .iter()+ .map(|e| e["element_index"].as_u64().unwrap())+ .collect();+ assert_eq!(kept, vec![8, 9]);+}++#[test]+fn a_list_popup_without_an_indexed_container_keeps_its_item_rows_only() {+ let elements = vec![+ json!({"element_index": 1, "role": "menu", "label": "Audio", "frame": {"x": 1, "y": 1, "w": 50, "h": 20}}),+ json!({"element_index": 8, "role": "list item", "label": "Desktop", "frame": {"x": 2, "y": 2, "w": 190, "h": 22}}),+ json!({"element_index": 9, "role": "tree item", "label": "user", "frame": {"x": 2, "y": 26, "w": 190, "h": 22}}),+ json!({"element_index": 12, "role": "push button", "label": "Open", "frame": {"x": 20, "y": 20, "w": 60, "h": 20}}),+ ];+ let kept: Vec<u64> = popup_menu_elements(elements, (0, 0), 200, 120)+ .iter()+ .map(|e| e["element_index"].as_u64().unwrap())+ .collect();+ assert_eq!(kept, vec![8, 9]);+}++#[test]+fn menu_roles_take_the_real_press() {+ for role in ["menu", "Menu Item", "check menu item", "radio menu item"] {+ assert!(element_is_menu_role(role), "{role}");+ }+ for role in ["menu bar", "push button", "text"] {+ assert!(!element_is_menu_role(role), "{role}");+ }+}++#[test]+fn overlays_name_the_follow_up_call_per_dialog_and_popup() {+ let overlays = WindowOverlays {+ dialogs: vec![json!({+ "window_id": 71, "title": "Position and Size", "transient_for": 3, "modal": true,+ "bounds": {"x": 100, "y": 100, "width": 400, "height": 300}+ })],+ popups: vec![json!({+ "window_id": 72, "title": "", "pid": 5,+ "bounds": {"x": 10, "y": 30, "width": 200, "height": 400}+ })],+ covers_window: true,+ window_rect: Some((0, 0, 800, 600)),+ };+ let note = overlays.follow_up(5).unwrap();+ assert!(+ note.contains("dialog \"Position and Size\" (window_id 71, transient of window 3, modal)"),+ "{note}"+ );+ assert!(+ note.contains("get_window_state(pid=5, window_id=71)"),+ "{note}"+ );+ assert!(+ note.contains("popup (window_id 72, bounds x=10 y=30 200x400)"),+ "{note}"+ );+ assert!(rects_intersect((0, 0, 800, 600), (100, 100, 400, 300)));+ assert!(!rects_intersect((0, 0, 800, 600), (800, 0, 10, 10)));+}++#[test]+fn a_cross_process_dialog_names_its_real_owning_pid_in_the_follow_up() {+ // GIMP's "Export Image as JPEG" dialog spawned as a separate process+ // (owning_pid 999) but is transient-for the target pid (5)'s window.+ let overlays = WindowOverlays {+ dialogs: vec![json!({+ "window_id": 90, "title": "Export Image as JPEG", "transient_for": 10,+ "modal": false,+ "bounds": {"x": 0, "y": 0, "width": 300, "height": 200},+ "owning_pid": 999,+ })],+ popups: vec![],+ covers_window: false,+ window_rect: Some((0, 0, 800, 600)),+ };+ let note = overlays.follow_up(5).unwrap();+ assert!(+ note.contains("owned by a different process pid 999, not pid 5"),+ "{note}"+ );+ assert!(+ note.contains("get_window_state(pid=5, window_id=90)"),+ "{note}"+ );+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/window_capture_dimension_tests.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/window_capture_dimension_tests.rsnew file mode 100644index 0000000000..f9ad1be0ca--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_/window_capture_dimension_tests.rs@@ -0,0 +1,13 @@+use super::{GetWindowStateTool, ToolState};+use cua_driver_core::tool::Tool;++#[test]+fn schema_exposes_zero_as_native_resolution() {+ let tool = GetWindowStateTool {+ state: ToolState::new(),+ };+ assert_eq!(+ tool.def().input_schema["properties"]["max_image_dimension"]["minimum"],+ 0+ );+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex 8400c45f91..0ce6c1b990 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -1015,79 +1015,10 @@ fn z_index_from_front_to_back(total: usize, position: usize) -> usize {}#[cfg(test)]-mod list_windows_z_index_tests {- use super::{exact_window_ownership_result, z_index_from_front_to_back};-- #[test]- fn enum_windows_front_to_back_order_normalizes_to_higher_is_frontmost() {- let indices: Vec<_> = (0..3)- .map(|position| z_index_from_front_to_back(3, position))- .collect();- assert_eq!(indices, vec![2, 1, 0]);- assert!(indices[0] > indices[2]);- }-- #[test]- fn explicit_pid_hwnd_guard_refuses_wrong_or_stale_owners() {- assert!(exact_window_ownership_result(42, 7, Some(42)).is_ok());-- let wrong = exact_window_ownership_result(42, 7, Some(99)).unwrap_err();- assert_eq!(wrong.is_error, Some(true));- assert_eq!(- wrong.structured_content.as_ref().unwrap()["code"],- "window_target_mismatch"- );- assert_eq!(wrong.structured_content.as_ref().unwrap()["owner_pid"], 99);-- let stale = exact_window_ownership_result(42, 7, None).unwrap_err();- assert_eq!(- stale.structured_content.as_ref().unwrap()["code"],- "window_target_not_found"- );- }-}+mod list_windows_z_index_tests;#[cfg(test)]-mod get_window_state_actions_tests {- use super::*;- use crate::uia::UiaNode;-- fn node(actions: Vec<String>) -> UiaNode {- UiaNode {- element_index: Some(1),- control_type: "Button".to_owned(),- name: Some("OK".to_owned()),- value: None,- automation_id: None,- help_text: None,- actions,- enabled: Some(true),- selected: None,- element_ptr: 0,- center_x: 0,- center_y: 0,- rect: None,- msaa_role: None,- depth: 0,- parent_element_index: None,- in_web_content: false,- }- }-- #[test]- fn element_entry_includes_actions_when_present() {- let n = node(vec!["invoke".to_owned(), "toggle".to_owned()]);- let entry = build_element_entry(&n, None).unwrap();- assert_eq!(entry["actions"], json!(["invoke", "toggle"]));- }-- #[test]- fn element_entry_omits_actions_when_empty() {- let n = node(Vec::new());- let entry = build_element_entry(&n, None).unwrap();- assert!(entry.get("actions").is_none());- }-}+mod get_window_state_actions_tests;// ── get_window_state ─────────────────────────────────────────────────────────@@ -1180,28 +1111,7 @@ pub struct GetWindowStateTool {static GWS_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();#[cfg(test)]-mod get_window_state_max_image_dimension_tests {- use super::resolve_max_image_dimension;-- #[test]- fn canonical_override_wins_and_zero_requests_native_resolution() {- assert_eq!(resolve_max_image_dimension(1568, None, None), 1568);- assert_eq!(resolve_max_image_dimension(1568, Some(800), None), 800);- assert_eq!(resolve_max_image_dimension(800, Some(1568), None), 1568);- assert_eq!(resolve_max_image_dimension(1568, Some(0), None), 0);- assert_eq!(- resolve_max_image_dimension(1568, Some(1200), Some(400)),- 1200- );- }-- #[test]- fn omitted_canonical_override_preserves_legacy_folding() {- assert_eq!(resolve_max_image_dimension(1568, None, Some(800)), 800);- assert_eq!(resolve_max_image_dimension(800, None, Some(1568)), 800);- assert_eq!(resolve_max_image_dimension(0, None, Some(800)), 800);- }-}+mod get_window_state_max_image_dimension_tests;/// Slack past `timeout_ms` before the walk task is abandoned.const UIA_WALK_BACKSTOP_GRACE: std::time::Duration = std::time::Duration::from_millis(500);@@ -4323,207 +4233,10 @@ impl Tool for ClickTool {}#[cfg(test)]-mod pixel_click_transport_tests {- use super::{finish_pixel_uia_attempt, posted_pixel_click_result};- use crate::uia::windows_enum::PointInvokeOutcome;- use cua_driver_core::action_record::{- ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,- };-- #[test]- fn uia_unavailable_errors_advertise_foreground_escalation() {- use cua_driver_core::action_record::EscalationKind;- use cua_driver_core::protocol::Content;- for (outcome, status) in [- (PointInvokeOutcome::Busy, "busy"),- (PointInvokeOutcome::Timeout, "timeout"),- (PointInvokeOutcome::Unavailable, "unavailable"),- ] {- let result = finish_pixel_uia_attempt(outcome, 7, 3, 4)- .expect("unavailable UIA must stop the route without fallback");- assert!(result.is_error.unwrap_or(false), "{outcome:?}");- let data = result- .structured_content- .as_ref()- .expect("structured error");- assert_eq!(data["code"], "background_unavailable");- assert_eq!(data["uia_status"], status);- assert_eq!(data["path"], "ax");- assert_eq!(data["effect"], "unverifiable");- assert_eq!(- data["suggestion"].as_str(),- Some("Retry this action with delivery_mode:\"foreground\"."),- "{outcome:?}"- );- assert_eq!(- data["escalation"]["recommended"].as_str(),- Some("foreground"),- "{outcome:?}"- );- let reason = data["escalation"]["reason"]- .as_str()- .expect("escalation reason");- assert!(- reason.contains(status),- "reason must name the UIA status: {reason}"- );- assert!(- reason.contains("delivery_mode:\"foreground\""),- "reason must name the next rung: {reason}"- );- let text = match &result.content[0] {- Content::Text { text, .. } => text,- _ => panic!("expected text content for {outcome:?}"),- };- assert!(- text.contains("No fallback input was sent"),- "text must keep the no-replay guarantee: {text}"- );- assert!(- text.contains("delivery_mode:\"foreground\""),- "text must surface the escalation: {text}"- );- let record = ActionExecutionRecord::from_legacy(- "click",- &serde_json::json!({ "delivery_mode": "background" }),- data,- )- .expect("UIA refusal should normalize into the public action contract");- let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))- .expect("serialize ActionResult");- assert_eq!(public["effect"], "unverifiable", "{outcome:?}");- }- // The completed-miss boundary is unchanged: only Miss falls through,- // and a delivered Invoke carries no escalation hint.- assert!(finish_pixel_uia_attempt(PointInvokeOutcome::Miss, 7, 3, 4).is_none());- let ok = finish_pixel_uia_attempt(PointInvokeOutcome::Invoked, 7, 3, 4)- .expect("invoked click reports success");- assert!(!ok.is_error.unwrap_or(false));- let ok_data = ok.structured_content.as_ref().expect("structured success");- assert_eq!(ok_data["path"], "ax");- assert!(ok_data.get("escalation").is_none());- assert!(ok_data.get("suggestion").is_none());- let ok_record = ActionExecutionRecord::from_legacy(- "click",- &serde_json::json!({ "delivery_mode": "background" }),- ok_data,- )- .expect("UIA invoke should normalize into the public action contract");- let ok_public =- serde_json::to_value(ok_record.public_result().expect("valid ActionResult"))- .expect("serialize ActionResult");- assert_eq!(ok_public["effect"], "unverifiable");- // The hint must flow into the existing escalation pipeline, not sit- // as inert metadata: Timeout (the #3621 case) normalizes to a- // foreground-delivery escalation on the internal record.- let timeout_data = finish_pixel_uia_attempt(PointInvokeOutcome::Timeout, 7, 3, 4)- .expect("timeout stops the route")- .structured_content- .expect("structured error");- let timeout_record = ActionExecutionRecord::from_legacy(- "click",- &serde_json::json!({ "delivery_mode": "background" }),- &timeout_data,- )- .expect("UIA timeout should normalize into the public action contract");- assert_eq!(- timeout_record.escalation.map(|escalation| escalation.kind),- Some(EscalationKind::RetryWithForegroundDelivery)- );- }-- #[test]- fn post_message_pixel_click_reports_synthetic_transport() {- let result = posted_pixel_click_result(42, "click");- let structured = result- .structured_content- .as_ref()- .expect("posted click should expose legacy transport metadata");- assert_eq!(structured["path"], "post_message");-- let record = ActionExecutionRecord::from_legacy(- "click",- &serde_json::json!({ "delivery_mode": "background" }),- structured,- )- .expect("posted click should normalize into the public action contract");- assert_eq!(record.transport, ActionTransport::WindowsPostMessage);- assert_eq!(record.requested_delivery, RequestedDelivery::Background);- assert_eq!(record.actual_delivery, Some(ActualDelivery::Background));-- let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))- .expect("serialize ActionResult");- assert_eq!(public["route"], "synthetic_events");- assert_eq!(public["delivery"]["mode"], "background");- }-}+mod pixel_click_transport_tests;#[cfg(test)]-mod background_element_click_record_tests {- use super::{background_element_click_result, ActionTransport};-- #[test]- fn raw_fallback_reports_its_physical_transport() {- for (transport, path) in [- (ActionTransport::WindowsTargetedInjection, "pixel"),- (ActionTransport::WindowsPostMessage, "post_message"),- ] {- let result = background_element_click_result(- "physical fallback".into(),- transport,- vec![ActionTransport::WindowsUiaInvoke],- );- assert_eq!(result.structured_content.as_ref().unwrap()["path"], path);- let record = result.action_record.unwrap();- assert_eq!(record.transport, transport);- let truth = record.debug_json();- assert_ne!(truth["route"], "accessibility");- assert_eq!(- record.attempts[0].transport,- ActionTransport::WindowsUiaInvoke- );- assert_eq!(record.fallbacks[0].to, transport);- }- }-- #[test]- fn failed_provider_calls_disqualify_single_action_marker_exemption() {- let result = background_element_click_result(- "semantic success after provider failure".into(),- ActionTransport::WindowsUiaToggle,- vec![ActionTransport::WindowsUiaInvoke],- );- let record = result.action_record.unwrap();- assert_eq!(record.transport, ActionTransport::WindowsUiaToggle);- assert_eq!(record.attempts.len(), 1);- assert_eq!(record.fallbacks.len(), 1);- assert_eq!(record.fallbacks[0].from, ActionTransport::WindowsUiaInvoke);- assert_eq!(record.fallbacks[0].to, ActionTransport::WindowsUiaToggle);- // Point-free recording requires an empty fallback journal.- assert!(!record.debug_json()["fallbacks"]- .as_array()- .unwrap()- .is_empty());- }-- #[test]- fn single_provider_success_has_no_invented_attempts() {- for transport in [- ActionTransport::WindowsUiaInvoke,- ActionTransport::WindowsUiaToggle,- ActionTransport::WindowsUiaSelection,- ActionTransport::WindowsUiaExpandCollapse,- ] {- let result =- background_element_click_result("semantic success".into(), transport, vec![]);- assert_eq!(result.structured_content.as_ref().unwrap()["path"], "ax");- let record = result.action_record.unwrap();- assert_eq!(record.transport, transport);- assert!(record.attempts.is_empty());- assert!(record.fallbacks.is_empty());- }- }-}+mod background_element_click_record_tests;// ── type_text ─────────────────────────────────────────────────────────────────@@ -5296,55 +5009,7 @@ fn changed_contains_post_message_result(text_len: usize) -> serde_json::Value {}#[cfg(test)]-mod post_message_readback_tests {- use super::{changed_contains_post_message_result, post_message_readback_observed};-- #[test]- fn observes_only_a_changed_value_containing_the_requested_text() {- assert!(post_message_readback_observed(- Some("prefix"),- Some("prefixhello"),- "hello"- ));- assert!(!post_message_readback_observed(None, None, "hello"));- assert!(!post_message_readback_observed(- Some("hello"),- Some("hello"),- "hello"- ));- assert!(!post_message_readback_observed(- Some(""),- Some("h"),- "hello"- ));- assert!(!post_message_readback_observed(- Some("before"),- Some("different"),- "hello"- ));- }-- #[test]- fn changed_contains_remains_unverifiable_without_retry_escalation() {- let result = changed_contains_post_message_result(5);- assert_eq!(result["effect"], "unverifiable");- assert_eq!(result["verify"], "changed_contains");- assert_eq!(result["verified"], false);- assert!(result.get("escalation").is_none());-- let record = cua_driver_core::action_record::ActionExecutionRecord::from_legacy(- "type_text",- &serde_json::json!({"delivery_mode": "background"}),- &result,- )- .expect("changed-and-contains PostMessage result should normalize");- let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))- .expect("serialize ActionResult");- assert_eq!(public["effect"], "unverifiable");- assert!(public.get("escalation").is_none());- assert!(public.get("evidence").is_none());- }-}+mod post_message_readback_tests;fn classify_value_write_readback(value: Option<&str>,@@ -10566,510 +10231,31 @@ pub fn build_registry_with_provider(}#[cfg(test)]-mod cursor_key_resolution_tests {- use super::{resolve_cursor_key, NO_CURSOR};- use serde_json::json;-- #[test]- fn direct_platform_call_without_lifecycle_resolves_to_no_cursor() {- // No session/cursor_id → NO_CURSOR (""): the action still runs but no- // cursor is shown. Canonical core dispatch injects `_session_id` before- // real platform calls.- assert_eq!(resolve_cursor_key(&json!({})), NO_CURSOR);- assert_eq!(resolve_cursor_key(&json!({ "pid": 1 })), NO_CURSOR);- assert_eq!(- resolve_cursor_key(&json!({ "_session_id": "mcp-1-2" })),- "mcp-1-2"- );- }-- #[test]- fn explicit_session_owns_a_cursor() {- assert_eq!(- resolve_cursor_key(&json!({ "session": "research-run" })),- "research-run"- );- }-- #[test]- fn cursor_id_is_a_legacy_alias_and_session_wins() {- assert_eq!(- resolve_cursor_key(&json!({ "cursor_id": "user-handle" })),- "user-handle"- );- assert_eq!(- resolve_cursor_key(&json!({ "session": "s1", "cursor_id": "c1" })),- "s1"- );- assert_eq!(- resolve_cursor_key(&json!({ "_session_id": "implicit", "cursor_id": "c1" })),- "implicit"- );- }-- #[test]- fn empty_strings_fall_through_to_no_cursor() {- // An empty `session` falls through to `cursor_id`; both empty → NO_CURSOR.- assert_eq!(- resolve_cursor_key(&json!({ "session": "", "cursor_id": "c1" })),- "c1"- );- assert_eq!(- resolve_cursor_key(&json!({ "session": "", "cursor_id": "" })),- NO_CURSOR- );- }-}+mod cursor_key_resolution_tests;#[cfg(test)]-mod launch_focus_restore_decision_tests {- use super::{- first_unopened_shell_url_index, should_restore_foreground_after_launch, LaunchTargetShape,- };-- #[test]- fn only_app_identifying_launches_restore_foreground() {- for (fields, restore) in [- // A urls-only launch explicitly asks for navigation in the default- // browser; that browser is the legitimate foreground.- (&["urls"][..], false),- (&["name"], true),- (&["path"], true),- // The AUMID path restores synchronously in launch_uwp.rs; the- // caller gates the polling restore on `aumid_for_uwp.is_none()`.- (&["aumid"], true),- (&["bundle_id"], true),- (&["launch_path"], true),- // An app-identifying field alongside urls opens them in that app- // in the background, so the prior foreground is restored.- (&["name", "urls"], true),- (&["path", "urls"], true),- (&["aumid", "urls"], true),- // Nothing was launched.- (&[], false),- ] {- let shape = LaunchTargetShape {- has_aumid: fields.contains(&"aumid"),- has_bundle_id: fields.contains(&"bundle_id"),- has_name: fields.contains(&"name"),- has_path: fields.contains(&"path"),- has_launch_path: fields.contains(&"launch_path"),- has_urls: fields.contains(&"urls"),- };- assert_eq!(- should_restore_foreground_after_launch(shape),- restore,- "{fields:?}"- );- }- }-- #[test]- fn named_app_launch_forwards_every_url() {- assert_eq!(first_unopened_shell_url_index(true), 0);- }-- #[test]- fn urls_only_launch_does_not_reopen_primary_url() {- assert_eq!(first_unopened_shell_url_index(false), 1);- }-}+mod launch_focus_restore_decision_tests;#[cfg(test)]-mod chromium_flag_injection_tests {- use super::{inject_chromium_anti_throttling_flags, is_chromium_browser_target};-- #[test]- fn detects_bare_browser_names() {- for name in [- "msedge", "chrome", "brave", "opera", "vivaldi", "chromium", "thorium", "iridium",- "browser", "arc",- ] {- assert!(is_chromium_browser_target(name), "{name} should match");- assert!(- is_chromium_browser_target(&format!("{name}.exe")),- "{name}.exe should match"- );- // Case-insensitive.- assert!(- is_chromium_browser_target(&name.to_uppercase()),- "uppercase {name} should match"- );- }- }-- #[test]- fn detects_full_paths() {- assert!(is_chromium_browser_target(- r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"- ));- assert!(is_chromium_browser_target(- r"C:\Program Files\Google\Chrome\Application\chrome.exe"- ));- // Forward slashes too (some shells write paths that way).- assert!(is_chromium_browser_target(- r"C:/Program Files/Google/Chrome/Application/chrome.exe"- ));- }-- #[test]- fn detects_launch_path_with_trailing_args() {- // Round-tripped launch_path from list_apps with shortcut arguments.- assert!(is_chromium_browser_target(- r#""C:\Program Files\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 2""#- ));- }-- #[test]- fn does_not_match_non_chromium_apps() {- for name in ["firefox", "notepad", "explorer", "code", "soffice"] {- assert!(!is_chromium_browser_target(name), "{name} should NOT match");- assert!(- !is_chromium_browser_target(&format!("{name}.exe")),- "{name}.exe should NOT match"- );- }- // Empty target.- assert!(!is_chromium_browser_target(""));- }-- #[test]- fn injects_three_flags_into_empty_args() {- let mut args: Vec<String> = vec![];- inject_chromium_anti_throttling_flags(&mut args);- assert!(args.contains(&"--disable-features=CalculateNativeWinOcclusion".to_string()));- assert!(args.contains(&"--disable-backgrounding-occluded-windows".to_string()));- assert!(args.contains(&"--disable-renderer-backgrounding".to_string()));- assert_eq!(args.len(), 3);- }-- #[test]- fn merges_into_existing_disable_features_list() {- let mut args = vec!["--disable-features=Foo,Bar".to_string()];- inject_chromium_anti_throttling_flags(&mut args);- // Should NOT have two --disable-features= entries.- let dfe: Vec<_> = args- .iter()- .filter(|a| a.starts_with("--disable-features="))- .collect();- assert_eq!(dfe.len(), 1);- assert!(dfe[0].contains("CalculateNativeWinOcclusion"));- assert!(dfe[0].contains("Foo"));- assert!(dfe[0].contains("Bar"));- }-- #[test]- fn idempotent_when_all_flags_already_present() {- let mut args = vec![- "--disable-features=CalculateNativeWinOcclusion".to_string(),- "--disable-backgrounding-occluded-windows".to_string(),- "--disable-renderer-backgrounding".to_string(),- ];- let before = args.clone();- inject_chromium_anti_throttling_flags(&mut args);- assert_eq!(args, before, "must not duplicate flags");- }-- #[test]- fn preserves_user_url_argument_after_flags() {- let mut args = vec!["file:///C:/test_page.html".to_string()];- inject_chromium_anti_throttling_flags(&mut args);- // URL must still be present.- assert!(args.iter().any(|a| a == "file:///C:/test_page.html"));- // All three flags now in args.- assert!(args- .iter()- .any(|a| a == "--disable-features=CalculateNativeWinOcclusion"));- assert!(args- .iter()- .any(|a| a == "--disable-backgrounding-occluded-windows"));- assert!(args.iter().any(|a| a == "--disable-renderer-backgrounding"));- }-}+mod chromium_flag_injection_tests;#[cfg(test)]-mod click_capture_id_schema_tests {- use super::ClickTool;- use cua_driver_core::tool::Tool;-- /// The portable click contract pins `button` and the other accepted- /// fields. A live schema may broaden `capture_id`, which the subset gate- /// allows, so the non-empty bound is pinned here.- #[test]- fn schema_requires_non_empty_capture_id() {- let tool = ClickTool {- state: super::ToolState::new(None),- };- let d = tool.def();- let props = d.input_schema.get("properties").expect("properties");- let capture_id = props.get("capture_id").expect("capture_id field present");- assert_eq!(capture_id["type"], "string");- assert_eq!(capture_id["minLength"], 1);- }-}+mod click_capture_id_schema_tests;#[cfg(test)]-mod snapshot_coordinate_tests {- use super::{focus_by_pixel_click_args, ToolState, ZoomTool};- use cua_driver_core::tool::Tool;-- #[test]- fn schema_keeps_pid_optional_for_window_owned_lookup() {- let tool = ZoomTool {- state: ToolState::new(None),- };- let required = tool.def().input_schema["required"].as_array().unwrap();- assert!(!required.iter().any(|field| field == "pid"));- assert!(tool.def().input_schema["properties"].get("pid").is_some());- }-- #[test]- fn press_key_native_element_focus_skips_second_screenshot_scaling() {- let native = focus_by_pixel_click_args(- 42,- Some(7),- 120.0,- 80.0,- false,- None,- Some("client-a".to_owned()),- false,- true,- );- assert_eq!(native["_native_coordinates"], true);-- let screenshot = focus_by_pixel_click_args(- 42,- Some(7),- 60.0,- 40.0,- false,- None,- Some("client-a".to_owned()),- false,- false,- );- assert!(screenshot.get("_native_coordinates").is_none());- }-}+mod snapshot_coordinate_tests;#[cfg(test)]-mod set_window_frame_geometry_tests {- use super::outer_frame_for_visible_request;-- #[test]- fn compensates_for_invisible_resize_borders() {- assert_eq!(- outer_frame_for_visible_request(- (65, 52, 872, 626),- (40, 40, 886, 633),- (47, 40, 872, 626),- )- .unwrap(),- (58, 52, 886, 633)- );- }-- #[test]- fn leaves_outer_request_unchanged_when_dwm_bounds_are_unavailable() {- assert_eq!(- outer_frame_for_visible_request(- (-25, 10, 640, 480),- (20, 30, 800, 600),- (20, 30, 800, 600),- )- .unwrap(),- (-25, 10, 640, 480)- );- }-}+mod set_window_frame_geometry_tests;#[cfg(test)]-mod desktop_scope_tests {- use super::{is_windowless_desktop_action, GetDesktopStateTool};- use cua_driver_core::tool::Tool;- use serde_json::json;-- // ── is_windowless_desktop_action ──────────────────────────────────────────-- #[test]- fn windowless_true_for_xy_under_desktop_scope_click_shape() {- // Click arg shape: {x, y}.- assert!(is_windowless_desktop_action(- &json!({"x": 10, "y": 20, "scope": "desktop"})- ));- }-- #[test]- fn windowless_true_for_xy_under_desktop_scope_scroll_shape() {- // Scroll arg shape: {direction, x, y}.- assert!(is_windowless_desktop_action(&json!({- "direction": "down", "x": 10, "y": 20, "scope": "desktop"- })));- }-- #[test]- fn windowless_false_when_pid_present() {- assert!(!is_windowless_desktop_action(&json!({- "x": 10, "y": 20, "pid": 5, "scope": "desktop"- })));- }-- #[test]- fn windowless_false_when_window_id_present() {- assert!(!is_windowless_desktop_action(&json!({- "x": 10, "y": 20, "window_id": 99, "scope": "desktop"- })));- }-- #[test]- fn windowless_false_under_window_scope() {- assert!(!is_windowless_desktop_action(&json!({- "x": 10, "y": 20, "scope": "window"- })));- }-- #[test]- fn windowless_false_when_xy_missing() {- assert!(!is_windowless_desktop_action(- &json!({"x": 10, "scope": "desktop"})- ));- assert!(!is_windowless_desktop_action(- &json!({"y": 20, "scope": "desktop"})- ));- assert!(!is_windowless_desktop_action(&json!({"scope": "desktop"})));- // Non-numeric x/y must not qualify.- assert!(!is_windowless_desktop_action(&json!({- "x": "10", "y": "20", "scope": "desktop"- })));- }-- // ── get_desktop_state schema ──────────────────────────────────────────────-- #[test]- fn get_desktop_state_schema_rejects_window_scoped_fields() {- let tool = GetDesktopStateTool {- state: super::ToolState::new(None),- };- // The portable get_desktop_state contract pins the accepted fields and- // annotations; it cannot see a window-scoped field added to live.- let d = tool.def();- let props = d.input_schema["properties"].as_object().unwrap();- assert!(!props.contains_key("pid"), "must not accept pid");- assert!(- !props.contains_key("window_id"),- "must not accept window_id"- );- assert_eq!(d.input_schema["additionalProperties"], json!(false));- }-}+mod desktop_scope_tests;#[cfg(test)]-mod browser_launch_guard_tests {- use super::contains_remote_debugging_flag;-- #[test]- fn rejects_all_chromium_remote_debugging_spellings() {- assert!(contains_remote_debugging_flag("--remote-debugging-port=0"));- assert!(contains_remote_debugging_flag("--REMOTE-DEBUGGING-PIPE"));- assert!(contains_remote_debugging_flag(- r#"C:\Program Files\Chrome\chrome.exe --remote-debugging-port 9222"#- ));- assert!(!contains_remote_debugging_flag(- r#"--user-data-dir=C:\Temp\profile"#- ));- }-}+mod browser_launch_guard_tests;#[cfg(test)]-mod pid_window_target_tests {- use super::*;- use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};-- fn window(hwnd: u64, pid: u32) -> crate::win32::WindowInfo {- crate::win32::WindowInfo {- hwnd,- pid,- title: format!("Document {hwnd}"),- x: 0,- y: 0,- width: 640,- height: 480,- is_on_screen: true,- minimized: false,- }- }-- #[test]- fn same_pid_sibling_windows_are_ambiguous() {- let candidates =- window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);- assert!(matches!(- resolve_pid_window_target(candidates),- PidWindowTargetResolution::Ambiguous(windows)- if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]- ));- }-}+mod pid_window_target_tests;#[cfg(test)]-mod value_write_readback_tests {- use super::{classify_value_write_readback, value_write_structured_result};-- #[test]- fn confirms_when_the_expected_value_replaces_the_prior_value() {- assert_eq!(- classify_value_write_readback(Some("beforeinserted"), "before", "beforeinserted"),- "confirmed"- );- }-- #[test]- fn treats_stale_or_unreadable_value_as_pending() {- assert_eq!(- classify_value_write_readback(Some("old value"), "old value", "old valueinserted"),- "pending"- );- assert_eq!(- classify_value_write_readback(None, "old value", "old valueinserted"),- "pending"- );- }-- #[test]- fn deferred_publication_remains_unverifiable_without_retry_escalation() {- let result = value_write_structured_result(8, "pending", false);- assert_eq!(result["effect"], "unverifiable");- assert_eq!(result["verify"], "pending");- assert_eq!(result["verified"], false);- assert!(result.get("escalation").is_none());-- let record = cua_driver_core::action_record::ActionExecutionRecord::from_legacy(- "type_text",- &serde_json::json!({"delivery_mode": "background"}),- &result,- )- .expect("deferred ValuePattern result should normalize");- let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))- .expect("serialize ActionResult");- assert_eq!(public["effect"], "unverifiable");- assert!(public.get("escalation").is_none());- assert!(public.get("evidence").is_none());- }-- #[test]- fn does_not_confirm_when_stale_value_contains_the_typed_text() {- assert_eq!(- classify_value_write_readback(Some("10.00"), "10.00", "10.000"),- "pending"- );- }-- #[test]- fn does_not_confirm_an_empty_write() {- assert_eq!(- classify_value_write_readback(Some("unchanged"), "unchanged", "unchanged"),- "pending"- );- }-}+mod value_write_readback_tests;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/background_element_click_record_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/background_element_click_record_tests.rsnew file mode 100644index 0000000000..b0af8269af--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/background_element_click_record_tests.rs@@ -0,0 +1,62 @@+use super::{background_element_click_result, ActionTransport};++#[test]+fn raw_fallback_reports_its_physical_transport() {+ for (transport, path) in [+ (ActionTransport::WindowsTargetedInjection, "pixel"),+ (ActionTransport::WindowsPostMessage, "post_message"),+ ] {+ let result = background_element_click_result(+ "physical fallback".into(),+ transport,+ vec![ActionTransport::WindowsUiaInvoke],+ );+ assert_eq!(result.structured_content.as_ref().unwrap()["path"], path);+ let record = result.action_record.unwrap();+ assert_eq!(record.transport, transport);+ let truth = record.debug_json();+ assert_ne!(truth["route"], "accessibility");+ assert_eq!(+ record.attempts[0].transport,+ ActionTransport::WindowsUiaInvoke+ );+ assert_eq!(record.fallbacks[0].to, transport);+ }+}++#[test]+fn failed_provider_calls_disqualify_single_action_marker_exemption() {+ let result = background_element_click_result(+ "semantic success after provider failure".into(),+ ActionTransport::WindowsUiaToggle,+ vec![ActionTransport::WindowsUiaInvoke],+ );+ let record = result.action_record.unwrap();+ assert_eq!(record.transport, ActionTransport::WindowsUiaToggle);+ assert_eq!(record.attempts.len(), 1);+ assert_eq!(record.fallbacks.len(), 1);+ assert_eq!(record.fallbacks[0].from, ActionTransport::WindowsUiaInvoke);+ assert_eq!(record.fallbacks[0].to, ActionTransport::WindowsUiaToggle);+ // Point-free recording requires an empty fallback journal.+ assert!(!record.debug_json()["fallbacks"]+ .as_array()+ .unwrap()+ .is_empty());+}++#[test]+fn single_provider_success_has_no_invented_attempts() {+ for transport in [+ ActionTransport::WindowsUiaInvoke,+ ActionTransport::WindowsUiaToggle,+ ActionTransport::WindowsUiaSelection,+ ActionTransport::WindowsUiaExpandCollapse,+ ] {+ let result = background_element_click_result("semantic success".into(), transport, vec![]);+ assert_eq!(result.structured_content.as_ref().unwrap()["path"], "ax");+ let record = result.action_record.unwrap();+ assert_eq!(record.transport, transport);+ assert!(record.attempts.is_empty());+ assert!(record.fallbacks.is_empty());+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/browser_launch_guard_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/browser_launch_guard_tests.rsnew file mode 100644index 0000000000..af60987603--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/browser_launch_guard_tests.rs@@ -0,0 +1,13 @@+use super::contains_remote_debugging_flag;++#[test]+fn rejects_all_chromium_remote_debugging_spellings() {+ assert!(contains_remote_debugging_flag("--remote-debugging-port=0"));+ assert!(contains_remote_debugging_flag("--REMOTE-DEBUGGING-PIPE"));+ assert!(contains_remote_debugging_flag(+ r#"C:\Program Files\Chrome\chrome.exe --remote-debugging-port 9222"#+ ));+ assert!(!contains_remote_debugging_flag(+ r#"--user-data-dir=C:\Temp\profile"#+ ));+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/chromium_flag_injection_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/chromium_flag_injection_tests.rsnew file mode 100644index 0000000000..c7235df25d--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/chromium_flag_injection_tests.rs@@ -0,0 +1,108 @@+use super::{inject_chromium_anti_throttling_flags, is_chromium_browser_target};++#[test]+fn detects_bare_browser_names() {+ for name in [+ "msedge", "chrome", "brave", "opera", "vivaldi", "chromium", "thorium", "iridium",+ "browser", "arc",+ ] {+ assert!(is_chromium_browser_target(name), "{name} should match");+ assert!(+ is_chromium_browser_target(&format!("{name}.exe")),+ "{name}.exe should match"+ );+ // Case-insensitive.+ assert!(+ is_chromium_browser_target(&name.to_uppercase()),+ "uppercase {name} should match"+ );+ }+}++#[test]+fn detects_full_paths() {+ assert!(is_chromium_browser_target(+ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"+ ));+ assert!(is_chromium_browser_target(+ r"C:\Program Files\Google\Chrome\Application\chrome.exe"+ ));+ // Forward slashes too (some shells write paths that way).+ assert!(is_chromium_browser_target(+ r"C:/Program Files/Google/Chrome/Application/chrome.exe"+ ));+}++#[test]+fn detects_launch_path_with_trailing_args() {+ // Round-tripped launch_path from list_apps with shortcut arguments.+ assert!(is_chromium_browser_target(+ r#""C:\Program Files\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 2""#+ ));+}++#[test]+fn does_not_match_non_chromium_apps() {+ for name in ["firefox", "notepad", "explorer", "code", "soffice"] {+ assert!(!is_chromium_browser_target(name), "{name} should NOT match");+ assert!(+ !is_chromium_browser_target(&format!("{name}.exe")),+ "{name}.exe should NOT match"+ );+ }+ // Empty target.+ assert!(!is_chromium_browser_target(""));+}++#[test]+fn injects_three_flags_into_empty_args() {+ let mut args: Vec<String> = vec![];+ inject_chromium_anti_throttling_flags(&mut args);+ assert!(args.contains(&"--disable-features=CalculateNativeWinOcclusion".to_string()));+ assert!(args.contains(&"--disable-backgrounding-occluded-windows".to_string()));+ assert!(args.contains(&"--disable-renderer-backgrounding".to_string()));+ assert_eq!(args.len(), 3);+}++#[test]+fn merges_into_existing_disable_features_list() {+ let mut args = vec!["--disable-features=Foo,Bar".to_string()];+ inject_chromium_anti_throttling_flags(&mut args);+ // Should NOT have two --disable-features= entries.+ let dfe: Vec<_> = args+ .iter()+ .filter(|a| a.starts_with("--disable-features="))+ .collect();+ assert_eq!(dfe.len(), 1);+ assert!(dfe[0].contains("CalculateNativeWinOcclusion"));+ assert!(dfe[0].contains("Foo"));+ assert!(dfe[0].contains("Bar"));+}++#[test]+fn idempotent_when_all_flags_already_present() {+ let mut args = vec![+ "--disable-features=CalculateNativeWinOcclusion".to_string(),+ "--disable-backgrounding-occluded-windows".to_string(),+ "--disable-renderer-backgrounding".to_string(),+ ];+ let before = args.clone();+ inject_chromium_anti_throttling_flags(&mut args);+ assert_eq!(args, before, "must not duplicate flags");+}++#[test]+fn preserves_user_url_argument_after_flags() {+ let mut args = vec!["file:///C:/test_page.html".to_string()];+ inject_chromium_anti_throttling_flags(&mut args);+ // URL must still be present.+ assert!(args.iter().any(|a| a == "file:///C:/test_page.html"));+ // All three flags now in args.+ assert!(args+ .iter()+ .any(|a| a == "--disable-features=CalculateNativeWinOcclusion"));+ assert!(args+ .iter()+ .any(|a| a == "--disable-backgrounding-occluded-windows"));+ assert!(args.iter().any(|a| a == "--disable-renderer-backgrounding"));+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/click_capture_id_schema_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/click_capture_id_schema_tests.rsnew file mode 100644index 0000000000..709bdce421--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/click_capture_id_schema_tests.rs@@ -0,0 +1,17 @@+use super::ClickTool;+use cua_driver_core::tool::Tool;++/// The portable click contract pins `button` and the other accepted+/// fields. A live schema may broaden `capture_id`, which the subset gate+/// allows, so the non-empty bound is pinned here.+#[test]+fn schema_requires_non_empty_capture_id() {+ let tool = ClickTool {+ state: super::ToolState::new(None),+ };+ let d = tool.def();+ let props = d.input_schema.get("properties").expect("properties");+ let capture_id = props.get("capture_id").expect("capture_id field present");+ assert_eq!(capture_id["type"], "string");+ assert_eq!(capture_id["minLength"], 1);+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/cursor_key_resolution_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/cursor_key_resolution_tests.rsnew file mode 100644index 0000000000..7baba3a989--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/cursor_key_resolution_tests.rs@@ -0,0 +1,52 @@+use super::{resolve_cursor_key, NO_CURSOR};+use serde_json::json;++#[test]+fn direct_platform_call_without_lifecycle_resolves_to_no_cursor() {+ // No session/cursor_id → NO_CURSOR (""): the action still runs but no+ // cursor is shown. Canonical core dispatch injects `_session_id` before+ // real platform calls.+ assert_eq!(resolve_cursor_key(&json!({})), NO_CURSOR);+ assert_eq!(resolve_cursor_key(&json!({ "pid": 1 })), NO_CURSOR);+ assert_eq!(+ resolve_cursor_key(&json!({ "_session_id": "mcp-1-2" })),+ "mcp-1-2"+ );+}++#[test]+fn explicit_session_owns_a_cursor() {+ assert_eq!(+ resolve_cursor_key(&json!({ "session": "research-run" })),+ "research-run"+ );+}++#[test]+fn cursor_id_is_a_legacy_alias_and_session_wins() {+ assert_eq!(+ resolve_cursor_key(&json!({ "cursor_id": "user-handle" })),+ "user-handle"+ );+ assert_eq!(+ resolve_cursor_key(&json!({ "session": "s1", "cursor_id": "c1" })),+ "s1"+ );+ assert_eq!(+ resolve_cursor_key(&json!({ "_session_id": "implicit", "cursor_id": "c1" })),+ "implicit"+ );+}++#[test]+fn empty_strings_fall_through_to_no_cursor() {+ // An empty `session` falls through to `cursor_id`; both empty → NO_CURSOR.+ assert_eq!(+ resolve_cursor_key(&json!({ "session": "", "cursor_id": "c1" })),+ "c1"+ );+ assert_eq!(+ resolve_cursor_key(&json!({ "session": "", "cursor_id": "" })),+ NO_CURSOR+ );+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/desktop_scope_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/desktop_scope_tests.rsnew file mode 100644index 0000000000..cc55418372--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/desktop_scope_tests.rs@@ -0,0 +1,76 @@+use super::{is_windowless_desktop_action, GetDesktopStateTool};+use cua_driver_core::tool::Tool;+use serde_json::json;++// ── is_windowless_desktop_action ──────────────────────────────────────────++#[test]+fn windowless_true_for_xy_under_desktop_scope_click_shape() {+ // Click arg shape: {x, y}.+ assert!(is_windowless_desktop_action(+ &json!({"x": 10, "y": 20, "scope": "desktop"})+ ));+}++#[test]+fn windowless_true_for_xy_under_desktop_scope_scroll_shape() {+ // Scroll arg shape: {direction, x, y}.+ assert!(is_windowless_desktop_action(&json!({+ "direction": "down", "x": 10, "y": 20, "scope": "desktop"+ })));+}++#[test]+fn windowless_false_when_pid_present() {+ assert!(!is_windowless_desktop_action(&json!({+ "x": 10, "y": 20, "pid": 5, "scope": "desktop"+ })));+}++#[test]+fn windowless_false_when_window_id_present() {+ assert!(!is_windowless_desktop_action(&json!({+ "x": 10, "y": 20, "window_id": 99, "scope": "desktop"+ })));+}++#[test]+fn windowless_false_under_window_scope() {+ assert!(!is_windowless_desktop_action(&json!({+ "x": 10, "y": 20, "scope": "window"+ })));+}++#[test]+fn windowless_false_when_xy_missing() {+ assert!(!is_windowless_desktop_action(+ &json!({"x": 10, "scope": "desktop"})+ ));+ assert!(!is_windowless_desktop_action(+ &json!({"y": 20, "scope": "desktop"})+ ));+ assert!(!is_windowless_desktop_action(&json!({"scope": "desktop"})));+ // Non-numeric x/y must not qualify.+ assert!(!is_windowless_desktop_action(&json!({+ "x": "10", "y": "20", "scope": "desktop"+ })));+}++// ── get_desktop_state schema ──────────────────────────────────────────────++#[test]+fn get_desktop_state_schema_rejects_window_scoped_fields() {+ let tool = GetDesktopStateTool {+ state: super::ToolState::new(None),+ };+ // The portable get_desktop_state contract pins the accepted fields and+ // annotations; it cannot see a window-scoped field added to live.+ let d = tool.def();+ let props = d.input_schema["properties"].as_object().unwrap();+ assert!(!props.contains_key("pid"), "must not accept pid");+ assert!(+ !props.contains_key("window_id"),+ "must not accept window_id"+ );+ assert_eq!(d.input_schema["additionalProperties"], json!(false));+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/get_window_state_actions_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/get_window_state_actions_tests.rsnew file mode 100644index 0000000000..1690dc3e34--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/get_window_state_actions_tests.rs@@ -0,0 +1,38 @@+use super::*;+use crate::uia::UiaNode;++fn node(actions: Vec<String>) -> UiaNode {+ UiaNode {+ element_index: Some(1),+ control_type: "Button".to_owned(),+ name: Some("OK".to_owned()),+ value: None,+ automation_id: None,+ help_text: None,+ actions,+ enabled: Some(true),+ selected: None,+ element_ptr: 0,+ center_x: 0,+ center_y: 0,+ rect: None,+ msaa_role: None,+ depth: 0,+ parent_element_index: None,+ in_web_content: false,+ }+}++#[test]+fn element_entry_includes_actions_when_present() {+ let n = node(vec!["invoke".to_owned(), "toggle".to_owned()]);+ let entry = build_element_entry(&n, None).unwrap();+ assert_eq!(entry["actions"], json!(["invoke", "toggle"]));+}++#[test]+fn element_entry_omits_actions_when_empty() {+ let n = node(Vec::new());+ let entry = build_element_entry(&n, None).unwrap();+ assert!(entry.get("actions").is_none());+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/get_window_state_max_image_dimension_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/get_window_state_max_image_dimension_tests.rsnew file mode 100644index 0000000000..5273873505--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/get_window_state_max_image_dimension_tests.rs@@ -0,0 +1,20 @@+use super::resolve_max_image_dimension;++#[test]+fn canonical_override_wins_and_zero_requests_native_resolution() {+ assert_eq!(resolve_max_image_dimension(1568, None, None), 1568);+ assert_eq!(resolve_max_image_dimension(1568, Some(800), None), 800);+ assert_eq!(resolve_max_image_dimension(800, Some(1568), None), 1568);+ assert_eq!(resolve_max_image_dimension(1568, Some(0), None), 0);+ assert_eq!(+ resolve_max_image_dimension(1568, Some(1200), Some(400)),+ 1200+ );+}++#[test]+fn omitted_canonical_override_preserves_legacy_folding() {+ assert_eq!(resolve_max_image_dimension(1568, None, Some(800)), 800);+ assert_eq!(resolve_max_image_dimension(800, None, Some(1568)), 800);+ assert_eq!(resolve_max_image_dimension(0, None, Some(800)), 800);+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/launch_focus_restore_decision_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/launch_focus_restore_decision_tests.rsnew file mode 100644index 0000000000..8c3da651ce--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/launch_focus_restore_decision_tests.rs@@ -0,0 +1,50 @@+use super::{+ first_unopened_shell_url_index, should_restore_foreground_after_launch, LaunchTargetShape,+};++#[test]+fn only_app_identifying_launches_restore_foreground() {+ for (fields, restore) in [+ // A urls-only launch explicitly asks for navigation in the default+ // browser; that browser is the legitimate foreground.+ (&["urls"][..], false),+ (&["name"], true),+ (&["path"], true),+ // The AUMID path restores synchronously in launch_uwp.rs; the+ // caller gates the polling restore on `aumid_for_uwp.is_none()`.+ (&["aumid"], true),+ (&["bundle_id"], true),+ (&["launch_path"], true),+ // An app-identifying field alongside urls opens them in that app+ // in the background, so the prior foreground is restored.+ (&["name", "urls"], true),+ (&["path", "urls"], true),+ (&["aumid", "urls"], true),+ // Nothing was launched.+ (&[], false),+ ] {+ let shape = LaunchTargetShape {+ has_aumid: fields.contains(&"aumid"),+ has_bundle_id: fields.contains(&"bundle_id"),+ has_name: fields.contains(&"name"),+ has_path: fields.contains(&"path"),+ has_launch_path: fields.contains(&"launch_path"),+ has_urls: fields.contains(&"urls"),+ };+ assert_eq!(+ should_restore_foreground_after_launch(shape),+ restore,+ "{fields:?}"+ );+ }+}++#[test]+fn named_app_launch_forwards_every_url() {+ assert_eq!(first_unopened_shell_url_index(true), 0);+}++#[test]+fn urls_only_launch_does_not_reopen_primary_url() {+ assert_eq!(first_unopened_shell_url_index(false), 1);+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/list_windows_z_index_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/list_windows_z_index_tests.rsnew file mode 100644index 0000000000..76c72dd1c9--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/list_windows_z_index_tests.rs@@ -0,0 +1,29 @@+use super::{exact_window_ownership_result, z_index_from_front_to_back};++#[test]+fn enum_windows_front_to_back_order_normalizes_to_higher_is_frontmost() {+ let indices: Vec<_> = (0..3)+ .map(|position| z_index_from_front_to_back(3, position))+ .collect();+ assert_eq!(indices, vec![2, 1, 0]);+ assert!(indices[0] > indices[2]);+}++#[test]+fn explicit_pid_hwnd_guard_refuses_wrong_or_stale_owners() {+ assert!(exact_window_ownership_result(42, 7, Some(42)).is_ok());++ let wrong = exact_window_ownership_result(42, 7, Some(99)).unwrap_err();+ assert_eq!(wrong.is_error, Some(true));+ assert_eq!(+ wrong.structured_content.as_ref().unwrap()["code"],+ "window_target_mismatch"+ );+ assert_eq!(wrong.structured_content.as_ref().unwrap()["owner_pid"], 99);++ let stale = exact_window_ownership_result(42, 7, None).unwrap_err();+ assert_eq!(+ stale.structured_content.as_ref().unwrap()["code"],+ "window_target_not_found"+ );+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/pid_window_target_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/pid_window_target_tests.rsnew file mode 100644index 0000000000..f0631d067b--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/pid_window_target_tests.rs@@ -0,0 +1,27 @@+use super::*;+use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};++fn window(hwnd: u64, pid: u32) -> crate::win32::WindowInfo {+ crate::win32::WindowInfo {+ hwnd,+ pid,+ title: format!("Document {hwnd}"),+ x: 0,+ y: 0,+ width: 640,+ height: 480,+ is_on_screen: true,+ minimized: false,+ }+}++#[test]+fn same_pid_sibling_windows_are_ambiguous() {+ let candidates =+ window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);+ assert!(matches!(+ resolve_pid_window_target(candidates),+ PidWindowTargetResolution::Ambiguous(windows)+ if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]+ ));+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/pixel_click_transport_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/pixel_click_transport_tests.rsnew file mode 100644index 0000000000..6c7922bb07--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/pixel_click_transport_tests.rs@@ -0,0 +1,131 @@+use super::{finish_pixel_uia_attempt, posted_pixel_click_result};+use crate::uia::windows_enum::PointInvokeOutcome;+use cua_driver_core::action_record::{+ ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,+};++#[test]+fn uia_unavailable_errors_advertise_foreground_escalation() {+ use cua_driver_core::action_record::EscalationKind;+ use cua_driver_core::protocol::Content;+ for (outcome, status) in [+ (PointInvokeOutcome::Busy, "busy"),+ (PointInvokeOutcome::Timeout, "timeout"),+ (PointInvokeOutcome::Unavailable, "unavailable"),+ ] {+ let result = finish_pixel_uia_attempt(outcome, 7, 3, 4)+ .expect("unavailable UIA must stop the route without fallback");+ assert!(result.is_error.unwrap_or(false), "{outcome:?}");+ let data = result+ .structured_content+ .as_ref()+ .expect("structured error");+ assert_eq!(data["code"], "background_unavailable");+ assert_eq!(data["uia_status"], status);+ assert_eq!(data["path"], "ax");+ assert_eq!(data["effect"], "unverifiable");+ assert_eq!(+ data["suggestion"].as_str(),+ Some("Retry this action with delivery_mode:\"foreground\"."),+ "{outcome:?}"+ );+ assert_eq!(+ data["escalation"]["recommended"].as_str(),+ Some("foreground"),+ "{outcome:?}"+ );+ let reason = data["escalation"]["reason"]+ .as_str()+ .expect("escalation reason");+ assert!(+ reason.contains(status),+ "reason must name the UIA status: {reason}"+ );+ assert!(+ reason.contains("delivery_mode:\"foreground\""),+ "reason must name the next rung: {reason}"+ );+ let text = match &result.content[0] {+ Content::Text { text, .. } => text,+ _ => panic!("expected text content for {outcome:?}"),+ };+ assert!(+ text.contains("No fallback input was sent"),+ "text must keep the no-replay guarantee: {text}"+ );+ assert!(+ text.contains("delivery_mode:\"foreground\""),+ "text must surface the escalation: {text}"+ );+ let record = ActionExecutionRecord::from_legacy(+ "click",+ &serde_json::json!({ "delivery_mode": "background" }),+ data,+ )+ .expect("UIA refusal should normalize into the public action contract");+ let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))+ .expect("serialize ActionResult");+ assert_eq!(public["effect"], "unverifiable", "{outcome:?}");+ }+ // The completed-miss boundary is unchanged: only Miss falls through,+ // and a delivered Invoke carries no escalation hint.+ assert!(finish_pixel_uia_attempt(PointInvokeOutcome::Miss, 7, 3, 4).is_none());+ let ok = finish_pixel_uia_attempt(PointInvokeOutcome::Invoked, 7, 3, 4)+ .expect("invoked click reports success");+ assert!(!ok.is_error.unwrap_or(false));+ let ok_data = ok.structured_content.as_ref().expect("structured success");+ assert_eq!(ok_data["path"], "ax");+ assert!(ok_data.get("escalation").is_none());+ assert!(ok_data.get("suggestion").is_none());+ let ok_record = ActionExecutionRecord::from_legacy(+ "click",+ &serde_json::json!({ "delivery_mode": "background" }),+ ok_data,+ )+ .expect("UIA invoke should normalize into the public action contract");+ let ok_public = serde_json::to_value(ok_record.public_result().expect("valid ActionResult"))+ .expect("serialize ActionResult");+ assert_eq!(ok_public["effect"], "unverifiable");+ // The hint must flow into the existing escalation pipeline, not sit+ // as inert metadata: Timeout (the #3621 case) normalizes to a+ // foreground-delivery escalation on the internal record.+ let timeout_data = finish_pixel_uia_attempt(PointInvokeOutcome::Timeout, 7, 3, 4)+ .expect("timeout stops the route")+ .structured_content+ .expect("structured error");+ let timeout_record = ActionExecutionRecord::from_legacy(+ "click",+ &serde_json::json!({ "delivery_mode": "background" }),+ &timeout_data,+ )+ .expect("UIA timeout should normalize into the public action contract");+ assert_eq!(+ timeout_record.escalation.map(|escalation| escalation.kind),+ Some(EscalationKind::RetryWithForegroundDelivery)+ );+}++#[test]+fn post_message_pixel_click_reports_synthetic_transport() {+ let result = posted_pixel_click_result(42, "click");+ let structured = result+ .structured_content+ .as_ref()+ .expect("posted click should expose legacy transport metadata");+ assert_eq!(structured["path"], "post_message");++ let record = ActionExecutionRecord::from_legacy(+ "click",+ &serde_json::json!({ "delivery_mode": "background" }),+ structured,+ )+ .expect("posted click should normalize into the public action contract");+ assert_eq!(record.transport, ActionTransport::WindowsPostMessage);+ assert_eq!(record.requested_delivery, RequestedDelivery::Background);+ assert_eq!(record.actual_delivery, Some(ActualDelivery::Background));++ let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))+ .expect("serialize ActionResult");+ assert_eq!(public["route"], "synthetic_events");+ assert_eq!(public["delivery"]["mode"], "background");+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/post_message_readback_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/post_message_readback_tests.rsnew file mode 100644index 0000000000..b1a69139b9--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/post_message_readback_tests.rs@@ -0,0 +1,47 @@+use super::{changed_contains_post_message_result, post_message_readback_observed};++#[test]+fn observes_only_a_changed_value_containing_the_requested_text() {+ assert!(post_message_readback_observed(+ Some("prefix"),+ Some("prefixhello"),+ "hello"+ ));+ assert!(!post_message_readback_observed(None, None, "hello"));+ assert!(!post_message_readback_observed(+ Some("hello"),+ Some("hello"),+ "hello"+ ));+ assert!(!post_message_readback_observed(+ Some(""),+ Some("h"),+ "hello"+ ));+ assert!(!post_message_readback_observed(+ Some("before"),+ Some("different"),+ "hello"+ ));+}++#[test]+fn changed_contains_remains_unverifiable_without_retry_escalation() {+ let result = changed_contains_post_message_result(5);+ assert_eq!(result["effect"], "unverifiable");+ assert_eq!(result["verify"], "changed_contains");+ assert_eq!(result["verified"], false);+ assert!(result.get("escalation").is_none());++ let record = cua_driver_core::action_record::ActionExecutionRecord::from_legacy(+ "type_text",+ &serde_json::json!({"delivery_mode": "background"}),+ &result,+ )+ .expect("changed-and-contains PostMessage result should normalize");+ let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))+ .expect("serialize ActionResult");+ assert_eq!(public["effect"], "unverifiable");+ assert!(public.get("escalation").is_none());+ assert!(public.get("evidence").is_none());+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/set_window_frame_geometry_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/set_window_frame_geometry_tests.rsnew file mode 100644index 0000000000..0f30e69c28--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/set_window_frame_geometry_tests.rs@@ -0,0 +1,27 @@+use super::outer_frame_for_visible_request;++#[test]+fn compensates_for_invisible_resize_borders() {+ assert_eq!(+ outer_frame_for_visible_request(+ (65, 52, 872, 626),+ (40, 40, 886, 633),+ (47, 40, 872, 626),+ )+ .unwrap(),+ (58, 52, 886, 633)+ );+}++#[test]+fn leaves_outer_request_unchanged_when_dwm_bounds_are_unavailable() {+ assert_eq!(+ outer_frame_for_visible_request(+ (-25, 10, 640, 480),+ (20, 30, 800, 600),+ (20, 30, 800, 600),+ )+ .unwrap(),+ (-25, 10, 640, 480)+ );+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/snapshot_coordinate_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/snapshot_coordinate_tests.rsnew file mode 100644index 0000000000..e5b6cf4b81--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/snapshot_coordinate_tests.rs@@ -0,0 +1,41 @@+use super::{focus_by_pixel_click_args, ToolState, ZoomTool};+use cua_driver_core::tool::Tool;++#[test]+fn schema_keeps_pid_optional_for_window_owned_lookup() {+ let tool = ZoomTool {+ state: ToolState::new(None),+ };+ let required = tool.def().input_schema["required"].as_array().unwrap();+ assert!(!required.iter().any(|field| field == "pid"));+ assert!(tool.def().input_schema["properties"].get("pid").is_some());+}++#[test]+fn press_key_native_element_focus_skips_second_screenshot_scaling() {+ let native = focus_by_pixel_click_args(+ 42,+ Some(7),+ 120.0,+ 80.0,+ false,+ None,+ Some("client-a".to_owned()),+ false,+ true,+ );+ assert_eq!(native["_native_coordinates"], true);++ let screenshot = focus_by_pixel_click_args(+ 42,+ Some(7),+ 60.0,+ 40.0,+ false,+ None,+ Some("client-a".to_owned()),+ false,+ false,+ );+ assert!(screenshot.get("_native_coordinates").is_none());+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/value_write_readback_tests.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/value_write_readback_tests.rsnew file mode 100644index 0000000000..9b7c1867c1--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_/value_write_readback_tests.rs@@ -0,0 +1,58 @@+use super::{classify_value_write_readback, value_write_structured_result};++#[test]+fn confirms_when_the_expected_value_replaces_the_prior_value() {+ assert_eq!(+ classify_value_write_readback(Some("beforeinserted"), "before", "beforeinserted"),+ "confirmed"+ );+}++#[test]+fn treats_stale_or_unreadable_value_as_pending() {+ assert_eq!(+ classify_value_write_readback(Some("old value"), "old value", "old valueinserted"),+ "pending"+ );+ assert_eq!(+ classify_value_write_readback(None, "old value", "old valueinserted"),+ "pending"+ );+}++#[test]+fn deferred_publication_remains_unverifiable_without_retry_escalation() {+ let result = value_write_structured_result(8, "pending", false);+ assert_eq!(result["effect"], "unverifiable");+ assert_eq!(result["verify"], "pending");+ assert_eq!(result["verified"], false);+ assert!(result.get("escalation").is_none());++ let record = cua_driver_core::action_record::ActionExecutionRecord::from_legacy(+ "type_text",+ &serde_json::json!({"delivery_mode": "background"}),+ &result,+ )+ .expect("deferred ValuePattern result should normalize");+ let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))+ .expect("serialize ActionResult");+ assert_eq!(public["effect"], "unverifiable");+ assert!(public.get("escalation").is_none());+ assert!(public.get("evidence").is_none());+}++#[test]+fn does_not_confirm_when_stale_value_contains_the_typed_text() {+ assert_eq!(+ classify_value_write_readback(Some("10.00"), "10.00", "10.000"),+ "pending"+ );+}++#[test]+fn does_not_confirm_an_empty_write() {+ assert_eq!(+ classify_value_write_readback(Some("unchanged"), "unchanged", "unchanged"),+ "pending"+ );+}diff --git a/libs/cua-driver/rust/test-apps/README.md b/libs/cua-driver/rust/test-apps/README.mdindex 69c993e721..3a98982a6e 100644--- a/libs/cua-driver/rust/test-apps/README.md+++ b/libs/cua-driver/rust/test-apps/README.md@@ -4,7 +4,9 @@ Local staging directory for cua-driver test fixture applications.Build scripts under `../tests/fixtures/build/` write `harness-<name>/`directories here. The staged outputs are intentionally git-ignored; rebuild-them from source instead of committing binaries.+them from source instead of committing binaries. Keep this README and the+`.gitignore`: the Linux and macOS build scripts `cd` into this directory and+fail when a fresh checkout lacks it.Common outputs:diff --git a/libs/cua-driver/tests/linux-mpx-recovery.py b/scripts/ci/linux/run-mpx-recovery-e2e.pysimilarity index 100%rename from libs/cua-driver/tests/linux-mpx-recovery.pyrename to scripts/ci/linux/run-mpx-recovery-e2e.py