Skip to content

armgit / cua

Public Imported from GitHub
0

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

test(cua-driver): isolate testkit daemons from host state (#4102)

Francesco Bonacci1d7c04aeaf79
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs
index 5c79b6a075..8b03458596 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs
@@ -67,6 +67,12 @@ impl CliDriver {
self.bin.exists() && self.daemon.is_some()
}
+ /// Isolated per-user state root given to the test-owned daemon, or `None`
+ /// when the caller passed [`crate::SHARE_HOST_STATE`].
+ pub fn state_root(&self) -> Option<&std::path::Path> {
+ self.daemon.as_ref().and_then(TestDaemon::state_root)
+ }
+
pub fn daemon_socket(&self) -> Option<&str> {
self.daemon.as_ref().map(|daemon| daemon.socket.as_str())
}
@@ -88,15 +94,16 @@ impl Driver for CliDriver {
Value::Null,
);
};
- let mut child = match Command::new(&self.bin)
+ let mut command = Command::new(&self.bin);
+ command
.arg("call")
.arg(tool)
.args(["--socket", &daemon.socket])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- {
+ .stderr(Stdio::piped());
+ daemon.apply_state_root(&mut command);
+ let mut child = match command.spawn() {
Ok(c) => c,
Err(e) => {
let msg = format!("spawn failed: {e}");
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs
index 2a29c55c80..2590b03df0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs
@@ -6,6 +6,7 @@ use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
+use crate::host_state::{apply_env, IsolatedStateRoot};
use crate::reaper::{spawn_in_job, ChildReaper};
#[cfg(not(unix))]
@@ -17,9 +18,25 @@ pub(crate) struct TestDaemon {
pub(crate) pid: u32,
#[cfg(unix)]
_socket_dir: tempfile::TempDir,
+ /// Per-user state root shared by the daemon and its transport clients.
+ /// `None` only when the caller opted into host state.
+ state_root: Option<IsolatedStateRoot>,
}
impl TestDaemon {
+ /// Give a transport client (stdio proxy, one-shot CLI call) the same
+ /// per-user state root as the daemon it talks to.
+ pub(crate) fn apply_state_root(&self, command: &mut Command) {
+ if let Some(root) = &self.state_root {
+ root.apply(command);
+ }
+ }
+
+ /// Root of the isolated per-user state, when the daemon has one.
+ pub(crate) fn state_root(&self) -> Option<&Path> {
+ self.state_root.as_ref().map(IsolatedStateRoot::path)
+ }
+
pub(crate) fn spawn(
binary: &Path,
reaper: &mut ChildReaper,
@@ -83,9 +100,13 @@ impl TestDaemon {
if !overlay_enabled {
command.arg("--no-overlay");
}
- for (key, value) in env {
- command.env(key, value);
+ // Never let a test-owned daemon read the developer's installed-product
+ // state (Computer History admission, config, extensions, ...).
+ let state_root = IsolatedStateRoot::for_env(env);
+ if state_root.is_none() && !crate::host_state::shares_host_state(env) {
+ return None;
}
+ apply_env(&mut command, state_root.as_ref(), env);
// Spawn directly so the `Child` stays reachable for `try_wait` below;
// the reaper adopts it on every exit path. Without the handle, a daemon
// that dies during startup is indistinguishable from one that is merely
@@ -117,6 +138,7 @@ impl TestDaemon {
pid,
#[cfg(unix)]
_socket_dir: socket_dir,
+ state_root,
});
}
std::thread::sleep(Duration::from_millis(50));
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/host_state.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/host_state.rs
new file mode 100644
index 0000000000..f1a9f2819f
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/host_state.rs
@@ -0,0 +1,222 @@
+//! Per-daemon isolation from the developer's real per-user state.
+//!
+//! The driver resolves its own persistent state (Computer History admission,
+//! the `~/.cua-driver` config, telemetry markers, extension installs, release
+//! channel, libei restore tokens, ...) from `HOME`, the XDG base directories,
+//! and on Windows `LOCALAPPDATA` / `USERPROFILE`. A test-owned daemon that
+//! inherits those values reads whatever the developer's installed product left
+//! behind, so the same test can pass in CI and fail on a maintainer's machine
+//! (for example, a real `admission.json` that makes a debug daemon request
+//! History admission and exit before binding, #4094).
+//!
+//! Isolation is deliberately limited to the locations the driver derives its
+//! own state from. Locations the operating system uses to discover installed
+//! apps stay on the host, because tests launch real apps through the daemon:
+//!
+//! - Windows keeps `USERPROFILE`, `APPDATA`, and `LOCALAPPDATA`. The in-process
+//! `shell:AppsFolder` enumeration depends on `LOCALAPPDATA` (a redirected
+//! value makes Microsoft Edge unresolvable, `0x80070002`), and the shell
+//! expands per-user known folders through `%USERPROFILE%`. The driver's
+//! `USERPROFILE`-derived state goes through its own `CUA_DRIVER_RS_HOME`
+//! override instead. Known limitation: the Windows Computer History root
+//! (`%LOCALAPPDATA%\cua-driver\computer-history`) has no separate driver
+//! override, so a Windows host with History admitted still leaks into test
+//! daemons.
+//! - Linux pins `XDG_DATA_HOME` to the host data directory so user `.desktop`
+//! entries remain discoverable after `HOME` moves.
+//!
+//! Every testkit spawner therefore points those variables at a fresh temporary
+//! directory owned by the spawned daemon. Callers keep full control:
+//!
+//! - any state variable in the caller's `env` wins over the isolated default,
+//! so a test that needs one root across several spawns creates its own
+//! tempdir and passes it explicitly; and
+//! - [`SHARE_HOST_STATE`] in the caller's `env` disables isolation entirely for
+//! tests that intentionally observe host-owned state. The marker itself is
+//! never forwarded to the child.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+/// Environment marker that opts a testkit spawn out of state isolation.
+///
+/// Include it in the `env` slice passed to a testkit constructor. It is
+/// consumed by the testkit and is not forwarded to the spawned driver.
+pub const SHARE_HOST_STATE: (&str, &str) = ("CUA_TESTKIT_SHARE_HOST_STATE", "1");
+
+/// Variables that locate per-user driver state on the current platform,
+/// relative to the isolated root.
+#[cfg(target_os = "windows")]
+const STATE_VARIABLES: &[(&str, &str)] = &[("HOME", ""), ("CUA_DRIVER_RS_HOME", ".cua-driver")];
+
+#[cfg(not(target_os = "windows"))]
+const STATE_VARIABLES: &[(&str, &str)] = &[
+ ("HOME", ""),
+ ("XDG_CONFIG_HOME", ".config"),
+ ("XDG_STATE_HOME", ".local/state"),
+];
+
+/// Host app-discovery locations that must survive the `HOME` redirect.
+fn host_discovery_env() -> Vec<(&'static str, PathBuf)> {
+ #[cfg(all(unix, not(target_os = "macos")))]
+ {
+ let data_home = std::env::var_os("XDG_DATA_HOME")
+ .filter(|value| !value.is_empty())
+ .map(PathBuf::from)
+ .or_else(|| {
+ std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/share"))
+ });
+ if let Some(data_home) = data_home {
+ return vec![("XDG_DATA_HOME", data_home)];
+ }
+ }
+ Vec::new()
+}
+
+/// A temporary per-user state root for one test-owned driver.
+///
+/// Testkit transports create one automatically. Tests that launch a driver
+/// through another path (for example the SDK's embedded host) create one
+/// directly and pass [`IsolatedStateRoot::env`] to that launcher. The
+/// directory is removed on drop, so keep the value alive for the child's
+/// lifetime.
+pub struct IsolatedStateRoot {
+ dir: tempfile::TempDir,
+}
+
+impl IsolatedStateRoot {
+ /// Create a fresh, empty per-user state root.
+ pub fn new() -> std::io::Result<Self> {
+ let dir = tempfile::Builder::new()
+ .prefix("cua-driver-test-home-")
+ .tempdir()?;
+ for (_, relative) in STATE_VARIABLES {
+ if !relative.is_empty() {
+ std::fs::create_dir_all(dir.path().join(relative))?;
+ }
+ }
+ Ok(Self { dir })
+ }
+
+ /// Create an isolated root unless the caller opted into host state.
+ pub(crate) fn for_env(env: &[(&str, &str)]) -> Option<Self> {
+ if shares_host_state(env) {
+ return None;
+ }
+ Self::new()
+ .inspect_err(|error| {
+ eprintln!("[testkit] create isolated driver state root failed: {error}")
+ })
+ .ok()
+ }
+
+ /// Root directory standing in for the user's home.
+ pub fn path(&self) -> &Path {
+ self.dir.path()
+ }
+
+ /// Per-user state variables pointing into this root, plus any host
+ /// app-discovery location that must stay visible after `HOME` moves.
+ pub fn env(&self) -> Vec<(&'static str, PathBuf)> {
+ STATE_VARIABLES
+ .iter()
+ .map(|(name, relative)| (*name, self.dir.path().join(relative)))
+ .chain(host_discovery_env())
+ .collect()
+ }
+
+ /// Point every state variable at this root. Call before applying the
+ /// caller's environment so explicit caller values take precedence.
+ pub(crate) fn apply(&self, command: &mut Command) {
+ command.envs(self.env());
+ }
+}
+
+/// Apply an optional isolated root, then the caller's environment minus the
+/// testkit-only [`SHARE_HOST_STATE`] marker.
+pub(crate) fn apply_env(
+ command: &mut Command,
+ state_root: Option<&IsolatedStateRoot>,
+ env: &[(&str, &str)],
+) {
+ if let Some(root) = state_root {
+ root.apply(command);
+ }
+ for (key, value) in env {
+ if *key != SHARE_HOST_STATE.0 {
+ command.env(key, value);
+ }
+ }
+}
+
+pub(crate) fn shares_host_state(env: &[(&str, &str)]) -> bool {
+ env.iter().any(|(key, _)| *key == SHARE_HOST_STATE.0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn envs(command: &Command) -> Vec<(String, Option<String>)> {
+ command
+ .get_envs()
+ .map(|(key, value)| {
+ (
+ key.to_string_lossy().into_owned(),
+ value.map(|value| value.to_string_lossy().into_owned()),
+ )
+ })
+ .collect()
+ }
+
+ fn value_of(command: &Command, name: &str) -> Option<String> {
+ envs(command)
+ .into_iter()
+ .find(|(key, _)| key == name)
+ .and_then(|(_, value)| value)
+ }
+
+ #[test]
+ fn isolated_root_redirects_every_state_variable() {
+ let root = IsolatedStateRoot::for_env(&[]).expect("isolated root");
+ let mut command = Command::new("unused");
+ apply_env(&mut command, Some(&root), &[]);
+ for (name, relative) in STATE_VARIABLES {
+ let value = value_of(&command, name).unwrap_or_else(|| panic!("{name} not set"));
+ assert_eq!(Path::new(&value), root.path().join(relative));
+ assert!(Path::new(&value).is_dir(), "{name} directory must exist");
+ }
+ }
+
+ #[test]
+ fn host_app_discovery_locations_are_not_redirected() {
+ let root = IsolatedStateRoot::new().expect("isolated root");
+ let env = root.env();
+ for name in ["USERPROFILE", "APPDATA", "LOCALAPPDATA", "XDG_DATA_HOME"] {
+ if let Some((_, value)) = env.iter().find(|(key, _)| *key == name) {
+ assert!(
+ !value.starts_with(root.path()),
+ "{name} locates installed apps and must stay on the host"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn caller_values_override_isolated_defaults() {
+ let root = IsolatedStateRoot::for_env(&[("HOME", "/caller/home")]).expect("root");
+ let mut command = Command::new("unused");
+ apply_env(&mut command, Some(&root), &[("HOME", "/caller/home")]);
+ assert_eq!(value_of(&command, "HOME").as_deref(), Some("/caller/home"));
+ }
+
+ #[test]
+ fn share_marker_disables_isolation_and_is_not_forwarded() {
+ assert!(IsolatedStateRoot::for_env(&[SHARE_HOST_STATE]).is_none());
+ let mut command = Command::new("unused");
+ apply_env(&mut command, None, &[SHARE_HOST_STATE, ("A", "b")]);
+ assert_eq!(value_of(&command, SHARE_HOST_STATE.0), None);
+ assert_eq!(value_of(&command, "HOME"), None);
+ assert_eq!(value_of(&command, "A").as_deref(), Some("b"));
+ }
+}
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 c3519e0222..81e51fc24d 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
@@ -43,6 +43,7 @@ mod cli;
mod daemon;
mod driver;
pub mod e2e;
+mod host_state;
mod journal;
mod mcp;
pub mod observer;
@@ -56,6 +57,7 @@ mod windows_setup;
pub use browser_fixture::BrowserFixtureServer;
pub use cli::CliDriver;
pub use driver::{BehaviorRecording, Driver};
+pub use host_state::{IsolatedStateRoot, SHARE_HOST_STATE};
pub use journal::FixtureJournal;
pub use mcp::McpDriver;
pub use paths::{
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
index 6630e04bbf..e1fbcb4994 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
@@ -205,12 +205,13 @@ impl McpDriver {
.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);
}
- for (key, value) in &daemon_env {
- cmd.env(key, value);
- }
+ 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()?;
@@ -300,6 +301,13 @@ impl McpDriver {
)
}
+ /// 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": {}
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
index c65bcb7e6f..be8c76c0ab 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
@@ -15,6 +15,7 @@ use std::process::{ChildStdin, ChildStdout, Command, Stdio};
use serde_json::Value;
use crate::daemon::TestDaemon;
+use crate::host_state::IsolatedStateRoot;
use crate::paths::{driver_binary, ensure_driver_binary};
use crate::reaper::{spawn_in_job, ChildReaper};
@@ -23,6 +24,8 @@ use crate::reaper::{spawn_in_job, ChildReaper};
pub struct RawDriver {
_reaper: ChildReaper,
_daemon: Option<TestDaemon>,
+ /// State root for a direct runtime; daemon-backed drivers use the daemon's.
+ _state_root: Option<IsolatedStateRoot>,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
}
@@ -35,6 +38,15 @@ impl RawDriver {
self._daemon.as_ref().map(|daemon| daemon.pid)
}
+ /// Isolated per-user state root given to the spawned driver, or `None`
+ /// when the caller passed [`crate::SHARE_HOST_STATE`].
+ pub fn state_root(&self) -> Option<&std::path::Path> {
+ self._daemon
+ .as_ref()
+ .and_then(TestDaemon::state_root)
+ .or_else(|| self._state_root.as_ref().map(IsolatedStateRoot::path))
+ }
+
/// 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, unless `CUA_TEST_REQUIRE_DRIVER_BIN=1` makes a
@@ -88,6 +100,7 @@ impl RawDriver {
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
+ daemon.apply_state_root(&mut command);
let mut child = spawn_in_job(&mut command)
.inspect_err(|e| eprintln!("[testkit] driver spawn failed: {e}"))
.ok()?;
@@ -97,6 +110,7 @@ impl RawDriver {
Some(RawDriver {
_reaper: reaper,
_daemon: Some(daemon),
+ _state_root: None,
stdin,
stdout,
})
@@ -125,6 +139,9 @@ impl RawDriver {
return None;
}
let mut reaper = ChildReaper::new();
+ // A direct runtime owns its state just like a daemon, so it receives
+ // the same isolation from the developer's installed-product state.
+ let state_root = IsolatedStateRoot::for_env(&[])?;
let mut command = Command::new(&bin);
command
.args(args)
@@ -132,6 +149,7 @@ impl RawDriver {
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
+ state_root.apply(&mut command);
let mut child = spawn_in_job(&mut command)
.inspect_err(|e| eprintln!("[testkit] direct driver spawn failed: {e}"))
.ok()?;
@@ -141,6 +159,7 @@ impl RawDriver {
Some(Self {
_reaper: reaper,
_daemon: None,
+ _state_root: Some(state_root),
stdin,
stdout,
})
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
index c40dd92f43..f371240ced 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
@@ -9,8 +9,11 @@ use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use cua_driver_contract::{CaptureScope, GetSessionStateInput, StartSessionInput};
-use cua_driver_sdk::{CuaDriver, DriverError, EmbeddedCuaDriverHost, EmbeddedDriverHostState};
-use cua_driver_testkit::{spawn_in_job, ChildReaper};
+use cua_driver_sdk::{
+ CuaDriver, DriverError, EmbeddedCuaDriverHost, EmbeddedDriverHostOptions,
+ EmbeddedDriverHostState, EmbeddedEnvironmentVariable,
+};
+use cua_driver_testkit::{spawn_in_job, ChildReaper, IsolatedStateRoot};
use serde_json::{json, Value};
fn read_json(reader: &mut BufReader<std::process::ChildStdout>) -> Value {
@@ -19,6 +22,43 @@ fn read_json(reader: &mut BufReader<std::process::ChildStdout>) -> Value {
serde_json::from_str(line.trim()).expect("parse MCP response")
}
+/// Construct a host for the source-built driver with per-user state isolated
+/// from the developer's installed product (#4094). Keep the returned root alive
+/// for as long as the daemon runs.
+fn isolated_driver_host(
+ host_bundle_id: &str,
+) -> (std::sync::Arc<EmbeddedCuaDriverHost>, IsolatedStateRoot) {
+ let state = IsolatedStateRoot::new().expect("isolated driver state root");
+ let host = EmbeddedCuaDriverHost::with_options(EmbeddedDriverHostOptions {
+ binary_path: env!("CARGO_BIN_EXE_cua-driver").into(),
+ host_bundle_id: host_bundle_id.into(),
+ socket_path: None,
+ startup_timeout_ms: None,
+ shutdown_timeout_ms: None,
+ permission_mode: None,
+ capability_manifest_path: None,
+ approve_capability_manifest: false,
+ session_policy_path: None,
+ approve_session_policy: false,
+ dangerously_bypass_approvals: false,
+ environment: state
+ .env()
+ .into_iter()
+ // The SDK forwards only its safe allowlist; without XDG overrides
+ // the driver derives its XDG state from the isolated HOME.
+ .filter(|(name, _)| matches!(*name, "HOME" | "APPDATA" | "LOCALAPPDATA"))
+ .map(|(name, value)| EmbeddedEnvironmentVariable {
+ name: name.into(),
+ value: value.to_string_lossy().into_owned(),
+ })
+ .collect(),
+ inherit_stderr: true,
+ no_overlay: false,
+ })
+ .expect("construct host");
+ (host, state)
+}
+
fn tool_names(value: &Value, field: &str) -> BTreeSet<String> {
value[field]
.as_array()
@@ -77,11 +117,7 @@ fn write_test_shell_script(path: &std::path::Path, body: &str) {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn embedded_host_serves_sdk_and_mcp_with_one_contract() {
- let host = EmbeddedCuaDriverHost::new(
- env!("CARGO_BIN_EXE_cua-driver").into(),
- "com.trycua.embedded-contract-test".into(),
- )
- .expect("construct host");
+ let (host, _state) = isolated_driver_host("com.trycua.embedded-contract-test");
let connection = host.clone().start().await.expect("start embedded host");
assert_eq!(host.state(), EmbeddedDriverHostState::Ready);
@@ -235,11 +271,7 @@ async fn embedded_host_serves_sdk_and_mcp_with_one_contract() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn dropping_the_host_cannot_orphan_its_daemon() {
- let host = EmbeddedCuaDriverHost::new(
- env!("CARGO_BIN_EXE_cua-driver").into(),
- "com.trycua.embedded-drop-test".into(),
- )
- .expect("construct host");
+ let (host, _state) = isolated_driver_host("com.trycua.embedded-drop-test");
let connection = host.clone().start().await.expect("start embedded host");
drop(host);
@@ -262,11 +294,7 @@ async fn dropping_the_host_cannot_orphan_its_daemon() {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_start_coalesces_and_restart_rotates_generation() {
- let host = EmbeddedCuaDriverHost::new(
- env!("CARGO_BIN_EXE_cua-driver").into(),
- "com.trycua.embedded-lifecycle-test".into(),
- )
- .expect("construct host");
+ let (host, _state) = isolated_driver_host("com.trycua.embedded-lifecycle-test");
let (left, right, third) = tokio::join!(
host.clone().start(),
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
index b61131bee7..f44b70e949 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
@@ -1,10 +1,28 @@
+use cua_driver_testkit::IsolatedStateRoot;
+
use cua_driver_sdk::{
ConfiguredDriverOptions, DriverExecutionMode, EmbeddedDriverHostOptions,
EmbeddedEnvironmentVariable, EmbeddedPermissionMode, PrivateWorkerOptions,
RuntimeAuthorizationOptions, SessionPermissionMode, TrustedSessionOptions,
};
-fn worker_options() -> PrivateWorkerOptions {
+/// Per-user state variables for a source-built driver, isolated from the
+/// developer's installed product (#4094).
+fn isolated_environment(state: &IsolatedStateRoot) -> Vec<EmbeddedEnvironmentVariable> {
+ state
+ .env()
+ .into_iter()
+ // The SDK forwards only its safe allowlist; without XDG overrides the
+ // driver derives its XDG state from the isolated HOME.
+ .filter(|(name, _)| matches!(*name, "HOME" | "APPDATA" | "LOCALAPPDATA"))
+ .map(|(name, value)| EmbeddedEnvironmentVariable {
+ name: name.into(),
+ value: value.to_string_lossy().into_owned(),
+ })
+ .collect()
+}
+
+fn worker_options(state: &IsolatedStateRoot) -> PrivateWorkerOptions {
PrivateWorkerOptions {
binary_path: env!("CARGO_BIN_EXE_cua-driver").to_owned(),
host_bundle_id: "com.trycua.private-worker-test".into(),
@@ -25,14 +43,15 @@ fn worker_options() -> PrivateWorkerOptions {
max_idle_ttl_seconds: 30,
},
},
- environment: Vec::new(),
+ environment: isolated_environment(state),
inherit_stderr: true,
}
}
#[tokio::test]
async fn private_worker_owns_one_runtime_without_a_reconnect_endpoint() {
- let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options()).unwrap();
+ let state = IsolatedStateRoot::new().unwrap();
+ let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options(&state)).unwrap();
assert_eq!(driver.execution_mode(), DriverExecutionMode::PrivateWorker);
assert!(driver.socket_path().is_empty());
assert!(driver.is_available());
@@ -78,7 +97,8 @@ async fn private_worker_owns_one_runtime_without_a_reconnect_endpoint() {
#[cfg(target_os = "macos")]
#[tokio::test]
async fn private_worker_owns_the_macos_cursor_overlay_facility() {
- let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options()).unwrap();
+ let state = IsolatedStateRoot::new().unwrap();
+ let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options(&state)).unwrap();
let result = driver
.call_tool(
"get_agent_cursor_state".into(),
@@ -122,7 +142,8 @@ async fn private_worker_inherits_the_interactive_linux_display_scope() {
"canonical GUI E2E requires DISPLAY or WAYLAND_DISPLAY"
);
- let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options()).unwrap();
+ let state = IsolatedStateRoot::new().unwrap();
+ let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options(&state)).unwrap();
let standard = driver
.create_trusted_session(TrustedSessionOptions {
public_session: "worker-standard-display-scope".into(),
@@ -218,7 +239,8 @@ async fn private_worker_inherits_the_interactive_linux_display_scope() {
#[tokio::test]
async fn dropping_the_host_closes_and_terminates_the_private_worker() {
- let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options()).unwrap();
+ let state = IsolatedStateRoot::new().unwrap();
+ let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options(&state)).unwrap();
let pid = driver.metadata().await.unwrap().pid;
drop(driver);
@@ -238,6 +260,7 @@ async fn dropping_the_host_closes_and_terminates_the_private_worker() {
#[tokio::test]
async fn embedded_service_binds_authority_to_the_original_host_connection() {
+ let state = IsolatedStateRoot::new().unwrap();
let host = cua_driver_sdk::EmbeddedCuaDriverHost::with_options(EmbeddedDriverHostOptions {
binary_path: env!("CARGO_BIN_EXE_cua-driver").to_owned(),
host_bundle_id: "com.trycua.trusted-service-test".into(),
@@ -250,7 +273,7 @@ async fn embedded_service_binds_authority_to_the_original_host_connection() {
session_policy_path: None,
approve_session_policy: false,
dangerously_bypass_approvals: false,
- environment: Vec::<EmbeddedEnvironmentVariable>::new(),
+ environment: isolated_environment(&state),
inherit_stderr: true,
no_overlay: false,
})
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
index b8e7ca8201..8c6e98ddee 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
@@ -26,6 +26,7 @@ use cua_driver_testkit::observer::TargetWindow;
use cua_driver_testkit::sentinel::ForegroundSentinel;
use cua_driver_testkit::{
spawn_in_job, BrowserFixtureServer, Driver, McpDriver, RawDriver, ToolResponse,
+ SHARE_HOST_STATE,
};
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::Message;
@@ -754,6 +755,9 @@ fn profile_entries(root: &Path) -> HashSet<std::ffi::OsString> {
.collect()
}
+// Standalone browser E2E observes host-owned browser profiles and download
+// directories that must stay visible to sandboxed browser packages, so these
+// daemons deliberately share the runner's per-user state.
fn spawn_driver(label: &str) -> McpDriver {
#[cfg(target_os = "macos")]
let driver = McpDriver::spawn_macos_daemon_proxy_named(label);
@@ -765,6 +769,7 @@ fn spawn_driver(label: &str) -> McpDriver {
label,
&[
("SWAYSOCK", "/dev/null/cua-e2e-withheld"),
+ SHARE_HOST_STATE,
("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
],
@@ -773,6 +778,7 @@ fn spawn_driver(label: &str) -> McpDriver {
McpDriver::spawn_named_with_env(
label,
&[
+ SHARE_HOST_STATE,
("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
],
@@ -782,6 +788,7 @@ fn spawn_driver(label: &str) -> McpDriver {
let driver = McpDriver::spawn_named_with_env(
label,
&[
+ SHARE_HOST_STATE,
("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
],
@@ -794,6 +801,7 @@ fn spawn_standard_driver(label: &str) -> McpDriver {
McpDriver::spawn_named_with_env(
label,
&[
+ SHARE_HOST_STATE,
("CUA_DRIVER_PERMISSION_MODE", "standard"),
("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "0"),
],
@@ -2443,6 +2451,7 @@ fn standalone_browser_prepare_isolated_source_smoke() {
let driver_profiles = driver_profile_root();
let profiles_before = profile_entries(&driver_profiles);
let mut driver = RawDriver::spawn_with_env(&[
+ SHARE_HOST_STATE,
("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
])
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/testkit_host_state_isolation_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/testkit_host_state_isolation_test.rs
new file mode 100644
index 0000000000..da34d41ad5
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/testkit_host_state_isolation_test.rs
@@ -0,0 +1,95 @@
+//! Regression coverage for #4094: testkit-owned daemons must not inherit the
+//! developer's installed-product state.
+//!
+//! A maintainer machine with Computer History admitted keeps
+//! `{"history_preview_admitted":true}` in the per-user history root. A
+//! source-built daemon that reads it requests admission, fails installed-app
+//! verification, and exits before binding its socket, so every testkit
+//! transport silently becomes unavailable.
+//!
+//! This binary contains exactly one test so it can safely point its own
+//! `HOME` (and the platform state variables) at a temporary directory before
+//! any daemon starts. The real user's files are never touched.
+//!
+//! Windows is excluded: its History root derives from `LOCALAPPDATA`, which the
+//! testkit must leave on the host because `shell:AppsFolder` app resolution
+//! depends on it (see `cua-driver-testkit/src/host_state.rs`).
+#![cfg(not(target_os = "windows"))]
+
+use std::path::{Path, PathBuf};
+
+use cua_driver_testkit::{driver_binary, CliDriver, McpDriver, RawDriver, SHARE_HOST_STATE};
+
+/// Every per-user history root the driver may resolve for `home`.
+fn history_roots(home: &Path) -> Vec<PathBuf> {
+ let base = if cfg!(target_os = "macos") {
+ home.join("Library").join("Application Support")
+ } else {
+ home.join(".local").join("state")
+ };
+ ["cua-driver", "cua-driver-local"]
+ .into_iter()
+ .map(|namespace| base.join(namespace).join("computer-history"))
+ .collect()
+}
+
+fn seed_admitted_host_home() -> tempfile::TempDir {
+ let home = tempfile::Builder::new()
+ .prefix("cua-host-home-")
+ .tempdir()
+ .expect("temporary host home");
+ for root in history_roots(home.path()) {
+ std::fs::create_dir_all(&root).expect("history root");
+ std::fs::write(
+ root.join("admission.json"),
+ br#"{"history_preview_admitted":true}"#,
+ )
+ .expect("seed admission preference");
+ }
+ // Only this single-test binary's process environment changes; it runs
+ // before any thread or child exists.
+ std::env::set_var("HOME", home.path());
+ if !cfg!(target_os = "macos") {
+ std::env::set_var("XDG_STATE_HOME", home.path().join(".local").join("state"));
+ }
+ home
+}
+
+#[test]
+fn testkit_daemons_ignore_host_history_admission() {
+ if !driver_binary().exists() {
+ eprintln!("[skip] driver binary not built at {:?}", driver_binary());
+ return;
+ }
+ let host_home = seed_admitted_host_home();
+
+ // Control: sharing the seeded host state reproduces the original failure,
+ // proving the seed is the state that used to leak into test daemons.
+ assert!(
+ McpDriver::spawn_with_env(&[SHARE_HOST_STATE]).is_none(),
+ "a daemon sharing the admitted host state is expected to refuse to start; \
+ if product admission behavior changed, update this control"
+ );
+
+ let mcp =
+ McpDriver::spawn().expect("MCP testkit daemon must start despite host history admission");
+ let mcp_root = mcp.state_root().expect("MCP daemon uses an isolated root");
+ assert!(!mcp_root.starts_with(host_home.path()));
+
+ let raw =
+ RawDriver::spawn().expect("raw testkit daemon must start despite host history admission");
+ let raw_root = raw.state_root().expect("raw daemon uses an isolated root");
+ assert_ne!(raw_root, mcp_root, "each daemon owns its own state root");
+
+ let cli = CliDriver::new();
+ assert!(
+ cli.available(),
+ "CLI testkit daemon must start despite host history admission"
+ );
+ assert!(cli.state_root().is_some());
+
+ // The seeded host preference is still intact: isolation is read-side only.
+ for root in history_roots(host_home.path()) {
+ assert!(root.join("admission.json").is_file());
+ }
+}