Skip to content

armgit / cua

Public Imported from GitHub
0

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

refactor(cua-driver): test taxonomy + protocol split/dedup + transport coverage (Phases 3-6) (#2043)

Francesco Bonacci708986d9a8fe
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs
index 63fc7bf56c..9f213aace0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs
@@ -30,11 +30,13 @@ mod driver;
mod mcp;
mod cli;
mod paths;
+mod raw;
mod reaper;
mod response;
pub use driver::Driver;
pub use mcp::McpDriver;
+pub use raw::RawDriver;
pub use cli::CliDriver;
pub use paths::{driver_binary, harness_app, workspace_root};
pub use reaper::{spawn_in_job, ChildReaper};
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
new file mode 100644
index 0000000000..7943a3e9c9
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
@@ -0,0 +1,68 @@
+//! Raw JSON-RPC transport — lockstep send/recv with **no** auto-initialize.
+//!
+//! [`crate::McpDriver`] auto-`initialize`s on spawn and only exposes
+//! `tools/call`, which is the right ergonomics for behavior tests. The MCP
+//! *protocol* tests need the opposite: drive the `initialize` handshake
+//! themselves, send arbitrary methods (`tools/list`, `unknown/method`,
+//! malformed frames), and read each raw response line in order. `RawDriver`
+//! gives them exactly that, shared across the `protocol_*` test files so they
+//! don't each re-implement `send_request`/`read_response`.
+
+use std::io::{BufRead, BufReader, Write};
+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
+
+use serde_json::Value;
+
+use crate::paths::driver_binary;
+
+/// A spawned cua-driver with raw stdio access and no handshake performed.
+/// Killed on drop.
+pub struct RawDriver {
+ child: Child,
+ stdin: ChildStdin,
+ stdout: BufReader<ChildStdout>,
+}
+
+impl RawDriver {
+ /// Spawn the driver with piped stdio. Returns `None` (with a skip eprintln)
+ /// if the binary isn't built — callers early-return so an un-built binary
+ /// skips rather than fails.
+ pub fn spawn() -> Option<Self> {
+ let bin = driver_binary();
+ if !bin.exists() {
+ eprintln!("[testkit] driver binary not built at {bin:?} — skipping");
+ return None;
+ }
+ let mut child = Command::new(&bin)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .inspect_err(|e| eprintln!("[testkit] driver spawn failed: {e}"))
+ .ok()?;
+ let stdin = child.stdin.take().unwrap();
+ let stdout = BufReader::new(child.stdout.take().unwrap());
+ Some(RawDriver { child, stdin, stdout })
+ }
+
+ /// Write one JSON-RPC frame (newline-delimited) and flush.
+ pub fn send(&mut self, req: &Value) {
+ writeln!(self.stdin, "{}", serde_json::to_string(req).unwrap()).unwrap();
+ let _ = self.stdin.flush();
+ }
+
+ /// Read and parse the next response line. Panics on read/parse failure
+ /// (a malformed or missing response is a protocol-test failure).
+ pub fn recv(&mut self) -> Value {
+ let mut line = String::new();
+ self.stdout.read_line(&mut line).expect("read response line");
+ serde_json::from_str(line.trim()).expect("parse JSON response")
+ }
+}
+
+impl Drop for RawDriver {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/ux_guard_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/guard_ux_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/ux_guard_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/guard_ux_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_lo_vcl_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_libreoffice_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/harness_lo_vcl_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/harness_libreoffice_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_web_windows_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_web_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/harness_web_windows_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/harness_web_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/mcp_protocol_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/mcp_protocol_test.rs
deleted file mode 100644
index c068874bb3..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver/tests/mcp_protocol_test.rs
+++ /dev/null
@@ -1,3412 +0,0 @@
-//! Integration tests for the MCP JSON-RPC 2.0 protocol.
-//!
-//! Tests the server protocol without any platform-specific automation —
-//! verifies request/response format, initialize handshake, tools/list,
-//! and error handling.
-
-use std::io::{BufRead, BufReader, Write};
-use std::process::{Command, Stdio};
-use std::time::Duration;
-
-/// Path to the built binary.
-fn binary_path() -> std::path::PathBuf {
- // CARGO_MANIFEST_DIR is crates/cua-driver; workspace root is two levels up.
- let manifest = std::env::var("CARGO_MANIFEST_DIR")
- .expect("CARGO_MANIFEST_DIR not set");
- std::path::PathBuf::from(manifest)
- .parent().unwrap() // crates/
- .parent().unwrap() // workspace root (cua-driver-rs/)
- .join("target/debug/cua-driver")
-}
-
-fn send_request(stdin: &mut impl Write, request: &serde_json::Value) {
- let line = serde_json::to_string(request).unwrap();
- writeln!(stdin, "{}", line).unwrap();
-}
-
-fn read_response(reader: &mut impl BufRead) -> serde_json::Value {
- let mut line = String::new();
- reader.read_line(&mut line).expect("read line");
- serde_json::from_str(line.trim()).expect("parse JSON")
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_initialize_handshake() {
- let binary = binary_path();
- if !binary.exists() {
- eprintln!("Binary not found at {:?} — run `cargo build` first", binary);
- return;
- }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn cua-driver");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- // 1. Send initialize request.
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": 1,
- "method": "initialize",
- "params": {
- "protocolVersion": "2024-11-05",
- "clientInfo": { "name": "test-client", "version": "0.0.1" }
- }
- }));
-
- let resp = read_response(&mut stdout);
- assert_eq!(resp["jsonrpc"], "2.0");
- assert_eq!(resp["id"], 1);
- assert!(resp["result"]["protocolVersion"].is_string());
- assert_eq!(resp["result"]["serverInfo"]["name"], "cua-driver");
-
- // 2. Send notifications/initialized (no response expected).
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "method": "notifications/initialized"
- }));
-
- // 3. Request tool list.
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": 2,
- "method": "tools/list"
- }));
-
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 2);
- let tools = resp["result"]["tools"].as_array().expect("tools array");
- assert!(!tools.is_empty(), "Should have at least one tool");
-
- // Verify tool names match reference implementation.
- let tool_names: Vec<&str> = tools.iter()
- .filter_map(|t| t["name"].as_str())
- .collect();
-
- for expected in &["list_apps", "list_windows", "get_window_state", "click", "type_text", "press_key"] {
- assert!(
- tool_names.contains(expected),
- "Missing tool: {} (have: {:?})", expected, tool_names
- );
- }
-
- // 4. Verify unknown method returns -32601.
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": 3,
- "method": "unknown/method"
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 3);
- assert_eq!(resp["error"]["code"], -32601);
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_tools_call_list_apps() {
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- // Initialize.
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Call list_apps.
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": 2,
- "method": "tools/call",
- "params": { "name": "list_apps", "arguments": {} }
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 2);
- assert!(resp["result"]["content"].is_array());
- let content = &resp["result"]["content"][0];
- assert_eq!(content["type"], "text");
- let text = content["text"].as_str().unwrap();
- // Should contain some running apps.
- assert!(text.contains("Found"), "Expected app list text, got: {}", text);
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_tools_call_unknown_tool() {
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": 2,
- "method": "tools/call",
- "params": { "name": "nonexistent_tool", "arguments": {} }
- }));
- let resp = read_response(&mut stdout);
- // Error should be in the content with isError=true, not a protocol error.
- let result = &resp["result"];
- let is_error = result["isError"].as_bool().unwrap_or(false);
- assert!(is_error, "Expected isError=true for unknown tool");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_concurrent_clients() {
- //! Verify two concurrent cua-driver-rs processes both respond correctly.
- //! This tests the "multiple cua-driver processes" scenario relevant to
- //! the multi-cursor use case.
-
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut processes: Vec<std::process::Child> = (0..2).map(|_| {
- Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn")
- }).collect();
-
- for (i, child) in processes.iter_mut().enumerate() {
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": i + 1,
- "method": "initialize",
- "params": {}
- }));
-
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], (i + 1) as i64);
- assert!(resp["result"]["protocolVersion"].is_string(),
- "Process {i} failed to initialize");
- }
-
- for mut child in processes {
- child.kill().ok();
- }
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_overlay_move_cursor_stays_alive() {
- //! Verify that calling move_cursor with the overlay enabled does not crash the process.
- //! The overlay renders to a transparent NSWindow on the main thread; the MCP server
- //! sends commands via the global channel. Any crash in the render thread (e.g. wrong
- //! GCD queue pointer, bad CGImage argument types) would cause this test to fail with
- //! an early EOF or a non-zero exit code.
-
- let binary = binary_path();
- if !binary.exists() { return; }
-
- // Start WITHOUT --no-overlay so the AppKit render loop runs.
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- // Initialize.
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Call move_cursor several times to drive the overlay render loop.
- for (id, (x, y)) in [(2, (100.0_f64, 200.0_f64)), (3, (400.0, 300.0)), (4, (800.0, 600.0))] {
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": id,
- "method": "tools/call",
- "params": { "name": "move_cursor", "arguments": { "x": x, "y": y } }
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], id);
- // Should succeed (isError absent or false).
- let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
- assert!(!is_error, "move_cursor failed: {:?}", resp);
- }
-
- // Also call get_agent_cursor_state — should report the last position.
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0",
- "id": 5,
- "method": "tools/call",
- "params": { "name": "get_agent_cursor_state", "arguments": {} }
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 5);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
-
- // Give the render loop a chance to tick (two frames ≈ 33 ms).
- std::thread::sleep(Duration::from_millis(100));
-
- // Process must still be alive.
- assert!(
- child.try_wait().expect("try_wait").is_none(),
- "cua-driver crashed during overlay move_cursor test"
- );
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_all_expected_tools_registered() {
- //! Verify that all tools from the reference implementation are registered.
- //! Adding a new tool to the macOS reference requires adding it to this list.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
- let resp = read_response(&mut stdout);
- let tools = resp["result"]["tools"].as_array().expect("tools array");
- let names: std::collections::HashSet<&str> = tools.iter()
- .filter_map(|t| t["name"].as_str())
- .collect();
-
- let expected = [
- "list_apps", "list_windows", "get_window_state", "launch_app",
- "click", "double_click", "right_click", "type_text",
- "press_key", "hotkey", "set_value", "scroll", "zoom",
- "get_screen_size", "get_cursor_position",
- "move_cursor", "set_agent_cursor_enabled", "set_agent_cursor_motion",
- "get_agent_cursor_state", "check_permissions", "get_config", "set_config",
- "get_accessibility_tree",
- "start_recording", "stop_recording", "get_recording_state", "replay_trajectory",
- "page",
- ];
- for name in &expected {
- assert!(names.contains(name), "Missing tool: {name} (registered: {names:?})");
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_get_screen_size_and_cursor_position() {
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // get_screen_size
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"get_screen_size","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_screen_size failed: {resp:?}");
- let sc = &resp["result"]["structuredContent"];
- assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0, "width should be positive");
- assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0, "height should be positive");
-
- // get_cursor_position
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_cursor_position","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_cursor_position failed: {resp:?}");
- // x and y may be 0,0 or any value — just verify the keys exist and are numbers.
- assert!(resp["result"]["structuredContent"]["x"].is_number(), "x should be a number");
- assert!(resp["result"]["structuredContent"]["y"].is_number(), "y should be a number");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_get_config_and_check_permissions() {
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"get_config","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- assert_eq!(resp["result"]["structuredContent"]["platform"], "macos");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"check_permissions","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- // Returns structured content with accessibility and screen_recording booleans.
- assert!(resp["result"]["structuredContent"]["accessibility"].is_boolean());
-
- // set_config — change capture_mode to "ax" and verify get_config reflects the new value.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"set_config","arguments":{"capture_mode": "ax", "max_image_dimension": 1920}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from set_config: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "set_config returned empty content");
-
- // get_config should now reflect the updated values.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"get_config","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["result"]["structuredContent"]["capture_mode"], "ax",
- "get_config should reflect set_config change");
- assert_eq!(resp["result"]["structuredContent"]["max_image_dimension"], 1920,
- "get_config should reflect max_image_dimension change");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_multi_cursor_instance_state() {
- //! Two cursor instances can be created with different IDs; each has independent state.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Move cursor "agent1" to (100, 200).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"x":100.0,"y":200.0,"cursor_id":"agent1"}}
- }));
- let r2 = read_response(&mut stdout);
- assert!(!r2["result"]["isError"].as_bool().unwrap_or(false));
-
- // Move cursor "agent2" to (300, 400).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"x":300.0,"y":400.0,"cursor_id":"agent2"}}
- }));
- let r3 = read_response(&mut stdout);
- assert!(!r3["result"]["isError"].as_bool().unwrap_or(false));
-
- // Configure cursor "agent1" with a custom color.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"set_agent_cursor_motion","arguments":{
- "cursor_id":"agent1","cursor_color":"#FF0000","cursor_label":"AI-1"
- }}
- }));
- let r4 = read_response(&mut stdout);
- assert!(!r4["result"]["isError"].as_bool().unwrap_or(false));
-
- // Hide cursor "agent2".
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"set_agent_cursor_enabled","arguments":{"enabled":false,"cursor_id":"agent2"}}
- }));
- let r5 = read_response(&mut stdout);
- assert!(!r5["result"]["isError"].as_bool().unwrap_or(false));
-
- // get_agent_cursor_state is now session-scoped: each call returns ONLY the
- // cursor it resolves to (explicit cursor_id > injected _session_id >
- // "default"). Query each instance by its cursor_id and assert independent
- // state (agent2 was hidden; agent1 was left enabled).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":6,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent1"}}
- }));
- let resp1 = read_response(&mut stdout);
- assert!(!resp1["result"]["isError"].as_bool().unwrap_or(false));
- let cursors1 = resp1["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
- assert_eq!(cursors1.len(), 1, "agent1 query must return exactly its own cursor, got: {cursors1:?}");
- assert_eq!(cursors1[0]["config"]["cursor_id"].as_str(), Some("agent1"));
- assert_eq!(resp1["result"]["structuredContent"]["enabled"].as_bool(), Some(true),
- "agent1 was never disabled");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":7,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent2"}}
- }));
- let resp2 = read_response(&mut stdout);
- assert!(!resp2["result"]["isError"].as_bool().unwrap_or(false));
- let cursors2 = resp2["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
- assert_eq!(cursors2.len(), 1, "agent2 query must return exactly its own cursor, got: {cursors2:?}");
- assert_eq!(cursors2[0]["config"]["cursor_id"].as_str(), Some("agent2"));
- assert_eq!(resp2["result"]["structuredContent"]["enabled"].as_bool(), Some(false),
- "agent2 was hidden");
-
- std::thread::sleep(Duration::from_millis(50));
- assert!(child.try_wait().expect("try_wait").is_none(), "cua-driver crashed during multi-cursor test");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_set_agent_cursor_motion_bezier_knobs() {
- //! set_agent_cursor_motion with Bezier/timing knobs — verifies schema accepts them
- //! and returns a non-error response with the updated values in the response text.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Set Bezier motion knobs including integer-encoded numbers (common from MCP clients).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"set_agent_cursor_motion","arguments":{
- "cursor_id": "agent1",
- "arc_size": 0.4,
- "spring": 0.85,
- "glide_duration_ms": 500,
- "dwell_after_click_ms": 200,
- "idle_hide_ms": 5000
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from set_agent_cursor_motion: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
- "set_agent_cursor_motion returned isError: {resp:?}");
- // Response text should mention the new glide duration.
- let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- assert!(text.contains("500") || text.contains("motion"),
- "Expected motion summary in response, got: {text}");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_concurrent_clients_with_cursor_moves() {
- //! Two concurrent cua-driver processes, each driving their own cursor, should not crash.
- //! This covers the multi-cursor use case where two Codex agents run simultaneously.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut processes: Vec<(std::process::Child, usize)> = (0..2).map(|i| {
- let child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
- (child, i)
- }).collect();
-
- // Initialize all processes.
- for (child, i) in &mut processes {
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 1, "Process {i} initialize failed");
- }
-
- // Each process moves its cursor to different positions.
- let positions = vec![(100.0_f64, 200.0_f64), (500.0, 600.0)];
- for ((child, i), (px, py)) in processes.iter_mut().zip(positions.iter()) {
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"x":px,"y":py}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
- "Process {i} move_cursor failed: {resp:?}");
- }
-
- std::thread::sleep(Duration::from_millis(100));
-
- for (child, i) in &mut processes {
- assert!(child.try_wait().expect("try_wait").is_none(),
- "cua-driver process {i} crashed during concurrent cursor test");
- child.kill().ok();
- }
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_zoom_tool_returns_jpeg() {
- //! Call zoom on a visible window and verify the result contains a JPEG image.
- //! Skips gracefully if no windows are visible (headless environment).
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // List on-screen windows only — off-screen/minimized windows may not be capturable.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
- }));
- let resp = read_response(&mut stdout);
- let windows = resp["result"]["structuredContent"]["windows"]
- .as_array()
- .cloned()
- .unwrap_or_default();
-
- // Try windows until one captures successfully.
- let mut found_jpeg = false;
- let mut tried = 0usize;
- for win in windows.iter().take(5) {
- let Some(wid) = win["window_id"].as_u64() else { continue; };
- tried += 1;
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id": 2 + tried as u64,"method":"tools/call",
- "params":{"name":"zoom","arguments":{
- "window_id": wid,
- "x1": 0, "y1": 0, "x2": 100, "y2": 100
- }}
- }));
- let r = read_response(&mut stdout);
- if r["result"]["isError"].as_bool().unwrap_or(false) {
- // This window might be off-screen or not capturable — try the next.
- continue;
- }
- let content = r["result"]["content"].as_array().expect("content array");
- found_jpeg = content.iter().any(|c| {
- c["type"] == "image" && c["mimeType"].as_str().unwrap_or("") == "image/jpeg"
- && c["data"].as_str().map(|s| s.len() > 10).unwrap_or(false)
- });
- if found_jpeg {
- // Also verify structuredContent.
- let sc = &r["result"]["structuredContent"];
- assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive width: {sc:?}");
- assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive height: {sc:?}");
- assert_eq!(sc["format"].as_str().unwrap_or(""), "jpeg", "Expected format=jpeg: {sc:?}");
- break;
- }
- }
-
- if tried == 0 {
- eprintln!("No on-screen windows found — skipping zoom test");
- child.kill().ok();
- return;
- }
- assert!(found_jpeg, "Expected at least one window to return a valid JPEG from zoom");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_type_text_chars_tool() {
- //! Verify type_text_chars with delay_ms is accepted without error (dry-run via TextEdit or
- //! a pid that accepts WM_CHAR). We just verify the tool responds with a non-error.
- //! Skips gracefully if no visible TextEdit window.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // list_apps to find a target (e.g. TextEdit).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_apps","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let apps = resp["result"]["structuredContent"]["apps"].as_array();
- let textedit_pid = apps.and_then(|arr| {
- arr.iter().find(|a| a["name"].as_str().unwrap_or("").contains("TextEdit"))
- .and_then(|a| a["pid"].as_i64())
- });
-
- let Some(pid) = textedit_pid else {
- eprintln!("TextEdit not running — skipping type_text_chars test");
- child.kill().ok();
- return;
- };
-
- // type_text_chars with delay_ms=5 — just verify the tool invocation is accepted.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"type_text_chars","arguments":{
- "pid": pid, "text": "hi", "delay_ms": 5
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
- "type_text_chars returned error: {resp:?}");
- let msg = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- assert!(
- msg.contains("Typed") || msg.contains("Inserted"),
- "Unexpected message: {msg}"
- );
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_recording_session() {
- //! Enable recording, invoke move_cursor (non-read-only), disable, verify action.json written.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-rec-test-{}", std::process::id()));
- let tmp_str = tmp_dir.to_string_lossy().to_string();
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Enable recording.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"start_recording","arguments":{"output_dir":tmp_str,"record_video":false}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "start_recording failed: {resp:?}");
- assert!(resp["result"]["structuredContent"]["enabled"].as_bool().unwrap_or(false));
-
- // Invoke a non-read-only tool — should be recorded.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"set_agent_cursor_enabled","arguments":{"enabled":false}}
- }));
- read_response(&mut stdout);
-
- // get_recording_state — next_turn should advance after one recorded action.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"get_recording_state","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let next_turn = resp["result"]["structuredContent"]["next_turn"].as_u64().unwrap_or(0);
- assert!(next_turn >= 2, "expected next_turn >= 2, got {next_turn}");
-
- // Disable recording.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"stop_recording","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["structuredContent"]["enabled"].as_bool().unwrap_or(true));
- child.kill().ok();
-
- // Small sync wait for the write to flush.
- std::thread::sleep(Duration::from_millis(50));
-
- // Verify turn-00001/action.json was written.
- let action_path = tmp_dir.join("turn-00001").join("action.json");
- assert!(action_path.exists(), "Expected {action_path:?} to exist");
- let content: serde_json::Value = serde_json::from_str(
- &std::fs::read_to_string(&action_path).unwrap()
- ).unwrap();
- assert_eq!(content["tool"].as_str().unwrap_or(""), "set_agent_cursor_enabled");
- assert_eq!(content["arguments"]["enabled"].as_bool(), Some(false));
-
- let _ = std::fs::remove_dir_all(&tmp_dir);
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_recording_screenshot_capture() {
- //! When recording is active and a tool call includes a window_id, a screenshot.png
- //! should appear alongside action.json in the turn folder.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-rec-ss-{}", std::process::id()));
- let tmp_str = tmp_dir.to_string_lossy().to_string();
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Find a capturable on-screen window.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array().cloned().unwrap_or_default();
- // Prefer windows with non-empty titles (more likely capturable).
- let win = wins.iter()
- .find(|w| w["pid"].as_i64().is_some() && !w["title"].as_str().unwrap_or("").is_empty())
- .or_else(|| wins.iter().find(|w| w["pid"].as_i64().is_some()));
- let Some(win) = win else {
- eprintln!("No on-screen windows — skipping recording screenshot test");
- child.kill().ok();
- return;
- };
- let window_id = win["window_id"].as_u64().unwrap();
- let pid = win["pid"].as_i64().unwrap();
-
- // Enable recording.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"start_recording","arguments":{"output_dir":tmp_str,"record_video":false}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "start_recording failed: {resp:?}");
-
- // Invoke click (non-read-only) with window_id + pid — recording should capture screenshot.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"click","arguments":{"pid": pid, "window_id": window_id, "x":0.0,"y":0.0}}
- }));
- read_response(&mut stdout); // result may be error if coords are off-window — that's ok
-
- // Disable recording.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"stop_recording","arguments":{}}
- }));
- read_response(&mut stdout);
- child.kill().ok();
-
- std::thread::sleep(Duration::from_millis(100));
-
- // action.json must exist.
- let turn_dir = tmp_dir.join("turn-00001");
- let action_path = turn_dir.join("action.json");
- assert!(action_path.exists(), "Expected action.json at {action_path:?}");
- let content: serde_json::Value = serde_json::from_str(
- &std::fs::read_to_string(&action_path).unwrap()
- ).unwrap();
- assert_eq!(content["tool"].as_str().unwrap_or(""), "click");
-
- // screenshot.png should exist if screencapture succeeded for this window.
- let ss_path = turn_dir.join("screenshot.png");
- if !ss_path.exists() {
- eprintln!("screenshot.png not written for window {window_id} (may be uncapturable) — skipping PNG check");
- } else {
- let ss_bytes = std::fs::read(&ss_path).unwrap();
- assert!(!ss_bytes.is_empty(), "screenshot.png should not be empty");
- assert_eq!(&ss_bytes[..4], b"\x89PNG", "screenshot.png should be a valid PNG");
-
- // click.png should also exist (click at 0,0 with crosshair marker).
- let click_path = turn_dir.join("click.png");
- if !click_path.exists() {
- eprintln!("click.png not written — skipping click PNG check");
- } else {
- let click_bytes = std::fs::read(&click_path).unwrap();
- assert!(!click_bytes.is_empty(), "click.png should not be empty");
- assert_eq!(&click_bytes[..4], b"\x89PNG", "click.png should be a valid PNG");
- }
- }
-
- let _ = std::fs::remove_dir_all(&tmp_dir);
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_replay_trajectory() {
- //! Write a minimal trajectory (one move_cursor turn), replay it, verify succeeded=1.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let traj_dir = std::env::temp_dir().join(format!("cua-driver-rs-replay-{}", std::process::id()));
- let turn_dir = traj_dir.join("turn-00001");
- std::fs::create_dir_all(&turn_dir).unwrap();
- std::fs::write(
- turn_dir.join("action.json"),
- r#"{"tool":"move_cursor","arguments":{"x":50.0,"y":60.0}}"#,
- ).unwrap();
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"replay_trajectory","arguments":{
- "dir": traj_dir.to_string_lossy(),
- "delay_ms": 0
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "replay error: {resp:?}");
- let sc = &resp["result"]["structuredContent"];
- assert_eq!(sc["attempted"].as_u64().unwrap_or(0), 1, "expected attempted=1");
- assert_eq!(sc["succeeded"].as_u64().unwrap_or(0), 1, "expected succeeded=1");
- assert_eq!(sc["failed"].as_u64().unwrap_or(99), 0, "expected failed=0");
-
- child.kill().ok();
- let _ = std::fs::remove_dir_all(&traj_dir);
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_page_unknown_action_error() {
- //! Verify the cross-platform `page` tool is registered and rejects an
- //! unknown action with a meaningful error.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"page","arguments":{
- "pid": 1,
- "window_id": 0,
- "action": "definitely_not_a_real_action"
- }}
- }));
- let resp = read_response(&mut stdout);
-
- assert!(
- resp["result"]["isError"].as_bool().unwrap_or(false),
- "expected isError=true for unknown action: {resp:?}"
- );
- let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- assert!(
- text.to_ascii_lowercase().contains("unknown action"),
- "error text should mention 'Unknown action': {text}"
- );
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_screenshot_no_window_id() {
- //! Call screenshot without window_id — should capture the full display and return image content.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"screenshot","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from screenshot: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "screenshot should return at least one content item");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_screenshot_jpeg_format() {
- //! Call screenshot with format=jpeg — should return a JPEG image.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"screenshot","arguments":{"format":"jpeg","quality":70}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from screenshot: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
- if !is_error {
- let has_jpeg = content.iter().any(|c| {
- c["type"] == "image" && c["mimeType"].as_str().unwrap_or("") == "image/jpeg"
- && c["data"].as_str().map(|s| s.len() > 10).unwrap_or(false)
- });
- assert!(has_jpeg, "Expected image/jpeg in screenshot response, got: {content:?}");
- // Verify structured content has width and height.
- let sc = &resp["result"]["structuredContent"];
- assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive width in structuredContent");
- assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive height in structuredContent");
- assert_eq!(sc["format"].as_str().unwrap_or(""), "jpeg", "Expected format=jpeg");
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_hotkey_keys_array() {
- //! Verify hotkey accepts a keys array (["cmd","a"]) without a protocol error.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let windows = resp["result"]["structuredContent"]["windows"].as_array();
- let first_win = windows.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some()));
-
- let Some(win) = first_win else {
- eprintln!("No windows found — skipping hotkey keys array test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- // keys array should be parsed and the tool invoked; result may succeed or fail depending
- // on whether the target app accepts the hotkey, but there must be no protocol error.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"hotkey","arguments":{
- "pid": pid, "window_id": wid, "keys": ["cmd","a"]
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from hotkey: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "hotkey should return content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_get_accessibility_tree() {
- //! get_accessibility_tree returns a lightweight process+window snapshot.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"get_accessibility_tree","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
- "get_accessibility_tree returned error: {resp:?}");
-
- let sc = &resp["result"]["structuredContent"];
- // macOS backend returns "apps"; Linux returns "processes". Either key is valid.
- let has_apps = sc["apps"].is_array() || sc["processes"].is_array();
- assert!(has_apps, "Expected apps or processes array in structured content, got: {sc:?}");
-
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "Expected non-empty content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_get_window_state_ax_mode() {
- //! get_window_state with capture_mode="ax" should return a tree but no screenshot image.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let windows = resp["result"]["structuredContent"]["windows"].as_array();
- let first_win = windows.and_then(|a| a.iter().find(|w| {
- w["pid"].as_i64().is_some() && w["window_id"].as_u64().is_some()
- }));
-
- let Some(win) = first_win else {
- eprintln!("No windows found — skipping get_window_state ax test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_window_state","arguments":{
- "pid": pid, "window_id": wid, "capture_mode": "ax"
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from get_window_state: {resp:?}");
-
- let content = resp["result"]["content"].as_array().expect("content array");
- // ax mode must NOT return an image content item.
- let has_image = content.iter().any(|c| c["type"] == "image");
- assert!(!has_image, "capture_mode=ax should not return an image, got: {content:?}");
- assert!(!content.is_empty(), "Expected at least one content item");
-
- // structuredContent must include window_id, pid, element_count.
- let sc = &resp["result"]["structuredContent"];
- assert_eq!(sc["window_id"].as_u64().unwrap_or(0), wid, "structuredContent.window_id mismatch");
- assert_eq!(sc["pid"].as_i64().unwrap_or(0), pid, "structuredContent.pid mismatch");
- assert!(sc["element_count"].is_number(), "expected element_count in structuredContent: {sc:?}");
- // ax mode — screenshot_width should NOT be present.
- assert!(sc["screenshot_width"].is_null(), "ax mode should not have screenshot_width: {sc:?}");
-
- // Also test vision mode: screenshot_width/height should be present.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"get_window_state","arguments":{
- "pid": pid, "window_id": wid, "capture_mode": "vision"
- }}
- }));
- let vision_resp = read_response(&mut stdout);
- assert!(vision_resp["error"].is_null(), "Protocol error from vision get_window_state: {vision_resp:?}");
- if !vision_resp["result"]["isError"].as_bool().unwrap_or(false) {
- let vsc = &vision_resp["result"]["structuredContent"];
- assert!(vsc["screenshot_width"].as_f64().unwrap_or(0.0) > 0.0,
- "vision mode should have screenshot_width: {vsc:?}");
- assert!(vsc["screenshot_height"].as_f64().unwrap_or(0.0) > 0.0,
- "vision mode should have screenshot_height: {vsc:?}");
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_type_text_chars_type_chars_only_schema() {
- //! Verify the deprecated type_text_chars alias stays hidden from tools/list
- //! while related active tool schemas retain their expected knobs.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // The deprecated alias is accepted at invoke time but intentionally hidden
- // from tools/list.
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}));
- let list_resp = read_response(&mut stdout);
- let tools = list_resp["result"]["tools"].as_array().expect("tools array");
- assert!(
- tools.iter().all(|t| t["name"] != "type_text_chars"),
- "deprecated type_text_chars alias should not appear in tools/list"
- );
-
- // Also verify list_windows schema has on_screen_only.
- let lw = tools.iter().find(|t| t["name"] == "list_windows")
- .expect("list_windows not found in tools/list");
- let lw_props = &lw["inputSchema"]["properties"];
- assert!(lw_props["on_screen_only"].is_object(),
- "list_windows schema missing on_screen_only property: {lw_props:?}");
-
- // Verify set_agent_cursor_motion has Bezier motion knobs.
- let sacm = tools.iter().find(|t| t["name"] == "set_agent_cursor_motion")
- .expect("set_agent_cursor_motion not found in tools/list");
- let sacm_props = &sacm["inputSchema"]["properties"];
- for knob in &["arc_size", "spring", "glide_duration_ms", "dwell_after_click_ms", "idle_hide_ms"] {
- assert!(sacm_props[knob].is_object(),
- "set_agent_cursor_motion schema missing {knob}: {sacm_props:?}");
- }
- // Also verify set_config schema has the enum restriction.
- let sc = tools.iter().find(|t| t["name"] == "set_config")
- .expect("set_config not found in tools/list");
- let sc_props = &sc["inputSchema"]["properties"];
- assert!(sc_props["capture_mode"]["enum"].is_array(),
- "set_config capture_mode should have enum: {sc_props:?}");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_list_windows_structured_content() {
- //! Verify list_windows returns structuredContent.windows array with expected fields.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
- "list_windows returned error: {resp:?}");
-
- let sc = &resp["result"]["structuredContent"];
- assert!(sc["windows"].is_array(), "Expected windows array in structuredContent: {sc:?}");
-
- // If there are any windows, verify the expected fields are present.
- if let Some(wins) = sc["windows"].as_array() {
- if let Some(w) = wins.first() {
- assert!(w["window_id"].is_number(), "window_id missing from window: {w:?}");
- assert!(w["pid"].is_number(), "pid missing from window: {w:?}");
- }
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_press_key_harmless() {
- //! press_key with a harmless key (F24 — virtually no app responds to it) sent to the
- //! first available window. Just verifies the tool doesn't return a protocol error.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Find a window to target.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
- eprintln!("No windows found — skipping press_key test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- // F24 is a function key that virtually no app binds — safe to send.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"press_key","arguments":{"pid": pid, "window_id": wid, "key": "F24"}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from press_key: {resp:?}");
- // Tool may succeed or return an app error, but must NOT be a protocol-level error.
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "press_key returned empty content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_scroll_tool() {
- //! scroll with direction=down, by=line, amount=1 against the first available window.
- //! Verifies the tool is accepted and returns content, not a protocol error.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Find a pid with a window.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_apps","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let apps = resp["result"]["structuredContent"]["apps"].as_array();
- let Some(app) = apps.and_then(|a| a.iter().find(|a| a["pid"].as_i64().is_some())) else {
- eprintln!("No apps found — skipping scroll test");
- child.kill().ok();
- return;
- };
- let pid = app["pid"].as_i64().unwrap();
-
- // scroll with minimal parameters — window_id is auto-resolved from pid.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"scroll","arguments":{"pid": pid, "direction": "down", "amount": 1}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from scroll: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "scroll returned empty content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_click_pixel_path() {
- //! click at window-local (5, 5) — title bar area, safe to click without disrupting UI.
- //! Verifies the pixel-coordinate path for click works without a protocol error.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Find an on-screen window.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
- eprintln!("No on-screen windows — skipping click pixel path test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- // Click at (5, 5) in window-local coords — title bar, harmless.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from click: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "click returned empty content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_type_text_tool() {
- //! Opens TextEdit (or reuses it if already running) and types a short string via type_text.
- //! Skips gracefully if TextEdit is not available or has no window.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Launch TextEdit (no-op if already running).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"launch_app","arguments":{"name":"TextEdit"}}
- }));
- read_response(&mut stdout);
- std::thread::sleep(std::time::Duration::from_millis(800));
-
- // Find TextEdit's pid.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"list_apps","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let apps = resp["result"]["structuredContent"]["apps"].as_array();
- let Some(app) = apps.and_then(|a| {
- a.iter().find(|a| {
- a["name"].as_str().map(|n| n.eq_ignore_ascii_case("textedit")).unwrap_or(false)
- })
- }) else {
- eprintln!("TextEdit not found — skipping type_text test");
- child.kill().ok();
- return;
- };
- let pid = app["pid"].as_i64().unwrap();
-
- // Find TextEdit's first on-screen window.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"pid": pid, "on_screen_only": true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.first()) else {
- eprintln!("TextEdit has no on-screen windows — skipping type_text test");
- child.kill().ok();
- return;
- };
- let wid = win["window_id"].as_u64().unwrap();
-
- // type_text into TextEdit's window.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"type_text","arguments":{"pid": pid, "window_id": wid, "text": "cua-test"}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from type_text: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "type_text returned empty content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_double_click_and_right_click_pixel_path() {
- //! double_click and right_click at title-bar coords — verifies both tools accept pixel path.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
- eprintln!("No on-screen windows — skipping double/right click test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- // double_click at safe coords.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"double_click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from double_click: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true),
- "double_click returned empty content");
-
- // right_click at same coords.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"right_click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from right_click: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true),
- "right_click returned empty content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_set_value_via_element_index() {
- //! get_window_state on TextEdit → find a text-area element → set_value on it.
- //! Skips gracefully if TextEdit is not available.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Ensure TextEdit is running.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"launch_app","arguments":{"name":"TextEdit"}}
- }));
- read_response(&mut stdout);
- std::thread::sleep(std::time::Duration::from_millis(800));
-
- // Find TextEdit.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"list_apps","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let apps = resp["result"]["structuredContent"]["apps"].as_array();
- let Some(app) = apps.and_then(|a| {
- a.iter().find(|a| a["name"].as_str()
- .map(|n| n.eq_ignore_ascii_case("textedit")).unwrap_or(false))
- }) else {
- eprintln!("TextEdit not found — skipping set_value test");
- child.kill().ok();
- return;
- };
- let pid = app["pid"].as_i64().unwrap();
-
- // Get first window.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"pid": pid, "on_screen_only": true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.first()) else {
- eprintln!("TextEdit has no on-screen windows — skipping set_value test");
- child.kill().ok();
- return;
- };
- let wid = win["window_id"].as_u64().unwrap();
-
- // Walk AX tree to get element_count — we'll target element_index 0.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"get_window_state","arguments":{"pid": pid, "window_id": wid, "capture_mode": "ax"}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from get_window_state: {resp:?}");
- let element_count = resp["result"]["structuredContent"]["element_count"].as_u64().unwrap_or(0);
- if element_count == 0 {
- eprintln!("No AX elements — skipping set_value test");
- child.kill().ok();
- return;
- }
-
- // set_value on element 0 — this is the document / text area in a new TextEdit document.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":6,"method":"tools/call",
- "params":{"name":"set_value","arguments":{"pid": pid, "window_id": wid, "element_index": 0, "value": "cua-test-value"}}
- }));
- let resp = read_response(&mut stdout);
- // set_value may fail if element 0 is not settable; accept tool-level errors but not protocol errors.
- assert!(resp["error"].is_null(), "Protocol error from set_value: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "set_value returned empty content");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_click_debug_image_out() {
- //! click with debug_image_out writes a PNG crosshair file and then proceeds.
- //! Verifies the debug capture path works end-to-end.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- // Prefer a window with a non-empty title to avoid uncapturable overlay/system windows.
- let Some(win) = wins.and_then(|a| a.iter().find(|w| {
- w["pid"].as_i64().is_some() && !w["title"].as_str().unwrap_or("").is_empty()
- }).or_else(|| a.iter().find(|w| w["pid"].as_i64().is_some()))) else {
- eprintln!("No on-screen windows — skipping debug_image_out test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- let dbg_path = std::env::temp_dir().join(format!("cua-driver-rs-dbg-{}.png", std::process::id()));
- let dbg_path_str = dbg_path.to_string_lossy().to_string();
-
- // Click with debug_image_out — should write the PNG and then proceed.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"click","arguments":{
- "pid": pid, "window_id": wid,
- "x": 10.0, "y": 10.0,
- "debug_image_out": dbg_path_str
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from click+debug_image_out: {resp:?}");
-
- // The tool may return isError if screencapture can't capture this particular window
- // (e.g., overlay windows, system windows). If that happens, skip the PNG check.
- let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
- if is_error {
- let msg = resp["result"]["content"][0]["text"].as_str().unwrap_or("?");
- eprintln!("debug_image_out screenshot failed for this window ({msg}) — skipping PNG check");
- child.kill().ok();
- return;
- }
-
- // Verify the PNG was actually written.
- assert!(dbg_path.exists(), "debug_image_out PNG was not written to {dbg_path:?}");
- let meta = std::fs::metadata(&dbg_path).expect("metadata");
- assert!(meta.len() > 100, "debug_image_out PNG is suspiciously small");
-
- let _ = std::fs::remove_file(&dbg_path);
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_concurrent_multi_driver_isolation() {
- //! Two cua-driver processes running simultaneously with different cursor IDs.
- //! Verifies that concurrent sessions don't interfere — each tracks its own
- //! cursor state and the overlay stays alive under concurrent load.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- // Spawn two drivers concurrently.
- let mut child_a = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn driver A");
- let mut child_b = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn driver B");
-
- let stdin_a = child_a.stdin.as_mut().unwrap();
- let mut stdout_a = BufReader::new(child_a.stdout.as_mut().unwrap());
- let stdin_b = child_b.stdin.as_mut().unwrap();
- let mut stdout_b = BufReader::new(child_b.stdout.as_mut().unwrap());
-
- // Initialize both.
- send_request(stdin_a, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- send_request(stdin_b, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout_a);
- read_response(&mut stdout_b);
-
- // Driver A: set_agent_cursor_enabled for cursor "alpha", Driver B for cursor "beta".
- send_request(stdin_a, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"set_agent_cursor_enabled","arguments":{"cursor_id":"alpha","enabled":true}}
- }));
- send_request(stdin_b, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"set_agent_cursor_enabled","arguments":{"cursor_id":"beta","enabled":false}}
- }));
- let resp_a = read_response(&mut stdout_a);
- let resp_b = read_response(&mut stdout_b);
- assert!(resp_a["error"].is_null(), "Driver A set_agent_cursor_enabled failed: {resp_a:?}");
- assert!(resp_b["error"].is_null(), "Driver B set_agent_cursor_enabled failed: {resp_b:?}");
-
- // Each driver queries its own cursor state — should reflect what it set.
- // get_agent_cursor_state is session-scoped, so pass the cursor_id each
- // driver owns; the response carries { "cursors": [<that one>], "enabled" }.
- send_request(stdin_a, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"alpha"}}
- }));
- send_request(stdin_b, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"beta"}}
- }));
- let state_a = read_response(&mut stdout_a);
- let state_b = read_response(&mut stdout_b);
- assert!(state_a["error"].is_null(), "Driver A get_agent_cursor_state failed: {state_a:?}");
- assert!(state_b["error"].is_null(), "Driver B get_agent_cursor_state failed: {state_b:?}");
-
- // cursors is an array of { config: { cursor_id, enabled, ... }, x, y }.
- // Cursor alpha should be enabled (we set true), beta disabled (we set false).
- // The state lives per process — processes don't share CursorRegistry.
- let cursors_a = state_a["result"]["structuredContent"]["cursors"].as_array();
- let cursors_b = state_b["result"]["structuredContent"]["cursors"].as_array();
-
- let alpha_enabled = cursors_a.and_then(|arr| arr.iter().find(|c| {
- c["config"]["cursor_id"].as_str() == Some("alpha")
- })).and_then(|c| c["config"]["enabled"].as_bool());
- let beta_enabled = cursors_b.and_then(|arr| arr.iter().find(|c| {
- c["config"]["cursor_id"].as_str() == Some("beta")
- })).and_then(|c| c["config"]["enabled"].as_bool());
-
- assert_eq!(alpha_enabled, Some(true), "Cursor alpha should be enabled in driver A");
- assert_eq!(beta_enabled, Some(false), "Cursor beta should be disabled in driver B");
-
- // Move cursor on driver A without crashing driver B.
- send_request(stdin_a, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"cursor_id":"alpha","x":100,"y":100}}
- }));
- send_request(stdin_b, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"cursor_id":"beta","x":200,"y":200}}
- }));
- let mv_a = read_response(&mut stdout_a);
- let mv_b = read_response(&mut stdout_b);
- assert!(mv_a["error"].is_null(), "Driver A move_cursor failed: {mv_a:?}");
- assert!(mv_b["error"].is_null(), "Driver B move_cursor failed: {mv_b:?}");
-
- child_a.kill().ok();
- child_b.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_set_config_screenshot_resize() {
- //! set_config(max_image_dimension=200) then screenshot — returned image must
- //! have both dimensions ≤ 200. Verifies the ResizeRegistry pipeline end-to-end.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Set a tiny max_image_dimension so the full display screenshot will be resized.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"set_config","arguments":{"max_image_dimension":200}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "set_config failed: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "set_config returned error: {resp:?}");
-
- // Capture full display; must be ≤ 200 px in both dimensions.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"screenshot","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "screenshot failed: {resp:?}");
- if resp["result"]["isError"].as_bool().unwrap_or(false) {
- eprintln!("screenshot unavailable — skipping resize assertion: {resp:?}");
- child.kill().ok();
- return;
- }
-
- let w = resp["result"]["structuredContent"]["width"].as_u64().unwrap_or(9999);
- let h = resp["result"]["structuredContent"]["height"].as_u64().unwrap_or(9999);
- assert!(w <= 200, "screenshot width {w} should be ≤ 200 after max_image_dimension=200");
- assert!(h <= 200, "screenshot height {h} should be ≤ 200 after max_image_dimension=200");
-
- // get_config should reflect the updated value.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"get_config","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let dim = resp["result"]["structuredContent"]["max_image_dimension"].as_u64();
- assert_eq!(dim, Some(200), "get_config should reflect max_image_dimension=200");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_zoom_from_zoom_click_round_trip() {
- //! Verify the zoom → from_zoom click pipeline:
- //! 1. click(from_zoom=true) with no zoom context returns the expected error.
- //! 2. zoom() stores context; subsequent click(from_zoom=true) does NOT return
- //! that error (translation succeeded, even if the click itself may fail).
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // List on-screen windows to find a target window and pid.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array().cloned().unwrap_or_default();
- let Some(win) = wins.iter().find(|w| w["pid"].as_i64().is_some()) else {
- eprintln!("No on-screen windows — skipping from_zoom test");
- child.kill().ok();
- return;
- };
- let window_id = win["window_id"].as_u64().unwrap();
- let pid = win["pid"].as_i64().unwrap();
-
- // Step 1: click with from_zoom=true and NO prior zoom context — expect error.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"click","arguments":{"pid": pid, "window_id": window_id, "x":10.0,"y":10.0,"from_zoom":true}}
- }));
- let resp = read_response(&mut stdout);
- let is_err = resp["result"]["isError"].as_bool().unwrap_or(false);
- let err_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- assert!(is_err, "Expected error when from_zoom=true with no context, got: {resp:?}");
- assert!(err_text.contains("no zoom context"), "Expected 'no zoom context' error, got: {err_text}");
-
- // Step 2: call zoom on that window to store context.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"zoom","arguments":{"window_id": window_id, "pid": pid, "x1":0,"y1":0,"x2":50,"y2":50}}
- }));
- let resp = read_response(&mut stdout);
- if resp["result"]["isError"].as_bool().unwrap_or(false) {
- // Window may not be capturable (e.g. system UI) — skip.
- eprintln!("zoom failed — skipping from_zoom click test");
- child.kill().ok();
- return;
- }
- // Verify zoom returned structured content with width/height.
- let sc = &resp["result"]["structuredContent"];
- assert!(sc["width"].as_u64().unwrap_or(0) > 0, "zoom should return positive width: {sc:?}");
-
- // Step 3: click with from_zoom=true — should NOT return the "no zoom context" error.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"click","arguments":{"pid": pid, "window_id": window_id, "x":10.0,"y":10.0,"from_zoom":true}}
- }));
- let resp = read_response(&mut stdout);
- let is_err = resp["result"]["isError"].as_bool().unwrap_or(false);
- let err_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- // Translation should succeed — if click fails it's for another reason (target app state), not missing context.
- assert!(!err_text.contains("no zoom context"),
- "After zoom(), from_zoom click should not say 'no zoom context', got: {err_text}");
- // (is_err may be true if the click target was invalid; that's acceptable.)
- let _ = is_err;
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_start_recording_record_video_flag_accepted() {
- //! `record_video` is the new on/off flag (replaces the old
- //! `video_experimental`). Default is true. This test passes
- //! `record_video: false` to bypass the ffmpeg dependency in CI;
- //! we only verify that the schema accepts the call and the
- //! session enters the enabled state. Full video lifecycle is
- //! covered by the manual demo + the per-platform smoke when
- //! ffmpeg is installed.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-recvid-{}", std::process::id()));
- let tmp_str = tmp_dir.to_string_lossy().to_string();
- std::fs::create_dir_all(&tmp_dir).unwrap();
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"start_recording","arguments":{
- "output_dir": tmp_str, "record_video": false
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Expected no JSON-RPC error, got: {resp:?}");
- let is_err = resp["result"]["isError"].as_bool().unwrap_or(false);
- assert!(!is_err, "start_recording with record_video:false should succeed: {resp:?}");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"stop_recording","arguments":{}}
- }));
- read_response(&mut stdout);
- child.kill().ok();
- let _ = std::fs::remove_dir_all(&tmp_dir);
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// Windows integration tests
-//
-// Mirrors the macOS tests above with Windows-specific adaptations:
-// - binary path includes .exe
-// - list_apps returns structuredContent.processes (not .apps)
-// - get_config returns platform="windows"
-// - check_permissions returns { elevated, uia, post_message } (not accessibility)
-// - get_accessibility_tree returns processes + windows keys
-// - type_text tests target Notepad instead of TextEdit
-// ─────────────────────────────────────────────────────────────────────────────
-
-#[cfg(target_os = "windows")]
-fn binary_path_windows() -> std::path::PathBuf {
- binary_path().with_extension("exe")
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_initialize_handshake_windows() {
- let binary = binary_path_windows();
- if !binary.exists() {
- eprintln!("Binary not found at {:?} — run `cargo build` first", binary);
- return;
- }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn cua-driver");
-
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc": "2.0", "id": 1, "method": "initialize",
- "params": {
- "protocolVersion": "2024-11-05",
- "clientInfo": { "name": "test-client", "version": "0.0.1" }
- }
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["jsonrpc"], "2.0");
- assert_eq!(resp["id"], 1);
- assert!(resp["result"]["protocolVersion"].is_string());
- assert_eq!(resp["result"]["serverInfo"]["name"], "cua-driver-rs");
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","method":"notifications/initialized"}));
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 2);
- let tools = resp["result"]["tools"].as_array().expect("tools array");
- assert!(!tools.is_empty());
-
- let tool_names: Vec<&str> = tools.iter()
- .filter_map(|t| t["name"].as_str()).collect();
- for expected in &["list_apps", "list_windows", "get_window_state", "click", "type_text", "press_key"] {
- assert!(tool_names.contains(expected), "Missing tool: {}", expected);
- }
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":3,"method":"unknown/method"}));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 3);
- assert_eq!(resp["error"]["code"], -32601);
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_tools_call_list_apps_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_apps","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 2);
- assert!(resp["result"]["content"].is_array());
- let text = resp["result"]["content"][0]["text"].as_str().unwrap();
- assert!(text.contains("Found"), "Expected process list text, got: {}", text);
- // Windows backend returns "processes" key.
- assert!(resp["result"]["structuredContent"]["processes"].is_array(),
- "Expected processes array: {:?}", resp["result"]["structuredContent"]);
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_tools_call_unknown_tool_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"nonexistent_tool","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
- assert!(is_error, "Expected isError=true for unknown tool");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_all_expected_tools_registered_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
- let resp = read_response(&mut stdout);
- let tools = resp["result"]["tools"].as_array().expect("tools array");
- let names: std::collections::HashSet<&str> = tools.iter()
- .filter_map(|t| t["name"].as_str()).collect();
-
- let expected = [
- "list_apps", "list_windows", "get_window_state", "launch_app",
- "click", "double_click", "right_click", "type_text", "type_text_chars",
- "press_key", "hotkey", "set_value", "scroll", "screenshot", "zoom",
- "get_screen_size", "get_cursor_position",
- "move_cursor", "set_agent_cursor_enabled", "set_agent_cursor_motion",
- "get_agent_cursor_state", "check_permissions", "get_config", "set_config",
- "get_accessibility_tree",
- "start_recording", "stop_recording", "get_recording_state", "replay_trajectory",
- "page",
- ];
- for name in &expected {
- assert!(names.contains(name), "Missing tool: {name} (registered: {names:?})");
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_get_screen_size_and_cursor_position_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"get_screen_size","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_screen_size failed: {resp:?}");
- let sc = &resp["result"]["structuredContent"];
- assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0);
- assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_cursor_position","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_cursor_position failed: {resp:?}");
- assert!(resp["result"]["structuredContent"]["x"].is_number());
- assert!(resp["result"]["structuredContent"]["y"].is_number());
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_get_config_and_check_permissions_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"get_config","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- assert_eq!(resp["result"]["structuredContent"]["platform"], "windows");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"check_permissions","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- let sc = &resp["result"]["structuredContent"];
- // Windows returns elevated, uia, post_message booleans.
- assert!(sc["uia"].as_bool().unwrap_or(false), "uia should be true: {sc:?}");
- assert!(sc["post_message"].as_bool().unwrap_or(false), "post_message should be true: {sc:?}");
- assert!(sc["elevated"].is_boolean(), "elevated should be a boolean: {sc:?}");
-
- // set_config — change capture_mode and verify get_config reflects it.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"set_config","arguments":{"capture_mode":"ax","max_image_dimension":1920}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from set_config: {resp:?}");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"get_config","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["result"]["structuredContent"]["capture_mode"], "ax");
- assert_eq!(resp["result"]["structuredContent"]["max_image_dimension"], 1920);
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_concurrent_clients_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut processes: Vec<std::process::Child> = (0..2).map(|_| {
- Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn")
- }).collect();
-
- for (i, child) in processes.iter_mut().enumerate() {
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id": i + 1,"method":"initialize","params":{}
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], (i + 1) as i64);
- assert!(resp["result"]["protocolVersion"].is_string(), "Process {i} failed to initialize");
- }
-
- for mut child in processes { child.kill().ok(); }
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_list_windows_structured_content_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- let sc = &resp["result"]["structuredContent"];
- assert!(sc["windows"].is_array(), "Expected windows array: {sc:?}");
- if let Some(wins) = sc["windows"].as_array() {
- if let Some(w) = wins.first() {
- assert!(w["window_id"].is_number(), "window_id missing: {w:?}");
- assert!(w["pid"].is_number(), "pid missing: {w:?}");
- }
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_get_accessibility_tree_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"get_accessibility_tree","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- let sc = &resp["result"]["structuredContent"];
- // Windows backend returns both "processes" and "windows" keys.
- assert!(sc["processes"].is_array(), "Expected processes array: {sc:?}");
- assert!(sc["windows"].is_array(), "Expected windows array: {sc:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty());
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_screenshot_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Full-display screenshot (no window_id).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"screenshot","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- assert!(!content.is_empty(), "screenshot returned empty content");
-
- // JPEG format.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"screenshot","arguments":{"format":"jpeg","quality":70}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from screenshot jpeg: {resp:?}");
- if !resp["result"]["isError"].as_bool().unwrap_or(false) {
- let content = resp["result"]["content"].as_array().expect("content array");
- let has_jpeg = content.iter().any(|c| {
- c["type"] == "image" && c["mimeType"].as_str().unwrap_or("") == "image/jpeg"
- && c["data"].as_str().map(|s| s.len() > 10).unwrap_or(false)
- });
- assert!(has_jpeg, "Expected image/jpeg in screenshot response: {content:?}");
- let sc = &resp["result"]["structuredContent"];
- assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0);
- assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0);
- assert_eq!(sc["format"].as_str().unwrap_or(""), "jpeg");
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_zoom_tool_returns_jpeg_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
- }));
- let resp = read_response(&mut stdout);
- let windows = resp["result"]["structuredContent"]["windows"]
- .as_array().cloned().unwrap_or_default();
-
- let mut found_jpeg = false;
- let mut tried = 0usize;
- for win in windows.iter().take(5) {
- let Some(wid) = win["window_id"].as_u64() else { continue; };
- tried += 1;
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id": 2 + tried as u64,"method":"tools/call",
- "params":{"name":"zoom","arguments":{
- "window_id":wid,"x1":0,"y1":0,"x2":100,"y2":100
- }}
- }));
- let r = read_response(&mut stdout);
- if r["result"]["isError"].as_bool().unwrap_or(false) { continue; }
- let content = r["result"]["content"].as_array().expect("content array");
- found_jpeg = content.iter().any(|c| {
- c["type"] == "image" && c["mimeType"].as_str().unwrap_or("") == "image/jpeg"
- && c["data"].as_str().map(|s| s.len() > 10).unwrap_or(false)
- });
- if found_jpeg {
- let sc = &r["result"]["structuredContent"];
- assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0);
- assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0);
- assert_eq!(sc["format"].as_str().unwrap_or(""), "jpeg");
- break;
- }
- }
-
- if tried == 0 {
- eprintln!("No on-screen windows found — skipping zoom test");
- child.kill().ok();
- return;
- }
- assert!(found_jpeg, "Expected at least one window to return a valid JPEG from zoom");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_overlay_move_cursor_stays_alive_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- for (id, (x, y)) in [(2u64, (100.0_f64, 200.0_f64)), (3, (400.0, 300.0)), (4, (800.0, 600.0))] {
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":id,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"x":x,"y":y}}
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], id);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "move_cursor failed: {:?}", resp);
- }
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["id"], 5);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
-
- std::thread::sleep(Duration::from_millis(100));
-
- assert!(
- child.try_wait().expect("try_wait").is_none(),
- "cua-driver crashed during overlay move_cursor test"
- );
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_multi_cursor_instance_state_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"x":100.0,"y":200.0,"cursor_id":"agent1"}}
- }));
- assert!(!read_response(&mut stdout)["result"]["isError"].as_bool().unwrap_or(false));
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"x":300.0,"y":400.0,"cursor_id":"agent2"}}
- }));
- assert!(!read_response(&mut stdout)["result"]["isError"].as_bool().unwrap_or(false));
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"set_agent_cursor_motion","arguments":{
- "cursor_id":"agent1","cursor_color":"#FF0000","cursor_label":"AI-1"
- }}
- }));
- assert!(!read_response(&mut stdout)["result"]["isError"].as_bool().unwrap_or(false));
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"set_agent_cursor_enabled","arguments":{"enabled":false,"cursor_id":"agent2"}}
- }));
- assert!(!read_response(&mut stdout)["result"]["isError"].as_bool().unwrap_or(false));
-
- // Session-scoped: query each instance by cursor_id (see the macOS variant).
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":6,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent1"}}
- }));
- let resp1 = read_response(&mut stdout);
- assert!(!resp1["result"]["isError"].as_bool().unwrap_or(false));
- let cursors1 = resp1["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
- assert_eq!(cursors1.len(), 1, "agent1 query must return exactly its own cursor: {cursors1:?}");
- assert_eq!(cursors1[0]["config"]["cursor_id"].as_str(), Some("agent1"));
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":7,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent2"}}
- }));
- let resp2 = read_response(&mut stdout);
- assert!(!resp2["result"]["isError"].as_bool().unwrap_or(false));
- let cursors2 = resp2["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
- assert_eq!(cursors2.len(), 1, "agent2 query must return exactly its own cursor: {cursors2:?}");
- assert_eq!(cursors2[0]["config"]["cursor_id"].as_str(), Some("agent2"));
- assert_eq!(resp2["result"]["structuredContent"]["enabled"].as_bool(), Some(false), "agent2 hidden");
-
- std::thread::sleep(Duration::from_millis(50));
- assert!(child.try_wait().expect("try_wait").is_none(), "cua-driver crashed during multi-cursor test");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_press_key_harmless_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
- eprintln!("No windows found — skipping press_key test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"press_key","arguments":{"pid":pid,"window_id":wid,"key":"F24"}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from press_key: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_scroll_tool_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Windows list_apps returns "processes".
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_apps","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let procs = resp["result"]["structuredContent"]["processes"].as_array();
- let Some(proc_) = procs.and_then(|a| a.iter().find(|p| p["pid"].as_i64().is_some())) else {
- eprintln!("No processes found — skipping scroll test");
- child.kill().ok();
- return;
- };
- let pid = proc_["pid"].as_i64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"scroll","arguments":{"pid":pid,"direction":"down","amount":1}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from scroll: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_click_pixel_path_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
- eprintln!("No on-screen windows — skipping click pixel path test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"click","arguments":{"pid":pid,"window_id":wid,"x":5.0,"y":5.0}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from click: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_double_click_and_right_click_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
- eprintln!("No on-screen windows — skipping double/right click test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"double_click","arguments":{"pid":pid,"window_id":wid,"x":5.0,"y":5.0}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from double_click: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"right_click","arguments":{"pid":pid,"window_id":wid,"x":5.0,"y":5.0}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from right_click: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_hotkey_keys_array_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let windows = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = windows.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
- eprintln!("No windows found — skipping hotkey test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"hotkey","arguments":{"pid":pid,"window_id":wid,"keys":["ctrl","a"]}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from hotkey: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_get_window_state_ax_mode_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let windows = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = windows.and_then(|a| a.iter().find(|w| {
- w["pid"].as_i64().is_some() && w["window_id"].as_u64().is_some()
- })) else {
- eprintln!("No windows found — skipping get_window_state ax test");
- child.kill().ok();
- return;
- };
- let pid = win["pid"].as_i64().unwrap();
- let wid = win["window_id"].as_u64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_window_state","arguments":{"pid":pid,"window_id":wid,"capture_mode":"ax"}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
- let content = resp["result"]["content"].as_array().expect("content array");
- let has_image = content.iter().any(|c| c["type"] == "image");
- assert!(!has_image, "capture_mode=ax should not return an image");
- assert!(!content.is_empty());
-
- let sc = &resp["result"]["structuredContent"];
- assert_eq!(sc["window_id"].as_u64().unwrap_or(0), wid);
- assert_eq!(sc["pid"].as_i64().unwrap_or(0), pid);
- assert!(sc["element_count"].is_number(), "expected element_count: {sc:?}");
-
- // vision mode should include screenshot dimensions.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"get_window_state","arguments":{"pid":pid,"window_id":wid,"capture_mode":"vision"}}
- }));
- let vision_resp = read_response(&mut stdout);
- assert!(vision_resp["error"].is_null(), "Protocol error from vision get_window_state: {vision_resp:?}");
- if !vision_resp["result"]["isError"].as_bool().unwrap_or(false) {
- let vsc = &vision_resp["result"]["structuredContent"];
- assert!(vsc["screenshot_width"].as_f64().unwrap_or(0.0) > 0.0, "vision mode should have screenshot_width: {vsc:?}");
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_type_text_chars_schema_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}));
- let list_resp = read_response(&mut stdout);
- let tools = list_resp["result"]["tools"].as_array().expect("tools array");
-
- let ttc = tools.iter().find(|t| t["name"] == "type_text_chars")
- .expect("type_text_chars not found");
- let props = &ttc["inputSchema"]["properties"];
- assert!(props["type_chars_only"].is_object(),
- "type_text_chars schema missing type_chars_only: {props:?}");
-
- let lw = tools.iter().find(|t| t["name"] == "list_windows").expect("list_windows not found");
- assert!(lw["inputSchema"]["properties"]["on_screen_only"].is_object());
-
- let sacm = tools.iter().find(|t| t["name"] == "set_agent_cursor_motion")
- .expect("set_agent_cursor_motion not found");
- let sacm_props = &sacm["inputSchema"]["properties"];
- for knob in &["arc_size", "spring", "glide_duration_ms", "dwell_after_click_ms", "idle_hide_ms"] {
- assert!(sacm_props[knob].is_object(), "missing {knob}: {sacm_props:?}");
- }
-
- let sc = tools.iter().find(|t| t["name"] == "set_config").expect("set_config not found");
- assert!(sc["inputSchema"]["properties"]["capture_mode"]["enum"].is_array());
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_type_text_notepad_windows() {
- //! Launch Notepad, type a short string via type_text. Skips if Notepad unavailable.
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- // Launch Notepad.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"launch_app","arguments":{"name":"notepad.exe"}}
- }));
- read_response(&mut stdout);
- std::thread::sleep(std::time::Duration::from_millis(1000));
-
- // Find Notepad in running processes.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"list_apps","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let procs = resp["result"]["structuredContent"]["processes"].as_array();
- let Some(proc_) = procs.and_then(|a| {
- a.iter().find(|p| {
- p["name"].as_str().map(|n| n.to_lowercase().contains("notepad")).unwrap_or(false)
- })
- }) else {
- eprintln!("Notepad not found — skipping type_text test");
- child.kill().ok();
- return;
- };
- let pid = proc_["pid"].as_i64().unwrap();
-
- // Find Notepad's window.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"pid":pid,"on_screen_only":true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array();
- let Some(win) = wins.and_then(|a| a.first()) else {
- eprintln!("Notepad has no on-screen windows — skipping type_text test");
- child.kill().ok();
- return;
- };
- let wid = win["window_id"].as_u64().unwrap();
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"type_text","arguments":{"pid":pid,"window_id":wid,"text":"cua-test"}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Protocol error from type_text: {resp:?}");
- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_recording_session_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-rec-test-{}", std::process::id()));
- let tmp_str = tmp_dir.to_string_lossy().to_string();
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"start_recording","arguments":{"output_dir":tmp_str,"record_video":false}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "start_recording failed: {resp:?}");
- assert!(resp["result"]["structuredContent"]["enabled"].as_bool().unwrap_or(false));
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"move_cursor","arguments":{"x":100.0,"y":200.0}}
- }));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"get_recording_state","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- let next_turn = resp["result"]["structuredContent"]["next_turn"].as_u64().unwrap_or(0);
- assert!(next_turn >= 2, "expected next_turn >= 2, got {next_turn}");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"stop_recording","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["structuredContent"]["enabled"].as_bool().unwrap_or(true));
- child.kill().ok();
-
- std::thread::sleep(Duration::from_millis(50));
-
- let action_path = tmp_dir.join("turn-00001").join("action.json");
- assert!(action_path.exists(), "Expected action.json at {action_path:?}");
- let content: serde_json::Value = serde_json::from_str(
- &std::fs::read_to_string(&action_path).unwrap()
- ).unwrap();
- assert_eq!(content["tool"].as_str().unwrap_or(""), "move_cursor");
- assert_eq!(content["arguments"]["x"].as_f64().unwrap_or(0.0), 100.0);
-
- let _ = std::fs::remove_dir_all(&tmp_dir);
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_replay_trajectory_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let traj_dir = std::env::temp_dir().join(format!("cua-driver-rs-replay-{}", std::process::id()));
- let turn_dir = traj_dir.join("turn-00001");
- std::fs::create_dir_all(&turn_dir).unwrap();
- std::fs::write(
- turn_dir.join("action.json"),
- r#"{"tool":"move_cursor","arguments":{"x":50.0,"y":60.0}}"#,
- ).unwrap();
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"replay_trajectory","arguments":{
- "dir":traj_dir.to_string_lossy(),"delay_ms":0
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "replay error: {resp:?}");
- let sc = &resp["result"]["structuredContent"];
- assert_eq!(sc["attempted"].as_u64().unwrap_or(0), 1);
- assert_eq!(sc["succeeded"].as_u64().unwrap_or(0), 1);
- assert_eq!(sc["failed"].as_u64().unwrap_or(99), 0);
-
- child.kill().ok();
- let _ = std::fs::remove_dir_all(&traj_dir);
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_page_unknown_action_error_windows() {
- //! Verify the cross-platform `page` tool is registered on Windows and
- //! rejects an unknown action with a meaningful error.
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"page","arguments":{
- "pid":1,"window_id":0,"action":"definitely_not_a_real_action"
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(
- resp["result"]["isError"].as_bool().unwrap_or(false),
- "expected isError=true for unknown action: {resp:?}"
- );
- let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- assert!(
- text.to_ascii_lowercase().contains("unknown action"),
- "error text should mention 'Unknown action': {text}"
- );
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_set_config_screenshot_resize_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"set_config","arguments":{"max_image_dimension":200}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "set_config failed: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"screenshot","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "screenshot failed: {resp:?}");
-
- let w = resp["result"]["structuredContent"]["width"].as_u64().unwrap_or(9999);
- let h = resp["result"]["structuredContent"]["height"].as_u64().unwrap_or(9999);
- assert!(w <= 200, "screenshot width {w} should be ≤ 200 after max_image_dimension=200");
- assert!(h <= 200, "screenshot height {h} should be ≤ 200 after max_image_dimension=200");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"get_config","arguments":{}}
- }));
- let resp = read_response(&mut stdout);
- assert_eq!(resp["result"]["structuredContent"]["max_image_dimension"].as_u64(), Some(200));
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_zoom_from_zoom_click_round_trip_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
- }));
- let resp = read_response(&mut stdout);
- let wins = resp["result"]["structuredContent"]["windows"].as_array().cloned().unwrap_or_default();
- let Some(win) = wins.iter().find(|w| w["pid"].as_i64().is_some()) else {
- eprintln!("No on-screen windows — skipping from_zoom test");
- child.kill().ok();
- return;
- };
- let window_id = win["window_id"].as_u64().unwrap();
- let pid = win["pid"].as_i64().unwrap();
-
- // click with from_zoom=true and no prior zoom context — expect error.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"click","arguments":{"pid":pid,"window_id":window_id,"x":10.0,"y":10.0,"from_zoom":true}}
- }));
- let resp = read_response(&mut stdout);
- let is_err = resp["result"]["isError"].as_bool().unwrap_or(false);
- let err_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- assert!(is_err, "Expected error when from_zoom=true with no context: {resp:?}");
- assert!(err_text.contains("no zoom context"), "Expected 'no zoom context': {err_text}");
-
- // Call zoom to store context.
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":4,"method":"tools/call",
- "params":{"name":"zoom","arguments":{"window_id":window_id,"pid":pid,"x1":0,"y1":0,"x2":50,"y2":50}}
- }));
- let resp = read_response(&mut stdout);
- if resp["result"]["isError"].as_bool().unwrap_or(false) {
- eprintln!("zoom failed — skipping from_zoom click test");
- child.kill().ok();
- return;
- }
-
- // click with from_zoom=true should NOT say "no zoom context".
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":5,"method":"tools/call",
- "params":{"name":"click","arguments":{"pid":pid,"window_id":window_id,"x":10.0,"y":10.0,"from_zoom":true}}
- }));
- let resp = read_response(&mut stdout);
- let err_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
- assert!(!err_text.contains("no zoom context"),
- "After zoom(), from_zoom click should not say 'no zoom context': {err_text}");
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_start_recording_record_video_flag_accepted_windows() {
- //! `record_video` is the new on/off flag. Pass false here so the test
- //! doesn't depend on ffmpeg being installed in CI.
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-recvid-{}", std::process::id()));
- let tmp_str = tmp_dir.to_string_lossy().to_string();
- std::fs::create_dir_all(&tmp_dir).unwrap();
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"start_recording","arguments":{
- "output_dir":tmp_str,"record_video":false
- }}
- }));
- let resp = read_response(&mut stdout);
- assert!(resp["error"].is_null(), "Expected no JSON-RPC error: {resp:?}");
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
- "start_recording with record_video:false should succeed: {resp:?}");
-
- send_request(stdin, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"stop_recording","arguments":{}}
- }));
- read_response(&mut stdout);
- child.kill().ok();
- let _ = std::fs::remove_dir_all(&tmp_dir);
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_concurrent_multi_driver_isolation_windows() {
- let binary = binary_path_windows();
- if !binary.exists() { return; }
-
- let mut child_a = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn driver A");
- let mut child_b = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn driver B");
-
- let stdin_a = child_a.stdin.as_mut().unwrap();
- let mut stdout_a = BufReader::new(child_a.stdout.as_mut().unwrap());
- let stdin_b = child_b.stdin.as_mut().unwrap();
- let mut stdout_b = BufReader::new(child_b.stdout.as_mut().unwrap());
-
- send_request(stdin_a, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- send_request(stdin_b, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout_a);
- read_response(&mut stdout_b);
-
- send_request(stdin_a, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"set_agent_cursor_enabled","arguments":{"cursor_id":"alpha","enabled":true}}
- }));
- send_request(stdin_b, &serde_json::json!({
- "jsonrpc":"2.0","id":2,"method":"tools/call",
- "params":{"name":"set_agent_cursor_enabled","arguments":{"cursor_id":"beta","enabled":false}}
- }));
- let resp_a = read_response(&mut stdout_a);
- let resp_b = read_response(&mut stdout_b);
- assert!(resp_a["error"].is_null(), "Driver A failed: {resp_a:?}");
- assert!(resp_b["error"].is_null(), "Driver B failed: {resp_b:?}");
-
- // Session-scoped: query each driver's own cursor by id (see macOS variant).
- send_request(stdin_a, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"alpha"}}
- }));
- send_request(stdin_b, &serde_json::json!({
- "jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"beta"}}
- }));
- let state_a = read_response(&mut stdout_a);
- let state_b = read_response(&mut stdout_b);
- assert!(state_a["error"].is_null());
- assert!(state_b["error"].is_null());
-
- let cursors_a = state_a["result"]["structuredContent"]["cursors"].as_array();
- let cursors_b = state_b["result"]["structuredContent"]["cursors"].as_array();
-
- let alpha_enabled = cursors_a.and_then(|arr| arr.iter().find(|c| {
- c["config"]["cursor_id"].as_str() == Some("alpha")
- })).and_then(|c| c["config"]["enabled"].as_bool());
- let beta_enabled = cursors_b.and_then(|arr| arr.iter().find(|c| {
- c["config"]["cursor_id"].as_str() == Some("beta")
- })).and_then(|c| c["config"]["enabled"].as_bool());
-
- assert_eq!(alpha_enabled, Some(true), "Cursor alpha should be enabled in driver A");
- assert_eq!(beta_enabled, Some(false), "Cursor beta should be disabled in driver B");
-
- child_a.kill().ok();
- child_b.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_tools_list_includes_per_tool_capabilities() {
- //! Surface 4 contract (part 1): every entry in `tools/list` must
- //! include a `capabilities` array of dotted-namespace tokens.
- //! Downstream consumers (Hermes' cua_backend.py, Codex) dispatch
- //! by capability instead of hardcoding tool names, so this is the
- //! wire contract. Additive-only — existing keys must still be
- //! present.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
- let resp = read_response(&mut stdout);
- let result = &resp["result"];
-
- let tools = result["tools"].as_array().expect("tools array");
- assert!(!tools.is_empty(), "tools array must be non-empty");
-
- // Every entry has a `capabilities` array (may be empty for tools
- // without a mapping in `default_capabilities_for`).
- for tool in tools {
- let name = tool["name"].as_str().unwrap_or("<no name>");
- assert!(tool["capabilities"].is_array(),
- "tool {name:?} missing capabilities array: {tool:?}");
- }
-
- // Specifically: `click` claims input.pointer.click + .left, and
- // `type_text` claims input.keyboard.type — these are the contracts
- // Hermes' cua_backend.py is expected to route by.
- let click = tools.iter().find(|t| t["name"] == "click")
- .expect("click tool must be registered");
- let click_caps: Vec<&str> = click["capabilities"].as_array().unwrap()
- .iter().filter_map(|v| v.as_str()).collect();
- assert!(click_caps.contains(&"input.pointer.click"),
- "click missing input.pointer.click: {click_caps:?}");
- assert!(click_caps.contains(&"input.pointer.click.left"),
- "click missing input.pointer.click.left: {click_caps:?}");
-
- let type_text = tools.iter().find(|t| t["name"] == "type_text")
- .expect("type_text tool must be registered");
- let tt_caps: Vec<&str> = type_text["capabilities"].as_array().unwrap()
- .iter().filter_map(|v| v.as_str()).collect();
- assert!(tt_caps.contains(&"input.keyboard.type"),
- "type_text missing input.keyboard.type: {tt_caps:?}");
-
- // Regression guard for additive-only contract: every pre-existing
- // top-level field on a tool entry must still be present.
- for tool in tools {
- let name = tool["name"].as_str().unwrap_or("<no name>");
- assert!(tool["name"].is_string(), "{name}: name missing");
- assert!(tool["description"].is_string(), "{name}: description missing");
- assert!(tool["inputSchema"].is_object(), "{name}: inputSchema missing");
- assert!(tool["annotations"].is_object(), "{name}: annotations missing");
- }
-
- child.kill().ok();
-}
-
-#[test]
-#[cfg(target_os = "macos")]
-fn test_tools_list_includes_capability_and_schema_versions() {
- //! Surface 4 contract (part 2): top-level `tools/list` response
- //! must include `capability_version` and `schema_version` so
- //! downstream consumers (Hermes' cua_backend.py, Codex) can gate
- //! strict-vs-tolerant capability matching by version. Both pinned
- //! at "1" on first ship.
- let binary = binary_path();
- if !binary.exists() { return; }
-
- let mut child = Command::new(&binary)
- .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
- .spawn().expect("spawn");
- let stdin = child.stdin.as_mut().unwrap();
- let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- read_response(&mut stdout);
-
- send_request(stdin, &serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
- let resp = read_response(&mut stdout);
- let result = &resp["result"];
-
- // Both version fields default to "1" on first ship — the surface
- // is brand new, so there's no pre-existing contract to bump.
- assert_eq!(result["capability_version"], "1",
- "capability_version must default to \"1\" on first ship");
- assert_eq!(result["schema_version"], "1",
- "schema_version must default to \"1\" on first ship");
-
- // Additive guard: tools array must still be there alongside the
- // new envelope keys — old consumers that only read `tools` keep
- // working.
- assert!(result["tools"].is_array(),
- "tools array must still be present alongside version envelope");
- assert!(!result["tools"].as_array().unwrap().is_empty(),
- "tools array must be non-empty");
-
- child.kill().ok();
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_bg_modality_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_background_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/harness_bg_modality_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/modality_background_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_desktop_scope_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_desktop_scope_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/harness_desktop_scope_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/modality_desktop_scope_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/focus_check_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_focus_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/focus_check_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/modality_focus_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/e2e_windows_bg_input_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_input_e2e_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/e2e_windows_bg_input_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/modality_input_e2e_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/element_token_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs
similarity index 100%
rename from libs/cua-driver/rust/crates/cua-driver/tests/element_token_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs
new file mode 100644
index 0000000000..5a7982cd75
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs
@@ -0,0 +1,244 @@
+//! MCP JSON-RPC handshake + tools/list contract tests.
+//!
+//! initialize handshake, the registered-tools roster, per-tool capability
+//! claims, the capability/schema version envelope, and the unknown-tool /
+//! unknown-action error surfaces. Split out of the old monolithic
+//! `mcp_protocol_test.rs`; mac/windows pairs are merged into one fn that
+//! branches only where the platforms genuinely differ.
+
+#![cfg(any(target_os = "macos", target_os = "windows"))]
+
+use cua_driver_testkit::RawDriver;
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn initialize_handshake() {
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ // 1. Send initialize request.
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "clientInfo": { "name": "test-client", "version": "0.0.1" }
+ }
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["jsonrpc"], "2.0");
+ assert_eq!(resp["id"], 1);
+ assert!(resp["result"]["protocolVersion"].is_string());
+ // The server reports "cua-driver" on every platform. (The old Windows
+ // mirror asserted a stale "cua-driver-rs"; it had never been run.)
+ assert_eq!(resp["result"]["serverInfo"]["name"], "cua-driver");
+
+ // 2. Send notifications/initialized (no response expected).
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "method": "notifications/initialized"
+ }));
+
+ // 3. Request tool list.
+ d.send(&serde_json::json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 2);
+ let tools = resp["result"]["tools"].as_array().expect("tools array");
+ assert!(!tools.is_empty(), "Should have at least one tool");
+
+ // Verify tool names match reference implementation.
+ let tool_names: Vec<&str> = tools.iter()
+ .filter_map(|t| t["name"].as_str())
+ .collect();
+ for expected in &["list_apps", "list_windows", "get_window_state", "click", "type_text", "press_key"] {
+ assert!(
+ tool_names.contains(expected),
+ "Missing tool: {} (have: {:?})", expected, tool_names
+ );
+ }
+
+ // 4. Verify unknown method returns -32601.
+ d.send(&serde_json::json!({"jsonrpc": "2.0", "id": 3, "method": "unknown/method"}));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 3);
+ assert_eq!(resp["error"]["code"], -32601);
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn all_expected_tools_registered() {
+ //! Verify that all tools from the reference implementation are registered.
+ //! Adding a new tool to the reference requires adding it to this list.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
+ let resp = d.recv();
+ let tools = resp["result"]["tools"].as_array().expect("tools array");
+ let names: std::collections::HashSet<&str> = tools.iter()
+ .filter_map(|t| t["name"].as_str())
+ .collect();
+
+ // Baseline roster that must be registered on every platform. (The old
+ // Windows mirror additionally listed type_text_chars + screenshot, which
+ // the Windows build does NOT register — a stale, never-run assertion.)
+ let expected: &[&str] = &[
+ "list_apps", "list_windows", "get_window_state", "launch_app",
+ "click", "double_click", "right_click", "type_text",
+ "press_key", "hotkey", "set_value", "scroll", "zoom",
+ "get_screen_size", "get_cursor_position",
+ "move_cursor", "set_agent_cursor_enabled", "set_agent_cursor_motion",
+ "get_agent_cursor_state", "check_permissions", "get_config", "set_config",
+ "get_accessibility_tree",
+ "start_recording", "stop_recording", "get_recording_state", "replay_trajectory",
+ "page",
+ ];
+ for name in expected {
+ assert!(names.contains(name), "Missing tool: {name} (registered: {names:?})");
+ }
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn tools_list_includes_per_tool_capabilities() {
+ //! Surface 4 contract (part 1): every entry in `tools/list` must
+ //! include a `capabilities` array of dotted-namespace tokens.
+ //! Downstream consumers (Hermes' cua_backend.py, Codex) dispatch
+ //! by capability instead of hardcoding tool names, so this is the
+ //! wire contract. Additive-only — existing keys must still be
+ //! present.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
+ let resp = d.recv();
+ let result = &resp["result"];
+
+ let tools = result["tools"].as_array().expect("tools array");
+ assert!(!tools.is_empty(), "tools array must be non-empty");
+
+ // Every entry has a `capabilities` array (may be empty for tools
+ // without a mapping in `default_capabilities_for`).
+ for tool in tools {
+ let name = tool["name"].as_str().unwrap_or("<no name>");
+ assert!(tool["capabilities"].is_array(),
+ "tool {name:?} missing capabilities array: {tool:?}");
+ }
+
+ // Specifically: `click` claims input.pointer.click + .left, and
+ // `type_text` claims input.keyboard.type — these are the contracts
+ // Hermes' cua_backend.py is expected to route by.
+ let click = tools.iter().find(|t| t["name"] == "click")
+ .expect("click tool must be registered");
+ let click_caps: Vec<&str> = click["capabilities"].as_array().unwrap()
+ .iter().filter_map(|v| v.as_str()).collect();
+ assert!(click_caps.contains(&"input.pointer.click"),
+ "click missing input.pointer.click: {click_caps:?}");
+ assert!(click_caps.contains(&"input.pointer.click.left"),
+ "click missing input.pointer.click.left: {click_caps:?}");
+
+ let type_text = tools.iter().find(|t| t["name"] == "type_text")
+ .expect("type_text tool must be registered");
+ let tt_caps: Vec<&str> = type_text["capabilities"].as_array().unwrap()
+ .iter().filter_map(|v| v.as_str()).collect();
+ assert!(tt_caps.contains(&"input.keyboard.type"),
+ "type_text missing input.keyboard.type: {tt_caps:?}");
+
+ // Regression guard for additive-only contract: every pre-existing
+ // top-level field on a tool entry must still be present.
+ for tool in tools {
+ let name = tool["name"].as_str().unwrap_or("<no name>");
+ assert!(tool["name"].is_string(), "{name}: name missing");
+ assert!(tool["description"].is_string(), "{name}: description missing");
+ assert!(tool["inputSchema"].is_object(), "{name}: inputSchema missing");
+ assert!(tool["annotations"].is_object(), "{name}: annotations missing");
+ }
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn tools_list_includes_capability_and_schema_versions() {
+ //! Surface 4 contract (part 2): top-level `tools/list` response
+ //! must include `capability_version` and `schema_version` so
+ //! downstream consumers (Hermes' cua_backend.py, Codex) can gate
+ //! strict-vs-tolerant capability matching by version. Both pinned
+ //! at "1" on first ship.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
+ let resp = d.recv();
+ let result = &resp["result"];
+
+ // Both version fields default to "1" on first ship — the surface
+ // is brand new, so there's no pre-existing contract to bump.
+ assert_eq!(result["capability_version"], "1",
+ "capability_version must default to \"1\" on first ship");
+ assert_eq!(result["schema_version"], "1",
+ "schema_version must default to \"1\" on first ship");
+
+ // Additive guard: tools array must still be there alongside the
+ // new envelope keys — old consumers that only read `tools` keep
+ // working.
+ assert!(result["tools"].is_array(),
+ "tools array must still be present alongside version envelope");
+ assert!(!result["tools"].as_array().unwrap().is_empty(),
+ "tools array must be non-empty");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn tools_call_unknown_tool() {
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": { "name": "nonexistent_tool", "arguments": {} }
+ }));
+ let resp = d.recv();
+ // Error should be in the content with isError=true, not a protocol error.
+ let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
+ assert!(is_error, "Expected isError=true for unknown tool");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn page_unknown_action_error() {
+ //! Verify the cross-platform `page` tool is registered and rejects an
+ //! unknown action with a meaningful error.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"page","arguments":{
+ "pid": 1,
+ "window_id": 0,
+ "action": "definitely_not_a_real_action"
+ }}
+ }));
+ let resp = d.recv();
+
+ assert!(
+ resp["result"]["isError"].as_bool().unwrap_or(false),
+ "expected isError=true for unknown action: {resp:?}"
+ );
+ let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
+ assert!(
+ text.to_ascii_lowercase().contains("unknown action"),
+ "error text should mention 'Unknown action': {text}"
+ );
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs
new file mode 100644
index 0000000000..e79ced7c48
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs
@@ -0,0 +1,576 @@
+//! Image / capture / recording tool tests.
+//!
+//! screenshot (full-display + JPEG), zoom + the zoom→from_zoom click round
+//! trip, the recording session lifecycle (start/stop + action.json), recording
+//! screenshot capture, the `record_video` flag, trajectory replay, click
+//! `debug_image_out`, and the `set_config` screenshot-resize pipeline. Split
+//! out of the old monolithic `mcp_protocol_test.rs`; mac/windows pairs merge
+//! and branch only where assertions differ.
+
+#![cfg(any(target_os = "macos", target_os = "windows"))]
+
+use cua_driver_testkit::RawDriver;
+
+#[test]
+#[cfg(target_os = "windows")]
+fn screenshot() {
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Full-display screenshot (no window_id).
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"screenshot","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "screenshot returned empty content");
+
+ // JPEG format.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"screenshot","arguments":{"format":"jpeg","quality":70}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from screenshot jpeg: {resp:?}");
+ if !resp["result"]["isError"].as_bool().unwrap_or(false) {
+ let content = resp["result"]["content"].as_array().expect("content array");
+ let has_jpeg = content.iter().any(|c| {
+ c["type"] == "image" && c["mimeType"].as_str().unwrap_or("") == "image/jpeg"
+ && c["data"].as_str().map(|s| s.len() > 10).unwrap_or(false)
+ });
+ assert!(has_jpeg, "Expected image/jpeg in screenshot response: {content:?}");
+ let sc = &resp["result"]["structuredContent"];
+ assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0);
+ assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0);
+ assert_eq!(sc["format"].as_str().unwrap_or(""), "jpeg");
+ }
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn screenshot_no_window_id() {
+ //! Call screenshot without window_id — should capture the full display and return image content.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"screenshot","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from screenshot: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "screenshot should return at least one content item");
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn screenshot_jpeg_format() {
+ //! Call screenshot with format=jpeg — should return a JPEG image.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"screenshot","arguments":{"format":"jpeg","quality":70}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from screenshot: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
+ if !is_error {
+ let has_jpeg = content.iter().any(|c| {
+ c["type"] == "image" && c["mimeType"].as_str().unwrap_or("") == "image/jpeg"
+ && c["data"].as_str().map(|s| s.len() > 10).unwrap_or(false)
+ });
+ assert!(has_jpeg, "Expected image/jpeg in screenshot response, got: {content:?}");
+ // Verify structured content has width and height.
+ let sc = &resp["result"]["structuredContent"];
+ assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive width in structuredContent");
+ assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive height in structuredContent");
+ assert_eq!(sc["format"].as_str().unwrap_or(""), "jpeg", "Expected format=jpeg");
+ }
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn zoom_tool_returns_jpeg() {
+ //! Call zoom on a visible window and verify the result contains a JPEG image.
+ //! Skips gracefully if no windows are visible (headless environment).
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // List on-screen windows only — off-screen/minimized windows may not be capturable.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
+ }));
+ let resp = d.recv();
+ let windows = resp["result"]["structuredContent"]["windows"]
+ .as_array()
+ .cloned()
+ .unwrap_or_default();
+
+ // Try windows until one captures successfully.
+ let mut found_jpeg = false;
+ let mut tried = 0usize;
+ for win in windows.iter().take(5) {
+ let Some(wid) = win["window_id"].as_u64() else { continue; };
+ tried += 1;
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id": 2 + tried as u64,"method":"tools/call",
+ "params":{"name":"zoom","arguments":{
+ "window_id": wid,
+ "x1": 0, "y1": 0, "x2": 100, "y2": 100
+ }}
+ }));
+ let r = d.recv();
+ if r["result"]["isError"].as_bool().unwrap_or(false) {
+ // This window might be off-screen or not capturable — try the next.
+ continue;
+ }
+ let content = r["result"]["content"].as_array().expect("content array");
+ found_jpeg = content.iter().any(|c| {
+ c["type"] == "image" && c["mimeType"].as_str().unwrap_or("") == "image/jpeg"
+ && c["data"].as_str().map(|s| s.len() > 10).unwrap_or(false)
+ });
+ if found_jpeg {
+ // Also verify structuredContent.
+ let sc = &r["result"]["structuredContent"];
+ assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive width: {sc:?}");
+ assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0, "Expected positive height: {sc:?}");
+ assert_eq!(sc["format"].as_str().unwrap_or(""), "jpeg", "Expected format=jpeg: {sc:?}");
+ break;
+ }
+ }
+
+ if tried == 0 {
+ eprintln!("No on-screen windows found — skipping zoom test");
+ return;
+ }
+ assert!(found_jpeg, "Expected at least one window to return a valid JPEG from zoom");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn zoom_from_zoom_click_round_trip() {
+ //! Verify the zoom → from_zoom click pipeline:
+ //! 1. click(from_zoom=true) with no zoom context returns the expected error.
+ //! 2. zoom() stores context; subsequent click(from_zoom=true) does NOT return
+ //! that error (translation succeeded, even if the click itself may fail).
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // List on-screen windows to find a target window and pid.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array().cloned().unwrap_or_default();
+ let Some(win) = wins.iter().find(|w| w["pid"].as_i64().is_some()) else {
+ eprintln!("No on-screen windows — skipping from_zoom test");
+ return;
+ };
+ let window_id = win["window_id"].as_u64().unwrap();
+ let pid = win["pid"].as_i64().unwrap();
+
+ // Step 1: click with from_zoom=true and NO prior zoom context — expect error.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"click","arguments":{"pid": pid, "window_id": window_id, "x":10.0,"y":10.0,"from_zoom":true}}
+ }));
+ let resp = d.recv();
+ let is_err = resp["result"]["isError"].as_bool().unwrap_or(false);
+ let err_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
+ assert!(is_err, "Expected error when from_zoom=true with no context, got: {resp:?}");
+ assert!(err_text.contains("no zoom context"), "Expected 'no zoom context' error, got: {err_text}");
+
+ // Step 2: call zoom on that window to store context.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"zoom","arguments":{"window_id": window_id, "pid": pid, "x1":0,"y1":0,"x2":50,"y2":50}}
+ }));
+ let resp = d.recv();
+ if resp["result"]["isError"].as_bool().unwrap_or(false) {
+ // Window may not be capturable (e.g. system UI) — skip.
+ eprintln!("zoom failed — skipping from_zoom click test");
+ return;
+ }
+ if !cfg!(target_os = "windows") {
+ // Verify zoom returned structured content with width/height.
+ let sc = &resp["result"]["structuredContent"];
+ assert!(sc["width"].as_u64().unwrap_or(0) > 0, "zoom should return positive width: {sc:?}");
+ }
+
+ // Step 3: click with from_zoom=true — should NOT return the "no zoom context" error.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"click","arguments":{"pid": pid, "window_id": window_id, "x":10.0,"y":10.0,"from_zoom":true}}
+ }));
+ let resp = d.recv();
+ let err_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
+ // Translation should succeed — if click fails it's for another reason (target app state), not missing context.
+ assert!(!err_text.contains("no zoom context"),
+ "After zoom(), from_zoom click should not say 'no zoom context', got: {err_text}");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn recording_session() {
+ //! Enable recording, invoke a non-read-only tool (recorded), disable, verify action.json written.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-rec-test-{}", std::process::id()));
+ let tmp_str = tmp_dir.to_string_lossy().to_string();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Enable recording.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"start_recording","arguments":{"output_dir":tmp_str,"record_video":false}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "start_recording failed: {resp:?}");
+ assert!(resp["result"]["structuredContent"]["enabled"].as_bool().unwrap_or(false));
+
+ // Invoke a non-read-only tool — should be recorded.
+ if cfg!(target_os = "windows") {
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"move_cursor","arguments":{"x":100.0,"y":200.0}}
+ }));
+ } else {
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"set_agent_cursor_enabled","arguments":{"enabled":false}}
+ }));
+ }
+ d.recv();
+
+ // get_recording_state — next_turn should advance after one recorded action.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"get_recording_state","arguments":{}}
+ }));
+ let resp = d.recv();
+ let next_turn = resp["result"]["structuredContent"]["next_turn"].as_u64().unwrap_or(0);
+ assert!(next_turn >= 2, "expected next_turn >= 2, got {next_turn}");
+
+ // Disable recording.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"stop_recording","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["structuredContent"]["enabled"].as_bool().unwrap_or(true));
+ drop(d);
+
+ // Small sync wait for the write to flush.
+ std::thread::sleep(std::time::Duration::from_millis(50));
+
+ // Verify turn-00001/action.json was written.
+ let action_path = tmp_dir.join("turn-00001").join("action.json");
+ assert!(action_path.exists(), "Expected {action_path:?} to exist");
+ let content: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(&action_path).unwrap()
+ ).unwrap();
+ if cfg!(target_os = "windows") {
+ assert_eq!(content["tool"].as_str().unwrap_or(""), "move_cursor");
+ assert_eq!(content["arguments"]["x"].as_f64().unwrap_or(0.0), 100.0);
+ } else {
+ assert_eq!(content["tool"].as_str().unwrap_or(""), "set_agent_cursor_enabled");
+ assert_eq!(content["arguments"]["enabled"].as_bool(), Some(false));
+ }
+
+ let _ = std::fs::remove_dir_all(&tmp_dir);
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn recording_screenshot_capture() {
+ //! When recording is active and a tool call includes a window_id, a screenshot.png
+ //! should appear alongside action.json in the turn folder.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-rec-ss-{}", std::process::id()));
+ let tmp_str = tmp_dir.to_string_lossy().to_string();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Find a capturable on-screen window.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array().cloned().unwrap_or_default();
+ // Prefer windows with non-empty titles (more likely capturable).
+ let win = wins.iter()
+ .find(|w| w["pid"].as_i64().is_some() && !w["title"].as_str().unwrap_or("").is_empty())
+ .or_else(|| wins.iter().find(|w| w["pid"].as_i64().is_some()));
+ let Some(win) = win else {
+ eprintln!("No on-screen windows — skipping recording screenshot test");
+ return;
+ };
+ let window_id = win["window_id"].as_u64().unwrap();
+ let pid = win["pid"].as_i64().unwrap();
+
+ // Enable recording.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"start_recording","arguments":{"output_dir":tmp_str,"record_video":false}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "start_recording failed: {resp:?}");
+
+ // Invoke click (non-read-only) with window_id + pid — recording should capture screenshot.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"click","arguments":{"pid": pid, "window_id": window_id, "x":0.0,"y":0.0}}
+ }));
+ d.recv(); // result may be error if coords are off-window — that's ok
+
+ // Disable recording.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"stop_recording","arguments":{}}
+ }));
+ d.recv();
+ drop(d);
+
+ std::thread::sleep(std::time::Duration::from_millis(100));
+
+ // action.json must exist.
+ let turn_dir = tmp_dir.join("turn-00001");
+ let action_path = turn_dir.join("action.json");
+ assert!(action_path.exists(), "Expected action.json at {action_path:?}");
+ let content: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(&action_path).unwrap()
+ ).unwrap();
+ assert_eq!(content["tool"].as_str().unwrap_or(""), "click");
+
+ // screenshot.png should exist if screencapture succeeded for this window.
+ let ss_path = turn_dir.join("screenshot.png");
+ if !ss_path.exists() {
+ eprintln!("screenshot.png not written for window {window_id} (may be uncapturable) — skipping PNG check");
+ } else {
+ let ss_bytes = std::fs::read(&ss_path).unwrap();
+ assert!(!ss_bytes.is_empty(), "screenshot.png should not be empty");
+ assert_eq!(&ss_bytes[..4], b"\x89PNG", "screenshot.png should be a valid PNG");
+
+ // click.png should also exist (click at 0,0 with crosshair marker).
+ let click_path = turn_dir.join("click.png");
+ if !click_path.exists() {
+ eprintln!("click.png not written — skipping click PNG check");
+ } else {
+ let click_bytes = std::fs::read(&click_path).unwrap();
+ assert!(!click_bytes.is_empty(), "click.png should not be empty");
+ assert_eq!(&click_bytes[..4], b"\x89PNG", "click.png should be a valid PNG");
+ }
+ }
+
+ let _ = std::fs::remove_dir_all(&tmp_dir);
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn start_recording_record_video_flag_accepted() {
+ //! `record_video` is the new on/off flag (replaces the old
+ //! `video_experimental`). Default is true. This test passes
+ //! `record_video: false` to bypass the ffmpeg dependency in CI;
+ //! we only verify that the schema accepts the call and the
+ //! session enters the enabled state. Full video lifecycle is
+ //! covered by the manual demo + the per-platform smoke when
+ //! ffmpeg is installed.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ let tmp_dir = std::env::temp_dir().join(format!("cua-driver-rs-recvid-{}", std::process::id()));
+ let tmp_str = tmp_dir.to_string_lossy().to_string();
+ std::fs::create_dir_all(&tmp_dir).unwrap();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"start_recording","arguments":{
+ "output_dir": tmp_str, "record_video": false
+ }}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Expected no JSON-RPC error, got: {resp:?}");
+ let is_err = resp["result"]["isError"].as_bool().unwrap_or(false);
+ assert!(!is_err, "start_recording with record_video:false should succeed: {resp:?}");
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"stop_recording","arguments":{}}
+ }));
+ d.recv();
+ drop(d);
+ let _ = std::fs::remove_dir_all(&tmp_dir);
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn replay_trajectory() {
+ //! Write a minimal trajectory (one move_cursor turn), replay it, verify succeeded=1.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ let traj_dir = std::env::temp_dir().join(format!("cua-driver-rs-replay-{}", std::process::id()));
+ let turn_dir = traj_dir.join("turn-00001");
+ std::fs::create_dir_all(&turn_dir).unwrap();
+ std::fs::write(
+ turn_dir.join("action.json"),
+ r#"{"tool":"move_cursor","arguments":{"x":50.0,"y":60.0}}"#,
+ ).unwrap();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"replay_trajectory","arguments":{
+ "dir": traj_dir.to_string_lossy(),
+ "delay_ms": 0
+ }}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "replay error: {resp:?}");
+ let sc = &resp["result"]["structuredContent"];
+ assert_eq!(sc["attempted"].as_u64().unwrap_or(0), 1, "expected attempted=1");
+ assert_eq!(sc["succeeded"].as_u64().unwrap_or(0), 1, "expected succeeded=1");
+ assert_eq!(sc["failed"].as_u64().unwrap_or(99), 0, "expected failed=0");
+
+ drop(d);
+ let _ = std::fs::remove_dir_all(&traj_dir);
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn click_debug_image_out() {
+ //! click with debug_image_out writes a PNG crosshair file and then proceeds.
+ //! Verifies the debug capture path works end-to-end.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ // Prefer a window with a non-empty title to avoid uncapturable overlay/system windows.
+ let Some(win) = wins.and_then(|a| a.iter().find(|w| {
+ w["pid"].as_i64().is_some() && !w["title"].as_str().unwrap_or("").is_empty()
+ }).or_else(|| a.iter().find(|w| w["pid"].as_i64().is_some()))) else {
+ eprintln!("No on-screen windows — skipping debug_image_out test");
+ return;
+ };
+ let pid = win["pid"].as_i64().unwrap();
+ let wid = win["window_id"].as_u64().unwrap();
+
+ let dbg_path = std::env::temp_dir().join(format!("cua-driver-rs-dbg-{}.png", std::process::id()));
+ let dbg_path_str = dbg_path.to_string_lossy().to_string();
+
+ // Click with debug_image_out — should write the PNG and then proceed.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"click","arguments":{
+ "pid": pid, "window_id": wid,
+ "x": 10.0, "y": 10.0,
+ "debug_image_out": dbg_path_str
+ }}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from click+debug_image_out: {resp:?}");
+
+ // The tool may return isError if screencapture can't capture this particular window
+ // (e.g., overlay windows, system windows). If that happens, skip the PNG check.
+ let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
+ if is_error {
+ let msg = resp["result"]["content"][0]["text"].as_str().unwrap_or("?");
+ eprintln!("debug_image_out screenshot failed for this window ({msg}) — skipping PNG check");
+ return;
+ }
+
+ // Verify the PNG was actually written.
+ assert!(dbg_path.exists(), "debug_image_out PNG was not written to {dbg_path:?}");
+ let meta = std::fs::metadata(&dbg_path).expect("metadata");
+ assert!(meta.len() > 100, "debug_image_out PNG is suspiciously small");
+
+ let _ = std::fs::remove_file(&dbg_path);
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn set_config_screenshot_resize() {
+ //! set_config(max_image_dimension=200) then screenshot — returned image must
+ //! have both dimensions ≤ 200. Verifies the ResizeRegistry pipeline end-to-end.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Set a tiny max_image_dimension so the full display screenshot will be resized.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"set_config","arguments":{"max_image_dimension":200}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "set_config failed: {resp:?}");
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "set_config returned error: {resp:?}");
+
+ // Capture full display; must be ≤ 200 px in both dimensions.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"screenshot","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "screenshot failed: {resp:?}");
+ // A screenshot can be unavailable in a non-interactive session (Session 0 on
+ // Windows, no display) — there's nothing to resize, so skip rather than fail.
+ // (The old Windows mirror lacked this skip and asserted unconditionally; it
+ // had never been run in such an environment.)
+ if resp["result"]["isError"].as_bool().unwrap_or(false) {
+ eprintln!("screenshot unavailable — skipping resize assertion: {resp:?}");
+ return;
+ }
+ let (Some(w), Some(h)) = (
+ resp["result"]["structuredContent"]["width"].as_u64(),
+ resp["result"]["structuredContent"]["height"].as_u64(),
+ ) else {
+ eprintln!("screenshot returned no dimensions — skipping resize assertion: {resp:?}");
+ return;
+ };
+ assert!(w <= 200, "screenshot width {w} should be ≤ 200 after max_image_dimension=200");
+ assert!(h <= 200, "screenshot height {h} should be ≤ 200 after max_image_dimension=200");
+
+ // get_config should reflect the updated value.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"get_config","arguments":{}}
+ }));
+ let resp = d.recv();
+ let dim = resp["result"]["structuredContent"]["max_image_dimension"].as_u64();
+ assert_eq!(dim, Some(200), "get_config should reflect max_image_dimension=200");
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
new file mode 100644
index 0000000000..48cf0057b3
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
@@ -0,0 +1,54 @@
+//! Pure `tools/list` schema-shape assertions.
+//!
+//! These never invoke a tool — they only inspect the advertised inputSchemas:
+//! that `type_text_chars` is hidden, the `list_windows.on_screen_only` knob, the
+//! `set_agent_cursor_motion` Bezier knobs, and the `set_config.capture_mode`
+//! enum.
+
+#![cfg(any(target_os = "macos", target_os = "windows"))]
+
+use cua_driver_testkit::RawDriver;
+
+#[test]
+fn tools_list_schema_shape() {
+ //! `type_text_chars` is an accepted-but-deprecated invoke alias that stays
+ //! HIDDEN from tools/list on every platform (the live Windows roster carries
+ //! no `type_text_chars` either — the old Windows mirror asserted it was
+ //! exposed, but that had never been run). The advertised schemas must still
+ //! carry their expected knobs.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}));
+ let list_resp = d.recv();
+ let tools = list_resp["result"]["tools"].as_array().expect("tools array");
+
+ // Deprecated alias is hidden from tools/list (accepted at invoke time only).
+ assert!(
+ tools.iter().all(|t| t["name"] != "type_text_chars"),
+ "type_text_chars should be hidden from tools/list"
+ );
+
+ // list_windows schema has on_screen_only.
+ let lw = tools.iter().find(|t| t["name"] == "list_windows")
+ .expect("list_windows not found in tools/list");
+ assert!(lw["inputSchema"]["properties"]["on_screen_only"].is_object(),
+ "list_windows schema missing on_screen_only: {:?}", lw["inputSchema"]["properties"]);
+
+ // set_agent_cursor_motion has the Bezier motion knobs.
+ let sacm = tools.iter().find(|t| t["name"] == "set_agent_cursor_motion")
+ .expect("set_agent_cursor_motion not found in tools/list");
+ let sacm_props = &sacm["inputSchema"]["properties"];
+ for knob in &["arc_size", "spring", "glide_duration_ms", "dwell_after_click_ms", "idle_hide_ms"] {
+ assert!(sacm_props[knob].is_object(),
+ "set_agent_cursor_motion schema missing {knob}: {sacm_props:?}");
+ }
+
+ // set_config has the capture_mode enum restriction.
+ let sc = tools.iter().find(|t| t["name"] == "set_config")
+ .expect("set_config not found in tools/list");
+ assert!(sc["inputSchema"]["properties"]["capture_mode"]["enum"].is_array(),
+ "set_config capture_mode should have enum: {:?}", sc["inputSchema"]["properties"]);
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs
new file mode 100644
index 0000000000..40f88e2be0
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs
@@ -0,0 +1,349 @@
+//! Multi-client / multi-cursor / overlay session tests.
+//!
+//! Concurrent driver processes, per-cursor instance state, cross-process
+//! isolation, the live overlay render loop, and the `set_agent_cursor_motion`
+//! Bezier knobs. Split out of the old monolithic `mcp_protocol_test.rs`;
+//! mac/windows pairs merge and branch only where assertions differ.
+//!
+//! Note: the originals asserted process liveness with `child.try_wait()`.
+//! `RawDriver` kills its child on drop and does not expose the handle, so the
+//! liveness check is replaced with an equivalent post-sleep request probe — a
+//! crashed process would EOF and panic inside `recv()`.
+
+#![cfg(any(target_os = "macos", target_os = "windows"))]
+
+use cua_driver_testkit::RawDriver;
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn concurrent_clients() {
+ //! Verify two concurrent cua-driver-rs processes both respond correctly.
+ //! This tests the "multiple cua-driver processes" scenario relevant to
+ //! the multi-cursor use case.
+ let mut drivers: Vec<RawDriver> = Vec::new();
+ for _ in 0..2 {
+ let Some(d) = RawDriver::spawn() else { return; };
+ drivers.push(d);
+ }
+
+ for (i, d) in drivers.iter_mut().enumerate() {
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": i + 1,
+ "method": "initialize",
+ "params": {}
+ }));
+
+ let resp = d.recv();
+ assert_eq!(resp["id"], (i + 1) as i64);
+ assert!(resp["result"]["protocolVersion"].is_string(),
+ "Process {i} failed to initialize");
+ }
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn concurrent_clients_with_cursor_moves() {
+ //! Two concurrent cua-driver processes, each driving their own cursor, should not crash.
+ //! This covers the multi-cursor use case where two Codex agents run simultaneously.
+ let mut drivers: Vec<RawDriver> = Vec::new();
+ for _ in 0..2 {
+ let Some(d) = RawDriver::spawn() else { return; };
+ drivers.push(d);
+ }
+
+ // Initialize all processes.
+ for (i, d) in drivers.iter_mut().enumerate() {
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 1, "Process {i} initialize failed");
+ }
+
+ // Each process moves its cursor to different positions.
+ let positions = vec![(100.0_f64, 200.0_f64), (500.0, 600.0)];
+ for ((i, d), (px, py)) in drivers.iter_mut().enumerate().zip(positions.iter()) {
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"move_cursor","arguments":{"x":px,"y":py}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
+ "Process {i} move_cursor failed: {resp:?}");
+ }
+
+ std::thread::sleep(std::time::Duration::from_millis(100));
+
+ // Each process must still be alive: probe with one more request (a crashed
+ // process would EOF and panic in recv()).
+ for (i, d) in drivers.iter_mut().enumerate() {
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":99,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 99, "cua-driver process {i} crashed during concurrent cursor test");
+ }
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn concurrent_multi_driver_isolation() {
+ //! Two cua-driver processes running simultaneously with different cursor IDs.
+ //! Verifies that concurrent sessions don't interfere — each tracks its own
+ //! cursor state and the overlay stays alive under concurrent load.
+ let Some(mut child_a) = RawDriver::spawn() else { return; };
+ let Some(mut child_b) = RawDriver::spawn() else { return; };
+
+ // Initialize both.
+ child_a.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ child_b.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ child_a.recv();
+ child_b.recv();
+
+ // Driver A: set_agent_cursor_enabled for cursor "alpha", Driver B for cursor "beta".
+ child_a.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"set_agent_cursor_enabled","arguments":{"cursor_id":"alpha","enabled":true}}
+ }));
+ child_b.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"set_agent_cursor_enabled","arguments":{"cursor_id":"beta","enabled":false}}
+ }));
+ let resp_a = child_a.recv();
+ let resp_b = child_b.recv();
+ assert!(resp_a["error"].is_null(), "Driver A set_agent_cursor_enabled failed: {resp_a:?}");
+ assert!(resp_b["error"].is_null(), "Driver B set_agent_cursor_enabled failed: {resp_b:?}");
+
+ // Each driver queries its own cursor state — should reflect what it set.
+ // get_agent_cursor_state is session-scoped, so pass the cursor_id each
+ // driver owns; the response carries { "cursors": [<that one>], "enabled" }.
+ child_a.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"alpha"}}
+ }));
+ child_b.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"beta"}}
+ }));
+ let state_a = child_a.recv();
+ let state_b = child_b.recv();
+ assert!(state_a["error"].is_null(), "Driver A get_agent_cursor_state failed: {state_a:?}");
+ assert!(state_b["error"].is_null(), "Driver B get_agent_cursor_state failed: {state_b:?}");
+
+ // cursors is an array of { config: { cursor_id, enabled, ... }, x, y }.
+ // Cursor alpha should be enabled (we set true), beta disabled (we set false).
+ // The state lives per process — processes don't share CursorRegistry.
+ let cursors_a = state_a["result"]["structuredContent"]["cursors"].as_array();
+ let cursors_b = state_b["result"]["structuredContent"]["cursors"].as_array();
+
+ let alpha_enabled = cursors_a.and_then(|arr| arr.iter().find(|c| {
+ c["config"]["cursor_id"].as_str() == Some("alpha")
+ })).and_then(|c| c["config"]["enabled"].as_bool());
+ let beta_enabled = cursors_b.and_then(|arr| arr.iter().find(|c| {
+ c["config"]["cursor_id"].as_str() == Some("beta")
+ })).and_then(|c| c["config"]["enabled"].as_bool());
+
+ assert_eq!(alpha_enabled, Some(true), "Cursor alpha should be enabled in driver A");
+ assert_eq!(beta_enabled, Some(false), "Cursor beta should be disabled in driver B");
+
+ // macOS additionally exercises move_cursor on both drivers to confirm
+ // neither crashes the other (the Windows variant stops after the state check).
+ if !cfg!(target_os = "windows") {
+ child_a.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"move_cursor","arguments":{"cursor_id":"alpha","x":100,"y":100}}
+ }));
+ child_b.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"move_cursor","arguments":{"cursor_id":"beta","x":200,"y":200}}
+ }));
+ let mv_a = child_a.recv();
+ let mv_b = child_b.recv();
+ assert!(mv_a["error"].is_null(), "Driver A move_cursor failed: {mv_a:?}");
+ assert!(mv_b["error"].is_null(), "Driver B move_cursor failed: {mv_b:?}");
+ }
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn multi_cursor_instance_state() {
+ //! Two cursor instances can be created with different IDs; each has independent state.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Move cursor "agent1" to (100, 200).
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"move_cursor","arguments":{"x":100.0,"y":200.0,"cursor_id":"agent1"}}
+ }));
+ let r2 = d.recv();
+ assert!(!r2["result"]["isError"].as_bool().unwrap_or(false));
+
+ // Move cursor "agent2" to (300, 400).
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"move_cursor","arguments":{"x":300.0,"y":400.0,"cursor_id":"agent2"}}
+ }));
+ let r3 = d.recv();
+ assert!(!r3["result"]["isError"].as_bool().unwrap_or(false));
+
+ // Configure cursor "agent1" with a custom color.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"set_agent_cursor_motion","arguments":{
+ "cursor_id":"agent1","cursor_color":"#FF0000","cursor_label":"AI-1"
+ }}
+ }));
+ let r4 = d.recv();
+ assert!(!r4["result"]["isError"].as_bool().unwrap_or(false));
+
+ // Hide cursor "agent2".
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"set_agent_cursor_enabled","arguments":{"enabled":false,"cursor_id":"agent2"}}
+ }));
+ let r5 = d.recv();
+ assert!(!r5["result"]["isError"].as_bool().unwrap_or(false));
+
+ // get_agent_cursor_state reports independent per-cursor state. macOS scopes
+ // the response to the resolved cursor_id (returns ONLY that cursor); Windows
+ // returns ALL cursors in one list. Either way, agent1 must read back enabled
+ // and agent2 disabled.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":6,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent1"}}
+ }));
+ let resp1 = d.recv();
+ assert!(!resp1["result"]["isError"].as_bool().unwrap_or(false));
+ let cursors1 = resp1["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
+ if cfg!(target_os = "windows") {
+ // Windows returns the full cursor list; find agent1 within it.
+ let a1 = cursors1.iter()
+ .find(|c| c["config"]["cursor_id"].as_str() == Some("agent1"))
+ .expect("agent1 in returned cursor list");
+ assert_eq!(a1["config"]["enabled"].as_bool(), Some(true), "agent1 was never disabled");
+ } else {
+ assert_eq!(cursors1.len(), 1, "agent1 query must return exactly its own cursor, got: {cursors1:?}");
+ assert_eq!(cursors1[0]["config"]["cursor_id"].as_str(), Some("agent1"));
+ assert_eq!(resp1["result"]["structuredContent"]["enabled"].as_bool(), Some(true),
+ "agent1 was never disabled");
+ }
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":7,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent2"}}
+ }));
+ let resp2 = d.recv();
+ assert!(!resp2["result"]["isError"].as_bool().unwrap_or(false));
+ let cursors2 = resp2["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
+ if cfg!(target_os = "windows") {
+ // Windows returns the full cursor list; find agent2 within it.
+ let a2 = cursors2.iter()
+ .find(|c| c["config"]["cursor_id"].as_str() == Some("agent2"))
+ .expect("agent2 in returned cursor list");
+ assert_eq!(a2["config"]["enabled"].as_bool(), Some(false), "agent2 was hidden");
+ } else {
+ assert_eq!(cursors2.len(), 1, "agent2 query must return exactly its own cursor, got: {cursors2:?}");
+ assert_eq!(cursors2[0]["config"]["cursor_id"].as_str(), Some("agent2"));
+ assert_eq!(resp2["result"]["structuredContent"]["enabled"].as_bool(), Some(false),
+ "agent2 was hidden");
+ }
+
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ // Process must still be alive: probe with one more request (a crashed
+ // process would EOF and panic in recv()).
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":99,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent1"}}
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 99, "cua-driver crashed during multi-cursor test");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn overlay_move_cursor_stays_alive() {
+ //! Verify that calling move_cursor with the overlay enabled does not crash the process.
+ //! The overlay renders to a transparent NSWindow on the main thread; the MCP server
+ //! sends commands via the global channel. Any crash in the render thread (e.g. wrong
+ //! GCD queue pointer, bad CGImage argument types) would cause this test to fail with
+ //! an early EOF or a non-zero exit code.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Call move_cursor several times to drive the overlay render loop.
+ for (id, (x, y)) in [(2u64, (100.0_f64, 200.0_f64)), (3, (400.0, 300.0)), (4, (800.0, 600.0))] {
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": id,
+ "method": "tools/call",
+ "params": { "name": "move_cursor", "arguments": { "x": x, "y": y } }
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["id"], id);
+ // Should succeed (isError absent or false).
+ let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
+ assert!(!is_error, "move_cursor failed: {:?}", resp);
+ }
+
+ // Also call get_agent_cursor_state — should report the last position.
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 5,
+ "method": "tools/call",
+ "params": { "name": "get_agent_cursor_state", "arguments": {} }
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 5);
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
+
+ // Give the render loop a chance to tick (two frames ≈ 33 ms).
+ std::thread::sleep(std::time::Duration::from_millis(100));
+
+ // Process must still be alive: probe with one more request (a crashed
+ // process would EOF and panic in recv()).
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 99,
+ "method": "tools/call",
+ "params": { "name": "get_agent_cursor_state", "arguments": {} }
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 99, "cua-driver crashed during overlay move_cursor test");
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn set_agent_cursor_motion_bezier_knobs() {
+ //! set_agent_cursor_motion with Bezier/timing knobs — verifies schema accepts them
+ //! and returns a non-error response with the updated values in the response text.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Set Bezier motion knobs including integer-encoded numbers (common from MCP clients).
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"set_agent_cursor_motion","arguments":{
+ "cursor_id": "agent1",
+ "arc_size": 0.4,
+ "spring": 0.85,
+ "glide_duration_ms": 500,
+ "dwell_after_click_ms": 200,
+ "idle_hide_ms": 5000
+ }}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from set_agent_cursor_motion: {resp:?}");
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
+ "set_agent_cursor_motion returned isError: {resp:?}");
+ // Response text should mention the new glide duration.
+ let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
+ assert!(text.contains("500") || text.contains("motion"),
+ "Expected motion summary in response, got: {text}");
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs
new file mode 100644
index 0000000000..8d8b33b19a
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs
@@ -0,0 +1,746 @@
+//! Per-tool `tools/call` integration tests.
+//!
+//! Drives the real tools end-to-end over JSON-RPC: list_apps, get_config /
+//! check_permissions, the accessibility tree, list_windows, screen size /
+//! cursor position, window-state AX mode, scroll, type_text, hotkey,
+//! press_key, click / double_click / right_click, and set_value. Split out
+//! of the old monolithic `mcp_protocol_test.rs`; mac/windows pairs merge into
+//! one fn and branch only where the platforms differ (list_apps `apps` vs
+//! `processes`, get_config platform string, check_permissions keys, type_text
+//! target app, hotkey modifier, etc.).
+
+#![cfg(any(target_os = "macos", target_os = "windows"))]
+
+use cua_driver_testkit::RawDriver;
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn tools_call_list_apps() {
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ // Initialize.
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Call list_apps.
+ d.send(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": { "name": "list_apps", "arguments": {} }
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["id"], 2);
+ assert!(resp["result"]["content"].is_array());
+ if cfg!(target_os = "windows") {
+ let text = resp["result"]["content"][0]["text"].as_str().unwrap();
+ assert!(text.contains("Found"), "Expected process list text, got: {}", text);
+ // Windows backend returns "processes" key.
+ assert!(resp["result"]["structuredContent"]["processes"].is_array(),
+ "Expected processes array: {:?}", resp["result"]["structuredContent"]);
+ } else {
+ let content = &resp["result"]["content"][0];
+ assert_eq!(content["type"], "text");
+ let text = content["text"].as_str().unwrap();
+ // Should contain some running apps.
+ assert!(text.contains("Found"), "Expected app list text, got: {}", text);
+ }
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn get_config_and_check_permissions() {
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"get_config","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
+ if cfg!(target_os = "windows") {
+ assert_eq!(resp["result"]["structuredContent"]["platform"], "windows");
+ } else {
+ assert_eq!(resp["result"]["structuredContent"]["platform"], "macos");
+ }
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"check_permissions","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
+ if cfg!(target_os = "windows") {
+ let sc = &resp["result"]["structuredContent"];
+ // Windows returns elevated, uia, post_message booleans.
+ assert!(sc["uia"].as_bool().unwrap_or(false), "uia should be true: {sc:?}");
+ assert!(sc["post_message"].as_bool().unwrap_or(false), "post_message should be true: {sc:?}");
+ assert!(sc["elevated"].is_boolean(), "elevated should be a boolean: {sc:?}");
+ } else {
+ // Returns structured content with accessibility and screen_recording booleans.
+ assert!(resp["result"]["structuredContent"]["accessibility"].is_boolean());
+ }
+
+ // set_config — change capture_mode to "ax" and verify get_config reflects the new value.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"set_config","arguments":{"capture_mode": "ax", "max_image_dimension": 1920}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from set_config: {resp:?}");
+ if !cfg!(target_os = "windows") {
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "set_config returned empty content");
+ }
+
+ // get_config should now reflect the updated values.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"get_config","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert_eq!(resp["result"]["structuredContent"]["capture_mode"], "ax",
+ "get_config should reflect set_config change");
+ assert_eq!(resp["result"]["structuredContent"]["max_image_dimension"], 1920,
+ "get_config should reflect max_image_dimension change");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn get_accessibility_tree() {
+ //! get_accessibility_tree returns a lightweight process+window snapshot.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"get_accessibility_tree","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
+ "get_accessibility_tree returned error: {resp:?}");
+
+ let sc = &resp["result"]["structuredContent"];
+ if cfg!(target_os = "windows") {
+ // Windows backend returns both "processes" and "windows" keys.
+ assert!(sc["processes"].is_array(), "Expected processes array: {sc:?}");
+ assert!(sc["windows"].is_array(), "Expected windows array: {sc:?}");
+ } else {
+ // macOS backend returns "apps"; Linux returns "processes". Either key is valid.
+ let has_apps = sc["apps"].is_array() || sc["processes"].is_array();
+ assert!(has_apps, "Expected apps or processes array in structured content, got: {sc:?}");
+ }
+
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "Expected non-empty content");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn list_windows_structured_content() {
+ //! Verify list_windows returns structuredContent.windows array with expected fields.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error: {resp:?}");
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
+ "list_windows returned error: {resp:?}");
+
+ let sc = &resp["result"]["structuredContent"];
+ assert!(sc["windows"].is_array(), "Expected windows array in structuredContent: {sc:?}");
+
+ // If there are any windows, verify the expected fields are present.
+ if let Some(wins) = sc["windows"].as_array() {
+ if let Some(w) = wins.first() {
+ assert!(w["window_id"].is_number(), "window_id missing from window: {w:?}");
+ assert!(w["pid"].is_number(), "pid missing from window: {w:?}");
+ }
+ }
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn get_screen_size_and_cursor_position() {
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // get_screen_size
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"get_screen_size","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_screen_size failed: {resp:?}");
+ let sc = &resp["result"]["structuredContent"];
+ assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0, "width should be positive");
+ assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0, "height should be positive");
+
+ // get_cursor_position
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"get_cursor_position","arguments":{}}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_cursor_position failed: {resp:?}");
+ // x and y may be 0,0 or any value — just verify the keys exist and are numbers.
+ assert!(resp["result"]["structuredContent"]["x"].is_number(), "x should be a number");
+ assert!(resp["result"]["structuredContent"]["y"].is_number(), "y should be a number");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn get_window_state_ax_mode() {
+ //! get_window_state with capture_mode="ax" should return a tree but no screenshot image.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{}}
+ }));
+ let resp = d.recv();
+ let windows = resp["result"]["structuredContent"]["windows"].as_array();
+ let first_win = windows.and_then(|a| a.iter().find(|w| {
+ w["pid"].as_i64().is_some() && w["window_id"].as_u64().is_some()
+ }));
+
+ let Some(win) = first_win else {
+ eprintln!("No windows found — skipping get_window_state ax test");
+ return;
+ };
+ let pid = win["pid"].as_i64().unwrap();
+ let wid = win["window_id"].as_u64().unwrap();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"get_window_state","arguments":{
+ "pid": pid, "window_id": wid, "capture_mode": "ax"
+ }}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from get_window_state: {resp:?}");
+
+ let content = resp["result"]["content"].as_array().expect("content array");
+ // ax mode must NOT return an image content item.
+ let has_image = content.iter().any(|c| c["type"] == "image");
+ assert!(!has_image, "capture_mode=ax should not return an image, got: {content:?}");
+ assert!(!content.is_empty(), "Expected at least one content item");
+
+ // structuredContent must include window_id, pid, element_count.
+ let sc = &resp["result"]["structuredContent"];
+ assert_eq!(sc["window_id"].as_u64().unwrap_or(0), wid, "structuredContent.window_id mismatch");
+ assert_eq!(sc["pid"].as_i64().unwrap_or(0), pid, "structuredContent.pid mismatch");
+ assert!(sc["element_count"].is_number(), "expected element_count in structuredContent: {sc:?}");
+ if !cfg!(target_os = "windows") {
+ // ax mode — screenshot_width should NOT be present.
+ assert!(sc["screenshot_width"].is_null(), "ax mode should not have screenshot_width: {sc:?}");
+ }
+
+ // Also test vision mode: screenshot_width/height should be present.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"get_window_state","arguments":{
+ "pid": pid, "window_id": wid, "capture_mode": "vision"
+ }}
+ }));
+ let vision_resp = d.recv();
+ assert!(vision_resp["error"].is_null(), "Protocol error from vision get_window_state: {vision_resp:?}");
+ if !vision_resp["result"]["isError"].as_bool().unwrap_or(false) {
+ let vsc = &vision_resp["result"]["structuredContent"];
+ assert!(vsc["screenshot_width"].as_f64().unwrap_or(0.0) > 0.0,
+ "vision mode should have screenshot_width: {vsc:?}");
+ if !cfg!(target_os = "windows") {
+ assert!(vsc["screenshot_height"].as_f64().unwrap_or(0.0) > 0.0,
+ "vision mode should have screenshot_height: {vsc:?}");
+ }
+ }
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn scroll_tool() {
+ //! scroll with direction=down, by=line, amount=1 against the first available window.
+ //! Verifies the tool is accepted and returns content, not a protocol error.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Find a pid with a window.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_apps","arguments":{}}
+ }));
+ let resp = d.recv();
+ let pid = if cfg!(target_os = "windows") {
+ // Windows list_apps returns "processes".
+ let procs = resp["result"]["structuredContent"]["processes"].as_array();
+ let Some(proc_) = procs.and_then(|a| a.iter().find(|p| p["pid"].as_i64().is_some())) else {
+ eprintln!("No processes found — skipping scroll test");
+ return;
+ };
+ proc_["pid"].as_i64().unwrap()
+ } else {
+ let apps = resp["result"]["structuredContent"]["apps"].as_array();
+ let Some(app) = apps.and_then(|a| a.iter().find(|a| a["pid"].as_i64().is_some())) else {
+ eprintln!("No apps found — skipping scroll test");
+ return;
+ };
+ app["pid"].as_i64().unwrap()
+ };
+
+ // scroll with minimal parameters — window_id is auto-resolved from pid.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"scroll","arguments":{"pid": pid, "direction": "down", "amount": 1}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from scroll: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "scroll returned empty content");
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn type_text_tool() {
+ //! Opens TextEdit (or reuses it if already running) and types a short string via type_text.
+ //! Skips gracefully if TextEdit is not available or has no window.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Launch TextEdit (no-op if already running).
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"launch_app","arguments":{"name":"TextEdit"}}
+ }));
+ d.recv();
+ std::thread::sleep(std::time::Duration::from_millis(800));
+
+ // Find TextEdit's pid.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"list_apps","arguments":{}}
+ }));
+ let resp = d.recv();
+ let apps = resp["result"]["structuredContent"]["apps"].as_array();
+ let Some(app) = apps.and_then(|a| {
+ a.iter().find(|a| {
+ a["name"].as_str().map(|n| n.eq_ignore_ascii_case("textedit")).unwrap_or(false)
+ })
+ }) else {
+ eprintln!("TextEdit not found — skipping type_text test");
+ return;
+ };
+ let pid = app["pid"].as_i64().unwrap();
+
+ // Find TextEdit's first on-screen window.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"pid": pid, "on_screen_only": true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(win) = wins.and_then(|a| a.first()) else {
+ eprintln!("TextEdit has no on-screen windows — skipping type_text test");
+ return;
+ };
+ let wid = win["window_id"].as_u64().unwrap();
+
+ // type_text into TextEdit's window.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"type_text","arguments":{"pid": pid, "window_id": wid, "text": "cua-test"}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from type_text: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "type_text returned empty content");
+}
+
+#[test]
+#[cfg(target_os = "windows")]
+fn type_text_notepad() {
+ //! Launch Notepad, type a short string via type_text. Skips if Notepad unavailable.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Launch Notepad.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"launch_app","arguments":{"name":"notepad.exe"}}
+ }));
+ d.recv();
+ std::thread::sleep(std::time::Duration::from_millis(1000));
+
+ // Find Notepad in running processes.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"list_apps","arguments":{}}
+ }));
+ let resp = d.recv();
+ let procs = resp["result"]["structuredContent"]["processes"].as_array();
+ let Some(proc_) = procs.and_then(|a| {
+ a.iter().find(|p| {
+ p["name"].as_str().map(|n| n.to_lowercase().contains("notepad")).unwrap_or(false)
+ })
+ }) else {
+ eprintln!("Notepad not found — skipping type_text test");
+ return;
+ };
+ let pid = proc_["pid"].as_i64().unwrap();
+
+ // Find Notepad's window.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"pid":pid,"on_screen_only":true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(win) = wins.and_then(|a| a.first()) else {
+ eprintln!("Notepad has no on-screen windows — skipping type_text test");
+ return;
+ };
+ let wid = win["window_id"].as_u64().unwrap();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"type_text","arguments":{"pid":pid,"window_id":wid,"text":"cua-test"}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from type_text: {resp:?}");
+ assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn type_text_chars_tool() {
+ //! Verify type_text_chars with delay_ms is accepted without error (dry-run via TextEdit or
+ //! a pid that accepts WM_CHAR). We just verify the tool responds with a non-error.
+ //! Skips gracefully if no visible TextEdit window.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // list_apps to find a target (e.g. TextEdit).
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_apps","arguments":{}}
+ }));
+ let resp = d.recv();
+ let apps = resp["result"]["structuredContent"]["apps"].as_array();
+ let textedit_pid = apps.and_then(|arr| {
+ arr.iter().find(|a| a["name"].as_str().unwrap_or("").contains("TextEdit"))
+ .and_then(|a| a["pid"].as_i64())
+ });
+
+ let Some(pid) = textedit_pid else {
+ eprintln!("TextEdit not running — skipping type_text_chars test");
+ return;
+ };
+
+ // type_text_chars with delay_ms=5 — just verify the tool invocation is accepted.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"type_text_chars","arguments":{
+ "pid": pid, "text": "hi", "delay_ms": 5
+ }}
+ }));
+ let resp = d.recv();
+ assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),
+ "type_text_chars returned error: {resp:?}");
+ let msg = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
+ assert!(
+ msg.contains("Typed") || msg.contains("Inserted"),
+ "Unexpected message: {msg}"
+ );
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn hotkey_keys_array() {
+ //! Verify hotkey accepts a keys array without a protocol error.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{}}
+ }));
+ let resp = d.recv();
+ let windows = resp["result"]["structuredContent"]["windows"].as_array();
+ let first_win = windows.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some()));
+
+ let Some(win) = first_win else {
+ eprintln!("No windows found — skipping hotkey keys array test");
+ return;
+ };
+ let pid = win["pid"].as_i64().unwrap();
+ let wid = win["window_id"].as_u64().unwrap();
+
+ // keys array should be parsed and the tool invoked; result may succeed or fail depending
+ // on whether the target app accepts the hotkey, but there must be no protocol error.
+ // Windows uses ["ctrl","a"]; macOS uses ["cmd","a"].
+ let keys = if cfg!(target_os = "windows") {
+ serde_json::json!(["ctrl", "a"])
+ } else {
+ serde_json::json!(["cmd", "a"])
+ };
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"hotkey","arguments":{
+ "pid": pid, "window_id": wid, "keys": keys
+ }}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from hotkey: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "hotkey should return content");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn press_key_harmless() {
+ //! press_key with a harmless key (F24 — virtually no app responds to it) sent to the
+ //! first available window. Just verifies the tool doesn't return a protocol error.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Find a window to target.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
+ eprintln!("No windows found — skipping press_key test");
+ return;
+ };
+ let pid = win["pid"].as_i64().unwrap();
+ let wid = win["window_id"].as_u64().unwrap();
+
+ // F24 is a function key that virtually no app binds — safe to send.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"press_key","arguments":{"pid": pid, "window_id": wid, "key": "F24"}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from press_key: {resp:?}");
+ // Tool may succeed or return an app error, but must NOT be a protocol-level error.
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "press_key returned empty content");
+}
+
+#[test]
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+fn click_pixel_path() {
+ //! click at window-local (5, 5) — title bar area, safe to click without disrupting UI.
+ //! Verifies the pixel-coordinate path for click works without a protocol error.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Find an on-screen window.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
+ eprintln!("No on-screen windows — skipping click pixel path test");
+ return;
+ };
+ let pid = win["pid"].as_i64().unwrap();
+ let wid = win["window_id"].as_u64().unwrap();
+
+ // Click at (5, 5) in window-local coords — title bar, harmless.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from click: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "click returned empty content");
+}
+
+#[test]
+#[cfg(target_os = "windows")]
+fn double_click_and_right_click() {
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"on_screen_only":true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
+ eprintln!("No on-screen windows — skipping double/right click test");
+ return;
+ };
+ let pid = win["pid"].as_i64().unwrap();
+ let wid = win["window_id"].as_u64().unwrap();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"double_click","arguments":{"pid":pid,"window_id":wid,"x":5.0,"y":5.0}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from double_click: {resp:?}");
+ assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"right_click","arguments":{"pid":pid,"window_id":wid,"x":5.0,"y":5.0}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from right_click: {resp:?}");
+ assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn double_click_and_right_click_pixel_path() {
+ //! double_click and right_click at title-bar coords — verifies both tools accept pixel path.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"on_screen_only": true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(win) = wins.and_then(|a| a.iter().find(|w| w["pid"].as_i64().is_some())) else {
+ eprintln!("No on-screen windows — skipping double/right click test");
+ return;
+ };
+ let pid = win["pid"].as_i64().unwrap();
+ let wid = win["window_id"].as_u64().unwrap();
+
+ // double_click at safe coords.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"double_click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from double_click: {resp:?}");
+ assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true),
+ "double_click returned empty content");
+
+ // right_click at same coords.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"right_click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from right_click: {resp:?}");
+ assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true),
+ "right_click returned empty content");
+}
+
+#[test]
+#[cfg(target_os = "macos")]
+fn set_value_via_element_index() {
+ //! get_window_state on TextEdit → find a text-area element → set_value on it.
+ //! Skips gracefully if TextEdit is not available.
+ let Some(mut d) = RawDriver::spawn() else { return; };
+
+ d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
+ d.recv();
+
+ // Ensure TextEdit is running.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":2,"method":"tools/call",
+ "params":{"name":"launch_app","arguments":{"name":"TextEdit"}}
+ }));
+ d.recv();
+ std::thread::sleep(std::time::Duration::from_millis(800));
+
+ // Find TextEdit.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"list_apps","arguments":{}}
+ }));
+ let resp = d.recv();
+ let apps = resp["result"]["structuredContent"]["apps"].as_array();
+ let Some(app) = apps.and_then(|a| {
+ a.iter().find(|a| a["name"].as_str()
+ .map(|n| n.eq_ignore_ascii_case("textedit")).unwrap_or(false))
+ }) else {
+ eprintln!("TextEdit not found — skipping set_value test");
+ return;
+ };
+ let pid = app["pid"].as_i64().unwrap();
+
+ // Get first window.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"pid": pid, "on_screen_only": true}}
+ }));
+ let resp = d.recv();
+ let wins = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(win) = wins.and_then(|a| a.first()) else {
+ eprintln!("TextEdit has no on-screen windows — skipping set_value test");
+ return;
+ };
+ let wid = win["window_id"].as_u64().unwrap();
+
+ // Walk AX tree to get element_count — we'll target element_index 0.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":5,"method":"tools/call",
+ "params":{"name":"get_window_state","arguments":{"pid": pid, "window_id": wid, "capture_mode": "ax"}}
+ }));
+ let resp = d.recv();
+ assert!(resp["error"].is_null(), "Protocol error from get_window_state: {resp:?}");
+ let element_count = resp["result"]["structuredContent"]["element_count"].as_u64().unwrap_or(0);
+ if element_count == 0 {
+ eprintln!("No AX elements — skipping set_value test");
+ return;
+ }
+
+ // set_value on element 0 — this is the document / text area in a new TextEdit document.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":6,"method":"tools/call",
+ "params":{"name":"set_value","arguments":{"pid": pid, "window_id": wid, "element_index": 0, "value": "cua-test-value"}}
+ }));
+ let resp = d.recv();
+ // set_value may fail if element 0 is not settable; accept tool-level errors but not protocol errors.
+ assert!(resp["error"].is_null(), "Protocol error from set_value: {resp:?}");
+ let content = resp["result"]["content"].as_array().expect("content array");
+ assert!(!content.is_empty(), "set_value returned empty content");
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/transport_config_persistence_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/transport_config_persistence_test.rs
new file mode 100644
index 0000000000..0286758b94
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/transport_config_persistence_test.rs
@@ -0,0 +1,81 @@
+//! Transport axis: `set_config` persistence across the CLI vs MCP transports.
+//!
+//! This is the one behavior that only shows up when a test covers BOTH
+//! transports, so it lives on the shared testkit `Driver` abstraction:
+//!
+//! - **CLI** (`CliDriver`) is stateless — each `cua-driver call` is its own
+//! process. For a `set_config` to be visible to the *next* invocation it
+//! must persist to **disk**. #2034 made that true on Windows + Linux (macOS
+//! already did); this test guards against a regression.
+//! - **MCP** (`McpDriver`) is one long-lived connection — a `set_config` is
+//! visible to later calls on the SAME driver within the session.
+//!
+//! Both tests are `#[ignore]`: they mutate the real on-disk config, so they
+//! save the prior `capture_scope` and restore it. Run explicitly:
+//! cargo test -p cua-driver --test transport_config_persistence_test -- --ignored --nocapture
+
+use cua_driver_testkit::{CliDriver, Driver, McpDriver};
+
+const KEY: &str = "capture_scope";
+
+fn config_scope(structured: &serde_json::Value) -> Option<String> {
+ structured[KEY].as_str().map(str::to_owned)
+}
+
+/// CLI: a `set_config` in one process is observed by a *separate* `get_config`
+/// process — i.e. it persisted to disk (#2034). The two `cli.call(...)`s below
+/// are independent `cua-driver call` invocations.
+#[test]
+#[ignore]
+fn cli_set_config_persists_to_disk_across_invocations() {
+ let mut cli = CliDriver::new();
+ if !cli.available() {
+ eprintln!("[transport] driver binary not built — skipping");
+ return;
+ }
+
+ // Save the current value so we can restore it.
+ let original = config_scope(cli.call("get_config", serde_json::json!({})).structured());
+
+ let set = cli.call("set_config", serde_json::json!({ "key": KEY, "value": "desktop" }));
+ assert!(!set.is_error(), "CLI set_config errored: {}", set.text());
+
+ // A fresh process must see the persisted value.
+ let after = cli.call("get_config", serde_json::json!({}));
+ assert_eq!(
+ config_scope(after.structured()).as_deref(),
+ Some("desktop"),
+ "CLI set_config did NOT persist to disk across invocations (#2034 regression): {}",
+ after.text()
+ );
+
+ // Restore.
+ if let Some(orig) = original {
+ let _ = cli.call("set_config", serde_json::json!({ "key": KEY, "value": orig }));
+ }
+}
+
+/// MCP: a `set_config` is visible to a later call on the SAME long-lived driver
+/// (session scope). Restores the prior value before dropping the connection.
+#[test]
+#[ignore]
+fn mcp_set_config_visible_within_session() {
+ let Some(mut driver) = McpDriver::spawn() else { return };
+
+ let original = config_scope(driver.call("get_config", serde_json::json!({})).structured());
+
+ let set = driver.call("set_config", serde_json::json!({ "key": KEY, "value": "desktop" }));
+ assert!(!set.is_error(), "MCP set_config errored: {}", set.text());
+
+ let after = driver.call("get_config", serde_json::json!({}));
+ assert_eq!(
+ config_scope(after.structured()).as_deref(),
+ Some("desktop"),
+ "MCP set_config not visible within the same session: {}",
+ after.text()
+ );
+
+ if let Some(orig) = original {
+ let _ = driver.call("set_config", serde_json::json!({ "key": KEY, "value": orig }));
+ }
+}
diff --git a/libs/cua-driver/test-harness/TEST_HARNESS_STRUCTURE.md b/libs/cua-driver/test-harness/TEST_HARNESS_STRUCTURE.md
index 45d50988a4..bed697c1f7 100644
--- a/libs/cua-driver/test-harness/TEST_HARNESS_STRUCTURE.md
+++ b/libs/cua-driver/test-harness/TEST_HARNESS_STRUCTURE.md
@@ -36,13 +36,16 @@ libs/cua-driver/test-harness/
└── README.md
libs/cua-driver/rust/crates/cua-driver/tests/ ◀── the CONSUMERS (Rust integration tests)
+│ (all build on the cua-driver-testkit crate; named by 4-family taxonomy —
+│ harness_ / modality_ / protocol_ / guard_. See TEST_SUITE.md.)
├── harness_wpf_test.rs (Windows)
├── harness_winui3_test.rs (Windows)
-├── harness_web_windows_test.rs (Windows — WebView2 + Electron via CDP)
-├── harness_bg_modality_test.rs (Windows — focus-steal sentinel + capture_mode)
-├── harness_lo_vcl_test.rs (Windows — LibreOffice VCL/SAL via MSAA)
+├── harness_web_test.rs (Windows — WebView2 + Electron via CDP)
+├── harness_libreoffice_test.rs (Windows — LibreOffice VCL/SAL via MSAA)
├── harness_appkit_test.rs (macOS)
└── harness_swiftui_test.rs (macOS)
+ (the focus-steal sentinel + capture_mode tests now live under
+ modality_background_test.rs — see TEST_SUITE.md for the full inventory)
```
## How the pieces connect
@@ -92,14 +95,14 @@ The loop per test: **launch the built app → read `scenarios.json` for the expe
| App (`apps/…`) | OS | `scenarios.json` key | What it exercises | Rust test(s) |
|---|---|---|---|---|
-| `windows/wpf` | Windows | `wpf` | UIA Invoke, PostMessage type, right/double-click, scroll, modal MessageBox, owned + layered popups, native child HWNDs, accelerators | `harness_wpf_test`, `harness_bg_modality_test` |
+| `windows/wpf` | Windows | `wpf` | UIA Invoke, PostMessage type, right/double-click, scroll, modal MessageBox, owned + layered popups, native child HWNDs, accelerators | `harness_wpf_test`, `modality_background_test` |
| `windows/winui3` | Windows | `winui3` | UIA ValuePattern text, CommandBarFlyout, XAML Popup primitive | `harness_winui3_test` |
-| `windows/webview2` | Windows | `webview` | Chromium DevTools Protocol (CDP) `page` tool over the shared web page | `harness_web_windows_test` |
-| `cross-platform/electron` | Win / macOS / Linux | `electron` | CDP `page` tool over the shared web page | `harness_web_windows_test` (+ macOS) |
+| `windows/webview2` | Windows | `webview` | Chromium DevTools Protocol (CDP) `page` tool over the shared web page | `harness_web_test` |
+| `cross-platform/electron` | Win / macOS / Linux | `electron` | CDP `page` tool over the shared web page | `harness_web_test` (+ macOS) |
| `macos/appkit` | macOS | `appkit` | AX tree, NSButton AXPress, NSTextField, NSScrollView, NSMenu | `harness_appkit_test` |
| `macos/swiftui` | macOS | `swiftui` | AX tree, SwiftUI `.popover()` (separate AXWindow) | `harness_swiftui_test` |
-| *(LibreOffice — not a harness app)* | Windows | — | VCL/SAL SplitButton, modal dialogs, color picker via MSAA fallback | `harness_lo_vcl_test` |
-| *(WPF + focus sentinel)* | Windows | `wpf` | background-modality / no-focus-steal sentinel + `capture_mode` (ax / vision / som) | `harness_bg_modality_test` |
+| *(LibreOffice — not a harness app)* | Windows | — | VCL/SAL SplitButton, modal dialogs, color picker via MSAA fallback | `harness_libreoffice_test` |
+| *(WPF + focus sentinel)* | Windows | `wpf` | background-modality / no-focus-steal sentinel + `capture_mode` (ax / vision / som) | `modality_background_test` |
## Runtime requirements (why CI coverage is uneven)
diff --git a/libs/cua-driver/test-harness/TEST_SUITE.md b/libs/cua-driver/test-harness/TEST_SUITE.md
index 11f996b570..8e11f27ef0 100644
--- a/libs/cua-driver/test-harness/TEST_SUITE.md
+++ b/libs/cua-driver/test-harness/TEST_SUITE.md
@@ -1,78 +1,101 @@
# cua-driver test suite — how the tests look
-Companion to `TEST_HARNESS_STRUCTURE.md` (which covers the harness *apps*). This is the **test layer**: the integration tests in `libs/cua-driver/rust/crates/cua-driver/tests/` that launch the driver, drive a real app, and assert.
+The integration tests in `libs/cua-driver/rust/crates/cua-driver/tests/` all sit
+on one shared foundation — the **`cua-driver-testkit`** crate — and are named by
+a four-family taxonomy so `ls tests/` reads as a map. Companion:
+`TEST_HARNESS_STRUCTURE.md` (the harness *apps* the `harness_*` tests drive).
-## The loop every harness test runs
+## The shared foundation: `cua-driver-testkit`
+
+A dev-only crate (`crates/cua-driver-testkit`) that every test builds on, so no
+test re-implements process plumbing:
+
+- **Two transports, one shape.** `McpDriver` (one long-lived `cua-driver` server
+ over stdio JSON-RPC, session-scoped state) and `CliDriver` (stateless
+ `cua-driver call` per action) both implement the `Driver` trait and normalize
+ their differing payloads — the CLI prints `structuredContent` directly, MCP
+ returns the JSON-RPC envelope — into one `ToolResponse` (`text()` /
+ `structured()` / `is_error()`). `RawDriver` adds raw send/recv with no
+ auto-initialize for the protocol tests that drive the handshake themselves.
+- **`ChildReaper`** kills every spawned child on drop; on Windows it assigns them
+ to a kill-on-close Job Object (no orphaned windows / held ports).
+- **`paths`** (`driver_binary()` resolves release-or-debug + `.exe`), **`ax`**
+ (snapshot-text parsers), `McpDriver::find_window`.
+
+## The loop every behavior test runs
```mermaid
flowchart LR
- T["test (crates/cua-driver/tests/*.rs)"]
- D(["cua-driver — spawned as a long-lived<br/>MCP server over stdio"])
- A["target app<br/>(harness app · LibreOffice · Electron · notepad)"]
- S["shared/scenarios.json"]
-
- T -->|"spawn + initialize"| D
- T -->|"launch / attach"| A
- S -.->|"expected titles / AutomationIds / shape"| T
- T -->|"tools/call: click · type · scroll ·<br/>get_window_state · get_desktop_state · set_config"| D
+ T["test (tests/*.rs)"]
+ TK(["cua-driver-testkit<br/>McpDriver / CliDriver / RawDriver"])
+ D(["cua-driver"])
+ A["target app / harness app"]
+ T -->|"Driver::call(tool, args)"| TK
+ TK -->|"spawn + drive"| D
D -->|"acts on"| A
- T -->|"re-snapshot & assert"| T
+ T -->|"re-snapshot & assert (ToolResponse)"| T
```
-One MCP server per test (long-lived) — important for `set_config`, whose overrides are **session-scoped** (they persist for that one server connection, not across separate `cua-driver call` processes).
+## Inventory by family (18 files)
-## Inventory (13 files, ~135 test fns)
+| Family | File | Platform | What it covers |
+|---|---|---|---|
+| **protocol_** | `protocol_handshake_test` | mac+win | initialize handshake, tools/list registration, per-tool capability + version fields, unknown-method/tool errors |
+| | `protocol_tools_call_test` | mac+win | per-tool `tools/call` shape: list_apps, get_config, permissions, AX tree, list_windows, screen size, scroll, type_text, hotkey, press_key, click, set_value |
+| | `protocol_schema_test` | mac+win | inputSchema shape for the `type_text` chars variants |
+| | `protocol_media_test` | mac+win | screenshot / zoom (jpeg) / recording / replay / screenshot-resize |
+| | `protocol_session_test` | mac+win | concurrent clients, multi-driver isolation, cursor-overlay liveness |
+| | `protocol_element_token_test` | mac/linux | Surface 6 opaque `element_token` in schema + capabilities |
+| **transport_** | `transport_config_persistence_test` | any | `set_config` persists to disk across stateless **CLI** invocations (#2034) vs visible within an **MCP** session |
+| **harness_** | `harness_wpf_test` | win | WPF: UIA Invoke, type, clicks, scroll, modal, owned/layered popups, native child HWNDs |
+| | `harness_winui3_test` | win | WinUI3: ValuePattern, CommandBarFlyout, XAML Popup |
+| | `harness_web_test` | win | WebView2 + Electron via CDP `page` |
+| | `harness_libreoffice_test` | win | LibreOffice VCL/SAL via MSAA (some `dispatch:"foreground"`) |
+| | `harness_appkit_test` | mac | AppKit: AX tree, AXPress, NSTextField, NSScrollView, NSMenu |
+| | `harness_swiftui_test` | mac | SwiftUI: AX tree, `.popover()` |
+| **modality_** | `modality_background_test` | win | background-modality / no-focus-steal sentinel + `capture_mode` ax/vision/som |
+| | `modality_input_e2e_test` | win | unified background input across Electron/Tauri/Win32, no z-raise |
+| | `modality_desktop_scope_test` | win | desktop-scope (foreground): `capture_scope=desktop`, `get_desktop_state`, window-less screen-absolute actions |
+| | `modality_focus_test` | mac | background automation does not steal focus |
+| **guard_** | `guard_ux_test` | win | UX guards: background focus, click-opens-window, launch-visible, menu shortcut |
-| Test file | OS | #fns | What it covers |
-|---|---|---:|---|
-| `harness_wpf_test.rs` | Windows | 18 | WPF: UIA Invoke, type, right/double-click, scroll, modal, owned/layered popups, native child HWNDs, accelerators |
-| `harness_winui3_test.rs` | Windows | 7 | WinUI3: ValuePattern, CommandBarFlyout, XAML Popup |
-| `harness_web_windows_test.rs` | Windows | 5 | WebView2 + Electron via CDP `page` tool |
-| `harness_lo_vcl_test.rs` | Windows | 7 | LibreOffice VCL/SAL via MSAA — **uses `dispatch:"foreground"`** for SALFRAME cases |
-| `harness_appkit_test.rs` | macOS | 5 | AppKit: AX tree, AXPress, NSTextField, NSScrollView, NSMenu |
-| `harness_swiftui_test.rs` | macOS | 2 | SwiftUI: AX tree, `.popover()` |
-| `harness_bg_modality_test.rs` | Windows | 8 | **Background modality** (no-focus-steal sentinel) + `capture_mode` ax/vision/som |
-| **`harness_desktop_scope_test.rs`** ◀ NEW | Windows | 3 | **Desktop-scope / foreground modality**: `capture_scope=desktop`, `get_desktop_state`, window-less screen-absolute click/scroll, negative gate |
-| `e2e_windows_bg_input_test.rs` | Windows | 6 | Unified **background** input across Electron/Tauri/Win32 — asserts no `dispatch:foreground` needed, no z-raise |
-| `focus_check_test.rs` | macOS | 1 | Background automation does **not** steal focus (Terminal stays active) |
-| `ux_guard_test.rs` | Windows | 6 | UX guards: background focus, click-opens-window, launch-visible, background menu shortcut |
-| `mcp_protocol_test.rs` | any | 65 | MCP JSON-RPC 2.0 protocol (headless — **runs in CI**) |
-| `element_token_test.rs` | any | 3 | Surface 6 opaque `element_token` (headless — **runs in CI**) |
+The `protocol_*` family is the renamed + split successor of the old
+`mcp_protocol_test` (3,412 lines / 65 tests). The split deduped 24 macOS↔Windows
+mirror pairs into single `cfg!`-branching tests, sharing one `RawDriver`.
-Everything except `mcp_protocol_test` / `element_token_test` is `#[ignore]` — they need a real GUI session and are run explicitly:
-`cargo test -p cua-driver --test <name> -- --ignored --nocapture --test-threads=1`
-
-## Modality coverage — the two halves
+## Coverage on three axes: transport × modality × platform
```
- ┌─────────────────────────── MODALITY ───────────────────────────┐
- │ │
- BACKGROUND (default) │ no focus steal · no z-raise · per-window · element/pixel │
- ─────────────────────▶│ ✅ harness_bg_modality (sentinel) · e2e_windows_bg_input │
- │ focus_check (macOS) · ux_guard · all per-app harness tests │
- │ │
- FOREGROUND / │ raises target · vision-only · screen-absolute (capture_scope= │
- DESKTOP-SCOPE │ desktop) · the "Computer-Use 1.0" loop │
- ─────────────────────▶│ ✅ harness_desktop_scope ◀ NEW (capture + click/scroll + gate) │
- │ (~) harness_lo_vcl (dispatch:foreground — VCL edge cases only) │
- └─────────────────────────────────────────────────────────────────┘
+ ┌────────────── MODALITY ──────────────┐
+ │ background foreground/desktop-scope│
+ ─────────────────┼───────────────────────────────────────
+ MCP transport │ ✅ thorough ✅ desktop_scope (win) │
+ │ (background, focus (mac) │
+ │ input_e2e, │
+ │ focus, guard) │
+ CLI transport │ ⬚ ✅ config-persistence │
+ │ (transport_ test) │
+ └───────────────────────────────────────┘
+ Per-app AX (MCP): harness_{wpf,winui3,web,libreoffice}=win · {appkit,swiftui}=mac
+ Protocol (RawDriver): mac+win, deduped; element_token = mac/linux
```
-- **Background** was already well covered (4 dedicated tests + every per-app test runs background by default).
-- **Foreground** used to be tested only *incidentally* (LibreOffice/VCL via `dispatch:"foreground"`). The new **`harness_desktop_scope_test`** is the first dedicated foreground/desktop-scope test.
-
-### What `harness_desktop_scope_test` asserts
-1. `set_config capture_scope=desktop` → `get_desktop_state` returns a full-display capture with real `screen_width/height` (proves capture works in a live session; it fails in Session 0).
-2. Window-less screen-absolute `click` + `scroll` (no pid/window_id) land via `WindowFromPoint`, reported as `(desktop scope)`.
-3. Negative gate: a window-less click under `capture_scope=window` is **rejected** (`desktop_scope_disabled`), not silently retargeted.
+- **Background modality** is the most-covered: the sentinel oracle
+ (`modality_background`), unified input (`modality_input_e2e`), the macOS
+ no-focus-steal check (`modality_focus`), and the UX guards.
+- **Foreground / desktop-scope** is covered by `modality_desktop_scope`.
+- **Transport** is now a first-class axis: `transport_config_persistence`
+ exercises CLI (disk) vs MCP (session) directly; most other tests run over MCP.
+- **Known gaps** (honest): desktop-scope/foreground has no macOS or Linux test;
+ `capture_mode` only on Windows; CLI transport is otherwise lightly exercised.
## Where they run
| Lane | Tests | Runner |
|---|---|---|
-| **Headless / CI** | `mcp_protocol_test`, `element_token_test`, + the Linux Nix GUI scenarios | GitHub-hosted `ubuntu-latest` (Xvfb / NixOS VMs) |
-| **Interactive Windows** | all `*_windows*` + `harness_wpf/winui3/web/bg_modality/lo_vcl/desktop_scope`, `e2e`, `ux_guard` | needs a real desktop (UIA/SendInput/z-order) → self-hosted / VM |
-| **Interactive macOS** | `harness_appkit/swiftui`, `focus_check` | needs a logged-in session + TCC → self-hosted Mac |
+| **Runs without `#[ignore]`** | `protocol_*` (mac/win dev machines; linux excludes them via cfg) | local / VM |
+| **Interactive Windows** (`#[ignore]`) | `harness_{wpf,winui3,web,libreoffice}`, `modality_*` (win), `guard_ux`, `transport_*` | real desktop / VM |
+| **Interactive macOS** (`#[ignore]`) | `harness_{appkit,swiftui}`, `modality_focus` | logged-in session + TCC |
-## Status of the new test
-`harness_desktop_scope_test.rs` is on branch **`test/desktop-scope-harness`** (off latest `main`, which already has #2019). Compile-verifying on the Windows VM; a live run uses the interactive-session method. Not yet PR'd — pending decision on its own PR vs. folding into the harness suite.
+Run an `#[ignore]` suite explicitly:
+`cargo test -p cua-driver --test <name> -- --ignored --nocapture --test-threads=1`