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-macos): Cua Driver runs on every Mac, not only one set up for sharing (CUA-3638) (#6704)
cua-agents[bot]8b780ae694c1
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/DriverLauncher.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/DriverLauncher.swiftnew file mode 100644index 0000000000..2ce172de01--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/DriverLauncher.swift@@ -0,0 +1,66 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Cua Driver's login item (CUA-3638):+//+// CuaSpacesMac --driver-helper run SMAppService.agent, Contents/Library/+// LaunchAgents/<label>.plist (by+// default com.trycua.spaces.driver.plist):+// runs DriverSupervisor, which keeps+// Contents/Helpers/cua-driver serve+// --embedded up as its own child+//+// launchd starts this executable, so macOS holds the app ("Cua Spaces")+// responsible for the driver: its Accessibility and Screen Recording are the+// app's, as with the host service (ServiceLauncher.swift). It runs whether or+// not this Mac is set up, shared or signed in; only the person's "Let agents+// use apps on this Mac" switch (the pause marker) keeps the driver off.+//+// Stop (launchctl kill SIGTERM, logout) stops the driver and exits 0, which+// launchd leaves stopped until the next login or the app starts it again. An+// update in place exits non-zero once the driver is stopped, so launchd+// starts the new build. Never touches AppKit.++import CuaSpacesMacKit+import Darwin+import Foundation++private var driverStopping: sig_atomic_t = 0++enum DriverLauncher {+ static func serve() -> Never {+ guard let driver = EmbeddedDriver.current() else {+ NSLog("cua-spaces driver: this build of Cua Spaces carries no Cua Driver; nothing to run")+ exit(0)+ }+ for sig in [SIGTERM, SIGINT, SIGHUP] {+ signal(sig) { _ in driverStopping = 1 }+ }+ // The files it runs from: an update replaces them (restart onto the+ // new build), a removal deletes them (stop).+ let me = Bundle.main.executablePath.map { URL(fileURLWithPath: $0).resolvingSymlinksInPath().path }+ ?? CommandLine.arguments[0]+ let files = [me, driver.binary]+ let started = files.map(HelperService.identity)+ var misses = 0+ var lastLook = Date()+ var verdict = HelperService.WatchVerdict.keep+ let supervisor = DriverSupervisor(driver: driver)+ supervisor.run {+ if driverStopping != 0 { return true }+ if Date().timeIntervalSince(lastLook) >= 5 {+ lastLook = Date()+ verdict = HelperService.watch(started: started, now: files.map(HelperService.identity),+ specPresent: true, misses: &misses)+ switch verdict {+ case .keep: return false+ case .stop: NSLog("cua-spaces driver: the app's files are gone; stopping")+ case .restart: NSLog("cua-spaces driver: the app was updated; restarting onto the new build")+ }+ return true+ }+ return false+ }+ exit(verdict == .restart ? HelperService.restartExitCode : 0)+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swiftindex b1f21d59b9..87cdaecf28 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift@@ -189,7 +189,15 @@ enum ServiceLauncher {if !spec.args.contains("--no-desktop") && !appAsks {PermissionRequester.requestScreenRecordingAndAccessibility()}- guard let pid = spawn(spec.args, env: spec.env, logPath: spec.logPath, workingDir: spec.workingDir) else {+ // Cua Driver for this Mac's coding agents runs from its own login+ // item (DriverLauncher.swift), whatever this Mac shares: the host+ // service must not start a second one on the same socket.+ var env = spec.env+ if DriverService.isBundled() {+ env.removeAll { $0.0 == "CUA_SPACESD_EMBEDDED_DRIVER" }+ env.append(("CUA_SPACESD_EMBEDDED_DRIVER", "0"))+ }+ guard let pid = spawn(spec.args, env: env, logPath: spec.logPath, workingDir: spec.workingDir) else {exit(1)}serviceChild = piddiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swiftindex d16ecd9614..cc968f17e9 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift@@ -54,6 +54,16 @@ if launchArgs.first == "--service-helper" {if launchArgs.dropFirst().first == "run" { ServiceLauncher.serve() }exit(HelperService.run(Array(launchArgs.dropFirst())))}+// Cua Driver's own login item (DriverLauncher.swift, CUA-3638):+// * `--driver-helper run`: keeps Contents/Helpers/cua-driver running for the+// coding agents on this Mac, whatever this Mac shares;+// * `--driver-helper register|unregister|status`: the login item+// (Contents/Library/LaunchAgents/<label>.plist, by default+// com.trycua.spaces.driver.plist).+if launchArgs.first == "--driver-helper" {+ if launchArgs.dropFirst().first == "run" { DriverLauncher.serve() }+ exit(DriverService.run(Array(launchArgs.dropFirst())))+}if launchArgs.first == "check-permissions" {ServiceLauncher.passthrough(launchArgs)}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DriverService.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DriverService.swiftnew file mode 100644index 0000000000..7d5c002d8f--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DriverService.swift@@ -0,0 +1,115 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import CuaSpacesFFI+import Darwin+import Foundation+import ServiceManagement++/// Cua Driver's own login item (CUA-3638): this app's executable+/// (`CuaSpacesMac --driver-helper run`, so the driver's permissions are the+/// app's) run by `SMAppService.agent` from+/// `Contents/Library/LaunchAgents/<label>.plist`+/// (com.trycua.spaces.driver.plist for the released app). It runs+/// `DriverSupervisor`, which keeps `Contents/Helpers/cua-driver serve+/// --embedded` up for the coding agents on this Mac.+///+/// It is not the host service (`HelperService`): that one runs only while+/// this Mac is set up in Cua Spaces and signed in to the account it was set+/// up with, and is uninstalled while paused. Cua Driver for this Mac's own+/// agents needs none of that, so it has its own item, which the app+/// registers at launch and which only the person's "Let agents use apps on+/// this Mac" switch turns off.+public enum DriverService {+ /// The driver item's label: the host service's (`HelperService.label`)+ /// with `.driver` for `.helper`, so each channel has its own+ /// (com.trycua.spaces.driver, com.trycua.spaces.local.driver).+ public static func label(info: [String: Any]?) -> String {+ let helper = HelperService.label(info: info)+ let base = helper.hasSuffix(".helper") ? String(helper.dropLast(".helper".count)) : helper+ return base + ".driver"+ }++ /// The plist in Contents/Library/LaunchAgents: `<label>.plist`.+ public static func plistName(info: [String: Any]?) -> String {+ label(info: info) + ".plist"+ }++ public static var label: String { label(info: Bundle.main.infoDictionary) }++ static var service: SMAppService { SMAppService.agent(plistName: plistName(info: Bundle.main.infoDictionary)) }++ /// Whether `bundle` carries the driver item (every build from 0.21.1).+ public static func isBundled(_ bundle: Bundle = .main) -> Bool {+ let plist = bundle.bundleURL+ .appendingPathComponent("Contents/Library/LaunchAgents")+ .appendingPathComponent(plistName(info: bundle.infoDictionary))+ return FileManager.default.fileExists(atPath: plist.path)+ }++ public static func status() -> AppLoginItemStatus { MainAppLoginItem.map(service.status) }++ /// What the page says when macOS holds the item back.+ public static let needsApproval =+ "Cua Spaces isn't allowed to run in the background, so Cua Driver can't start. Turn on Cua Spaces in System Settings > General > Login Items & Extensions, then choose Repair."++ /// Registers the item when it isn't yet and starts it (`launchctl+ /// kickstart`, `-k` when `restart`). Blocks: call off the main thread.+ /// Returns why it couldn't, in plain words, or nil.+ @discardableResult+ public static func start(restart: Bool) -> String? {+ if service.status != .enabled {+ do {+ try service.register()+ } catch {+ if status() == .requiresApproval { return needsApproval }+ return "Couldn't start Cua Driver in the background: \(error.localizedDescription)"+ }+ }+ if status() == .requiresApproval { return needsApproval }+ if !kickstart(restart: restart) {+ return "Couldn't start Cua Driver in the background: launchd didn't start \(label)"+ }+ return nil+ }++ /// `launchctl kickstart [-k] gui/<uid>/<label>`. False when launchctl+ /// failed (the item 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+ }++ /// `CuaSpacesMac --driver-helper register|unregister|status`: prints one+ /// JSON object (`status`, and `error`), returns the exit code.+ public static func run(_ args: [String]) -> Int32 {+ var failure: String?+ switch args.first {+ case "register":+ do { try service.register() } catch { failure = error.localizedDescription }+ case "unregister":+ if service.status != .notRegistered {+ do { try service.unregister() } catch {+ if status() != .notRegistered, status() != .notFound { failure = error.localizedDescription }+ }+ }+ case "status": break+ default:+ FileHandle.standardError.write(Data("usage: CuaSpacesMac --driver-helper run|register|unregister|status\n".utf8))+ return 2+ }+ var out: [String: String] = ["status": HelperService.name(status())]+ if let failure { out["error"] = failure }+ if let data = try? JSONSerialization.data(withJSONObject: out, options: [.sortedKeys]) {+ FileHandle.standardOutput.write(data + Data("\n".utf8))+ }+ return failure == nil ? 0 : 1+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DriverSupervisor.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DriverSupervisor.swiftnew file mode 100644index 0000000000..8fd3c444be--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DriverSupervisor.swift@@ -0,0 +1,355 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Darwin+import Foundation++/// What Cua Driver's login item last reported, in+/// [`EmbeddedDriver.statusFile`] (`<CuaHome>/run/cua-driver.status.json`).+/// The Cua Driver page reads it to say why the driver isn't running.+public struct DriverSupervisorReport: Codable, Equatable, Sendable {+ /// `starting`, `ready`, `paused`, `waiting` (to start again after a+ /// failure) or `stopped`.+ public var state: String+ /// The running driver's pid (`ready`).+ public var pid: Int32?+ /// Why the last start failed or the driver stopped, in plain words.+ public var lastError: String?+ /// Restarts since the login item started.+ public var restarts: Int+ /// The login item's own pid.+ public var supervisorPid: Int32+ /// Seconds since 1970.+ public var at: Double++ public static func read(_ path: String) -> DriverSupervisorReport? {+ guard let data = FileManager.default.contents(atPath: path) else { return nil }+ return try? JSONDecoder().decode(DriverSupervisorReport.self, from: data)+ }++ /// Whether the login item that wrote this is still running.+ public var supervisorAlive: Bool { supervisorPid > 0 && (kill(supervisorPid, 0) == 0 || errno == EPERM) }+}++/// Keeps `cua-driver serve --embedded` running for the coding agents on+/// this Mac, as a direct child of the process that runs it (the app's Cua+/// Driver login item, `CuaSpacesMac --driver-helper run`), so macOS holds+/// Cua Spaces responsible for it. Starts it, waits until it answers on its+/// socket, restarts it with a backoff (1 s, doubling, at most a minute)+/// when it exits, stops it while the person has paused agents, and writes+/// every step and the last error to [`EmbeddedDriver.statusFile`].+///+/// The driver is started with a stdin pipe it watches+/// (`--parent-liveness-stdio`): when this process goes, so does it.+public final class DriverSupervisor: @unchecked Sendable {+ public struct Options: Sendable {+ /// How long a starting driver has to answer on its socket.+ public var startupTimeout: TimeInterval = 20+ /// Uptime after which an exit is a fresh failure, not a crash loop.+ public var stableUptime: TimeInterval = 120+ /// How often the loop looks at the child, the pause marker and the+ /// start request.+ public var poll: TimeInterval = 0.25+ /// The longest wait between two starts.+ public var maxDelay: TimeInterval = 60+ public init() {}+ }++ public let driver: EmbeddedDriver+ let options: Options+ private var child: Process?+ private var liveness: Pipe?+ private var restarts = 0+ private var lastError: String?++ public init(driver: EmbeddedDriver, options: Options = Options()) {+ self.driver = driver+ self.options = options+ }++ /// The wait before start number `attempt + 1` after `attempt` failures+ /// in a row: 1 s, doubling, at most `max`.+ public static func restartDelay(attempt: Int, max: TimeInterval = 60) -> TimeInterval {+ min(max, pow(2, Double(Swift.max(0, Swift.min(attempt, 16) - 1))))+ }++ /// `cua-driver serve --embedded ...`: what the driver SDK's embedded+ /// host passes (`EmbeddedCuaDriverHost::serve_args`).+ public static func serveArguments(_ d: EmbeddedDriver) -> [String] {+ ["serve", "--embedded", "--parent-liveness-stdio", "--no-permissions-gate",+ "--socket", d.socket, "--host-bundle-id", d.hostBundleId, "--permission-mode", "standard"]+ }++ /// The driver's environment: only what the SDK's embedded host passes+ /// on (`allowed_environment_name`), plus who hosts it.+ public static func childEnvironment(_ inherited: [String: String], hostPid: Int32) -> [String: String] {+ let names: Set<String> = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TMP", "TEMP", "LANG"]+ var env = inherited.filter { names.contains($0.key) || $0.key.hasPrefix("LC_") || $0.key.hasPrefix("CUA_DRIVER_") }+ env["CUA_DRIVER_EMBEDDED_HOST_PID"] = String(hostPid)+ return env+ }++ // MARK: - The loop++ /// Runs until `shouldStop` says so, then stops the driver. Never+ /// returns early: every failure is reported and retried.+ public func run(shouldStop: () -> Bool) {+ var attempt = 0+ outer: while !shouldStop() {+ if let error = prepareRunDirectory() {+ lastError = error+ report("waiting")+ if sleepWatching(5, shouldStop: shouldStop) == .stop { break }+ continue+ }+ if paused {+ report("paused")+ attempt = 0+ if sleepWatching(options.poll, shouldStop: shouldStop) == .stop { break }+ continue+ }+ // A request written while nothing waited for it is answered by+ // this start.+ _ = takeStartRequest()+ report("starting")+ let started = Date()+ switch launch(shouldStop: shouldStop) {+ case .stopped:+ break outer+ case let .failed(reason):+ lastError = reason+ NSLog("cua-spaces driver: Cua Driver didn't start: %@", reason)+ case let .ready(pid):+ lastError = nil+ report("ready", pid: pid)+ NSLog("cua-spaces driver: Cua Driver is running (pid %d)", pid)+ watch: while true {+ if shouldStop() { break outer }+ if paused {+ NSLog("cua-spaces driver: agents paused; stopping Cua Driver")+ stopChild()+ attempt = 0+ continue outer+ }+ if let child, !child.isRunning {+ lastError = "Cua Driver stopped (\(Self.exitText(child)))\(tail(of: child))"+ NSLog("cua-spaces driver: %@", lastError ?? "")+ self.child = nil+ liveness = nil+ break watch+ }+ Thread.sleep(forTimeInterval: options.poll)+ }+ }+ if Date().timeIntervalSince(started) >= options.stableUptime { attempt = 0 }+ attempt += 1+ restarts += 1+ report("waiting")+ if sleepWatching(Self.restartDelay(attempt: attempt, max: options.maxDelay), shouldStop: shouldStop,+ wakeOnStartRequest: true) == .stop { break }+ }+ stopChild()+ report("stopped")+ }++ enum Launch: Equatable {+ case ready(Int32)+ case failed(String)+ case stopped+ }++ private var logOffset: UInt64 = 0++ /// Starts the driver and waits until it answers on its socket as this+ /// child, embedded, for this app.+ func launch(shouldStop: () -> Bool) -> Launch {+ guard FileManager.default.isExecutableFile(atPath: driver.binary) else {+ return .failed("there is no Cua Driver at \(driver.binary); reinstall Cua Spaces")+ }+ if let conflict = Self.prepareEndpoint(driver.socket) { return .failed(conflict) }+ let log = openLog()+ let p = Process()+ p.executableURL = URL(fileURLWithPath: driver.binary)+ p.arguments = Self.serveArguments(driver)+ p.environment = Self.childEnvironment(ProcessInfo.processInfo.environment, hostPid: getpid())+ let pipe = Pipe()+ p.standardInput = pipe+ p.standardOutput = FileHandle.nullDevice+ p.standardError = log ?? FileHandle.nullDevice+ do {+ try p.run()+ } catch {+ return .failed("couldn't run \(driver.binary): \(error.localizedDescription)")+ }+ try? log?.close()+ child = p+ liveness = pipe+ let deadline = Date().addingTimeInterval(options.startupTimeout)+ while true {+ if shouldStop() {+ stopChild()+ return .stopped+ }+ if !p.isRunning {+ child = nil+ liveness = nil+ return .failed("Cua Driver quit while starting (\(Self.exitText(p)))\(tail(of: p))")+ }+ if let meta = driver.metadata(timeout: 1), meta.pid == p.processIdentifier {+ guard meta.embedded, meta.hostBundleId == driver.hostBundleId else {+ stopChild()+ return .failed("Cua Driver started, but not as part of Cua Spaces (embedded: \(meta.embedded), host: \(meta.hostBundleId ?? "none"))")+ }+ return .ready(p.processIdentifier)+ }+ if Date() >= deadline {+ stopChild()+ return .failed("Cua Driver didn't answer within \(Int(options.startupTimeout)) s\(tail(of: nil))")+ }+ Thread.sleep(forTimeInterval: 0.1)+ }+ }++ /// Stops the running driver: closes its stdin (it exits on its own),+ /// then SIGTERM, then SIGKILL.+ func stopChild() {+ guard let p = child else { return }+ child = nil+ try? liveness?.fileHandleForWriting.close()+ liveness = nil+ if waitExit(p, seconds: 5) { return }+ p.terminate()+ if waitExit(p, seconds: 2) { return }+ kill(p.processIdentifier, SIGKILL)+ _ = waitExit(p, seconds: 2)+ }++ private func waitExit(_ p: Process, seconds: TimeInterval) -> Bool {+ let end = Date().addingTimeInterval(seconds)+ while p.isRunning, Date() < end { Thread.sleep(forTimeInterval: 0.05) }+ return !p.isRunning+ }++ // MARK: - Files++ /// Clears the socket path before a start, as the SDK's embedded host+ /// does (`prepare_endpoint`): a driver that died (a crash, SIGKILL)+ /// leaves its socket file, and an embedded driver refuses to start over+ /// one. A socket nobody accepts on is removed; one that answers, or a+ /// path that isn't a socket, is reported. Nil, or why not.+ public static func prepareEndpoint(_ path: String) -> String? {+ var before = stat()+ guard lstat(path, &before) == 0 else {+ return errno == ENOENT ? nil : "can't read \(path): \(String(cString: strerror(errno)))"+ }+ guard before.st_mode & S_IFMT == S_IFSOCK else {+ return "\(path) is in the way (not a socket); remove it"+ }+ if acceptsConnections(path) {+ return "another Cua Driver is already running on \(path)"+ }+ var now = stat()+ guard lstat(path, &now) == 0, now.st_mode & S_IFMT == S_IFSOCK,+ now.st_dev == before.st_dev, now.st_ino == before.st_ino else {+ return "\(path) changed while it was checked"+ }+ guard unlink(path) == 0 else {+ return "can't remove the old socket \(path): \(String(cString: strerror(errno)))"+ }+ return nil+ }++ static func acceptsConnections(_ path: String) -> Bool {+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)+ guard fd >= 0 else { return false }+ defer { close(fd) }+ var addr = sockaddr_un()+ addr.sun_family = sa_family_t(AF_UNIX)+ let bytes = Array(path.utf8)+ guard bytes.count < MemoryLayout.size(ofValue: addr.sun_path) else { return false }+ withUnsafeMutableBytes(of: &addr.sun_path) { raw in+ raw.copyBytes(from: bytes)+ raw[bytes.count] = 0+ }+ return withUnsafePointer(to: &addr) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }+ } == 0+ }++ var paused: Bool { FileManager.default.fileExists(atPath: driver.pausedMarker) }++ func takeStartRequest() -> Bool {+ (try? FileManager.default.removeItem(atPath: driver.startRequest)) != nil+ }++ /// `<CuaHome>/run`, 0700 (the socket lives there). Nil, or why not.+ func prepareRunDirectory() -> String? {+ let dir = (driver.socket as NSString).deletingLastPathComponent+ do {+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: dir)+ return nil+ } catch {+ return "can't create \(dir): \(error.localizedDescription)"+ }+ }++ /// The driver's log, opened for appending; trimmed when over 8 MB.+ private func openLog() -> FileHandle? {+ let path = driver.logFile+ try? FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)+ if let size = (try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? UInt64, size > 8 << 20 {+ try? FileManager.default.removeItem(atPath: path)+ }+ if !FileManager.default.fileExists(atPath: path) {+ FileManager.default.createFile(atPath: path, contents: nil, attributes: [.posixPermissions: 0o600])+ }+ guard let h = FileHandle(forWritingAtPath: path) else { return nil }+ logOffset = (try? h.seekToEnd()) ?? 0+ return h+ }++ /// ": <the driver's last line of output since it started>", or "".+ private func tail(of _: Process?) -> String {+ guard let h = FileHandle(forReadingAtPath: driver.logFile) else { return "" }+ defer { try? h.close() }+ let end = (try? h.seekToEnd()) ?? 0+ let from = max(logOffset, end > 65536 ? end - 65536 : 0)+ guard end > from, (try? h.seek(toOffset: from)) != nil, let data = try? h.readToEnd() else { return "" }+ let line = String(decoding: data, as: UTF8.self)+ .split(whereSeparator: \.isNewline)+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .last { !$0.isEmpty } ?? ""+ return line.isEmpty ? "" : ": " + String(line.prefix(300))+ }++ static func exitText(_ p: Process) -> String {+ p.terminationReason == .uncaughtSignal ? "signal \(p.terminationStatus)" : "exit code \(p.terminationStatus)"+ }++ private func report(_ state: String, pid: Int32? = nil) {+ let r = DriverSupervisorReport(state: state, pid: pid, lastError: lastError, restarts: restarts,+ supervisorPid: getpid(), at: Date().timeIntervalSince1970)+ guard let data = try? JSONEncoder().encode(r) else { return }+ try? data.write(to: URL(fileURLWithPath: driver.statusFile), options: .atomic)+ }++ private enum Wake { case stop, time, request, pause }++ /// Sleeps `seconds`, or less when asked to stop, when the person pauses+ /// agents, or (`wakeOnStartRequest`) when the app asks for a start now.+ private func sleepWatching(_ seconds: TimeInterval, shouldStop: () -> Bool, wakeOnStartRequest: Bool = false) -> Wake {+ let end = Date().addingTimeInterval(seconds)+ let wasPaused = paused+ while Date() < end {+ if shouldStop() { return .stop }+ if wakeOnStartRequest, takeStartRequest() {+ NSLog("cua-spaces driver: Cua Spaces asked for Cua Driver now; starting it")+ return .request+ }+ if paused != wasPaused { return .pause }+ Thread.sleep(forTimeInterval: min(options.poll, max(0, end.timeIntervalSinceNow)))+ }+ return .time+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swiftindex a013b395a2..dde49f1b2f 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift@@ -5,8 +5,8 @@ import Darwinimport Foundation/// Cua Driver inside Cua Spaces (CUA-2706): the `cua-driver` this app-/// carries in `Contents/Helpers`, which cua-spacesd runs as its own child-/// (`serve --embedded`, `libs/cua-spacesd/.../embedded_driver.rs`). macOS+/// carries in `Contents/Helpers`, run as `serve --embedded` by the app's+/// own Cua Driver login item (`DriverService`, `DriverSupervisor`). macOS/// holds Cua Spaces responsible for it, so Accessibility and Screen/// Recording are Cua Spaces' and no second app shows in System Settings.///@@ -26,33 +26,42 @@ public struct EmbeddedDriver: Sendable {/// writes over the released app's entry.public let serverName: String- /// While this file exists the person has paused agents and cua-spacesd- /// runs no driver (`embedded_driver::paused_marker`).+ /// While this file exists the person has paused agents and the login item+ /// runs no driver (`DriverSupervisor`).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`).+ /// Written to have the login item start a driver that isn't running now,+ /// instead of after its restart backoff (`DriverSupervisor`).public var startRequest: String { ((socket as NSString).deletingLastPathComponent as NSString).appendingPathComponent("cua-driver.start") }+ /// What its login item reports (`DriverSupervisorReport`): beside the+ /// socket.+ public var statusFile: String { ((socket as NSString).deletingLastPathComponent as NSString).appendingPathComponent("cua-driver.status.json") }++ /// `<CuaHome>`: the folder above `run/`.+ public var cuaHome: String { ((socket as NSString).deletingLastPathComponent as NSString).deletingLastPathComponent }++ /// Where the driver's own output goes: `<CuaHome>/logs/cua-driver.log`.+ public var logFile: String { ((cuaHome as NSString).appendingPathComponent("logs") as NSString).appendingPathComponent("cua-driver.log") }+/// 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.+ /// do next to get a driver that isn't answering running. Cua Driver+ /// runs from its own login item (`DriverService`), so this never+ /// depends on whether this Mac is set up, shared, paused or signed in:+ /// only the person's switch turns it off (CUA-3638).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+ /// Register the login item if needed, start it and ask it for a+ /// driver now ([`startRequest`]).+ case startLoginItem+ /// That didn't bring a driver up: restart the login item.+ case restartLoginItem}- public static func startStep(paused: Bool, answering: Bool, setUp: Bool, askedHostService: Bool) -> StartStep {+ public static func startStep(paused: Bool, answering: Bool, askedLoginItem: Bool) -> StartStep {if paused || answering { return .none }- if !setUp { return .needsSetUp }- return askedHostService ? .restartHostService : .askHostService+ return askedLoginItem ? .restartLoginItem : .startLoginItem}/// This app's embedded driver, or nil when the bundle carries none (adiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swiftindex 6f16c34972..877b91885d 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift@@ -20,6 +20,10 @@ public struct HostSetupFailure: Equatable, Sendable {case signedOut/// macOS did not start the host service (launchd).case service+ /// The account already has computers: a new one is added from one+ /// of them, or with a pairing code (the relay's rule for an+ /// account with phone support).+ case addFromAnotherComputercase other}@@ -107,6 +111,8 @@ public struct HostSetupFailure: Equatable, Sendable {if any(["launchctl", "launchd", "host service", "bootstrap failed"]) { return .service }+ if any(["add computers from a computer you already added"]) { return .addFromAnotherComputer }+if word("401") || any(["signed out", "not signed in", "sign in again", "please sign in", "unauthenticated", "unauthorized","login required", "not logged in", "session expired", "token expired", "invalid token",@@ -142,6 +148,10 @@ public struct HostSetupFailure: Equatable, Sendable {return ("Couldn\u{2019}t start the Cua host service","macOS didn\u{2019}t start the service your other machines connect to. Try again; "+ "if it keeps failing, restart this Mac.")+ case .addFromAnotherComputer:+ return ("Add this Mac from another computer",+ "Your account already has computers, so a new Mac is added from one of them or with a pairing code. "+ + "Open Cua Spaces on one of your computers and add this Mac from there.")case .other:return ("Couldn\u{2019}t set up this Mac for access","Something went wrong. Try again, or open Details to see what happened.")diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swiftindex bdfbe0eba3..82cbc38dca 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift@@ -219,12 +219,13 @@ public enum HelperService {public static let restartExitCode: Int32 = 75/// A launch of this executable that is not the app's window: the host- /// service and its commands (`--service-helper`, `check-permissions`,+ /// service, Cua Driver's login item and their commands+ /// (`--service-helper`, `--driver-helper`, `check-permissions`,/// `preflight-permissions`). These must never touch AppKit or start/// anything that does (the Sentry SDK): a windowless process checked in/// with LaunchServices as "Cua Spaces" makes opening the app fail.public static func isServiceCommand(_ args: [String]) -> Bool {- ["--service-helper", "check-permissions", "preflight-permissions"].contains(args.first ?? "")+ ["--service-helper", "--driver-helper", "check-permissions", "preflight-permissions"].contains(args.first ?? "")}/// The service holds the app's LaunchServices entry: it shows as adiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swiftindex 86f476afcb..36d8efd8f1 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift@@ -301,6 +301,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {func applicationDidFinishLaunching(_ notification: Notification) {// The host service still running from before an update: onto this build (CUA-2457).HelperService.restartIfStale()+ // Cua Driver for this Mac's coding agents: its own login item,+ // registered and started here whatever this Mac shares (CUA-3638).+ if DriverService.isBundled(), EmbeddedDriver.current() != nil {+ DispatchQueue.global(qos: .utility).async {+ if let why = DriverService.start(restart: false) { NSLog("cua-spaces: %@", why) }+ }+ }start(Self.model)// The menu bar's low-disk warning: read now, then every 5 minutes.LowDiskMonitor.shared.start()diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swiftindex 7fdc5108dc..9454c59b58 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift@@ -59,8 +59,8 @@ 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.+ // Switched on: a driver that isn't running starts now, whatever+ // this Mac shares.if !paused { await startDriverIfNeeded(driver) }return NSNull()case "driver.setup":@@ -129,15 +129,12 @@ extension WebUIBridge {if paused {state = "paused"} else if meta == nil {- let spec = HelperService.specPath(info: Bundle.main.infoDictionary, home: NSHomeDirectory())- if spec.map({ !FileManager.default.fileExists(atPath: $0) }) ?? true {- state = "stopped"- lastError = "Cua Driver starts once this Mac is set up in Cua Spaces. Open Machines and set up this Mac."- } else if Date().timeIntervalSince(DriverPageState.shared.since) < 30 {+ let why = await Task.detached { Self.notRunningReason(driver) }.value+ if why == nil, Date().timeIntervalSince(DriverPageState.shared.since) < 30 {state = "starting"} else {state = "failed"- lastError = "Cua Driver isn't answering. Repair starts it again."+ lastError = why ?? "Cua Driver isn't answering. Repair starts it again."}} else if !screen || !accessibility {state = "needs-permission"@@ -192,6 +189,8 @@ extension WebUIBridge {_ = try driver.call("get_screen_size")_ = try driver.call("move_cursor", ["x": 200, "y": 200, "cursor_id": "cua-spaces-setup-test", "session": "cua-spaces-setup-test"])return nil+ } catch let error as EmbeddedDriver.CallError where error.message == "Cua Driver isn't running" {+ return Self.notRunningReason(driver).map { "Cua Driver isn't running. \($0)" } ?? error.message} catch {return "\(error)"}@@ -214,7 +213,7 @@ extension WebUIBridge {/// The driver keeps the Screen Recording answer it had when it started:/// granted to Cua Spaces since, it still says no until it starts again.- /// cua-spacesd starts it again within a second when it exits.+ /// Its login item starts it again within a second when it exits.func restartDriverIfStale(_ driver: EmbeddedDriver, force: Bool) async {let state = DriverPageState.sharedif !force, let last = state.lastRestart, Date().timeIntervalSince(last) < 60 { return }@@ -228,41 +227,63 @@ extension WebUIBridge {guard granted.contains(.screenRecording), granted.contains(.accessibility) else { return }state.lastRestart = Date()kill(pid, SIGTERM)- // Wait for cua-spacesd to bring it back (1 s backoff, then startup).+ // Wait for its login item to bring it back (1 s backoff, then startup).for _ in 0..<20 {try? await Task.sleep(for: .milliseconds(500))if let meta = await Task.detached(operation: { driver.metadata(timeout: 1) }).value, meta.pid != pid { return }}}+ /// Why the driver isn't answering, in plain words, or nil when its+ /// login item is (or may still be) starting it: macOS holds the login+ /// item back, the login item isn't running, or the driver's last start+ /// failed (`DriverSupervisorReport`). Blocks briefly: call off the main+ /// thread.+ nonisolated static func notRunningReason(_ driver: EmbeddedDriver) -> String? {+ guard DriverService.isBundled() else {+ return "This build of Cua Spaces has no Cua Driver login item; install the latest Cua Spaces."+ }+ let item = DriverService.status()+ if item == .requiresApproval { return DriverService.needsApproval }+ let report = DriverSupervisorReport.read(driver.statusFile)+ if item != .enabled || report.map({ !$0.supervisorAlive }) == true {+ return "Cua Driver's background item isn't running. Repair starts it again."+ }+ guard let report else { return nil }+ if let error = report.lastError, report.state != "ready" {+ return "Cua Driver didn't start: \(error)"+ }+ return nil+ }+/// 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.+ /// agents: registers and starts Cua Driver's login item and asks it for+ /// a driver now, then restarts the login item when that didn't work.+ /// Never depends on whether this Mac is set up, shared or signed in+ /// (CUA-3638). Returns once the driver answers or each step had its+ /// time; why it didn't is what `notRunningReason` says.func startDriverIfNeeded(_ driver: EmbeddedDriver) async {var asked = falsewhile 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:+ switch EmbeddedDriver.startStep(paused: paused, answering: answering, askedLoginItem: asked) {+ case .none:return- case .askHostService:+ case .startLoginItem:asked = truelet request = driver.startRequesttry? 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)+ if let why = await Task.detached(operation: { DriverService.start(restart: false) }).value {+ NSLog("cua-spaces: %@", why)+ return+ }+ if await waitForDriver(driver, seconds: 15) { return }+ case .restartLoginItem:+ NSLog("cua-spaces: Cua Driver didn't start; restarting its login item")+ _ = await Task.detached { DriverService.start(restart: true) }.value+ _ = await waitForDriver(driver, seconds: 25)return}}@@ -277,7 +298,7 @@ extension WebUIBridge {return false}- /// "Let agents use apps on this Mac": off writes the file cua-spacesd+ /// "Let agents use apps on this Mac": off writes the file the driver login item/// watches, which stops the driver; on removes it.private func setDriverPaused(_ driver: EmbeddedDriver, _ paused: Bool) throws {let marker = driver.pausedMarkerdiff --git a/apps/cua-spaces-macos/Support/Helper/com.trycua.spaces.driver.plist b/apps/cua-spaces-macos/Support/Helper/com.trycua.spaces.driver.plistnew file mode 100644index 0000000000..481fb33248--- /dev/null+++ b/apps/cua-spaces-macos/Support/Helper/com.trycua.spaces.driver.plist@@ -0,0 +1,45 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!--+ Cua Spaces.app/Contents/Library/LaunchAgents/com.trycua.spaces.driver.plist:+ Cua Driver for the coding agents on this Mac, as the app's login item,+ registered with SMAppService.agent(plistName:) by the app at launch+ (DriverService). It runs the app's own executable (`--driver-helper run`),+ which keeps Contents/Helpers/cua-driver serve --embedded running as its+ child, so the driver uses the app's Screen Recording and Accessibility+ grants: one name, "Cua Spaces", in System Settings. It runs whether or not+ this Mac is set up, shared or signed in (CUA-3638); only "Let agents use+ apps on this Mac" turns the driver off. Exit 0 (stopped, or the app was+ removed) stays stopped; any other exit (an update) is restarted.+-->+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.trycua.spaces.driver</string>+ <key>BundleProgram</key>+ <string>Contents/MacOS/CuaSpacesMac</string>+ <key>ProgramArguments</key>+ <array>+ <string>CuaSpacesMac</string>+ <string>--driver-helper</string>+ <string>run</string>+ </array>+ <key>AssociatedBundleIdentifiers</key>+ <array>+ <string>com.trycua.spaces.macos</string>+ </array>+ <key>LimitLoadToSessionType</key>+ <string>Aqua</string>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <dict>+ <key>SuccessfulExit</key>+ <false/>+ </dict>+ <key>ThrottleInterval</key>+ <integer>5</integer>+ <key>ProcessType</key>+ <string>Interactive</string>+</dict>+</plist>diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DriverSupervisorTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DriverSupervisorTests.swiftnew file mode 100644index 0000000000..cf7404ce59--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DriverSupervisorTests.swift@@ -0,0 +1,233 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Darwin+import Foundation+import Testing+@testable import CuaSpacesMacKit++/// Cua Driver's login item (CUA-3638): it starts the driver whatever this+/// Mac shares, restarts it with a backoff, honours the person's pause and,+/// when the driver won't start, says why in the report the page reads.+@Suite(.serialized)+struct DriverSupervisorTests {+ /// A scratch Cua home under /tmp (socket paths must stay short).+ final class Home: @unchecked Sendable {+ let dir: URL+ init() throws {+ dir = URL(fileURLWithPath: "/tmp").appendingPathComponent("ds-\(UUID().uuidString.prefix(8))")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ }+ deinit { try? FileManager.default.removeItem(at: dir) }++ func driver(script: String) throws -> EmbeddedDriver {+ let bin = dir.appendingPathComponent("cua-driver")+ try script.write(to: bin, atomically: true, encoding: .utf8)+ chmod(bin.path, 0o755)+ return EmbeddedDriver(binary: bin.path, socket: dir.appendingPathComponent("run/cua-driver.sock").path,+ hostBundleId: "com.trycua.spaces.macos", serverName: "cua-driver")+ }+ }++ /// A stand-in for `cua-driver serve --embedded`: answers `metadata` on+ /// its socket as itself, and exits when its stdin closes (the parent+ /// liveness pipe), as the real one does.+ static let answeringDriver = #"""+ #!/usr/bin/python3+ import json, os, socket, sys, threading+ a = sys.argv+ path = a[a.index("--socket") + 1]+ host = a[a.index("--host-bundle-id") + 1]+ assert "--embedded" in a and "--parent-liveness-stdio" in a+ def liveness():+ sys.stdin.buffer.read()+ os._exit(0)+ threading.Thread(target=liveness, daemon=True).start()+ try: os.unlink(path)+ except FileNotFoundError: pass+ s = socket.socket(socket.AF_UNIX); s.bind(path); s.listen(8)+ while True:+ c, _ = s.accept()+ c.recv(65536)+ c.sendall((json.dumps({"ok": True, "result": {"driver_version": "9.9.9", "pid": os.getpid(), "embedded": True, "host_bundle_id": host}}) + "\n").encode())+ c.close()+ """#++ static func options() -> DriverSupervisor.Options {+ var o = DriverSupervisor.Options()+ o.startupTimeout = 5+ o.poll = 0.05+ o.maxDelay = 0.2+ return o+ }++ /// Runs `supervisor` on a thread until `until` holds for its report+ /// (or 15 s), then stops it and returns the last report.+ static func run(_ supervisor: DriverSupervisor, until: @escaping (DriverSupervisorReport) -> Bool) -> DriverSupervisorReport? {+ let stop = Flag()+ let done = DispatchSemaphore(value: 0)+ Thread.detachNewThread {+ supervisor.run { stop.isSet }+ done.signal()+ }+ let end = Date().addingTimeInterval(15)+ var last: DriverSupervisorReport?+ while Date() < end {+ last = DriverSupervisorReport.read(supervisor.driver.statusFile)+ if let last, until(last) { break }+ Thread.sleep(forTimeInterval: 0.05)+ }+ stop.set()+ _ = done.wait(timeout: .now() + 15)+ return last+ }++ final class Flag: @unchecked Sendable {+ private let lock = NSLock()+ private var value = false+ var isSet: Bool { lock.lock(); defer { lock.unlock() }; return value }+ func set() { lock.lock(); value = true; lock.unlock() }+ }++ /// A driver that won't start is not a silent "not running": the report+ /// carries its exit and its last words, and it is tried again.+ @Test func aDriverThatWontStartSaysWhy() throws {+ let home = try Home()+ let driver = try home.driver(script: "#!/bin/sh\necho 'error: socket is held by another process' >&2\nexit 3\n")+ let report = Self.run(DriverSupervisor(driver: driver, options: Self.options())) { $0.restarts >= 2 }+ let r = try #require(report)+ let error = try #require(r.lastError)+ #expect(error.contains("exit code 3"), "\(error)")+ #expect(error.contains("socket is held by another process"), "\(error)")+ #expect(r.restarts >= 2)+ #expect(FileManager.default.fileExists(atPath: driver.logFile))+ // The run folder the socket lives in is private.+ let mode = try FileManager.default.attributesOfItem(atPath: (driver.socket as NSString).deletingLastPathComponent)[.posixPermissions] as? Int+ #expect(mode == 0o700)+ }++ /// A missing binary is reported plainly.+ @Test func aMissingDriverIsReported() throws {+ let home = try Home()+ var driver = try home.driver(script: "#!/bin/sh\n")+ driver = EmbeddedDriver(binary: home.dir.appendingPathComponent("nope").path, socket: driver.socket,+ hostBundleId: driver.hostBundleId, serverName: driver.serverName)+ let r = try #require(Self.run(DriverSupervisor(driver: driver, options: Self.options())) { $0.lastError != nil })+ #expect(r.lastError?.contains("there is no Cua Driver") == true)+ }++ /// Started, it answers as this child, embedded, for this app; killed,+ /// it comes back as a new process; stopped, it is gone.+ @Test func startsAndRestartsTheDriver() throws {+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { return }+ let home = try Home()+ let driver = try home.driver(script: Self.answeringDriver)+ let supervisor = DriverSupervisor(driver: driver, options: Self.options())+ var firstPid: Int32?+ let r = try #require(Self.run(supervisor) { report in+ guard report.state == "ready", let pid = report.pid else { return false }+ if firstPid == nil {+ firstPid = pid+ kill(pid, SIGKILL)+ return false+ }+ return pid != firstPid+ })+ #expect(r.state == "ready")+ #expect(r.restarts >= 1)+ #expect(r.lastError == nil)+ // After the stop, nothing answers and the report says stopped.+ #expect(driver.metadata(timeout: 0.5) == nil)+ #expect(DriverSupervisorReport.read(driver.statusFile)?.state == "stopped")+ }++ /// A driver killed outright leaves its socket file behind, and the+ /// real one refuses to start over it ("embedded daemon endpoint already+ /// exists"): the supervisor clears a socket nobody answers on, as the+ /// SDK's host does, and reports one that does answer or a path that+ /// isn't a socket (seen on the VM check for 0.21.1).+ @Test func aStaleSocketIsClearedBeforeAStart() throws {+ let home = try Home()+ let path = home.dir.appendingPathComponent("s.sock").path+ #expect(DriverSupervisor.prepareEndpoint(path) == nil, "nothing there")+ // A socket left by a dead process: bound, never listened on.+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)+ var addr = sockaddr_un()+ addr.sun_family = sa_family_t(AF_UNIX)+ withUnsafeMutableBytes(of: &addr.sun_path) { raw in+ let b = Array(path.utf8)+ raw.copyBytes(from: b)+ raw[b.count] = 0+ }+ let bound = withUnsafePointer(to: &addr) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }+ }+ #expect(bound == 0)+ close(fd)+ #expect(FileManager.default.fileExists(atPath: path))+ #expect(DriverSupervisor.prepareEndpoint(path) == nil)+ #expect(!FileManager.default.fileExists(atPath: path), "the stale socket is gone")+ // A file in the way is reported, never removed.+ FileManager.default.createFile(atPath: path, contents: Data())+ #expect(DriverSupervisor.prepareEndpoint(path)?.contains("not a socket") == true)+ #expect(FileManager.default.fileExists(atPath: path))+ }++ /// Killed with SIGKILL (its socket stays), the real driver's refusal+ /// to start over a stale socket never sticks: it comes back.+ @Test func comesBackAfterSIGKILLLeavesItsSocket() throws {+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { return }+ let home = try Home()+ // Like the real one: refuses an existing socket path.+ let script = Self.answeringDriver.replacingOccurrences(+ of: "try: os.unlink(path)\nexcept FileNotFoundError: pass",+ with: "if os.path.exists(path):\n sys.stderr.write('embedded daemon endpoint already exists\\n'); sys.exit(1)")+ #expect(script != Self.answeringDriver)+ let driver = try home.driver(script: script)+ var firstPid: Int32?+ let r = try #require(Self.run(DriverSupervisor(driver: driver, options: Self.options())) { report in+ guard report.state == "ready", let pid = report.pid else { return false }+ if firstPid == nil {+ firstPid = pid+ kill(pid, SIGKILL)+ return false+ }+ return pid != firstPid+ })+ #expect(r.state == "ready", "\(r)")+ #expect(r.pid != firstPid)+ }++ /// Paused by the person: no driver runs, and it starts once the pause+ /// marker goes.+ @Test func thePauseKeepsItOff() throws {+ let home = try Home()+ let ran = home.dir.appendingPathComponent("ran").path+ let driver = try home.driver(script: "#!/bin/sh\ntouch '\(ran)'\nexit 1\n")+ try FileManager.default.createDirectory(atPath: (driver.pausedMarker as NSString).deletingLastPathComponent, withIntermediateDirectories: true)+ FileManager.default.createFile(atPath: driver.pausedMarker, contents: Data("1\n".utf8))+ let r = try #require(Self.run(DriverSupervisor(driver: driver, options: Self.options())) { $0.state == "paused" })+ #expect(r.state == "paused")+ #expect(!FileManager.default.fileExists(atPath: ran))+ }++ @Test func restartsBackOffToAMinute() {+ let secs = (1...9).map { Int(DriverSupervisor.restartDelay(attempt: $0)) }+ #expect(secs == [1, 2, 4, 8, 16, 32, 60, 60, 60])+ }++ /// The driver gets the SDK's arguments and only a safe environment.+ @Test func argumentsAndEnvironment() {+ let d = EmbeddedDriver(binary: "/A/cua-driver", socket: "/h/.cua/run/cua-driver.sock",+ hostBundleId: "com.trycua.spaces.macos", serverName: "cua-driver")+ #expect(DriverSupervisor.serveArguments(d) == [+ "serve", "--embedded", "--parent-liveness-stdio", "--no-permissions-gate",+ "--socket", "/h/.cua/run/cua-driver.sock", "--host-bundle-id", "com.trycua.spaces.macos",+ "--permission-mode", "standard",+ ])+ let env = DriverSupervisor.childEnvironment(["HOME": "/h", "PATH": "/bin", "LC_ALL": "C", "SECRET_TOKEN": "x",+ "CUA_DRIVER_KEY_GAP_MS": "5", "DYLD_INSERT_LIBRARIES": "/x"], hostPid: 7)+ #expect(env == ["HOME": "/h", "PATH": "/bin", "LC_ALL": "C", "CUA_DRIVER_KEY_GAP_MS": "5",+ "CUA_DRIVER_EMBEDDED_HOST_PID": "7"])+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swiftindex d637a7fa81..caed1501a1 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift@@ -27,17 +27,28 @@ 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).+ /// Set up and Repair start a driver that isn't answering through its+ /// own login item, then restart that item. Never while the person has+ /// paused agents, and never "set up this Mac first": whether this Mac is+ /// set up, shared, paused for another account or signed out plays no+ /// part (CUA-3638).@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)+ #expect(D.startStep(paused: false, answering: true, askedLoginItem: false) == .none)+ #expect(D.startStep(paused: true, answering: false, askedLoginItem: false) == .none)+ #expect(D.startStep(paused: false, answering: false, askedLoginItem: false) == .startLoginItem)+ #expect(D.startStep(paused: false, answering: false, askedLoginItem: true) == .restartLoginItem)+ }++ /// Each channel has its own Cua Driver login item, named after its host+ /// service's.+ @Test func theDriverLoginItemFollowsTheChannel() throws {+ #expect(DriverService.label(info: [:]) == "com.trycua.spaces.driver")+ #expect(DriverService.plistName(info: nil) == "com.trycua.spaces.driver.plist")+ #expect(DriverService.label(info: ["CuaHelperLabel": "com.trycua.spaces.local.helper"]) == "com.trycua.spaces.local.driver")+ let d = try #require(EmbeddedDriver.make(binary: "/A/Contents/Helpers/cua-driver", info: [:], bundleId: nil, home: "/Users/ada"))+ #expect(d.statusFile == "/Users/ada/.cua/run/cua-driver.status.json")+ #expect(d.logFile == "/Users/ada/.cua/logs/cua-driver.log")}@Test func knowsItsOwnEntry() throws {diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swiftindex e008869c77..1c094c0a01 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift@@ -23,6 +23,18 @@ struct HostSetupFailureTests {#expect(f.details == Self.missingRelease, "details stay raw")}+ /// The relay refuses a new computer that arrives with a token alone on+ /// an account that already has computers: the page says what to do,+ /// not "Something went wrong" (seen on Share With This Account, 0.21.0).+ @Test func aNewComputerOnAnAccountWithComputersIsAddedFromOne() {+ let raw = "permission denied: relay: add computers from a computer you already added, or with a pairing code"+ let f = HostSetupFailure.presenting(raw)+ #expect(f.kind == .addFromAnotherComputer)+ #expect(f.title == "Add this Mac from another computer")+ #expect(f.message.contains("pairing code"))+ #expect(f.details == raw)+ }+@Test func aThrottledSetupSaysHowLongToWaitInPlainWords() {let raw = "http: Too many attempts right now. Wait 3 seconds, then try again."let f = HostSetupFailure.presenting(raw)diff --git a/apps/cua-spaces-macos/scripts/build-app.sh b/apps/cua-spaces-macos/scripts/build-app.shindex f01c82f856..7e853e848b 100755--- a/apps/cua-spaces-macos/scripts/build-app.sh+++ b/apps/cua-spaces-macos/scripts/build-app.sh@@ -249,6 +249,18 @@ if [ "$channel" = local ]; then/usr/libexec/PlistBuddy -c "Set :AssociatedBundleIdentifiers:0 $bundle_id" "$helper_plist"plutil -lint "$helper_plist" >/dev/nullfi+# Cua Driver's own login item (CUA-3638): `CuaSpacesMac --driver-helper run`+# keeps Contents/Helpers/cua-driver running for this Mac's coding agents,+# whether or not this Mac is set up or shared. Named after the helper's label+# (com.trycua.spaces.driver, com.trycua.spaces.local.driver).+driver_label="${helper_label%.helper}.driver"+driver_plist="$app/Contents/Library/LaunchAgents/$driver_label.plist"+cp "$here/Support/Helper/com.trycua.spaces.driver.plist" "$driver_plist"+if [ "$channel" = local ]; then+ /usr/libexec/PlistBuddy -c "Set :Label $driver_label" "$driver_plist"+ /usr/libexec/PlistBuddy -c "Set :AssociatedBundleIdentifiers:0 $bundle_id" "$driver_plist"+ plutil -lint "$driver_plist" >/dev/null+fi[ -x "$cli" ] && cp "$cli" "$app/Contents/MacOS/cua"# Release: symbols go to dSYMs, not into the download (about 40% of eachdiff --git a/apps/cua-spaces-macos/scripts/build-release.sh b/apps/cua-spaces-macos/scripts/build-release.shindex aa8dd1f4a1..05406071b9 100755--- a/apps/cua-spaces-macos/scripts/build-release.sh+++ b/apps/cua-spaces-macos/scripts/build-release.sh@@ -197,6 +197,8 @@ for f in cua-driver cua-cursor-theme; dodone[ -f "$app/Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist" ] ||{ echo "$app has no com.trycua.spaces.helper.plist" >&2; exit 1; }+[ -f "$app/Contents/Library/LaunchAgents/com.trycua.spaces.driver.plist" ] ||+ { echo "$app has no com.trycua.spaces.driver.plist (Cua Driver's login item)" >&2; exit 1; }# The symbols build-app.sh took out of the binaries, for symbolicating crash# reports (the release workflow keeps it as an artifact; not shipped).if [ -d "$out/dSYMs" ]; thendiff --git a/apps/cua-spaces-macos/scripts/check-local-bundle.sh b/apps/cua-spaces-macos/scripts/check-local-bundle.shindex 0ccaf1f888..d294d3f8f2 100755--- a/apps/cua-spaces-macos/scripts/check-local-bundle.sh+++ b/apps/cua-spaces-macos/scripts/check-local-bundle.sh@@ -114,7 +114,20 @@ if [ -f "$helper" ]; thenelsebad "no helper plist $want_helper.plist in Contents/Library/LaunchAgents"fi-others="$(find "$agents" -maxdepth 1 -name '*.plist' ! -name "$want_helper.plist" 2>/dev/null || true)"+# Cua Driver's login item: its own Local label and owner.+want_driver="${want_helper%.helper}.driver"+prod_driver="${prod_helper%.helper}.driver"+[ ! -e "$agents/$prod_driver.plist" ] || bad "Stable's driver plist ($prod_driver.plist) is in the bundle"+driver_item="$agents/$want_driver.plist"+if [ -f "$driver_item" ]; then+ label="$($pb -c "Print :Label" "$driver_item" 2>/dev/null || true)"+ [ "$label" = "$want_driver" ] || bad "driver plist Label is '$label', want '$want_driver'"+ owner="$($pb -c "Print :AssociatedBundleIdentifiers:0" "$driver_item" 2>/dev/null || true)"+ [ "$owner" = "$want_id" ] || bad "driver AssociatedBundleIdentifiers is '$owner', want '$want_id'"+else+ bad "no driver plist $want_driver.plist in Contents/Library/LaunchAgents"+fi+others="$(find "$agents" -maxdepth 1 -name '*.plist' ! -name "$want_helper.plist" ! -name "$want_driver.plist" 2>/dev/null || true)"[ -z "$others" ] || bad "other launch agents in the bundle: $(printf '%s' "$others" | tr '\n' ' ')"# The signature (build-app.sh signs ad hoc under the bundle id; install-localdiff --git a/apps/cua-spaces-macos/scripts/tests/embedded-driver-vm-check.sh b/apps/cua-spaces-macos/scripts/tests/embedded-driver-vm-check.shindex 69d6e63533..cd78c4a343 100755--- a/apps/cua-spaces-macos/scripts/tests/embedded-driver-vm-check.sh+++ b/apps/cua-spaces-macos/scripts/tests/embedded-driver-vm-check.sh@@ -2,25 +2,26 @@# SPDX-License-Identifier: FSL-1.1-MIT# Copyright (c) 2026 Cua AI, Inc.#-# Live check of the Cua Driver that Cua Spaces runs for coding agents-# (cua-spacesd's embedded child). Run it INSIDE a disposable macOS VM, never-# on a person's Mac: it turns the embedded driver on and drives the agent-# cursor. Before running it, in the VM: install the Cua Spaces build under-# test in /Applications, finish Set up, and allow Accessibility and Screen-# Recording for Cua Spaces when macOS asks (inside the VM only).+# Live check of the Cua Driver that Cua Spaces runs for coding agents (the+# embedded child of its Cua Driver login item, `CuaSpacesMac --driver-helper+# run`). Run it INSIDE a disposable macOS VM, never on a person's Mac: it+# drives the agent cursor. Before running it, in the VM: install the Cua+# Spaces build under test in /Applications, open it once, and allow+# Accessibility and Screen Recording for Cua Spaces when macOS asks (inside+# the VM only). The Mac need not be set up, shared or signed in (CUA-3638).## scripts/tests/embedded-driver-vm-check.sh [/Applications/Cua Spaces.app]## Checks (each prints ok/FAIL; exit 1 on any FAIL):# 1. Contents/Helpers has cua-driver and cua-cursor-theme, signed by the# Cua team; Contents/MacOS has no cua-driver.-# 2. cua-spacesd starts `cua-driver serve --embedded` (on by default) and-# is its parent process, also after the service restarts.+# 2. The driver login item starts `cua-driver serve --embedded` (on by+# default) and is its parent process, also after the item restarts.# 3. The coding-agent route (`cua-driver mcp --embedded --socket ...`)# answers initialize, check_permissions reports both permissions on,# and move_cursor moves the agent cursor without moving the real# pointer.-# 4. Killing the driver: cua-spacesd starts a new one within 10 s.+# 4. Killing the driver: the login item starts a new one within 10 s.# 5. Only Cua Spaces (no CuaDriver) is in the permission lists, when the# TCC databases are readable (needs sudo with Full Disk Access).#@@ -42,7 +43,6 @@ case "$bundle_id" in*) home="$HOME/.cua" ;;esacsocket="$home/run/cua-driver.sock"-spec="$home/helper/service.json"fails=0ok() { echo "ok: $*"; }fail() { echo "FAIL: $*"; fails=$((fails + 1)); }@@ -57,9 +57,12 @@ for f in cua-driver cua-cursor-theme; dodone[ ! -e "$app/Contents/MacOS/cua-driver" ] && ok "no cua-driver in Contents/MacOS" || fail "cua-driver is in Contents/MacOS"-# 2. Restart the host service: the driver comes back as its child.-[ -f "$spec" ] || { fail "no $spec (finish Set up in Cua Spaces first)"; exit 1; }-pkill -x cua-spacesd || true # the app's login item starts it again+# 2. Restart the driver login item: the driver comes back as its child.+case "$bundle_id" in+ com.trycua.spaces.macos.local) label=com.trycua.spaces.local.driver ;;+ *) label=com.trycua.spaces.driver ;;+esac+launchctl kickstart -k "gui/$(id -u)/$label" || fail "launchctl kickstart $label (open Cua Spaces once to register it)"driver_pid=""for _ in $(seq 1 30); dodriver_pid="$(pgrep -f "^$helpers/cua-driver serve --embedded" | head -1)"@@ -72,8 +75,8 @@ elseparent="$(ps -o ppid= -p "$driver_pid" | tr -d ' ')"parent_cmd="$(ps -o command= -p "$parent")"case "$parent_cmd" in- "$helpers/cua-spacesd"*) ok "cua-driver (pid $driver_pid) is cua-spacesd's child (pid $parent)" ;;- *) fail "cua-driver's parent is not cua-spacesd: $parent_cmd" ;;+ *"CuaSpacesMac --driver-helper run"*) ok "cua-driver (pid $driver_pid) is the driver login item's child (pid $parent)" ;;+ *) fail "cua-driver's parent is not the driver login item: $parent_cmd" ;;esacps -o command= -p "$driver_pid" | grep -q -- "--host-bundle-id $bundle_id" &&ok "it runs for $bundle_id" || fail "it doesn't name $bundle_id as its host"