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.

30.8 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.

//! MCP transport: one long-lived `cua-driver` server over stdio JSON-RPC.

use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::process::{ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{channel, Receiver};
use std::time::{Duration, Instant};

use serde_json::Value;

use crate::daemon::TestDaemon;
use crate::driver::{BehaviorRecording, Driver};
use crate::paths::{driver_binary, ensure_driver_binary};
use crate::reaper::{spawn_in_job, ChildReaper};
use crate::response::ToolResponse;
use crate::CALL_TIMEOUT;

/// A spawned cua-driver MCP server. State (e.g. `set_config`) persists for the
/// lifetime of this one connection — which is why config-scope tests drive a
/// single `McpDriver`. The server (and any apps spawned through [`reaper`]) are
/// reaped when this value drops.
///
/// [`reaper`]: McpDriver::reaper
pub struct McpDriver {
    reaper: ChildReaper,
    _daemon: Option<TestDaemon>,
    socket: String,
    stdin: ChildStdin,
    rx: Receiver<String>,
    next_id: u32,
    recording_dir: Option<PathBuf>,
    recording_started: bool,
    recording_started_at: Option<Instant>,
}

static RECORDING_SEQUENCE: AtomicU64 = AtomicU64::new(1);
// ScreenCaptureKit can acknowledge capture before SCRecordingOutput has
// durably emitted its first sample. This total includes the 300 ms baseline
// settle and keeps immediate-refusal trajectories from finalizing empty.
const MIN_BEHAVIOR_RECORDING_DURATION: Duration = Duration::from_millis(750);
// A recorded macOS action includes one synchronous window capture before and
// after dispatch. Keep the ordinary timeout for every other platform and for
// the recording controls themselves.
const MACOS_RECORDED_CALL_TIMEOUT: Duration = Duration::from_secs(CALL_TIMEOUT.as_secs() * 3);

fn call_timeout(recording_started: bool, tool: &str, is_macos: bool) -> Duration {
    let recording_meta_tool = matches!(
        tool,
        "start_recording" | "stop_recording" | "get_recording_state" | "replay_trajectory"
    );
    if is_macos && recording_started && !recording_meta_tool {
        MACOS_RECORDED_CALL_TIMEOUT
    } else {
        CALL_TIMEOUT
    }
}

fn timeout_error_message(tool: &str, timeout: Duration) -> String {
    format!("TIMEOUT (>{}s) on {tool}", timeout.as_secs())
}

impl McpDriver {
    /// Spawn the driver, start the stdout reader thread, and `initialize`.
    /// Returns `None` (with a skip message) if the binary isn't built — the
    /// caller's test should early-return so an un-built binary skips, not fails.
    /// `CUA_TEST_REQUIRE_DRIVER_BIN=1` makes a missing binary panic instead.
    pub fn spawn() -> Option<Self> {
        Self::spawn_internal(&[], &[], None, false, true)
    }

    /// Spawn through the exact binary selected by the caller.
    pub fn spawn_with_binary(bin: impl Into<PathBuf>) -> Option<Self> {
        Self::spawn_internal_with_binary(bin.into(), &[], &[], None, false, true)
    }

    /// Spawn the driver with a stable recording label for artifact naming.
    pub fn spawn_named(recording_label: &str) -> Option<Self> {
        Self::spawn_internal(&[], &[], Some(recording_label), false, true)
    }

    /// Spawn a named driver with the native cursor overlay enabled.
    ///
    /// Most testkit daemons disable the overlay so unrelated behavior tests
    /// cannot paint over their own pixel oracles. Cursor-specific E2E tests
    /// opt in through this constructor.
    pub fn spawn_named_with_overlay(recording_label: &str) -> Option<Self> {
        Self::spawn_internal(&[], &[], Some(recording_label), true, true)
    }

    /// Spawn a named driver with environment variables scoped to this child.
    pub fn spawn_named_with_env(recording_label: &str, env: &[(&str, &str)]) -> Option<Self> {
        Self::spawn_internal(env, &[], Some(recording_label), false, true)
    }

    /// Spawn a transport proxy through an already-running installed daemon.
    ///
    /// Computer History admission is tied to the installed product path and
    /// the daemon authenticates the local CLI peer. Cross-platform lifecycle
    /// tests therefore use this constructor instead of the testkit's ephemeral
    /// source-tree daemon.
    pub fn spawn_daemon_proxy_named(socket: &str, recording_label: &str) -> Option<Self> {
        if !daemon_socket_is_reachable(socket) {
            let hint = if cfg!(target_os = "macos") {
                " — run `./scripts/install-local.sh` and `cua-driver permissions grant`;"
            } else {
                " —"
            };
            eprintln!("[testkit] CuaDriver daemon not listening at {socket}{hint} skipping");
            return None;
        }
        Self::spawn_internal(
            &[],
            &["mcp", "--socket", socket],
            Some(recording_label),
            false,
            true,
        )
    }

    /// Spawn an installed-daemon proxy without allocating behavior artifacts.
    /// Used for post-restart continuity checks after the visible trajectory has
    /// already been captured by the same test case.
    pub fn spawn_daemon_proxy_unrecorded(socket: &str) -> Option<Self> {
        if !daemon_socket_is_reachable(socket) {
            eprintln!("[testkit] CuaDriver daemon not listening at {socket} — skipping");
            return None;
        }
        Self::spawn_internal(&[], &["mcp", "--socket", socket], None, false, false)
    }

    pub fn spawn_peer_unrecorded(&self) -> Option<Self> {
        Self::spawn_daemon_proxy_unrecorded(&self.socket)
    }

    /// Spawn the driver with extra environment variables set on the child.
    pub fn spawn_with_env(env: &[(&str, &str)]) -> Option<Self> {
        Self::spawn_internal(env, &[], None, false, true)
    }

    fn spawn_internal(
        env: &[(&str, &str)],
        args: &[&str],
        recording_label: Option<&str>,
        overlay_enabled: bool,
        prepare_recording: bool,
    ) -> Option<Self> {
        Self::spawn_internal_with_binary(
            driver_binary(),
            env,
            args,
            recording_label,
            overlay_enabled,
            prepare_recording,
        )
    }

    fn spawn_internal_with_binary(
        bin: PathBuf,
        env: &[(&str, &str)],
        args: &[&str],
        recording_label: Option<&str>,
        overlay_enabled: bool,
        prepare_recording: bool,
    ) -> Option<Self> {
        let mut daemon_env = env.to_vec();
        let e2e_unrestricted = std::env::var_os("CUA_E2E_UNRESTRICTED_GUI").is_some();
        let caller_selected_mode = daemon_env
            .iter()
            .any(|(name, _)| *name == "CUA_DRIVER_PERMISSION_MODE");
        if args.is_empty() && e2e_unrestricted && !caller_selected_mode {
            // Canonical GUI behavior runners execute in disposable desktops
            // and opt into this testkit-only switch. Translate it at the
            // daemon boundary so unrelated SDK/runtime tests in the same
            // runner do not inherit product authorization variables.
            daemon_env.extend([
                ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
                ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
            ]);
        }
        if !ensure_driver_binary(&bin) {
            return None;
        }

        let mut reaper = ChildReaper::new();
        let daemon = if args.is_empty() {
            // Environment that changes tool behavior belongs on the daemon,
            // because the stdio process is now only a transport proxy.
            Some(if overlay_enabled {
                TestDaemon::spawn_with_overlay(&bin, &mut reaper, &daemon_env)?
            } else {
                TestDaemon::spawn(&bin, &mut reaper, &daemon_env)?
            })
        } else {
            None
        };
        let mut cmd = Command::new(&bin);
        let stderr = if std::env::var_os("CUA_TEST_DRIVER_STDERR").is_some() {
            Stdio::inherit()
        } else {
            Stdio::null()
        };
        cmd.stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(stderr)
            // Product telemetry is default-on, but behavior harnesses should
            // remain deterministic and must not send CI traffic to PostHog.
            // A test that exercises telemetry can explicitly override this
            // through `spawn_with_env` / `spawn_named_with_env` below.
            .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false");
        if let Some(daemon) = &daemon {
            cmd.args(["mcp", "--socket", &daemon.socket]);
            daemon.apply_state_root(&mut cmd);
        } else {
            // Proxies to an externally owned daemon deliberately keep the
            // host's per-user state; the external daemon owns that state.
            cmd.args(args);
        }
        crate::host_state::apply_env(&mut cmd, None, &daemon_env);
        let mut driver = spawn_in_job(&mut cmd)
            .inspect_err(|e| eprintln!("[testkit] driver spawn failed: {e}"))
            .ok()?;
        let stdin = driver.stdin.take().unwrap();
        let stdout = driver.stdout.take().unwrap();
        reaper.push(driver);

        let (tx, rx) = channel::<String>();
        std::thread::spawn(move || {
            let mut reader = BufReader::new(stdout);
            let mut line = String::new();
            loop {
                line.clear();
                match reader.read_line(&mut line) {
                    Ok(0) | Err(_) => break,
                    Ok(_) => {
                        if tx.send(line.trim().to_string()).is_err() {
                            break;
                        }
                    }
                }
            }
        });

        let socket = daemon
            .as_ref()
            .map(|daemon| daemon.socket.clone())
            .or_else(|| {
                args.windows(2)
                    .find(|pair| pair[0] == "--socket")
                    .map(|pair| pair[1].to_owned())
            })?;
        let mut d = McpDriver {
            reaper,
            _daemon: daemon,
            socket,
            stdin,
            rx,
            next_id: 2,
            recording_dir: None,
            recording_started: false,
            recording_started_at: None,
        };
        d.initialize();
        if prepare_recording {
            d.prepare_e2e_recording(recording_label);
        }
        Some(d)
    }

    /// macOS GUI harness tests need the installed, TCC-authorized daemon path.
    ///
    /// A raw `target/debug/cua-driver` MCP process initializes AppKit for the
    /// cursor overlay and can lose Screen Recording-attributed window titles even
    /// when the shell's one-shot `cua-driver call` path can see them. The installed
    /// daemon is the product path agents use, so ignored GUI tests proxy through an
    /// already-running daemon and skip with a clear note when it is absent.
    #[cfg(target_os = "macos")]
    pub fn spawn_macos_daemon_proxy_named(recording_label: &str) -> Option<Self> {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
        let socket = std::env::var("CUA_E2E_MACOS_DAEMON_SOCKET")
            .unwrap_or_else(|_| format!("{home}/Library/Caches/cua-driver/cua-driver.sock"));
        Self::spawn_daemon_proxy_named(&socket, recording_label)
    }

    pub fn daemon_socket(&self) -> &str {
        &self.socket
    }

    pub fn daemon_pid(&self) -> Option<u32> {
        self._daemon.as_ref().map(|daemon| daemon.pid)
    }

    /// Isolated per-user state root (`HOME`, XDG/AppData directories) given to
    /// the test-owned daemon, or `None` for external-daemon proxies and spawns
    /// that passed [`crate::SHARE_HOST_STATE`].
    pub fn state_root(&self) -> Option<&std::path::Path> {
        self._daemon.as_ref().and_then(TestDaemon::state_root)
    }

    fn initialize(&mut self) {
        self.send(serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}
        }));
        let _ = self.rx.recv_timeout(CALL_TIMEOUT);
    }

    fn send(&mut self, req: Value) {
        let _ = writeln!(self.stdin, "{}", serde_json::to_string(&req).unwrap());
        let _ = self.stdin.flush();
    }

    fn prepare_e2e_recording(&mut self, explicit_label: Option<&str>) {
        let Some(root) = std::env::var_os("CUA_E2E_RECORDINGS_ROOT") else {
            return;
        };
        let sequence = RECORDING_SEQUENCE.fetch_add(1, Ordering::Relaxed);
        let thread_name = std::thread::current()
            .name()
            .unwrap_or("unnamed-test")
            .to_owned();
        let label = recording_label(explicit_label.unwrap_or(&thread_name));
        let output_dir =
            PathBuf::from(root).join(format!("{label}-pid{}-{sequence:03}", std::process::id()));
        std::fs::create_dir_all(&output_dir).unwrap_or_else(|error| {
            panic!("could not prepare E2E recording directory for {thread_name}: {error}")
        });
        let runner_console = crate::windows_setup::minimize_hosted_runner_console();
        let runner_console_status = runner_console.as_deref().unwrap_or("error");
        let manifest = serde_json::json!({
            "schema": "cua-e2e-trajectory/v1",
            "label": label,
            "rust_test_thread": thread_name,
            "process_id": std::process::id(),
            "daemon_pid": self.daemon_pid(),
            "sequence": sequence,
            "behavior_video": {
                "status": "pending",
                "baseline_settle_ms": 300,
                "minimum_duration_ms": MIN_BEHAVIOR_RECORDING_DURATION.as_millis() as u64
            },
            "hosted_runner_console": {
                "status": runner_console_status
            }
        });
        std::fs::write(
            output_dir.join("trajectory.json"),
            serde_json::to_vec_pretty(&manifest).unwrap_or_default(),
        )
        .expect("write prepared E2E trajectory manifest");
        eprintln!(
            "[testkit] prepared E2E evidence directory {}",
            output_dir.display()
        );
        self.recording_dir = Some(output_dir);
        if let Err(error) = runner_console {
            panic!("hosted-runner console cleanup failed before fixture setup: {error}");
        }
    }

    /// Begin the behavioral clip after fixture readiness and foreground or
    /// background posture have been established. The settle interval gives
    /// the video backend time to encode a visible baseline before dispatch.
    pub fn start_behavior_recording(&mut self) {
        let Some(output_dir) = self.recording_dir.clone() else {
            return;
        };
        if self.recording_started {
            return;
        }
        let response = self.call(
            "start_recording",
            serde_json::json!({
                "output_dir": output_dir.to_string_lossy(),
                "record_video": true
            }),
        );
        let video_active = response.structured()["video_active"]
            .as_bool()
            .unwrap_or(false);
        if response.is_error() || !video_active {
            update_behavior_video_status(&output_dir, "error");
            panic!(
                "E2E behavioral video did not start after setup: {}; structured={}",
                response.text(),
                response.structured()
            );
        }
        self.recording_started = true;
        self.recording_started_at = Some(Instant::now());
        update_behavior_video_status(&output_dir, "started");
        std::thread::sleep(Duration::from_millis(300));
        mark_behavior_video_baseline_ready(&output_dir);
        eprintln!(
            "[testkit] behavioral E2E video started at {}",
            output_dir.display()
        );
    }

    fn stop_e2e_recording(&mut self) {
        let Some(output_dir) = self.recording_dir.clone() else {
            return;
        };
        if !self.recording_started {
            let message = "E2E behavioral video boundary was never reached; fixture setup or posture failed before capture";
            eprintln!("[testkit] {message}");
            let _ = std::fs::write(output_dir.join("recording-error.txt"), message);
            return;
        }
        if let Some(started_at) = self.recording_started_at.take() {
            let remaining = remaining_behavior_recording_time(started_at.elapsed());
            if !remaining.is_zero() {
                std::thread::sleep(remaining);
            }
        }
        let response = self.call("stop_recording", serde_json::json!({}));
        let video_path = output_dir.join("recording.mp4");
        let valid_video = !response.is_error()
            && response.structured()["last_video_path"].as_str().is_some()
            && std::fs::metadata(&video_path)
                .map(|metadata| metadata.len() > 0)
                .unwrap_or(false);
        if valid_video {
            update_behavior_video_status(&output_dir, "finalized");
            eprintln!("[testkit] finalized E2E video at {}", video_path.display());
            return;
        }

        let message = format!(
            "E2E video failed to finalize at {}: {}",
            video_path.display(),
            response.text()
        );
        eprintln!("[testkit] {message}");
        update_behavior_video_status(&output_dir, "error");
        let _ = std::fs::create_dir_all(&output_dir);
        let _ = std::fs::write(output_dir.join("recording-error.txt"), message);
    }

    /// Mutable access to the child reaper, e.g. to launch a target app whose
    /// lifetime should be tied to this driver.
    pub fn reaper(&mut self) -> &mut ChildReaper {
        &mut self.reaper
    }

    /// Directory for this driver's active per-cell recording, when enabled.
    pub fn recording_dir(&self) -> Option<&std::path::Path> {
        self.recording_dir.as_deref()
    }

    /// Poll `list_windows` until a window of `pid` whose title contains
    /// `title_substr` appears (up to ~12s). Returns `(window_id, title)`.
    /// Replaces the per-file `find_harness_window` helper.
    pub fn find_window(&mut self, pid: i64, title_substr: &str) -> Option<(u64, String)> {
        let deadline = Instant::now() + Duration::from_secs(12);
        loop {
            let r = self.call("list_windows", serde_json::json!({ "pid": pid }));
            if let Some(wins) = r.structured()["windows"].as_array() {
                for w in wins {
                    if w["pid"].as_i64() != Some(pid) {
                        continue;
                    }
                    let title = w["title"].as_str().unwrap_or("");
                    if title.contains(title_substr) {
                        return Some((w["window_id"].as_u64()?, title.to_string()));
                    }
                }
            }
            if Instant::now() >= deadline {
                return None;
            }
            std::thread::sleep(Duration::from_millis(150));
        }
    }

    /// Raw JSON-RPC response envelope, for the rare assertion needing it.
    pub fn call_raw(&mut self, tool: &str, args: Value) -> Value {
        let id = self.next_id;
        self.next_id += 1;
        let timeout = call_timeout(self.recording_started, tool, cfg!(target_os = "macos"));
        let args = crate::driver::with_full_window_state(tool, args);
        let request = serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": { "name": tool, "arguments": args }
        });
        self.send(request.clone());
        let response = match self.rx.recv_timeout(timeout) {
            Ok(line) => serde_json::from_str(&line)
                .unwrap_or_else(|_| serde_json::json!({ "error": format!("bad json: {line}") })),
            Err(_) => serde_json::json!({
                "error": timeout_error_message(tool, timeout)
            }),
        };
        if let Some(dir) = &self.recording_dir {
            let mut row = serde_json::json!({"request": request, "response": response});
            elide_images(&mut row);
            let mut file = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(dir.join("tool-calls.jsonl"))
                .expect("open tool transcript");
            writeln!(file, "{row}").expect("append tool transcript");
        }
        response
    }
}

fn elide_images(value: &mut Value) {
    use std::hash::{Hash, Hasher};
    match value {
        Value::Object(object) => {
            let image = object.get("type").and_then(Value::as_str) == Some("image");
            for (key, value) in object {
                if (image && key == "data") || key.contains("base64") {
                    if let Some(data) = value.as_str() {
                        let mut hash = std::collections::hash_map::DefaultHasher::new();
                        data.hash(&mut hash);
                        *value = serde_json::json!({"bytes": data.len(), "hash": format!("{:016x}", hash.finish())});
                        continue;
                    }
                }
                elide_images(value);
            }
        }
        Value::Array(array) => array.iter_mut().for_each(elide_images),
        _ => {}
    }
}

#[cfg(unix)]
fn daemon_socket_is_reachable(socket: &str) -> bool {
    std::os::unix::net::UnixStream::connect(socket).is_ok()
}

#[cfg(windows)]
fn daemon_socket_is_reachable(socket: &str) -> bool {
    use std::os::windows::ffi::OsStrExt;

    #[link(name = "kernel32")]
    extern "system" {
        fn WaitNamedPipeW(lp_named_pipe_name: *const u16, timeout_ms: u32) -> i32;
    }

    let wide: Vec<u16> = std::ffi::OsStr::new(socket)
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    // NMPWAIT_NOWAIT == 1. Unlike opening the path, this does not consume the
    // daemon's available named-pipe instance before the MCP proxy connects.
    unsafe { WaitNamedPipeW(wide.as_ptr(), 1) != 0 }
}

impl Drop for McpDriver {
    fn drop(&mut self) {
        self.stop_e2e_recording();
    }
}

fn recording_label(name: &str) -> String {
    let label: String = name
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') {
                character
            } else {
                '-'
            }
        })
        .collect();
    let label = label.trim_matches('-');
    if label.is_empty() {
        "unnamed-test".to_owned()
    } else {
        label.chars().take(96).collect()
    }
}

fn remaining_behavior_recording_time(elapsed: Duration) -> Duration {
    MIN_BEHAVIOR_RECORDING_DURATION.saturating_sub(elapsed)
}

impl Driver for McpDriver {
    fn call(&mut self, tool: &str, args: Value) -> ToolResponse {
        ToolResponse::from_mcp(self.call_raw(tool, args))
    }
}

impl BehaviorRecording for McpDriver {
    fn start_behavior_recording(&mut self) {
        McpDriver::start_behavior_recording(self);
    }
}

fn update_behavior_video_status(output_dir: &std::path::Path, status: &str) {
    let path = output_dir.join("trajectory.json");
    let Ok(bytes) = std::fs::read(&path) else {
        return;
    };
    let Ok(mut manifest) = serde_json::from_slice::<Value>(&bytes) else {
        return;
    };
    manifest["behavior_video"]["status"] = Value::String(status.to_owned());
    let timestamp_field = match status {
        "started" => Some("started_at_unix_ms"),
        "finalized" => Some("finalized_at_unix_ms"),
        "error" => Some("error_at_unix_ms"),
        _ => None,
    };
    if let Some(field) = timestamp_field {
        manifest["behavior_video"][field] = Value::from(unix_ms());
    }
    let _ = std::fs::write(
        path,
        serde_json::to_vec_pretty(&manifest).unwrap_or_default(),
    );
}

fn mark_behavior_video_baseline_ready(output_dir: &std::path::Path) {
    let path = output_dir.join("trajectory.json");
    let Ok(bytes) = std::fs::read(&path) else {
        return;
    };
    let Ok(mut manifest) = serde_json::from_slice::<Value>(&bytes) else {
        return;
    };
    manifest["behavior_video"]["baseline_ready_at_unix_ms"] = Value::from(unix_ms());
    let _ = std::fs::write(
        path,
        serde_json::to_vec_pretty(&manifest).unwrap_or_default(),
    );
}

fn unix_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

#[cfg(test)]
mod tests {
    use super::{
        call_timeout, recording_label, remaining_behavior_recording_time, timeout_error_message,
        MACOS_RECORDED_CALL_TIMEOUT,
    };
    use crate::CALL_TIMEOUT;
    use std::time::Duration;

    #[cfg(unix)]
    #[test]
    fn transcript_retains_timeout_request_and_elides_images() {
        use super::*;
        let dir = tempfile::tempdir().unwrap();
        let mut command = Command::new("sh");
        command
            .args(["-c", "read line; sleep 1"])
            .stdin(Stdio::piped());
        let mut child = spawn_in_job(&mut command).unwrap();
        let stdin = child.stdin.take().unwrap();
        let mut reaper = ChildReaper::new();
        reaper.push(child);
        let (tx, rx) = channel();
        let mut driver = McpDriver {
            reaper,
            _daemon: None,
            socket: String::new(),
            stdin,
            rx,
            next_id: 2,
            recording_dir: Some(dir.path().to_owned()),
            recording_started: false,
            recording_started_at: None,
        };
        tx.send(
            serde_json::json!({"result": {"content": [
            {"type": "image", "data": "c2VjcmV0", "mimeType": "image/png"},
            {"type": "text", "text": "unchanged"}],
            "structuredContent": {"screenshot_base64": "c2VjcmV0", "count": 7}}})
            .to_string(),
        )
        .unwrap();
        driver.call_raw("get_window_state", serde_json::json!({"pid": 42}));
        drop(tx);
        let response = driver.call_raw("click", serde_json::json!({"element_token": "fresh"}));
        let text = std::fs::read_to_string(dir.path().join("tool-calls.jsonl")).unwrap();
        let rows: Vec<Value> = text
            .lines()
            .map(|line| serde_json::from_str(line).unwrap())
            .collect();
        assert_eq!(
            rows[1]["request"]["params"]["arguments"]["element_token"],
            "fresh"
        );
        assert_eq!(rows[1]["response"], response);
        assert!(response["error"].as_str().unwrap().contains("TIMEOUT"));
        assert!(!text.contains("c2VjcmV0"));
        assert_eq!(
            rows[0]["response"]["result"]["content"][0]["data"]["bytes"],
            8
        );
        assert!(rows[0]["response"]["result"]["content"][0]["data"]["hash"].is_string());
        assert_eq!(
            rows[0]["response"]["result"]["content"][1]["text"],
            "unchanged"
        );
        assert_eq!(
            rows[0]["response"]["result"]["structuredContent"]["count"],
            7
        );
        driver.recording_dir = None;
    }

    #[test]
    fn recording_label_is_artifact_safe() {
        assert_eq!(
            recording_label("module::test name/windows"),
            "module--test-name-windows"
        );
        assert_eq!(recording_label("///"), "unnamed-test");
    }

    #[test]
    fn short_behavior_recordings_receive_a_settle_interval() {
        assert_eq!(
            remaining_behavior_recording_time(Duration::from_millis(300)),
            Duration::from_millis(450)
        );
        assert!(remaining_behavior_recording_time(Duration::from_millis(750)).is_zero());
        assert!(remaining_behavior_recording_time(Duration::from_secs(2)).is_zero());
    }

    #[test]
    fn ordinary_calls_keep_the_base_timeout() {
        assert_eq!(call_timeout(false, "click", true), CALL_TIMEOUT);
    }

    #[test]
    fn recorded_macos_calls_allow_two_evidence_captures() {
        assert_eq!(
            call_timeout(true, "click", true),
            MACOS_RECORDED_CALL_TIMEOUT
        );
        assert_eq!(
            MACOS_RECORDED_CALL_TIMEOUT,
            Duration::from_secs(CALL_TIMEOUT.as_secs() * 3)
        );
    }

    #[test]
    fn recording_controls_keep_the_base_timeout() {
        assert_eq!(call_timeout(true, "start_recording", true), CALL_TIMEOUT);
        assert_eq!(call_timeout(true, "stop_recording", true), CALL_TIMEOUT);
        assert_eq!(
            call_timeout(true, "get_recording_state", true),
            CALL_TIMEOUT
        );
        assert_eq!(call_timeout(true, "replay_trajectory", true), CALL_TIMEOUT);
    }

    #[test]
    fn non_macos_calls_keep_the_base_timeout_during_recording() {
        assert_eq!(call_timeout(true, "click", false), CALL_TIMEOUT);
    }

    #[test]
    fn timeout_errors_report_the_effective_deadline() {
        assert_eq!(
            timeout_error_message("click", MACOS_RECORDED_CALL_TIMEOUT),
            "TIMEOUT (>75s) on click"
        );
    }

    #[cfg(target_os = "macos")]
    const PROXY_CHILD_ENV: &str = "CUA_TESTKIT_PROXY_CHILD";

    #[cfg(target_os = "macos")]
    #[test]
    #[ignore]
    fn macos_proxy_child() {
        if std::env::var_os(PROXY_CHILD_ENV).is_some() {
            assert!(super::McpDriver::spawn_macos_daemon_proxy_named("child").is_none());
        }
    }

    #[cfg(target_os = "macos")]
    fn run_proxy_child(socket: &std::path::Path) -> String {
        let out = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "mcp::tests::macos_proxy_child",
                "--exact",
                "--ignored",
                "--nocapture",
            ])
            .env(PROXY_CHILD_ENV, "1")
            .env("CUA_E2E_MACOS_DAEMON_SOCKET", socket)
            .env("CUA_TEST_DRIVER_BIN", socket.with_extension("missing-bin"))
            .output()
            .unwrap();
        assert!(out.status.success());
        assert!(String::from_utf8_lossy(&out.stdout).contains("running 1 test"));
        String::from_utf8_lossy(&out.stderr).into_owned()
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_proxy_with_missing_socket_prints_install_hint() {
        let dir = std::env::temp_dir().join(format!("cua-proxy-miss-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let socket = dir.join("d.sock");
        let stderr = run_proxy_child(&socket);
        let _ = std::fs::remove_dir_all(&dir);
        assert!(stderr.contains(&format!("not listening at {}", socket.display())));
        assert!(stderr.contains("./scripts/install-local.sh"));
        assert!(stderr.contains("cua-driver permissions grant"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_proxy_with_reachable_socket_probes_once() {
        let dir = std::env::temp_dir().join(format!("cua-proxy-ok-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let socket = dir.join("d.sock");
        let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
        listener.set_nonblocking(true).unwrap();
        let stderr = run_proxy_child(&socket);
        let mut probes = 0;
        while listener.accept().is_ok() {
            probes += 1;
        }
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(probes, 1);
        assert!(!stderr.contains("not listening"));
    }
}