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): stop unit tests mutating the process environment (#6417)
injaneity5fd41d86b4c3
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rsindex 07a79e8c3b..140abbfa2f 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs@@ -176,12 +176,15 @@ fn text(result: &ToolResult) -> String {#[tokio::test]async fn every_step_but_the_last_is_paced_as_a_batched_step() {use crate::step_pacing::StepPacing::{Batched, Single};+ // Each batch that types uses its own pid: text input admission is a+ // process-wide per-pid lock, so parallel tests sharing one pid refuse+ // each other with `input_busy`.let harness = Harness::new();let result = harness.run(json!({"steps": [- {"tool": "click", "args": {"pid": 42, "window_id": 7}},- {"tool": "type_text", "args": {"pid": 42, "text": "b"}},- {"tool": "press_key", "args": {"pid": 42}},+ {"tool": "click", "args": {"pid": 43, "window_id": 7}},+ {"tool": "type_text", "args": {"pid": 43, "text": "b"}},+ {"tool": "press_key", "args": {"pid": 43}},]})).await;assert_ne!(result.is_error, Some(true), "{}", text(&result));@@ -221,9 +224,9 @@ async fn runs_steps_in_order_and_reports_each() {let harness = Harness::new();let result = harness.run(json!({"steps": [- {"tool": "set_value", "args": {"pid": 42, "window_id": 7, "text": "a"}},- {"tool": "type_text", "args": {"pid": 42, "text": "b"}},- {"tool": "press_key", "args": {"pid": 42}},+ {"tool": "set_value", "args": {"pid": 44, "window_id": 7, "text": "a"}},+ {"tool": "type_text", "args": {"pid": 44, "text": "b"}},+ {"tool": "press_key", "args": {"pid": 44}},]})).await;assert_ne!(result.is_error, Some(true), "{}", text(&result));@@ -346,15 +349,15 @@ async fn observation_inherits_the_window_and_stays_bounded() {let result = harness.run(json!({"steps": [- {"tool": "click", "args": {"pid": 42, "window_id": 7}},- {"tool": "type_text", "args": {"pid": 42, "text": "x"}},+ {"tool": "click", "args": {"pid": 45, "window_id": 7}},+ {"tool": "type_text", "args": {"pid": 45, "text": "x"}},],"observe": {}})).await;assert_ne!(result.is_error, Some(true), "{}", text(&result));let observed = harness.last("get_window_state");- assert_eq!(observed["pid"], 42);+ assert_eq!(observed["pid"], 45);assert_eq!(observed["window_id"], 7);assert_eq!(observed["include_screenshot"], false);assert_eq!(diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rsindex e873f729b8..3cd70f0f62 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs@@ -39,7 +39,12 @@ pub const PARENT_LIVENESS_STDIN_ENV: &str = "CUA_DRIVER_PARENT_LIVENESS_STDIN";/// Only the exact value `1` counts — fail-safe for anything else.pub fn embedded_mode() -> bool {- std::env::var_os(EMBEDDED_ENV).is_some_and(|v| v == "1")+ is_embedded_sentinel(std::env::var_os(EMBEDDED_ENV).as_deref())+}++/// The [`EMBEDDED_ENV`] rule on an already-read value.+pub fn is_embedded_sentinel(value: Option<&std::ffi::OsStr>) -> bool {+ value.is_some_and(|v| v == "1")}/// Parent-EOF shutdown is valid only for a directly embedded daemon. Requiringdiff --git a/libs/cua-driver/rust/crates/cua-driver/src/bundle.rs b/libs/cua-driver/rust/crates/cua-driver/src/bundle.rsindex 3acc584956..98da60f0e5 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/bundle.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/bundle.rs@@ -108,12 +108,12 @@ pub fn is_executable_inside_cuadriver_app() -> bool {/// (case-insensitive). Anything else, including unset, is falsy.#[cfg(target_os = "windows")]pub fn is_env_truthy(name: &str) -> bool {- match std::env::var(name) {- Ok(value) => matches!(+ match crate::env_vars::var(name) {+ Some(value) => matches!(value.trim().to_ascii_lowercase().as_str(),"1" | "true" | "yes" | "on"),- Err(_) => false,+ None => false,}}@@ -139,14 +139,14 @@ mod tests {#[test]fn env_truthiness_is_strict() {let name = "CUA_DRIVER_RS_TEST_TRUTHY";+ let mut env = crate::env_vars::Overrides::new();for value in ["1", "true", "TRUE", "Yes", "on", " 1 "] {- std::env::set_var(name, value);+ env.set(name, value);assert!(is_env_truthy(name), "expected truthy for {value:?}");}for value in ["0", "false", "no", "off", ""] {- std::env::set_var(name, value);+ env.set(name, value);assert!(!is_env_truthy(name), "expected falsy for {value:?}");}- std::env::remove_var(name);}}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/env_vars.rs b/libs/cua-driver/rust/crates/cua-driver/src/env_vars.rsnew file mode 100644index 0000000000..efe617f5cb--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/src/env_vars.rs@@ -0,0 +1,119 @@+//! Process-environment reads that unit tests can override per thread.+//!+//! Unit tests share one process and run on parallel threads, so they must+//! never call `std::env::set_var` or `remove_var`. On glibc that can free the+//! `environ` array while another thread walks it, and libc's own readers (the+//! resolver inside `getaddrinfo`, libX11) take no lock, so the test binary+//! crashes with SIGSEGV. Tests use [`Overrides`] instead; it only affects the+//! calling thread and the child processes it configures with+//! [`Overrides::apply`].++use std::ffi::OsString;++/// `std::env::var_os`, seen through the calling test thread's overrides.+pub(crate) fn var_os(name: &str) -> Option<OsString> {+ #[cfg(test)]+ if let Some(value) = overrides::get(name) {+ return value;+ }+ std::env::var_os(name)+}++/// `std::env::var(name).ok()`, seen through the calling test thread's overrides.+pub(crate) fn var(name: &str) -> Option<String> {+ var_os(name).and_then(|value| value.into_string().ok())+}++#[cfg(test)]+pub(crate) use overrides::Overrides;++#[cfg(test)]+mod overrides {+ use std::cell::RefCell;+ use std::collections::HashMap;+ use std::ffi::{OsStr, OsString};++ thread_local! {+ static OVERRIDES: RefCell<HashMap<String, Option<OsString>>> = RefCell::new(HashMap::new());+ }++ pub(super) fn get(name: &str) -> Option<Option<OsString>> {+ OVERRIDES.with(|map| map.borrow().get(name).cloned())+ }++ /// Thread-local environment overrides, restored when dropped.+ #[must_use]+ #[derive(Default)]+ pub(crate) struct Overrides {+ saved: Vec<(String, Option<Option<OsString>>)>,+ }++ impl Overrides {+ pub(crate) fn new() -> Self {+ Self::default()+ }++ pub(crate) fn set(&mut self, name: &str, value: impl AsRef<OsStr>) -> &mut Self {+ self.put(name, Some(value.as_ref().to_owned()))+ }++ pub(crate) fn unset(&mut self, name: &str) -> &mut Self {+ self.put(name, None)+ }++ fn put(&mut self, name: &str, value: Option<OsString>) -> &mut Self {+ let previous = OVERRIDES.with(|map| map.borrow_mut().insert(name.to_owned(), value));+ if !self.saved.iter().any(|(saved, _)| saved == name) {+ self.saved.push((name.to_owned(), previous));+ }+ self+ }++ /// Give a child process this thread's view of the environment.+ pub(crate) fn apply(command: &mut std::process::Command) {+ OVERRIDES.with(|map| {+ for (name, value) in map.borrow().iter() {+ match value {+ Some(value) => command.env(name, value),+ None => command.env_remove(name),+ };+ }+ });+ }+ }++ impl Drop for Overrides {+ fn drop(&mut self) {+ OVERRIDES.with(|map| {+ let mut map = map.borrow_mut();+ for (name, previous) in self.saved.drain(..).rev() {+ match previous {+ Some(value) => map.insert(name, value),+ None => map.remove(&name),+ };+ }+ });+ }+ }++ #[test]+ fn overrides_are_per_thread_and_restored_on_drop() {+ let name = "CUA_DRIVER_ENV_VARS_TEST_ONLY";+ {+ let mut env = Overrides::new();+ env.set(name, "outer");+ {+ let mut inner = Overrides::new();+ inner.set(name, "inner");+ assert_eq!(super::var(name).as_deref(), Some("inner"));+ std::thread::spawn(move || assert_eq!(super::var(name), None))+ .join()+ .unwrap();+ }+ assert_eq!(super::var(name).as_deref(), Some("outer"));+ env.unset(name);+ assert_eq!(super::var(name), None);+ }+ assert_eq!(get(name), None);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/extension_manager.rs b/libs/cua-driver/rust/crates/cua-driver/src/extension_manager.rsindex 7f0fb845b3..460c4bb6df 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/extension_manager.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/extension_manager.rs@@ -676,7 +676,7 @@ impl Tool for InstallExtensionTool {}fn install_extension_from_mcp(confirmed: bool) -> Result<(String, serde_json::Value)> {- let catalog = std::env::var_os("CUA_DRIVER_PERCEPTION_CATALOG")+ let catalog = crate::env_vars::var_os("CUA_DRIVER_PERCEPTION_CATALOG").filter(|value| !value.is_empty()).map(PathBuf::from).ok_or_else(|| anyhow!("CUA_DRIVER_PERCEPTION_CATALOG must name the reviewed signed catalog at daemon launch"))?;@@ -1049,7 +1049,9 @@ fn registry_entry(id: &str) -> Result<&'static RegistryEntry> {}fn extension_root() -> Result<PathBuf> {- if let Some(home) = std::env::var_os("CUA_DRIVER_RS_HOME").filter(|value| !value.is_empty()) {+ if let Some(home) =+ crate::env_vars::var_os("CUA_DRIVER_RS_HOME").filter(|value| !value.is_empty())+ {return Ok(PathBuf::from(home).join("extensions"));}#[cfg(windows)]@@ -7283,13 +7285,12 @@ mod tests {#[cfg(feature = "review-trust-root")]#[test]fn mcp_install_requires_confirm_after_returning_the_exact_verified_plan() {- static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());- let _guard = ENV_LOCK.lock().unwrap();let temp = TempDir::new().unwrap();let (_archive, catalog) = review_fixture(temp.path());let home = temp.path().join("driver-home");- std::env::set_var("CUA_DRIVER_RS_HOME", &home);- std::env::set_var("CUA_DRIVER_PERCEPTION_CATALOG", &catalog);+ let mut env = crate::env_vars::Overrides::new();+ env.set("CUA_DRIVER_RS_HOME", &home)+ .set("CUA_DRIVER_PERCEPTION_CATALOG", &catalog);let (_, plan) = install_extension_from_mcp(false).unwrap();assert_eq!(plan["extension"], "perception");@@ -7341,9 +7342,6 @@ mod tests {assert_eq!(installed["authorization"]["mutation_performed"], true);assert_eq!(installed["mutation_performed"], true);assert!(home.join("extensions/cua-perception/active.json").is_file());-- std::env::remove_var("CUA_DRIVER_PERCEPTION_CATALOG");- std::env::remove_var("CUA_DRIVER_RS_HOME");}fn test_catalog_payload(key_id: &str, version: u64) -> CatalogPayload {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex 891da82b38..3593ca408b 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -26,6 +26,7 @@ mod doctor;mod driver_service_http;#[cfg(any(target_os = "macos", all(test, unix)))]mod duplicate_copies;+mod env_vars;mod extension_manager;mod history_runtime;mod mcp_envelope;diff --git a/libs/cua-driver/rust/crates/cua-driver/src/release_channel.rs b/libs/cua-driver/rust/crates/cua-driver/src/release_channel.rsindex 2e9e70bee9..68bf4340c0 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/release_channel.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/release_channel.rs@@ -122,11 +122,11 @@ fn set_at(path: &std::path::Path, channel: ReleaseChannel) -> Result<(), String>}pub fn state_path() -> Result<PathBuf, String> {- if let Some(home) = std::env::var_os("CUA_DRIVER_RS_HOME") {+ if let Some(home) = crate::env_vars::var_os("CUA_DRIVER_RS_HOME") {return Ok(PathBuf::from(home).join(FILE_NAME));}- let root = std::env::var_os("HOME")- .or_else(|| std::env::var_os("USERPROFILE"))+ let root = crate::env_vars::var_os("HOME")+ .or_else(|| crate::env_vars::var_os("USERPROFILE")).ok_or_else(|| "neither HOME nor USERPROFILE is set".to_owned())?;Ok(PathBuf::from(root).join(crate::bundle::user_home_subdirectory())diff --git a/libs/cua-driver/rust/crates/cua-driver/src/release_source.rs b/libs/cua-driver/rust/crates/cua-driver/src/release_source.rsindex a1094087f8..6601a7dcc1 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/release_source.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/release_source.rs@@ -246,8 +246,7 @@ impl Default for Endpoints {/// installer. Empty values count as unset.pub(crate) fn token_from_env() -> Option<String> {["GH_TOKEN", "GITHUB_TOKEN"].iter().find_map(|name| {- std::env::var(name)- .ok()+ crate::env_vars::var(name).map(|value| value.trim().to_owned()).filter(|value| !value.is_empty())})@@ -566,7 +565,6 @@ fn feed_tags(feed: &str) -> Vec<String> {mod tests {use super::*;use std::cell::RefCell;- use std::collections::HashMap;/// Scripted HTTP client. Responses are keyed by URL prefix; every call is/// recorded with the bearer token it carried.@@ -1020,32 +1018,13 @@ mod tests {#[test]fn token_env_prefers_gh_token_and_ignores_blank_values() {- let _guard = crate::version_check::ENV_LOCK- .lock()- .unwrap_or_else(|e| e.into_inner());- let saved: HashMap<&str, Option<std::ffi::OsString>> = ["GH_TOKEN", "GITHUB_TOKEN"]- .iter()- .map(|name| (*name, std::env::var_os(name)))- .collect();- unsafe {- std::env::set_var("GH_TOKEN", " ");- std::env::set_var("GITHUB_TOKEN", "from-github-token");- }+ let mut env = crate::env_vars::Overrides::new();+ env.set("GH_TOKEN", " ")+ .set("GITHUB_TOKEN", "from-github-token");assert_eq!(token_from_env().as_deref(), Some("from-github-token"));- unsafe {- std::env::set_var("GH_TOKEN", "from-gh-token");- }+ env.set("GH_TOKEN", "from-gh-token");assert_eq!(token_from_env().as_deref(), Some("from-gh-token"));- unsafe {- std::env::remove_var("GH_TOKEN");- std::env::remove_var("GITHUB_TOKEN");- }+ env.unset("GH_TOKEN").unset("GITHUB_TOKEN");assert_eq!(token_from_env(), None);- for (name, value) in saved {- match value {- Some(value) => unsafe { std::env::set_var(name, value) },- None => unsafe { std::env::remove_var(name) },- }- }}}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rs b/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rsindex f430982905..d0bd8c3b8f 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rs@@ -14,7 +14,7 @@ unsafe extern "C" {#[cfg(target_os = "macos")]pub fn already_disclaimed() -> bool {- std::env::var_os(cua_driver_core::RESPONSIBILITY_DISCLAIMED_ENV).is_some()+ crate::env_vars::var_os(cua_driver_core::RESPONSIBILITY_DISCLAIMED_ENV).is_some()}/// Split out from [`reexec_disclaimed_if_needed`] so the decision is@@ -225,17 +225,10 @@ mod tests {#[test]fn already_disclaimed_reflects_env_var() {let name = cua_driver_core::RESPONSIBILITY_DISCLAIMED_ENV;- let original = std::env::var_os(name);-- std::env::remove_var(name);+ let mut env = crate::env_vars::Overrides::new();+ env.unset(name);assert!(!already_disclaimed());-- std::env::set_var(name, "1");+ env.set(name, "1");assert!(already_disclaimed());-- match original {- Some(value) => std::env::set_var(name, value),- None => std::env::remove_var(name),- }}}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rsindex 0d1ed600c6..d24f5a60ed 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs@@ -215,7 +215,7 @@ pub fn is_enabled() -> bool {fn effective_enabled() -> (bool, &'static str) {// The cross-tool opt-out wins over everything.- if std::env::var("DO_NOT_TRACK").is_ok_and(|v| {+ if crate::env_vars::var("DO_NOT_TRACK").is_some_and(|v| {let v = v.trim();!v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false")}) {@@ -246,7 +246,7 @@ fn effective_enabled() -> (bool, &'static str) {/// off counts here; on is the driver's own default.fn shared_config_disabled() -> bool {let home = if cfg!(test) {- std::env::var_os("CUA_HOME").map(PathBuf::from)+ crate::env_vars::var_os("CUA_HOME").map(PathBuf::from)} else {cua_telemetry::config::cua_home(&cua_telemetry::config::process_env)};@@ -282,7 +282,7 @@ pub fn reset_id() -> Result<(), String> {let Some(home) = telemetry_home_dir() else {return Ok(());};- let legacy = if std::env::var_os(ENV_TELEMETRY_HOME).is_none()+ let legacy = if crate::env_vars::var_os(ENV_TELEMETRY_HOME).is_none()&& !crate::bundle::is_local_installation(){home_root().map(|root| root.join(LEGACY_HOME_SUBDIRECTORY))@@ -488,7 +488,9 @@ pub fn register_stdio_observer() {}fn execution_mode() -> &'static str {- if cua_driver_core::embedded_mode() {+ if cua_driver_core::is_embedded_sentinel(+ crate::env_vars::var_os(cua_driver_core::EMBEDDED_ENV).as_deref(),+ ) {"embedded"} else {"standalone"@@ -1901,7 +1903,7 @@ pub(crate) fn run_cli_completion_worker_if_requested() -> bool {.map(Duration::from_millis).unwrap_or_default();let command = fixed_cli_command(&command);- let tool_name = std::env::var(ENV_CLI_COMPLETION_TOOL).ok();+ let tool_name = crate::env_vars::var(ENV_CLI_COMPLETION_TOOL);let computer_action = parse_env_bool(ENV_CLI_COMPLETION_COMPUTER_ACTION).unwrap_or(false);let operation = std::env::var(ENV_CLI_COMPLETION_OPERATION).unwrap_or_default();let client_kind = std::env::var(ENV_CLI_COMPLETION_CLIENT_KIND).unwrap_or_default();@@ -2223,6 +2225,11 @@ fn post_to_posthog(payload: &Value) -> Result<u16, String> {}fn post_to_posthog_with_timeout(payload: &Value, timeout: Duration) -> Result<u16, String> {+ // Unit tests drive the real capture paths; none of them may reach the+ // network, whatever the developer's or runner's opt-out variables say.+ if cfg!(test) {+ return Err("telemetry delivery is disabled in unit tests".to_owned());+ }let agent = ureq::Agent::config_builder().timeout_global(Some(timeout)).build()@@ -2238,15 +2245,15 @@ fn post_to_posthog_with_timeout(payload: &Value, timeout: Duration) -> Result<u1}fn telemetry_home_dir() -> Option<PathBuf> {- if let Some(path) = std::env::var_os(ENV_TELEMETRY_HOME) {+ if let Some(path) = crate::env_vars::var_os(ENV_TELEMETRY_HOME) {return Some(PathBuf::from(path));}home_root().map(|home| home.join(crate::bundle::user_home_subdirectory()))}fn home_root() -> Option<PathBuf> {- std::env::var_os("HOME")- .or_else(|| std::env::var_os("USERPROFILE"))+ crate::env_vars::var_os("HOME")+ .or_else(|| crate::env_vars::var_os("USERPROFILE")).map(PathBuf::from)}@@ -2353,7 +2360,9 @@ fn try_lifecycle_lock(home: &Path) -> Option<File> {}fn migrate_legacy_telemetry_home() {- if std::env::var_os(ENV_TELEMETRY_HOME).is_some() || crate::bundle::is_local_installation() {+ if crate::env_vars::var_os(ENV_TELEMETRY_HOME).is_some()+ || crate::bundle::is_local_installation()+ {return;}let Some(root) = home_root() else {@@ -2476,8 +2485,7 @@ fn current_product_version() -> &'static str {}fn release_version() -> String {- std::env::var(ENV_RELEASE_VERSION)- .ok()+ crate::env_vars::var(ENV_RELEASE_VERSION).and_then(|value| strict_release_version(&value)).unwrap_or_else(|| current_product_version().to_owned())}@@ -2522,8 +2530,7 @@ fn duration_bucket(elapsed: Duration) -> &'static str {}fn install_channel() -> &'static str {- std::env::var(ENV_INSTALL_CHANNEL)- .ok()+ crate::env_vars::var(ENV_INSTALL_CHANNEL).and_then(|value| normalize_install_channel(&value)).or_else(|| {marker_path(TELEMETRY_INSTALL_CHANNEL_FILE_NAME)@@ -2550,7 +2557,7 @@ fn process_session_id() -> String {}fn parse_env_bool(name: &str) -> Option<bool> {- let value = std::env::var(name).ok()?;+ let value = crate::env_vars::var(name)?;match value.trim().to_ascii_lowercase().as_str() {"0" | "false" | "no" | "off" => Some(false),"1" | "true" | "yes" | "on" => Some(true),@@ -2657,7 +2664,7 @@ fn is_ci() -> bool {];VARIABLES.iter()- .any(|name| std::env::var_os(name).is_some())+ .any(|name| crate::env_vars::var_os(name).is_some())}#[cfg(test)]@@ -2667,7 +2674,18 @@ mod tests {use std::sync::Mutex;use std::time::Instant;+ use crate::env_vars::Overrides;++ // Telemetry tests share process-wide statics (pending sends, session+ // aggregates), so they still run one at a time. Environment changes are+ // thread-local `Overrides`, never `std::env::set_var`.static ENV_LOCK: Mutex<()> = Mutex::new(());++ fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ }const TEST_CHILD_KIND: &str = "CUA_DRIVER_TELEMETRY_TEST_CHILD_KIND";const TEST_CHILD_ROOT: &str = "CUA_DRIVER_TELEMETRY_TEST_CHILD_ROOT";const TEST_CHILD_INDEX: &str = "CUA_DRIVER_TELEMETRY_TEST_CHILD_INDEX";@@ -2676,24 +2694,16 @@ mod tests {fn with_isolated_home<R>(test: impl FnOnce(&Path) -> R) -> R {let root = std::env::temp_dir().join(format!("cua-telemetry-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&root).unwrap();- let telemetry_home = root.join(HOME_SUBDIRECTORY);- let old_telemetry_home = std::env::var_os(ENV_TELEMETRY_HOME);- unsafe {- std::env::set_var(ENV_TELEMETRY_HOME, &telemetry_home);- std::env::remove_var(ENV_TELEMETRY_ENABLED);- std::env::remove_var(ENV_TELEMETRY_ENABLED_COMPAT);- std::env::remove_var("DO_NOT_TRACK");- std::env::remove_var("CUA_TELEMETRY");- std::env::remove_var("CUA_HOME");- }+ let mut env = Overrides::new();+ env.set(ENV_TELEMETRY_HOME, root.join(HOME_SUBDIRECTORY))+ .unset(ENV_TELEMETRY_ENABLED)+ .unset(ENV_TELEMETRY_ENABLED_COMPAT)+ .unset("DO_NOT_TRACK")+ .unset("CUA_TELEMETRY")+ .unset("CUA_HOME");let result = test(&root);+ drop(env);let _ = std::fs::remove_dir_all(&root);- unsafe {- match old_telemetry_home {- Some(value) => std::env::set_var(ENV_TELEMETRY_HOME, value),- None => std::env::remove_var(ENV_TELEMETRY_HOME),- }- }result}@@ -2738,7 +2748,9 @@ mod tests {}fn spawn_test_child(kind: &str, root: &Path, index: usize) -> Child {- Command::new(std::env::current_exe().expect("current test executable"))+ let mut command = Command::new(std::env::current_exe().expect("current test executable"));+ Overrides::apply(&mut command);+ command.arg(match kind {"identity" => "telemetry::tests::identity_process_child","lifecycle-winner" | "lifecycle-contender" => {@@ -2806,7 +2818,7 @@ mod tests {#[test]fn installation_identity_creation_is_atomic_across_processes() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {const CHILDREN: usize = 8;let mut children: Vec<_> = (0..CHILDREN)@@ -2842,7 +2854,7 @@ mod tests {#[test]fn lifecycle_registration_is_single_writer_and_non_blocking_across_processes() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {let mut winner = spawn_test_child("lifecycle-winner", root, 0);assert!(wait_for_path(@@ -2917,40 +2929,31 @@ mod tests {#[test]fn precedence_is_environment_then_persisted_then_default() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|_| {assert_eq!(effective_enabled(), (true, "default"));set_enabled(false).unwrap();assert_eq!(effective_enabled(), (false, "persisted"));- unsafe {- std::env::set_var(ENV_TELEMETRY_ENABLED, "true");- }+ let mut env = Overrides::new();+ env.set(ENV_TELEMETRY_ENABLED, "true");assert_eq!(effective_enabled(), (true, "environment"));- unsafe {- std::env::remove_var(ENV_TELEMETRY_ENABLED);- }});}#[test]fn shared_cua_switches_turn_the_driver_off() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|home| {assert_eq!(effective_enabled(), (true, "default"));- unsafe {- std::env::set_var("DO_NOT_TRACK", "1");- std::env::set_var(ENV_TELEMETRY_ENABLED, "true");- }+ let mut env = Overrides::new();+ env.set("DO_NOT_TRACK", "1")+ .set(ENV_TELEMETRY_ENABLED, "true");assert_eq!(effective_enabled(), (false, "do_not_track"));- unsafe {- std::env::remove_var("DO_NOT_TRACK");- std::env::remove_var(ENV_TELEMETRY_ENABLED);- std::env::set_var("CUA_TELEMETRY", "0");- }+ env.unset("DO_NOT_TRACK")+ .unset(ENV_TELEMETRY_ENABLED)+ .set("CUA_TELEMETRY", "0");assert_eq!(effective_enabled(), (false, "environment_shared"));- unsafe {- std::env::remove_var("CUA_TELEMETRY");- }+ env.unset("CUA_TELEMETRY");let cua_home = home.join("cua-home");std::fs::create_dir_all(&cua_home).unwrap();std::fs::write(@@ -2958,19 +2961,11 @@ mod tests {"[telemetry]\nenabled = \"off\"\n",).unwrap();- unsafe {- std::env::set_var("CUA_HOME", &cua_home);- }+ env.set("CUA_HOME", &cua_home);assert_eq!(effective_enabled(), (false, "shared_config"));// The driver's own switch still wins over the shared file.- unsafe {- std::env::set_var(ENV_TELEMETRY_ENABLED, "true");- }+ env.set(ENV_TELEMETRY_ENABLED, "true");assert_eq!(effective_enabled(), (true, "environment"));- unsafe {- std::env::remove_var(ENV_TELEMETRY_ENABLED);- std::env::remove_var("CUA_HOME");- }});}@@ -2982,7 +2977,7 @@ mod tests {#[test]fn persisted_install_channel_prevents_first_run_attribution_race() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {let home = root.join(HOME_SUBDIRECTORY);std::fs::create_dir_all(&home).unwrap();@@ -2993,13 +2988,10 @@ mod tests {.unwrap();assert_eq!(install_channel(), "install_script");- unsafe {- std::env::set_var(ENV_INSTALL_CHANNEL, "update_apply");- }+ let mut env = Overrides::new();+ env.set(ENV_INSTALL_CHANNEL, "update_apply");assert_eq!(install_channel(), "update_apply");- unsafe {- std::env::remove_var(ENV_INSTALL_CHANNEL);- }+ env.unset(ENV_INSTALL_CHANNEL);std::fs::write(home.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME), "invalid").unwrap();assert_eq!(install_channel(), "first_run");@@ -3008,16 +3000,15 @@ mod tests {#[test]fn disabled_install_makes_no_request_or_marker_and_keeps_existing_id() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {let home = root.join(HOME_SUBDIRECTORY);std::fs::create_dir_all(&home).unwrap();let id = uuid::Uuid::new_v4().to_string();std::fs::write(home.join(TELEMETRY_ID_FILE_NAME), &id).unwrap();set_enabled(false).unwrap();- unsafe {- std::env::set_var(ENV_TELEMETRY_ENABLED, "false");- }+ let mut env = Overrides::new();+ env.set(ENV_TELEMETRY_ENABLED, "false");let mut calls = 0;capture_install_with_poster(|_| {calls += 1;@@ -3027,15 +3018,12 @@ mod tests {assert_eq!(read_install_id().as_deref(), Some(id.as_str()));assert!(!home.join(INSTALLATION_RECORDED_FILE_NAME).exists());assert!(!home.join(TELEMETRY_RETRY_AFTER_FILE_NAME).exists());- unsafe {- std::env::remove_var(ENV_TELEMETRY_ENABLED);- }});}#[test]fn disabled_permissions_events_do_not_create_an_installation_id() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|_| {set_enabled(false).unwrap();capture_permissions_gate_started(true, false);@@ -3063,13 +3051,31 @@ mod tests {assert_eq!(permissions_gate_resolution(true, true), "timeout");}+ /// A process forked by a parallel test holds a copy of the lifecycle lock+ /// descriptor until it execs, which makes the non-blocking lock report+ /// busy. Retry until the poster runs so that window cannot fail the test.+ fn capture_install_until_posted(mut post: impl FnMut(&Value) -> Result<u16, String>) {+ for _ in 0..200 {+ let mut posted = false;+ capture_install_with_poster(|payload| {+ posted = true;+ post(payload)+ });+ if posted {+ return;+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ panic!("lifecycle lock stayed busy");+ }+#[test]fn lifecycle_markers_are_written_only_after_each_2xx() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {let home = root.join(HOME_SUBDIRECTORY);let mut calls = 0;- capture_install_with_poster(|_| {+ capture_install_until_posted(|_| {calls += 1;if calls == 1 {Ok(200)@@ -3083,7 +3089,7 @@ mod tests {.exists());remove_file_if_exists(&home.join(TELEMETRY_RETRY_AFTER_FILE_NAME)).unwrap();- capture_install_with_poster(|_| Ok(200));+ capture_install_until_posted(|_| Ok(200));assert!(release_marker_path(current_product_version()).unwrap().exists());@@ -3092,11 +3098,11 @@ mod tests {#[test]fn failed_lifecycle_delivery_defers_retries_without_marking_success() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {let home = root.join(HOME_SUBDIRECTORY);let mut calls = 0;- capture_install_with_poster(|_| {+ capture_install_until_posted(|_| {calls += 1;Ok(503)});@@ -3117,7 +3123,7 @@ mod tests {#[test]fn reset_erases_identity_and_markers_but_preserves_preference() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {set_enabled(false).unwrap();let home = root.join(HOME_SUBDIRECTORY);@@ -3137,7 +3143,7 @@ mod tests {#[test]fn reset_erases_legacy_identity_before_migration_can_restore_it() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();let root =std::env::temp_dir().join(format!("cua-telemetry-reset-{}", uuid::Uuid::new_v4()));let current = root.join(HOME_SUBDIRECTORY);@@ -3156,7 +3162,7 @@ mod tests {#[test]fn v3_payload_disables_geoip_and_sends_no_ip_or_client_timestamp() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();let identity = InstallationIdentity {id: "test-id".into(),persisted: true,@@ -3224,19 +3230,11 @@ mod tests {#[test]fn synthetic_marker_is_explicit_and_common_to_all_events() {- let _guard = ENV_LOCK.lock().unwrap();- let original = std::env::var_os(ENV_TELEMETRY_SYNTHETIC);- unsafe {- std::env::set_var(ENV_TELEMETRY_SYNTHETIC, "true");- }+ let _guard = env_lock();+ let mut env = Overrides::new();+ env.set(ENV_TELEMETRY_SYNTHETIC, "true");let payload = inspect_event(event::MCP_TOOL_COMPLETED).unwrap();assert_eq!(payload["properties"]["is_synthetic"], true);- unsafe {- match original {- Some(value) => std::env::set_var(ENV_TELEMETRY_SYNTHETIC, value),- None => std::env::remove_var(ENV_TELEMETRY_SYNTHETIC),- }- }}#[test]@@ -3387,27 +3385,15 @@ mod tests {#[test]fn execution_mode_requires_the_exact_embedded_sentinel() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();let name = cua_driver_core::EMBEDDED_ENV;- let original = std::env::var_os(name);- unsafe {- std::env::remove_var(name);- }+ let mut env = Overrides::new();+ env.unset(name);assert_eq!(execution_mode(), "standalone");- unsafe {- std::env::set_var(name, "1");- }+ env.set(name, "1");assert_eq!(execution_mode(), "embedded");- unsafe {- std::env::set_var(name, "true");- }+ env.set(name, "true");assert_eq!(execution_mode(), "standalone");- unsafe {- match original {- Some(value) => std::env::set_var(name, value),- None => std::env::remove_var(name),- }- }}#[test]@@ -3771,7 +3757,7 @@ mod tests {SessionDeclaration, SessionObserver, SessionStartObservation, SessionTransport,};- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|_| {set_enabled(false).unwrap();let session_id = "private-disabled-session-telemetry-test";@@ -3913,7 +3899,7 @@ mod tests {#[test]fn process_session_id_is_stable_and_not_written_to_disk() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();with_isolated_home(|root| {assert_eq!(process_session_id(), process_session_id());let on_disk = std::fs::read_dir(root.join(HOME_SUBDIRECTORY))@@ -3928,22 +3914,14 @@ mod tests {#[test]fn release_version_is_bounded_and_safe_for_payloads_and_marker_paths() {- let _guard = ENV_LOCK.lock().unwrap();- let previous = std::env::var_os(ENV_RELEASE_VERSION);- unsafe {- std::env::set_var(- ENV_RELEASE_VERSION,- "v1.2.3/../../private path?token=secret-and-more",- );- }+ let _guard = env_lock();+ let mut env = Overrides::new();+ env.set(+ ENV_RELEASE_VERSION,+ "v1.2.3/../../private path?token=secret-and-more",+ );assert_eq!(release_version(), current_product_version());assert!(!release_version().contains("secret"));- unsafe {- match previous {- Some(value) => std::env::set_var(ENV_RELEASE_VERSION, value),- None => std::env::remove_var(ENV_RELEASE_VERSION),- }- }}#[test]@@ -3976,7 +3954,7 @@ mod tests {#[test]fn pending_send_flush_waits_for_bounded_delivery() {- let _guard = ENV_LOCK.lock().unwrap();+ let _guard = env_lock();assert_eq!(PENDING_SENDS.load(Ordering::SeqCst), 0);PENDING_SENDS.fetch_add(1, Ordering::SeqCst);std::thread::spawn(|| {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/updater.rs b/libs/cua-driver/rust/crates/cua-driver/src/updater.rsindex 65a7bfe234..12d207deb3 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/updater.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/updater.rs@@ -57,15 +57,27 @@ fn pacman_owns_path(path: &std::path::Path, pacman: &std::path::Path) -> bool {use std::process::Stdio;use std::time::{Duration, Instant};- let Ok(mut child) = Command::new(pacman)- .args(["-Qoq", "--"])- .arg(path)- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .spawn()- else {- return false;+ // A just-written executable is briefly ETXTBSY while a concurrent fork+ // still holds its write descriptor; that is not an answer, so retry.+ let mut attempts = 0;+ let mut child = loop {+ match Command::new(pacman)+ .args(["-Qoq", "--"])+ .arg(path)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ {+ Ok(child) => break child,+ Err(error)+ if error.kind() == std::io::ErrorKind::ExecutableFileBusy && attempts < 20 =>+ {+ attempts += 1;+ std::thread::sleep(Duration::from_millis(10));+ }+ Err(_) => return false,+ }};let deadline = Instant::now() + Duration::from_millis(500);loop {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rsindex b423fef21d..a850336bb4 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs@@ -560,7 +560,8 @@ fn is_enabled() -> bool {/// the `cua-driver config set` subcommand writes to. Returns `None` when/// the file is missing, unreadable, or doesn't have the key.fn read_config_flag() -> Option<bool> {- let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;+ let home =+ crate::env_vars::var_os("HOME").or_else(|| crate::env_vars::var_os("USERPROFILE"))?;let path = PathBuf::from(home).join(crate::bundle::user_home_subdirectory()).join("config.json");@@ -570,7 +571,7 @@ fn read_config_flag() -> Option<bool> {}fn parse_env_bool(var: &str) -> Option<bool> {- let raw = std::env::var(var).ok()?;+ let raw = crate::env_vars::var(var)?;match raw.trim().to_ascii_lowercase().as_str() {"0" | "false" | "no" | "off" => Some(false),"1" | "true" | "yes" | "on" => Some(true),@@ -677,7 +678,8 @@ fn write_cache(cache: &VersionCache) -> std::io::Result<()> {}fn home_root() -> Option<PathBuf> {- let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;+ let home =+ crate::env_vars::var_os("HOME").or_else(|| crate::env_vars::var_os("USERPROFILE"))?;Some(PathBuf::from(home))}@@ -878,19 +880,13 @@ fn civil_from_unix(unix_secs: u64) -> (i32, u32, u32, u32, u32, u32) {// ── Tests ────────────────────────────────────────────────────────────────-/// All env-mutating tests serialise on this lock — `std::env::set_var`-/// is process-global, parallel tests would race.-#[cfg(test)]-pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());-#[cfg(test)]mod tests {use super::*;- use std::sync::Mutex;+ use crate::env_vars::Overrides;#[test]fn pacman_managed_check_ignores_upstream_cache_and_channel() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|home| {write_cache(&VersionCache {latest_version: Some("999.0.0".into()),@@ -932,42 +928,17 @@ mod tests {assert!(banner.is_empty());}- use super::ENV_LOCK;-/// Redirect `HOME` / `USERPROFILE` to a fresh temp dir for the body/// of `f`, then restore. Ensures the cache file lives in an isolated/// directory and never touches the developer's real/// `~/.cua-driver/version_check.json`.fn with_isolated_home<R>(f: impl FnOnce(&std::path::Path) -> R) -> R {let tmp = tempfile::tempdir().expect("tempdir");- let saved_home = std::env::var_os("HOME");- let saved_userprofile = std::env::var_os("USERPROFILE");- unsafe {- std::env::set_var("HOME", tmp.path());- }- unsafe {- std::env::set_var("USERPROFILE", tmp.path());- }-- let result = f(tmp.path());-- match saved_home {- Some(s) => unsafe {- std::env::set_var("HOME", s);- },- None => unsafe {- std::env::remove_var("HOME");- },- }- match saved_userprofile {- Some(s) => unsafe {- std::env::set_var("USERPROFILE", s);- },- None => unsafe {- std::env::remove_var("USERPROFILE");- },- }- result+ let mut env = Overrides::new();+ env.set("HOME", tmp.path())+ .set("USERPROFILE", tmp.path())+ .unset("CUA_DRIVER_RS_HOME");+ f(tmp.path())}// ── is_newer ────────────────────────────────────────────────────────@@ -1052,7 +1023,6 @@ mod tests {#[test]fn cache_round_trips_through_tempdir() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|_| {let original = VersionCache {last_checked_unix: Some(1_700_000_000),@@ -1073,7 +1043,6 @@ mod tests {#[test]fn cache_lands_in_the_canonical_home() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|home| {write_cache(&VersionCache::default()).expect("write_cache");assert!(home@@ -1088,7 +1057,6 @@ mod tests {#[test]fn legacy_cache_is_migrated_and_its_home_removed() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|home| {let legacy_home = home.join(LEGACY_HOME_SUBDIRECTORY);std::fs::create_dir_all(&legacy_home).unwrap();@@ -1111,7 +1079,6 @@ mod tests {#[test]fn migration_leaves_a_legacy_home_that_still_holds_other_files() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|home| {let legacy_home = home.join(LEGACY_HOME_SUBDIRECTORY);std::fs::create_dir_all(&legacy_home).unwrap();@@ -1129,7 +1096,6 @@ mod tests {#[test]fn failed_migration_preserves_the_legacy_cache() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|home| {let legacy_home = home.join(LEGACY_HOME_SUBDIRECTORY);let legacy_cache = legacy_home.join(CACHE_FILE_NAME);@@ -1156,7 +1122,6 @@ mod tests {#[test]fn cache_older_than_threshold_triggers_refresh() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|_| {// Seed the cache 2 hours in the past.let now = unix_now();@@ -1196,7 +1161,6 @@ mod tests {#[test]fn cache_younger_than_threshold_skips_network() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|_| {// Seed the cache 30 minutes in the past with a known-newer version.let now = unix_now();@@ -1236,7 +1200,6 @@ mod tests {#[test]fn dismissed_latest_suppresses_banner() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|_| {// Cache is fresh and reports a newer version, but the user// dismissed exactly that version — banner must stay silent.@@ -1326,7 +1289,6 @@ mod tests {#[test]fn stale_cache_from_older_build_is_replaced_not_announced() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|_| {// The #4755 shape: a young cache saying 0.33.4, written by the// 0.33.4 build, read by the 0.34.0 build that replaced it.@@ -1352,7 +1314,6 @@ mod tests {#[test]fn failed_lookup_backs_off_but_never_serves_an_untrusted_result() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|_| {let now = unix_now();let fetches = std::sync::atomic::AtomicUsize::new(0);@@ -1399,7 +1360,6 @@ mod tests {#[test]fn invalidate_cache_drops_the_result_and_keeps_dismissals() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());with_isolated_home(|_| {let now = unix_now();let mut cache = seeded(now, 60, "0.33.4", Some("0.33.4"));@@ -1438,50 +1398,29 @@ mod tests {#[test]fn env_opt_out_short_circuits_enabled_check() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let saved = std::env::var_os(ENV_UPDATE_CHECK);-- unsafe {- std::env::set_var(ENV_UPDATE_CHECK, "false");- }+ let mut env = Overrides::new();+ env.set(ENV_UPDATE_CHECK, "false");// Use a separately-redirected HOME so any config file present on// the developer's machine can't influence the result.with_isolated_home(|_| {assert!(!is_enabled(), "explicit false env var must disable");});- unsafe {- std::env::set_var(ENV_UPDATE_CHECK, "0");- }+ env.set(ENV_UPDATE_CHECK, "0");with_isolated_home(|_| {assert!(!is_enabled(), "0 must disable");});- unsafe {- std::env::set_var(ENV_UPDATE_CHECK, "off");- }+ env.set(ENV_UPDATE_CHECK, "off");with_isolated_home(|_| {assert!(!is_enabled(), "off must disable");});-- // Restore.- match saved {- Some(s) => unsafe {- std::env::set_var(ENV_UPDATE_CHECK, s);- },- None => unsafe {- std::env::remove_var(ENV_UPDATE_CHECK);- },- }}#[test]fn config_flag_disables_check() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let saved = std::env::var_os(ENV_UPDATE_CHECK);- unsafe {- std::env::remove_var(ENV_UPDATE_CHECK);- }+ let mut env = Overrides::new();+ env.unset(ENV_UPDATE_CHECK);with_isolated_home(|home| {// Write a config that disables the check.@@ -1501,24 +1440,12 @@ mod tests {"persisted update_check_enabled=false must disable the check");});-- match saved {- Some(s) => unsafe {- std::env::set_var(ENV_UPDATE_CHECK, s);- },- None => unsafe {- std::env::remove_var(ENV_UPDATE_CHECK);- },- }}#[test]fn config_flag_true_or_missing_leaves_check_on() {- let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let saved = std::env::var_os(ENV_UPDATE_CHECK);- unsafe {- std::env::remove_var(ENV_UPDATE_CHECK);- }+ let mut env = Overrides::new();+ env.unset(ENV_UPDATE_CHECK);with_isolated_home(|home| {// Case A: no config file at all → enabled.@@ -1541,15 +1468,6 @@ mod tests {"explicit update_check_enabled=true must leave check on");});-- match saved {- Some(s) => unsafe {- std::env::set_var(ENV_UPDATE_CHECK, s);- },- None => unsafe {- std::env::remove_var(ENV_UPDATE_CHECK);- },- }}// ── Banner formatting ───────────────────────────────────────────────