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(spaces): Cua Driver runs after the new first run, whatever the Mac shares (CUA-3485) (#6534)
cua-agents[bot]97eabde88dd1
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swiftindex 1daf8d8803..a013b395a2 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift@@ -30,6 +30,31 @@ public struct EmbeddedDriver: Sendable {/// runs no driver (`embedded_driver::paused_marker`).public var pausedMarker: String { ((socket as NSString).deletingLastPathComponent as NSString).appendingPathComponent("cua-driver.off") }+ /// Written to have cua-spacesd start a driver that isn't running now,+ /// instead of after its restart backoff (`embedded_driver::start_request`).+ public var startRequest: String { ((socket as NSString).deletingLastPathComponent as NSString).appendingPathComponent("cua-driver.start") }++ /// What Set up, Repair and turning "Let agents use apps on this Mac" on+ /// do next to get a driver that isn't answering running. The driver's+ /// lifecycle follows that switch only, never desktop sharing.+ public enum StartStep: Equatable, Sendable {+ /// Running, or paused by the person: nothing to do.+ case none+ /// This Mac isn't set up yet, so no cua-spacesd runs to start it.+ case needsSetUp+ /// Ask cua-spacesd to start it now ([`startRequest`]).+ case askHostService+ /// cua-spacesd didn't start it (it isn't running, or it predates+ /// the request): restart the host service, which starts a driver.+ case restartHostService+ }++ public static func startStep(paused: Bool, answering: Bool, setUp: Bool, askedHostService: Bool) -> StartStep {+ if paused || answering { return .none }+ if !setUp { return .needsSetUp }+ return askedHostService ? .restartHostService : .askHostService+ }+/// This app's embedded driver, or nil when the bundle carries none (a/// bare build) or names a channel without a home.public static func current(bundle: Bundle = .main) -> EmbeddedDriver? {diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swiftindex bdb31458f8..bdfbe0eba3 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift@@ -310,6 +310,21 @@ public enum HelperService {}}+ /// Starts the host service, or restarts it when `restart` (`launchctl+ /// kickstart [-k]`). Blocks until launchctl returns: call off the main+ /// thread. False when launchctl failed (the service isn't loaded).+ @discardableResult+ public static func kickstart(restart: Bool) -> Bool {+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/bin/launchctl")+ p.arguments = ["kickstart"] + (restart ? ["-k"] : []) + ["gui/\(getuid())/\(label)"]+ p.standardOutput = FileHandle.nullDevice+ p.standardError = FileHandle.nullDevice+ guard (try? p.run()) != nil else { return false }+ p.waitUntilExit()+ return p.terminationStatus == 0+ }+private static func stamped(_ info: [String: Any]?, _ key: String) -> String? {guard let value = (info?[key] as? String)?.trimmingCharacters(in: .whitespaces),!value.isEmpty else { return nil }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swiftindex 3b95c5a109..ebf324be1b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift@@ -57,9 +57,15 @@ extension WebUIBridge {let driver = try needDriver()guard let paused = args["paused"] as? Bool else { throw Failure.badArgs("paused: boolean") }try setDriverPaused(driver, paused)+ // Switched on: a driver that isn't running starts now, also on a+ // Mac set up earlier without sharing its desktop.+ if !paused { await startDriverIfNeeded(driver) }return NSNull()case "driver.setup":let driver = try needDriver()+ // A driver that isn't running starts first, so the page answers+ // even when connecting the agents fails below.+ await startDriverIfNeeded(driver)try await setUpDriverAgents(driver, agents: driverAgents)// A driver whose permission answer is stale starts again.await restartDriverIfStale(driver, force: true)@@ -214,6 +220,48 @@ extension WebUIBridge {}}+ /// Gets a driver that isn't answering running, unless the person paused+ /// agents: asks cua-spacesd to start it now (it may be waiting out its+ /// restart backoff), then restarts the host service when that didn't+ /// work (cua-spacesd isn't running, or it is a build that never started+ /// a driver on a Mac that keeps its screen private). Returns once the+ /// driver answers or each step had its time.+ func startDriverIfNeeded(_ driver: EmbeddedDriver) async {+ var asked = false+ while true {+ let paused = FileManager.default.fileExists(atPath: driver.pausedMarker)+ let answering = await Task.detached { driver.metadata(timeout: 1) != nil }.value+ let spec = HelperService.specPath(info: Bundle.main.infoDictionary, home: NSHomeDirectory())+ let setUp = spec.map { FileManager.default.fileExists(atPath: $0) } ?? false+ switch EmbeddedDriver.startStep(paused: paused, answering: answering, setUp: setUp, askedHostService: asked) {+ case .none, .needsSetUp:+ return+ case .askHostService:+ asked = true+ let request = driver.startRequest+ try? FileManager.default.createDirectory(atPath: (request as NSString).deletingLastPathComponent, withIntermediateDirectories: true)+ FileManager.default.createFile(atPath: request, contents: Data())+ // A running host service with no driver up yet: start it too.+ _ = await Task.detached { HelperService.kickstart(restart: false) }.value+ if await waitForDriver(driver, seconds: 10) { return }+ case .restartHostService:+ NSLog("cua-spaces: Cua Driver didn't start; restarting the host service")+ _ = await Task.detached { HelperService.kickstart(restart: true) }.value+ _ = await waitForDriver(driver, seconds: 20)+ return+ }+ }+ }++ /// Whether the driver answers within `seconds`.+ private func waitForDriver(_ driver: EmbeddedDriver, seconds: Int) async -> Bool {+ for _ in 0..<(seconds * 2) {+ if await Task.detached(operation: { driver.metadata(timeout: 1) != nil }).value { return true }+ try? await Task.sleep(for: .milliseconds(500))+ }+ return false+ }+/// "Let agents use apps on this Mac": off writes the file cua-spacesd/// watches, which stops the driver; on removes it.private func setDriverPaused(_ driver: EmbeddedDriver, _ paused: Bool) throws {diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swiftindex 806ee2e1a7..d637a7fa81 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift@@ -12,6 +12,7 @@ struct EmbeddedDriverTests {bundleId: "com.trycua.spaces.macos", home: "/Users/ada"))#expect(stable.socket == "/Users/ada/.cua/run/cua-driver.sock")#expect(stable.pausedMarker == "/Users/ada/.cua/run/cua-driver.off")+ #expect(stable.startRequest == "/Users/ada/.cua/run/cua-driver.start")#expect(stable.serverName == "cua-driver")#expect(stable.mcpArguments == ["mcp", "--embedded", "--socket", "/Users/ada/.cua/run/cua-driver.sock","--host-bundle-id", "com.trycua.spaces.macos"])@@ -26,6 +27,19 @@ struct EmbeddedDriverTests {#expect(EmbeddedDriver.make(binary: "/x", info: ["CuaChannel": "local"], bundleId: "x.local", home: "/Users/ada") == nil)}+ /// Set up and Repair start a driver that isn't answering: through+ /// cua-spacesd first, then by restarting the host service. Never while+ /// the person has paused agents, and whether or not this Mac shares its+ /// desktop (a Mac set up with `--no-desktop --no-driver` included).+ @Test func setUpStartsADriverThatIsntRunning() {+ typealias D = EmbeddedDriver+ #expect(D.startStep(paused: false, answering: true, setUp: true, askedHostService: false) == .none)+ #expect(D.startStep(paused: true, answering: false, setUp: true, askedHostService: false) == .none)+ #expect(D.startStep(paused: false, answering: false, setUp: false, askedHostService: false) == .needsSetUp)+ #expect(D.startStep(paused: false, answering: false, setUp: true, askedHostService: false) == .askHostService)+ #expect(D.startStep(paused: false, answering: false, setUp: true, askedHostService: true) == .restartHostService)+ }+@Test func knowsItsOwnEntry() throws {let d = try #require(EmbeddedDriver.make(binary: "/A/Contents/Helpers/cua-driver", info: [:], bundleId: nil, home: "/h"))#expect(d.isOurs(command: d.binary, args: d.mcpArguments))diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/embedded_driver.rs b/libs/cua-spacesd/crates/cua-spacesd/src/embedded_driver.rsindex 45ade99495..ebc2a8e519 100644--- a/libs/cua-spacesd/crates/cua-spacesd/src/embedded_driver.rs+++ b/libs/cua-spacesd/crates/cua-spacesd/src/embedded_driver.rs@@ -18,7 +18,10 @@//! and is the one place the app asks for the driver's status, its settings//! (`get_config` / `set_config`), its permissions and a live test.//!-//! **On by default** in a desktop session on macOS.+//! **On by default** on macOS, whatever the host shares: a Mac set up to+//! keep its screen private (`--no-desktop --no-driver`, the new first+//! run's "Add this computer") still runs it, because those flags are about+//! remote callers and this driver is for the coding agents on this Mac.//! `CUA_SPACESD_EMBEDDED_DRIVER=0` turns it off for this process.//!//! **Paused by the person.** The app's "Let agents use apps on this Mac"@@ -27,6 +30,10 @@//! proxy's plain "open Cua Spaces" message; removing it starts the driver//! again within a couple of seconds.//!+//! **Started now on request.** Set up and Repair write [`start_request`]+//! (`<CuaHome>/run/cua-driver.start`): a driver waiting out its restart+//! backoff starts at once instead of up to a minute later.+//!//! **Cursor overlay.** The child draws the agent cursor for coding agents//! (the SDK default). cua-spacesd's own overlay keeps drawing remote people//! and host-Space agents. Each cursor has one owner; whether two overlay@@ -58,6 +65,8 @@ pub struct EmbeddedDriverConfig {pub host_bundle_id: String,/// While this file exists the person has paused agents: no driver runs.pub paused_marker: PathBuf,+ /// The app writes this file to have a stopped driver start now.+ pub start_request: PathBuf,}/// The file the app writes while agents are paused: beside the socket.@@ -65,6 +74,12 @@ pub fn paused_marker(socket: &Path) -> PathBuf {socket.with_file_name("cua-driver.off")}+/// The file the app writes to have a driver that isn't running start now+/// (Set up and Repair): beside the socket.+pub fn start_request(socket: &Path) -> PathBuf {+ socket.with_file_name("cua-driver.start")+}+/// How often the supervisor looks at [`paused_marker`].const PAUSE_POLL: Duration = Duration::from_secs(1);@@ -105,6 +120,7 @@ impl EmbeddedDriverConfig {Ok(Self {binary,paused_marker: paused_marker(&socket),+ start_request: start_request(&socket),socket,host_bundle_id: channel.bundle_id().to_string(),})@@ -227,6 +243,9 @@ impl EmbeddedDriver {_ = tokio::time::sleep(PAUSE_POLL) => continue,}}+ // A request written while nothing waited for it is answered by+ // this start.+ self.take_start_request();let started = std::time::Instant::now();let connection = tokio::select! {_ = shutdown.cancelled() => break,@@ -271,7 +290,7 @@ impl EmbeddedDriver {self.tracked.lock().unwrap().restarts += 1;tokio::select! {_ = shutdown.cancelled() => break,- _ = tokio::time::sleep(restart_delay(attempt)) => {}+ _ = self.backoff(restart_delay(attempt)) => {}}}if let Err(error) = self.host.clone().stop().await {@@ -284,6 +303,28 @@ impl EmbeddedDriver {self.config.paused_marker.exists()}+ /// Consumes a pending [`start_request`]; true when there was one.+ fn take_start_request(&self) -> bool {+ std::fs::remove_file(&self.config.start_request).is_ok()+ }++ /// Waits `delay` before the next start, or less when the app asks for+ /// a start now ([`start_request`]).+ async fn backoff(&self, delay: Duration) {+ let deadline = tokio::time::Instant::now() + delay;+ loop {+ if self.take_start_request() {+ tracing::info!("Cua Spaces asked for Cua Driver now: starting it");+ return;+ }+ let now = tokio::time::Instant::now();+ if now >= deadline {+ return;+ }+ tokio::time::sleep((deadline - now).min(PAUSE_POLL)).await;+ }+ }+async fn until_paused(&self) {while !self.paused() {tokio::time::sleep(PAUSE_POLL).await;@@ -485,6 +526,34 @@ mod tests {assert_eq!(c.paused_marker.parent(), c.socket.parent());}+ #[test]+ fn the_start_request_sits_beside_the_socket() {+ let (_dir, exe) = exe_with_driver();+ let c = EmbeddedDriverConfig::resolve(None, None, &exe, CuaChannel::Stable).unwrap();+ assert_eq!(c.start_request, c.socket.with_file_name("cua-driver.start"));+ }++ /// A driver that won't start waits its backoff, but a start request+ /// from the app ends the wait at once and is consumed.+ #[tokio::test]+ async fn a_start_request_cuts_the_backoff_short() {+ let (dir, exe) = exe_with_driver();+ let mut c = EmbeddedDriverConfig::resolve(None, None, &exe, CuaChannel::Stable).unwrap();+ c.socket = dir.path().join("run/cua-driver.sock");+ c.paused_marker = paused_marker(&c.socket);+ c.start_request = start_request(&c.socket);+ std::fs::create_dir_all(dir.path().join("run")).unwrap();+ let driver = EmbeddedDriver::new(c.clone()).unwrap();+ let t = std::time::Instant::now();+ driver.backoff(Duration::from_millis(300)).await;+ assert!(t.elapsed() >= Duration::from_millis(300));+ std::fs::write(&c.start_request, "").unwrap();+ let t = std::time::Instant::now();+ driver.backoff(Duration::from_secs(60)).await;+ assert!(t.elapsed() < Duration::from_secs(2), "{:?}", t.elapsed());+ assert!(!c.start_request.exists());+ }+#[test]fn uses_the_bundled_driver_and_the_channels_names() {let (_dir, exe) = exe_with_driver();diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs b/libs/cua-spacesd/crates/cua-spacesd/src/main.rsindex ce2c4611dd..e63960613a 100644--- a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs+++ b/libs/cua-spacesd/crates/cua-spacesd/src/main.rs@@ -181,11 +181,13 @@ struct ServeArgs {#[arg(long, env = "CUA_SPACESD_NO_ACCESS_LOG")]no_access_log: bool,/// Do not link the cua-driver tool registry (Driver service and /mcp- /// report unsupported).+ /// report unsupported). Remote callers only: the Cua Driver this Mac's+ /// coding agents use (`embedded_driver`) runs either way.#[arg(long, env = "CUA_ENV_NO_DRIVER")]no_driver: bool,/// Do not serve the desktop services (Computer, Windows, Accessibility,- /// Stream, Presence, /media).+ /// Stream, Presence, /media). The embedded Cua Driver for this Mac's+ /// coding agents still runs.#[arg(long, env = "CUA_ENV_NO_DESKTOP")]no_desktop: bool,/// Teleport destination (default ~/Downloads).@@ -957,12 +959,13 @@ async fn serve(args: ServeArgs, join: Option<JoinArgs>) -> Result<Exit, BoxErrorcua_spacesd::vsock_agent::start();// Cua Driver for the coding agents on this Mac, as this process's own// child (on unless CUA_SPACESD_EMBEDDED_DRIVER=0; see embedded_driver).+ // It follows only the person's "Let agents use apps on this Mac"+ // switch, never `--no-desktop` or `--no-driver`: those are about+ // remote callers (sharing this desktop, the Driver service and /mcp),+ // and a Mac that keeps its screen private still lets its own coding+ // agents use its apps.#[cfg(all(target_os = "macos", not(cua_headless)))]- let _embedded_driver = if no_desktop {- None- } else {- embedded_driver::spawn(shutdown.clone())- };+ let _embedded_driver = embedded_driver::spawn(shutdown.clone());// A direct host starts its cua daemon, which reopens the ports it// forwards to the Spaces it provides.if let Some(policy) = direct_host_policy {diff --git a/libs/cua-spacesd/crates/cua-spacesd/tests/embedded_driver_bin.rs b/libs/cua-spacesd/crates/cua-spacesd/tests/embedded_driver_bin.rsnew file mode 100644index 0000000000..521353844c--- /dev/null+++ b/libs/cua-spacesd/crates/cua-spacesd/tests/embedded_driver_bin.rs@@ -0,0 +1,123 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! The real binary starts the Cua Driver for this Mac's coding agents even+//! when it was set up to keep its screen private (`--no-desktop --no-driver+//! --no-mcp`, the new first run's "Add this computer"), and the only thing+//! that keeps it from running is the person's "Let agents use apps on this+//! Mac" switch (the pause marker). macOS only.+#![cfg(target_os = "macos")]++use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::time::{Duration, Instant};++struct Kill(Child);+impl Drop for Kill {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+}++/// A stand-in cua-driver that notes each start in `started` and stays up.+fn fake_driver(dir: &Path, started: &Path) -> PathBuf {+ use std::os::unix::fs::PermissionsExt as _;+ let path = dir.join("cua-driver");+ std::fs::write(+ &path,+ format!(+ "#!/bin/sh\necho \"$@\" >> '{}'\nexec sleep 30\n",+ started.display()+ ),+ )+ .unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ path+}++/// cua-spacesd as the host service runs it on a Mac that doesn't share its+/// desktop, with `home` as the user's home.+fn host_without_desktop(home: &Path, driver: &Path) -> Kill {+ let port = std::net::TcpListener::bind("127.0.0.1:0")+ .unwrap()+ .local_addr()+ .unwrap()+ .port();+ Kill(+ Command::new(env!("CARGO_BIN_EXE_cua-spacesd"))+ .args([+ "serve",+ "--no-desktop",+ "--no-driver",+ "--no-mcp",+ "--quic-port",+ "0",+ ])+ .arg("--listen")+ .arg(format!("127.0.0.1:{port}"))+ .arg("--data-dir")+ .arg(home.join("data"))+ .arg("--token-file")+ .arg(home.join("token"))+ .env("HOME", home)+ .env("CUA_ENV_TOKEN", uuid::Uuid::new_v4().to_string())+ .env("CUA_SPACESD_DRIVER_BIN", driver)+ .env("CUA_ENV_LOG", "warn")+ .env_remove("CUA_CHANNEL")+ .env_remove("CUA_HOME")+ .env_remove("CUA_SPACESD_EMBEDDED_DRIVER")+ .stdout(Stdio::null())+ .spawn()+ .unwrap(),+ )+}++fn wait_for(path: &Path, within: Duration) -> bool {+ let t = Instant::now();+ while t.elapsed() < within {+ if std::fs::metadata(path)+ .map(|m| m.len() > 0)+ .unwrap_or(false)+ {+ return true;+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ false+}++#[test]+fn a_mac_that_keeps_its_screen_private_still_runs_the_driver() {+ let home = tempfile::tempdir().unwrap();+ let started = home.path().join("driver-started");+ let driver = fake_driver(home.path(), &started);+ let _host = host_without_desktop(home.path(), &driver);+ assert!(+ wait_for(&started, Duration::from_secs(15)),+ "cua-spacesd --no-desktop --no-driver never started the embedded Cua Driver"+ );+ let args = std::fs::read_to_string(&started).unwrap();+ assert!(args.contains("--embedded"), "{args}");+}++#[test]+fn the_switch_alone_decides_whether_it_runs() {+ let home = tempfile::tempdir().unwrap();+ let run = home.path().join(".cua/run");+ std::fs::create_dir_all(&run).unwrap();+ let paused = run.join("cua-driver.off");+ std::fs::write(&paused, "1\n").unwrap();+ let started = home.path().join("driver-started");+ let driver = fake_driver(home.path(), &started);+ let _host = host_without_desktop(home.path(), &driver);+ // Switched off: nothing starts.+ assert!(!wait_for(&started, Duration::from_secs(4)));+ // Switched on: it starts within a couple of seconds, set up earlier+ // with --no-driver or not.+ std::fs::remove_file(&paused).unwrap();+ assert!(+ wait_for(&started, Duration::from_secs(10)),+ "turning the switch on didn't start the embedded Cua Driver"+ );+}diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex ca77b9fef0..7638d48fd2 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -1430,9 +1430,12 @@ impl Host {"--data-dir".into(),s(p.driver_data.clone()),]);- // A machine that does not share its desktop runs no desktop- // services, no cua-driver and no /mcp at all: providing Spaces- // never needs them (the policy refuses relayed calls to the rest).+ // A machine that does not share its desktop serves remote callers+ // no desktop services, no Driver service and no /mcp at all:+ // providing Spaces never needs them (the policy refuses relayed+ // calls to the rest). The Cua Driver for this Mac's own coding+ // agents still runs: cua-spacesd starts it whatever these flags say,+ // and only "Let agents use apps on this Mac" turns it off.if !config.share_desktop {args.extend(["--no-desktop".into(),diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex f177b85bcc..59e4ec3561 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -871,6 +871,16 @@ async fn a_spare_machine_provides_spaces_without_its_desktop() {spec.args);}+ // Keeping the screen private never turns off the Cua Driver this Mac's+ // own coding agents use (cua-spacesd runs it whatever the flags say).+ assert!(+ !spec+ .env+ .iter()+ .any(|(k, _)| k == "CUA_SPACESD_EMBEDDED_DRIVER"),+ "{:?}",+ spec.env+ );let policy = host.policy().unwrap().unwrap();assert!(!policy.share_desktop && policy.provide_spaces);let daemon = policy.spaces_daemon.clone().unwrap();