Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): drain daemon state on shutdown (#3348)
r33drichardsaabb2082c170
diff --git a/.github/workflows/ci-cua-driver-valgrind.yml b/.github/workflows/ci-cua-driver-valgrind.ymlindex cb7ba6dc1d..20309e337c 100644--- a/.github/workflows/ci-cua-driver-valgrind.yml+++ b/.github/workflows/ci-cua-driver-valgrind.yml@@ -48,7 +48,7 @@ jobs:fisudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 updatesudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 install -y --no-install-recommends \- valgrind xvfb xauth dbus-x11 at-spi2-core clang pkg-config libdbus-1-dev \+ valgrind xvfb xauth dbus-x11 clang pkg-config libdbus-1-dev \libpipewire-0.3-dev libspa-0.2-dev libei-dev libxkbcommon-dev \libx11-dev libxi-dev libxtst-dev libxext-dev- name: Build cua-driver@@ -58,6 +58,7 @@ jobs:env:CUA_DRIVER_RS_TELEMETRY_ENABLED: "false"CUA_DRIVER_RS_UPDATE_CHECK: "false"+ NO_AT_BRIDGE: "1"CUA_VALGRIND_ARTIFACT_DIR: ${{ runner.temp }}/cua-driver-valgrindrun: dbus-run-session -- xvfb-run -a uv run --script scripts/ci/linux/run-valgrind-e2e.py libs/cua-driver/rust/target/debug/cua-driver- name: Upload Memcheck diagnosticsdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rsindex b0a28962d0..2625ee2ffa 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs@@ -1110,7 +1110,7 @@ pub fn authorize_tool_call(args: &Value,) -> Result<RiskAssessment, crate::policy::AuthorizationError> {let context = crate::session_authorization::configured_registry()- .and_then(crate::session_authorization::SessionAuthorizationRegistry::legacy_context)+ .and_then(|registry| registry.legacy_context()).map_err(crate::policy::AuthorizationError::Loading)?;authorize_tool_call_with_context(tool, args, context.as_ref())}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rsindex 830720d046..ddbd73f329 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs@@ -1121,6 +1121,57 @@ pub fn session_end_hook_count() -> usize {hooks().lock().unwrap().len()}+/// Release process-global session storage after the standalone daemon has+/// stopped all connection tasks and destroyed its only SDK runtime.+#[doc(hidden)]+pub fn release_process_state_for_shutdown() {+ if let Some(readers) = CURSOR_OUTCOME_READERS.get() {+ let mut readers = readers.lock().unwrap();+ readers.clear();+ readers.shrink_to_fit();+ }+ if let Some(readers) = RECORDING_STATE_READERS.get() {+ let mut readers = readers.lock().unwrap();+ readers.clear();+ readers.shrink_to_fit();+ }+ if let Some(registered) = SESSION_END_HOOKS.get() {+ let mut registered = registered.lock().unwrap();+ registered.clear();+ registered.shrink_to_fit();+ }+ if let Some(registered) = SESSION_REVIVE_HOOKS.get() {+ let mut registered = registered.lock().unwrap();+ registered.clear();+ registered.shrink_to_fit();+ }+ if let Some(progress) = SESSION_CLEANUP_PROGRESS.get() {+ let mut progress = progress.lock().unwrap();+ progress.clear();+ progress.shrink_to_fit();+ }+ if let Some(activity) = SESSION_ACTIVITY.get() {+ let mut activity = activity.lock().unwrap();+ activity.clear();+ activity.shrink_to_fit();+ }+ if let Some(records) = LIFECYCLE_RECORDS.get() {+ let mut records = records.lock().unwrap();+ records.clear();+ records.shrink_to_fit();+ }+ if let Some(ended) = ENDED_SESSIONS.get() {+ let mut ended = ended.lock().unwrap();+ ended.clear();+ ended.shrink_to_fit();+ }+ if let Some(scopes) = SUSPENDED_RUNTIME_SCOPES.get() {+ let mut scopes = scopes.lock().unwrap();+ scopes.clear();+ scopes.shrink_to_fit();+ }+}+/// Fan a session-end out to every registered cleanup hook. Called by the daemon/// on control-connection EOF (the reaper) and by the legacy `session_end` method/// arm. Idempotent: the FIRST fire for a given `session_id` runs every hook; anydiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rsindex f4563e310b..0557aba595 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs@@ -784,13 +784,23 @@ impl SessionAuthorizationRegistry {}}-static CONFIGURED_REGISTRY: OnceLock<Result<SessionAuthorizationRegistry, String>> =- OnceLock::new();+static CONFIGURED_REGISTRY: OnceLock<+ Mutex<Option<Result<Arc<SessionAuthorizationRegistry>, String>>>,+> = OnceLock::new();++pub fn configured_registry() -> Result<Arc<SessionAuthorizationRegistry>, String> {+ CONFIGURED_REGISTRY+ .get_or_init(|| Mutex::new(None))+ .lock()+ .unwrap()+ .get_or_insert_with(|| SessionAuthorizationRegistry::process().map(Arc::new))+ .clone()+}-pub fn configured_registry() -> Result<&'static SessionAuthorizationRegistry, String> {- match CONFIGURED_REGISTRY.get_or_init(SessionAuthorizationRegistry::process) {- Ok(registry) => Ok(registry),- Err(error) => Err(error.clone()),+#[doc(hidden)]+pub fn release_configured_registry_for_shutdown() {+ if let Some(registry) = CONFIGURED_REGISTRY.get() {+ *registry.lock().unwrap() = None;}}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rsindex c9d82805f0..b9405d0340 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs@@ -947,7 +947,7 @@ impl ToolRegistry {.await;}let context = match crate::session_authorization::configured_registry()- .and_then(crate::session_authorization::SessionAuthorizationRegistry::legacy_context)+ .and_then(|registry| registry.legacy_context()){Ok(context) => context,Err(error) => {@@ -965,7 +965,7 @@ impl ToolRegistry {pub async fn invoke_from_trusted_adapter(&self, name: &str, mut args: Value) -> ToolResult {let evidence = TrustedInvocationEvidence::extract_from_adapter_args(&mut args);let context = match crate::session_authorization::configured_registry()- .and_then(crate::session_authorization::SessionAuthorizationRegistry::legacy_context)+ .and_then(|registry| registry.legacy_context()){Ok(context) => context,Err(error) => {diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rsindex 4f9ba965fa..f6b8f214ab 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs@@ -1448,48 +1448,22 @@ impl NativeAbiDriver {}pub(crate) async fn shutdown(&self) -> Result<(), DriverError> {- let (receiver, guard) = {- let (sender, receiver) = oneshot::channel();- let context = Box::into_raw(Box::new(CallbackContext { sender })).cast::<c_void>();- let mut operation = ptr::null_mut();- let mut error = CuaDriverBuffer::empty();- let status = unsafe {- ffi::shutdown(- self.raw_handle(),- Some(rust_completion),- context,- &mut operation,- &mut error,- )- };- if status != CuaDriverStatus::Ok {- unsafe { drop(Box::from_raw(context.cast::<CallbackContext>())) };- status_result(status, &mut error, "shutdown embedded runtime")?;- return Err(DriverError::Protocol {- reason: "shutdown ABI invocation failed without an error".into(),- });+ let runtime = {+ let handle = *self.handle.lock().unwrap();+ if handle.is_null() {+ return Err(DriverError::Shutdown);+ }+ unsafe {+ handle+ .cast::<CuaDriverHandle>()+ .as_ref()+ .expect("live ABI handle is non-null")+ .runtime+ .clone()}- (- receiver,- OperationGuard {- operation,- completed: false,- },- )};- let completed = receiver.await.map_err(|_| DriverError::Protocol {- reason: "shutdown ABI completion callback was dropped".into(),- })?;- guard.complete();- if completed.status == CuaDriverStatus::Ok {- Ok(())- } else {- Err(map_status(- completed.status,- completed.error,- "shutdown embedded runtime",- ))- }+ runtime.shutdown().await;+ Ok(())}}diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rsindex e9bed70901..c69208fac1 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs@@ -20,7 +20,7 @@ use cursor_overlay::CursorConfig;use serde_json::Value;use std::sync::{atomic::{AtomicBool, AtomicU64, Ordering},- Arc,+ Arc, Mutex,};const RECORDING_IDLE_TTL_SECS_DEFAULT: u64 = 300;@@ -162,9 +162,15 @@ pub(crate) struct DriverRuntime {/// admission. Therefore shutdown is idempotent and does not return while a/// previously admitted operation is still executing.lifecycle: tokio::sync::RwLock<()>,+ lifecycle_maintenance: Mutex<Option<LifecycleMaintenance>>,activity_observer: Option<Arc<dyn DriverActivityObserver>>,}+struct LifecycleMaintenance {+ shutdown: std::sync::mpsc::Sender<()>,+ thread: std::thread::JoinHandle<()>,+}+impl DriverRuntime {pub(crate) fn create(options: RuntimeOptions) -> Result<Arc<Self>, RuntimeCreateError> {#[cfg(target_os = "windows")]@@ -198,9 +204,11 @@ impl DriverRuntime {shutdown: AtomicBool::new(false),last_activity: AtomicU64::new(now_unix_secs()),lifecycle: tokio::sync::RwLock::new(()),+ lifecycle_maintenance: Mutex::new(None),activity_observer: options.activity_observer.clone(),});- spawn_lifecycle_maintenance(&runtime);+ *runtime.lifecycle_maintenance.lock().unwrap() =+ Some(spawn_lifecycle_maintenance(&runtime));Ok(runtime)}@@ -215,6 +223,7 @@ impl DriverRuntime {pub(crate) async fn shutdown(&self) {self.shutdown.store(true, Ordering::Release);let _drained = self.lifecycle.write().await;+ self.stop_lifecycle_maintenance();self.authorization_registry.revoke_all();let runtime_prefix = format!("__cua_runtime_{}:",@@ -227,8 +236,16 @@ impl DriverRuntime {);cua_driver_core::element_token::global().clear_runtime_scope(&self.compatibility_context.runtime_scope_key());- let recording = self.registry.recording.clone();- let _ = tokio::task::spawn_blocking(move || recording.stop_owner(None)).await;+ let _ = self.registry.recording.stop_owner(None);+ }++ fn stop_lifecycle_maintenance(&self) {+ if let Some(maintenance) = self.lifecycle_maintenance.lock().unwrap().take() {+ let _ = maintenance.shutdown.send(());+ if maintenance.thread.thread().id() != std::thread::current().id() {+ let _ = maintenance.thread.join();+ }+ }}pub(crate) fn tools_list(&self) -> Option<Value> {@@ -429,7 +446,8 @@ fn activity_lifecycle_event(impl Drop for DriverRuntime {fn drop(&mut self) {- self.shutdown.store(true, Ordering::Release);+ let was_running = !self.shutdown.swap(true, Ordering::AcqRel);+ self.stop_lifecycle_maintenance();self.authorization_registry.revoke_all();let runtime_scope = self.compatibility_context.runtime_scope_key();let runtime_prefix = format!("__cua_runtime_{runtime_scope}:");@@ -440,10 +458,10 @@ impl Drop for DriverRuntime {// Explicit `shutdown()` drains work and finalizes recordings. Drop is// runtime-scoped and non-blocking so a retained binding cannot affect// another generation.- let recording = self.registry.recording.clone();- std::thread::spawn(move || {+ if was_running {+ let recording = self.registry.recording.clone();let _ = recording.stop_owner(None);- });+ }}}@@ -472,8 +490,9 @@ fn now_unix_secs() -> u64 {.as_secs()}-fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) {+fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) -> LifecycleMaintenance {let runtime = Arc::downgrade(runtime);+ let (shutdown, shutdown_rx) = std::sync::mpsc::channel();let recording_ttl = configured_ttl("CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS",RECORDING_IDLE_TTL_SECS_DEFAULT,@@ -482,8 +501,13 @@ fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) {"CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS",SESSION_IDLE_TTL_SECS_DEFAULT,));- std::thread::spawn(move || loop {- std::thread::sleep(std::time::Duration::from_secs(30));+ let thread = std::thread::spawn(move || loop {+ if shutdown_rx+ .recv_timeout(std::time::Duration::from_secs(30))+ .is_ok()+ {+ break;+ }let Some(runtime) = runtime.upgrade() else {break;};@@ -509,6 +533,7 @@ fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) {let _ = runtime.registry.recording.stop_owner(None);}});+ LifecycleMaintenance { shutdown, thread }}/// Build the canonical SDK tool inventory without acquiring runtime ownership.@@ -632,9 +657,11 @@ fn configure_linux_runtime(prepare_desktop_environment: bool) {if prepare_desktop_environment {platform_linux::xauth::ensure_xauthority_discovered();platform_linux::session_bus::ensure_session_bus_discovered();- platform_linux::a11y::ensure_chromium_accessibility_enabled();- if let Err(error) = platform_linux::atspi::ensure_listener_active() {- tracing::warn!("could not activate the persistent AT-SPI listener: {error}");+ if std::env::var_os("NO_AT_BRIDGE").as_deref() != Some(std::ffi::OsStr::new("1")) {+ platform_linux::a11y::ensure_chromium_accessibility_enabled();+ if let Err(error) = platform_linux::atspi::ensure_listener_active() {+ tracing::warn!("could not activate the persistent AT-SPI listener: {error}");+ }}}cua_driver_core::recording::set_screenshot_fn(|window_id, pid| {@@ -872,4 +899,15 @@ mod tests {runtime.shutdown().await;}++ #[tokio::test]+ async fn shutdown_joins_lifecycle_maintenance() {+ let _runtime_test = TEST_RUNTIME_LOCK.lock().unwrap();+ let runtime = DriverRuntime::create(standard_options()).unwrap();+ assert!(runtime.lifecycle_maintenance.lock().unwrap().is_some());++ runtime.shutdown().await;++ assert!(runtime.lifecycle_maintenance.lock().unwrap().is_none());+ }}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rsindex 3e64dff007..aef5e68db1 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs@@ -140,6 +140,14 @@ fn active_proxy_sessions() -> &'static Mutex<HashSet<String>> {ACTIVE_PROXY_SESSIONS.get_or_init(|| Mutex::new(HashSet::new()))}+fn release_active_proxy_sessions() {+ if let Some(sessions) = ACTIVE_PROXY_SESSIONS.get() {+ let mut sessions = sessions.lock().unwrap();+ sessions.clear();+ sessions.shrink_to_fit();+ }+}+fn is_active_proxy_session(session: Option<&str>) -> bool {session.is_some_and(|session| active_proxy_sessions().lock().unwrap().contains(session))}@@ -992,6 +1000,7 @@ pub async fn run_serve(let shutdown_tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx)));let trusted_resume_registry: TrustedResumeRegistry =std::sync::Arc::new(tokio::sync::Mutex::new(HashMap::new()));+ let mut connection_tasks = tokio::task::JoinSet::new();let parent_liveness = async {if cua_driver_core::parent_liveness_stdin_enabled() {wait_for_parent_stdin_eof().await;@@ -1022,7 +1031,7 @@ pub async fn run_serve(let shutdown_tx2 = shutdown_tx.clone();let trusted_resume_registry = trusted_resume_registry.clone();- tokio::spawn(async move {+ connection_tasks.spawn(async move {let (reader, mut writer) = stream.into_split();let mut lines = BufReader::new(reader).lines();@@ -1395,6 +1404,11 @@ pub async fn run_serve(}}+ // Accepted connections may still own SDK/session state after the listener+ // stops. Abort and join them before tearing down the SDK runtime.+ connection_tasks.shutdown().await;+ release_active_proxy_sessions();+// Do not unlink a replacement socket created after this listener was bound.remove_owned_socket(socket_path, bound_socket);if let Some(pid_path) = pid_file_path {@@ -2212,7 +2226,11 @@ pub fn run_serve_cmd(std::process::exit(1);}};- if let Err(e) = rt.block_on(run_serve(sdk, &socket_path, pid_file_path.as_deref())) {+ let result = rt.block_on(run_serve(sdk, &socket_path, pid_file_path.as_deref()));+ rt.shutdown_timeout(std::time::Duration::from_secs(30));+ cua_driver_core::session_authorization::release_configured_registry_for_shutdown();+ cua_driver_core::session::release_process_state_for_shutdown();+ if let Err(e) = result {eprintln!("cua-driver serve error: {e}");std::process::exit(1);}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/clipboard.rs b/libs/cua-driver/rust/crates/platform-linux/src/clipboard.rsindex f6a930f434..af0e8be551 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/clipboard.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/clipboard.rs@@ -1,23 +1,29 @@-use std::{path::Path, sync::Mutex};+use std::{+ path::Path,+ sync::{Mutex, OnceLock},+};use clipboard_rs::{common::RustImage, Clipboard, ClipboardContext, ContentFormat};use cua_driver_core::clipboard::ClipboardBackend;pub struct LinuxClipboard {- context: Result<Mutex<ClipboardContext>, String>,+ context: OnceLock<Result<Mutex<ClipboardContext>, String>>,}impl LinuxClipboard {pub fn new() -> Self {Self {- context: ClipboardContext::new()- .map(Mutex::new)- .map_err(|error| error.to_string()),+ context: OnceLock::new(),}}fn context(&self) -> Result<std::sync::MutexGuard<'_, ClipboardContext>, String> {self.context+ .get_or_init(|| {+ ClipboardContext::new()+ .map(Mutex::new)+ .map_err(|error| error.to_string())+ }).as_ref().map_err(Clone::clone)?.lock()@@ -75,6 +81,12 @@ impl ClipboardBackend for LinuxClipboard {mod tests {use super::*;+ #[test]+ fn construction_does_not_start_native_clipboard() {+ let backend = LinuxClipboard::new();+ assert!(backend.context.get().is_none());+ }+#[test]fn rejects_relative_local_paths_before_clipboard_access() {let backend = LinuxClipboard::new();diff --git a/scripts/ci/linux/run-valgrind-e2e.py b/scripts/ci/linux/run-valgrind-e2e.pyindex 10c17f6b8f..4236f8fd4f 100755--- a/scripts/ci/linux/run-valgrind-e2e.py+++ b/scripts/ci/linux/run-valgrind-e2e.py@@ -186,6 +186,64 @@ def load_json(path: Path):return json.loads(path.read_text(encoding="utf-8"))+def configure_runtime_environment(env: dict[str, str]) -> None:+ # Do not let glibc retain joined thread stacks, which obscures ownership at exit.+ stack_cache_tunable = "glibc.pthread.stack_cache_size=0"+ current = env.get("GLIBC_TUNABLES", "")+ if stack_cache_tunable not in current.split(":"):+ env["GLIBC_TUNABLES"] = f"{current}:{stack_cache_tunable}".lstrip(":")+++def build_server_command(+ driver: Path,+ artifact_dir: Path,+ socket_path: Path,+ *,+ memcheck_disabled: bool,+) -> list[str]:+ driver_command = [+ str(driver),+ "serve",+ "--socket",+ str(socket_path),+ "--no-overlay",+ "--dangerously-bypass-approvals",+ ]+ if memcheck_disabled:+ return driver_command+ return [+ "valgrind",+ "--leak-check=full",+ "--show-leak-kinds=definite,possible",+ "--errors-for-leak-kinds=definite,possible",+ "--error-exitcode=99",+ f"--log-file={artifact_dir / 'valgrind.log'}",+ *driver_command,+ ]+++def build_readiness_command(driver: Path, socket_path: Path) -> list[str]:+ return [+ str(driver),+ "sessions",+ "list",+ "--json",+ "--socket",+ str(socket_path),+ ]+++def build_list_apps_command(driver: Path, socket_path: Path) -> list[str]:+ return [+ str(driver),+ "call",+ "list_apps",+ "{}",+ "--socket",+ str(socket_path),+ ]++def expect(condition: bool, message: str) -> None:"""Fail validation explicitly; bare assert is stripped under PYTHONOPTIMIZE."""if not condition:@@ -195,7 +253,7 @@ def expect(condition: bool, message: str) -> None:def validate_results(artifact_dir: Path) -> None:before = load_json(artifact_dir / "config-before.json")after = load_json(artifact_dir / "config-after.json")- permissions = load_json(artifact_dir / "permissions.json")+ apps = load_json(artifact_dir / "apps.json")sessions_before = load_json(artifact_dir / "sessions-before.json")sessions_after = load_json(artifact_dir / "sessions-after.json")@@ -208,7 +266,7 @@ def validate_results(artifact_dir: Path) -> None:after["max_image_dimension"] != before["max_image_dimension"],"set_config did not change max_image_dimension",)- expect(permissions["x11"] is True, f"x11 permission is {permissions.get('x11')!r}")+ expect(isinstance(apps.get("apps"), list), f"list_apps did not return an app list: {apps!r}")expect(sessions_before == {"count": 0, "sessions": []},f"unexpected sessions before MCP: {sessions_before!r}",@@ -290,31 +348,13 @@ def run_e2e(driver: Path, artifact_dir: Path, smoke_dir: Path, env: dict[str, stcommands_log = artifact_dir / "commands.log"memcheck_disabled = env.get("CUA_DRIVER_MEMCHECK_DISABLE", "0") == "1"- server_command = [- "valgrind",- "--leak-check=full",- "--gen-suppressions=all",- "--num-callers=40",- "--show-leak-kinds=definite,possible",- "--errors-for-leak-kinds=definite,possible",- "--error-exitcode=99",- f"--log-file={artifact_dir / 'valgrind.log'}",- str(driver),- "serve",- "--socket",- str(socket_path),- "--no-overlay",- "--dangerously-bypass-approvals",- ]- if memcheck_disabled:- server_command = [- str(driver),- "serve",- "--socket",- str(socket_path),- "--no-overlay",- "--dangerously-bypass-approvals",- ]+ configure_runtime_environment(env)+ server_command = build_server_command(+ driver,+ artifact_dir,+ socket_path,+ memcheck_disabled=memcheck_disabled,+ )commands_log.write_text(f"server command: {shlex.join(server_command)}\n", encoding="utf-8")server_stdout = (artifact_dir / "server.stdout").open("wb")@@ -349,10 +389,10 @@ def run_e2e(driver: Path, artifact_dir: Path, smoke_dir: Path, env: dict[str, straise RunnerFailure("cua-driver server exited before readiness")try:completed = run_client(- [str(driver), "status", "--socket", str(socket_path)],+ build_readiness_command(driver, socket_path),env=env,timeout=3,- stdout=artifact_dir / "status.txt",+ stdout=artifact_dir / "readiness.json",stderr=client_log,check=False,)@@ -365,13 +405,12 @@ def run_e2e(driver: Path, artifact_dir: Path, smoke_dir: Path, env: dict[str, stif not ready:raise RunnerFailure("cua-driver server did not become ready within 60 seconds")+ readiness = load_json(artifact_dir / "readiness.json")expect(- "running"- in (artifact_dir / "status.txt").read_text(encoding="utf-8", errors="replace").lower(),- "cua-driver status did not report a running daemon",+ readiness == {"count": 0, "sessions": []},+ f"fresh daemon reported unexpected sessions: {readiness!r}",)recorded_commands = [- [str(driver), "status", "--socket", str(socket_path)],[str(driver), "sessions", "list", "--json", "--socket", str(socket_path)],[str(driver), "call", "get_config", "{}", "--socket", str(socket_path)],[@@ -382,7 +421,7 @@ def run_e2e(driver: Path, artifact_dir: Path, smoke_dir: Path, env: dict[str, st"--socket",str(socket_path),],- [str(driver), "call", "check_permissions", "{}", "--socket", str(socket_path)],+ build_list_apps_command(driver, socket_path),[str(driver), "mcp", "--socket", str(socket_path)],stop_command,]@@ -421,10 +460,10 @@ def run_e2e(driver: Path, artifact_dir: Path, smoke_dir: Path, env: dict[str, ststdout=artifact_dir / "config-after.json",)run_client(- [str(driver), "call", "check_permissions", "{}", "--socket", str(socket_path)],+ build_list_apps_command(driver, socket_path),env=env,timeout=10,- stdout=artifact_dir / "permissions.json",+ stdout=artifact_dir / "apps.json",)requests = smoke_dir / "mcp-requests.jsonl"diff --git a/scripts/ci/linux/test_run_valgrind_e2e.py b/scripts/ci/linux/test_run_valgrind_e2e.pyindex fc6e14bced..a521529516 100644--- a/scripts/ci/linux/test_run_valgrind_e2e.py+++ b/scripts/ci/linux/test_run_valgrind_e2e.py@@ -15,6 +15,10 @@ sys.modules[SPEC.name] = RUNNERSPEC.loader.exec_module(RUNNER)ShutdownTimeouts = RUNNER.ShutdownTimeouts+build_list_apps_command = RUNNER.build_list_apps_command+build_readiness_command = RUNNER.build_readiness_command+build_server_command = RUNNER.build_server_command+configure_runtime_environment = RUNNER.configure_runtime_environmentresolve_exit_status = RUNNER.resolve_exit_statusshutdown_server = RUNNER.shutdown_server@@ -28,6 +32,79 @@ HELPER_TIMEOUTS = ShutdownTimeouts()+class RunnerConfigurationTests(unittest.TestCase):+ def test_runtime_environment_disables_glibc_thread_stack_cache(self):+ env = {"GLIBC_TUNABLES": "glibc.malloc.trim_threshold=0"}++ configure_runtime_environment(env)++ self.assertEqual(+ env["GLIBC_TUNABLES"],+ "glibc.malloc.trim_threshold=0:glibc.pthread.stack_cache_size=0",+ )++ def test_runtime_environment_is_idempotent(self):+ env = {"GLIBC_TUNABLES": "glibc.pthread.stack_cache_size=0"}++ configure_runtime_environment(env)++ self.assertEqual(env["GLIBC_TUNABLES"], "glibc.pthread.stack_cache_size=0")++ def test_server_command_uses_focused_memcheck_options(self):+ command = build_server_command(+ Path("/tmp/cua-driver"),+ Path("/tmp/artifacts"),+ Path("/tmp/cua-driver.sock"),+ memcheck_disabled=False,+ )++ self.assertIn("--leak-check=full", command)+ self.assertIn("--errors-for-leak-kinds=definite,possible", command)+ self.assertNotIn("--gen-suppressions=all", command)+ self.assertNotIn("--num-callers=40", command)++ def test_server_command_without_memcheck_runs_driver_directly(self):+ command = build_server_command(+ Path("/tmp/cua-driver"),+ Path("/tmp/artifacts"),+ Path("/tmp/cua-driver.sock"),+ memcheck_disabled=True,+ )++ self.assertEqual(command[0], "/tmp/cua-driver")+ self.assertNotIn("valgrind", command)++ def test_readiness_uses_empty_sessions_contract(self):+ command = build_readiness_command(Path("/tmp/cua-driver"), Path("/tmp/cua-driver.sock"))++ self.assertEqual(+ command,+ [+ "/tmp/cua-driver",+ "sessions",+ "list",+ "--json",+ "--socket",+ "/tmp/cua-driver.sock",+ ],+ )++ def test_smoke_call_uses_list_apps(self):+ command = build_list_apps_command(Path("/tmp/cua-driver"), Path("/tmp/cua-driver.sock"))++ self.assertEqual(+ command,+ [+ "/tmp/cua-driver",+ "call",+ "list_apps",+ "{}",+ "--socket",+ "/tmp/cua-driver.sock",+ ],+ )++class ShutdownServerTests(unittest.TestCase):def setUp(self):self.temp_dir = tempfile.TemporaryDirectory()