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
feat(spaces-macos): Cua Driver built into Cua Spaces (CUA-2771, CUA-2775) (#6505)
cua-agents[bot]b5125d2eaf24
diff --git a/apps/cua-spaces-desktop/src/bridge/driver.ts b/apps/cua-spaces-desktop/src/bridge/driver.tsnew file mode 100644index 0000000000..0345726dc5--- /dev/null+++ b/apps/cua-spaces-desktop/src/bridge/driver.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The Cua Driver page's methods (`driver.*`, the web's `ops/driver.ts`).+// Only the Mac app carries Cua Driver inside Cua Spaces (an embedded child+// of cua-spacesd, with Cua Spaces' permissions). On Windows and Linux the+// driver runs in-process in cua-spacesd, so this host has no driver of its+// own: `driver.status` answers null, which keeps the page and its sidebar+// entry hidden, and the actions say why.+import type { BridgeContext } from "./context";+import { Failure, type Handlers } from "./host";++const NONE = "Cua Driver inside Cua Spaces comes with the Mac app";++export function driverMethods(_ctx: BridgeContext): Handlers {+ const no = () => {+ throw Failure.unsupported(NONE);+ };+ return {+ "driver.status": () => null,+ "driver.list": () => [],+ "driver.config": no,+ "driver.setConfig": no,+ "driver.test": no,+ "driver.pause": no,+ "driver.setup": no,+ "driver.setApp": no,+ };+}diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.tsindex e802a0a127..3785e3b007 100644--- a/apps/cua-spaces-desktop/src/bridge/index.ts+++ b/apps/cua-spaces-desktop/src/bridge/index.ts@@ -25,6 +25,7 @@ import { joinMethods } from "./join-with-code";import { keyvaultMethods } from "./keyvault";import { hostStatus, machinesMethods } from "./machines";import { ELECTRON_METHODS, METHODS } from "./methods";+import { driverMethods } from "./driver";import { notificationsMethods } from "./notifications";import { nudgesMethods } from "./nudges";import { onboardingMethods } from "./onboarding";@@ -86,6 +87,7 @@ export const AREAS = [ciMethods,threadMethods,agentThreadsMethods,+ driverMethods,presenceMethods,];diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 9b6cd3b45e..bf59a22a3f 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -61,6 +61,8 @@ export const METHODS = ["thread.read", "thread.post", "thread.members", "thread.setRights","thread.agentAdd", "thread.agentRemove","thread.joinCodeCreate", "thread.joinCodeList", "thread.joinCodeCancel", "thread.settings",+ "driver.status", "driver.list", "driver.config", "driver.setConfig", "driver.test", "driver.pause",+ "driver.setup", "driver.setApp",] as const;/** A live desktop's media ticket for the page's WebCodecs player,diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swiftindex 9c6da95171..7f2dbefcd5 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift@@ -67,8 +67,18 @@ public final class LiveAgentSetup: AgentSetupRunning, @unchecked Sendable {return out.map { appAgentSetupOutcome(outcome: $0) }}+ /// With the Cua Driver this app carries ([`EmbeddedDriver`]), the+ /// agents' `cua-driver` entry runs its embedded proxy, so the driver+ /// uses Cua Spaces' permissions and no separate Cua Driver app is+ /// installed. A bare build sets up the installed Cua Driver instead.public func setUpCuaDriver(agents: [String]) async throws -> [AppAgentSetupOutcomeInput] {- try await inner.setupCuaDriver(agents: agents, command: nil, skills: true, mcp: true)+ if let driver = EmbeddedDriver.current() {+ var out = try await inner.installSkills(agents: agents, skills: ["cua-driver"], force: false)+ let server = AgentMcpServer(name: driver.serverName, command: driver.binary, args: driver.mcpArguments, env: [:])+ out += try await inner.configureMcp(agents: agents, server: server)+ return out.map { appAgentSetupOutcome(outcome: $0) }+ }+ return try await inner.setupCuaDriver(agents: agents, command: nil, skills: true, mcp: true).map { appAgentSetupOutcome(outcome: $0) }}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swiftnew file mode 100644index 0000000000..1daf8d8803--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/EmbeddedDriver.swift@@ -0,0 +1,210 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Darwin+import 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+/// holds Cua Spaces responsible for it, so Accessibility and Screen+/// Recording are Cua Spaces' and no second app shows in System Settings.+///+/// Coding agents reach it through `cua-driver mcp --embedded --socket+/// <socket> --host-bundle-id <id>` ([`mcpArguments`]), which Set up writes+/// into their configs. The app reads its state over the same socket.+public struct EmbeddedDriver: Sendable {+ /// `Contents/Helpers/cua-driver`.+ public let binary: String+ /// `<CuaHome>/run/cua-driver.sock`: the same for every launch, because+ /// agents' configs are static files.+ public let socket: String+ /// The app's bundle id: whose permissions the driver uses.+ public let hostBundleId: String+ /// The name agents' configs list it under: `cua-driver`, or+ /// `cua-driver-local` for Cua Spaces Local, so the Local app never+ /// 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`).+ public var pausedMarker: String { ((socket as NSString).deletingLastPathComponent as NSString).appendingPathComponent("cua-driver.off") }++ /// 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? {+ let binary = bundle.bundleURL.appendingPathComponent("Contents/Helpers/cua-driver").path+ guard FileManager.default.isExecutableFile(atPath: binary) else { return nil }+ return make(binary: binary, info: bundle.infoDictionary, bundleId: bundle.bundleIdentifier)+ }++ /// [`current`] with its inputs explicit (tests).+ static func make(binary: String, info: [String: Any]?, bundleId: String?, home: String = NSHomeDirectory()) -> EmbeddedDriver? {+ // <CuaHome>/helper/service.json -> <CuaHome>+ guard let spec = HelperService.specPath(info: info, home: home) else { return nil }+ let cuaHome = ((spec as NSString).deletingLastPathComponent as NSString).deletingLastPathComponent+ let id = bundleId ?? "com.trycua.spaces.macos"+ return EmbeddedDriver(+ binary: binary,+ socket: (cuaHome as NSString).appendingPathComponent("run/cua-driver.sock"),+ hostBundleId: id,+ serverName: id.hasSuffix(".local") ? "cua-driver-local" : "cua-driver")+ }++ /// The MCP server's arguments: the stdio proxy to the embedded driver.+ public var mcpArguments: [String] {+ ["mcp", "--embedded", "--socket", socket, "--host-bundle-id", hostBundleId]+ }++ /// Whether an agent's MCP entry runs this driver: our binary with+ /// `--embedded` and our socket.+ public func isOurs(command: String, args: [String]) -> Bool {+ let resolved = (command as NSString).resolvingSymlinksInPath+ return (command == binary || resolved == (binary as NSString).resolvingSymlinksInPath)+ && args.contains("--embedded") && args.contains(socket)+ }++ // MARK: - The driver's socket++ /// What the driver says about itself (`metadata`).+ public struct Metadata: Sendable, Equatable {+ public var version: String+ public var pid: Int32+ public var embedded: Bool+ public var hostBundleId: String?+ }++ public struct CallError: Error, Sendable, CustomStringConvertible {+ public let message: String+ public var description: String { message }+ }++ /// `metadata`, or nil when nothing answers on the socket.+ public func metadata(timeout: TimeInterval = 2) -> Metadata? {+ guard let reply = try? Self.request(socket: socket, ["method": "metadata"], timeout: timeout),+ reply["ok"] as? Bool == true, let m = reply["result"] as? [String: Any] else { return nil }+ return Metadata(version: m["driver_version"] as? String ?? "",+ pid: (m["pid"] as? NSNumber)?.int32Value ?? 0,+ embedded: m["embedded"] as? Bool ?? false,+ hostBundleId: m["host_bundle_id"] as? String)+ }++ /// One tool call: the tool's structured result (else its text), or the+ /// tool's error in its own words.+ public func call(_ tool: String, _ args: [String: Any] = [:], timeout: TimeInterval = 10) throws -> Any {+ let reply: [String: Any]+ do {+ reply = try Self.request(socket: socket, ["method": "call", "name": tool, "args": args], timeout: timeout)+ } catch {+ throw CallError(message: "Cua Driver isn't running")+ }+ guard reply["ok"] as? Bool == true else {+ throw CallError(message: reply["error"] as? String ?? "\(tool) failed")+ }+ let result = reply["result"] as? [String: Any] ?? [:]+ let text = (result["content"] as? [[String: Any]] ?? []).compactMap { $0["text"] as? String }.joined(separator: "\n")+ if result["isError"] as? Bool == true { throw CallError(message: text.isEmpty ? "\(tool) failed" : text) }+ return result["structuredContent"] ?? text+ }++ /// One request on a fresh connection: a JSON line out, a JSON line back.+ static func request(socket path: String, _ body: [String: Any], timeout: TimeInterval) throws -> [String: Any] {+ let fd = Darwin.socket(AF_UNIX, SOCK_STREAM, 0)+ guard fd >= 0 else { throw CallError(message: "socket: \(errno)") }+ defer { close(fd) }+ var tv = timeval(tv_sec: Int(timeout), tv_usec: Int32((timeout - floor(timeout)) * 1_000_000))+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout<timeval>.size))+ setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, socklen_t(MemoryLayout<timeval>.size))+ var one: Int32 = 1+ setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout<Int32>.size))+ 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 { throw CallError(message: "socket path too long") }+ withUnsafeMutableBytes(of: &addr.sun_path) { raw in+ raw.copyBytes(from: bytes)+ raw[bytes.count] = 0+ }+ let connected = withUnsafePointer(to: &addr) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }+ }+ guard connected == 0 else { throw CallError(message: "connect: \(errno)") }+ var line = try JSONSerialization.data(withJSONObject: body)+ line.append(0x0A)+ let sent = line.withUnsafeBytes { send(fd, $0.baseAddress, $0.count, 0) }+ guard sent == line.count else { throw CallError(message: "send: \(errno)") }+ var reply = Data()+ var buffer = [UInt8](repeating: 0, count: 64 * 1024)+ while !reply.contains(0x0A) {+ let n = recv(fd, &buffer, buffer.count, 0)+ guard n > 0 else { break }+ reply.append(contentsOf: buffer[0..<n])+ }+ let first = reply.split(separator: 0x0A, maxSplits: 1, omittingEmptySubsequences: true).first ?? Data()+ guard let obj = try JSONSerialization.jsonObject(with: Data(first)) as? [String: Any] else {+ throw CallError(message: "no answer")+ }+ return obj+ }++ // MARK: - Agents' configs++ /// An agent's entry for `name` in its MCP config: Claude Code's JSON+ /// (`mcpServers.<name>`) or Codex's TOML (`[mcp_servers.<name>]`).+ public struct Entry: Equatable, Sendable {+ public var command: String+ public var args: [String]+ }++ public static func entry(named name: String, inConfig path: String) -> Entry? {+ let file = (path as NSString).expandingTildeInPath+ guard let text = try? String(contentsOfFile: file, encoding: .utf8) else { return nil }+ if file.hasSuffix(".toml") { return tomlEntry(named: name, text) }+ guard let obj = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any],+ let server = (obj["mcpServers"] as? [String: Any])?[name] as? [String: Any],+ let command = server["command"] as? String else { return nil }+ return Entry(command: command, args: server["args"] as? [String] ?? [])+ }++ /// `[mcp_servers.<name>]` (or `."<name>"`) with its `command` and+ /// `args`: the two keys Set up writes, each on one line.+ static func tomlEntry(named name: String, _ text: String) -> Entry? {+ let headers = ["[mcp_servers.\(name)]", "[mcp_servers.\"\(name)\"]"]+ var inside = false+ var command: String?+ var args: [String] = []+ for raw in text.split(separator: "\n", omittingEmptySubsequences: false) {+ let line = raw.trimmingCharacters(in: .whitespaces)+ if line.hasPrefix("[") {+ if inside { break }+ inside = headers.contains(line)+ continue+ }+ guard inside, let eq = line.firstIndex(of: "=") else { continue }+ let key = line[..<eq].trimmingCharacters(in: .whitespaces)+ let value = String(line[line.index(after: eq)...]).trimmingCharacters(in: .whitespaces)+ if key == "command" { command = tomlStrings(value).first }+ if key == "args" { args = tomlStrings(value) }+ }+ return command.map { Entry(command: $0, args: args) }+ }++ /// The double-quoted strings in a TOML value (`"a"` or `["a", "b"]`).+ static func tomlStrings(_ value: String) -> [String] {+ var out: [String] = []+ var current: String?+ var escaped = false+ for ch in value {+ if var s = current {+ if escaped { s.append(ch); escaped = false; current = s; continue }+ if ch == "\\" { escaped = true; continue }+ if ch == "\"" { out.append(s); current = nil; continue }+ s.append(ch)+ current = s+ } else if ch == "\"" {+ current = ""+ }+ }+ return out+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swiftnew file mode 100644index 0000000000..3b95c5a109--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Driver.swift@@ -0,0 +1,251 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Darwin+import Foundation++/// The Cua Driver page's methods (`driver.*`, `apps/cua-spaces-web/src/+/// bridge/ops/driver.ts`): this Mac's embedded driver ([`EmbeddedDriver`]),+/// read over its socket, with Cua Spaces' own permission check as the truth+/// for Accessibility and Screen Recording (the driver uses the same grants).+@MainActor+final class DriverPageState {+ static let shared = DriverPageState()+ /// The last live test: `DriverLiveTest`.+ var lastTest: [String: Any]?+ /// When the app last restarted a driver whose permission answer was+ /// stale (a running process keeps the Screen Recording answer it had at+ /// launch), so a stuck driver is restarted at most once a minute.+ var lastRestart: Date?+ /// When this app first looked: a driver that isn't up yet is "starting"+ /// for a little while after launch, not "stopped".+ let since = Date()+}++/// The coding agents Set up connects.+private let driverAgents = ["claude-code", "codex"]++extension WebUIBridge {+ func routeDriver(_ method: String, _ args: [String: Any]) async throws -> Any? {+ guard method.hasPrefix("driver.") else { return nil }+ if let machine = args["machine"] as? String, !machine.isEmpty, machine != thisDriverMachineId {+ throw Failure.unsupported("Open Cua Spaces on that computer to see its Cua Driver")+ }+ switch method {+ case "driver.status":+ guard let driver = EmbeddedDriver.current() else { return NSNull() }+ return await driverStatus(driver)+ case "driver.list":+ guard let driver = EmbeddedDriver.current() else { return [Any]() }+ let s = await driverStatus(driver)+ return [["machineId": s["machineId"] ?? "", "name": s["machineName"] ?? "", "os": "macos", "thisMachine": true,+ "state": s["state"] ?? "stopped", "version": orNull(s["version"]), "update": NSNull()]]+ case "driver.config":+ return try await driverCall(try needDriver(), "get_config")+ case "driver.setConfig":+ let driver = try needDriver()+ guard var changes = args["changes"] as? [String: Any] else { throw Failure.badArgs("changes: {key: value}") }+ // The one key that isn't set_config's.+ if let show = changes.removeValue(forKey: "agent_cursor.enabled") as? Bool {+ _ = try await driverCall(driver, "set_agent_cursor_enabled", ["enabled": show])+ }+ if !changes.isEmpty { _ = try await driverCall(driver, "set_config", changes) }+ return try await driverCall(driver, "get_config")+ case "driver.test":+ return await driverLiveTest(try needDriver())+ case "driver.pause":+ let driver = try needDriver()+ guard let paused = args["paused"] as? Bool else { throw Failure.badArgs("paused: boolean") }+ try setDriverPaused(driver, paused)+ return NSNull()+ case "driver.setup":+ let driver = try needDriver()+ try await setUpDriverAgents(driver, agents: driverAgents)+ // A driver whose permission answer is stale starts again.+ await restartDriverIfStale(driver, force: true)+ _ = await driverLiveTest(driver)+ return await driverStatus(driver)+ case "driver.setApp":+ let driver = try needDriver()+ let app = try string(args, "app")+ guard driverAgents.contains(app) else { throw Failure.badArgs("\(app) brings its own Cua Driver") }+ guard args["on"] as? Bool == true else {+ throw Failure.unsupported("Remove Cua Driver from \(app)'s own settings")+ }+ try await setUpDriverAgents(driver, agents: [app])+ return NSNull()+ default:+ throw Failure.unimplemented(method)+ }+ }++ private var thisDriverMachineId: String { model.host.machineId ?? "this-mac" }++ private func needDriver() throws -> EmbeddedDriver {+ guard let driver = EmbeddedDriver.current() else { throw Failure.unsupported("This build of Cua Spaces carries no Cua Driver") }+ return driver+ }++ private func driverCall(_ driver: EmbeddedDriver, _ tool: String, _ args: [String: Any] = [:]) async throws -> Any {+ let sendable = SendableArgs(args)+ do {+ return try await Task.detached { try driver.call(tool, sendable.value) }.value+ } catch let error as EmbeddedDriver.CallError {+ throw Failure(code: "failed", message: error.message)+ }+ }++ /// `DriverStatus`.+ func driverStatus(_ driver: EmbeddedDriver) async -> [String: Any] {+ let paused = FileManager.default.fileExists(atPath: driver.pausedMarker)+ let meta = await Task.detached { driver.metadata() }.value+ let granted = await PermissionGuide.readGranted()+ let screen = granted.contains(.screenRecording), accessibility = granted.contains(.accessibility)+ var lastError: String?+ let state: String+ 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 {+ state = "starting"+ } else {+ state = "failed"+ lastError = "Cua Driver isn't answering. Repair starts it again."+ }+ } else if !screen || !accessibility {+ state = "needs-permission"+ } else {+ state = "ready"+ await restartDriverIfStale(driver, force: false)+ }+ var status: [String: Any] = [+ "machineId": thisDriverMachineId,+ "machineName": model.host.computerName() ?? "This Mac",+ "thisMachine": true,+ "state": state,+ "version": orNull(meta?.version),+ "update": NSNull(),+ "lastTest": orNull(DriverPageState.shared.lastTest),+ "lastError": orNull(lastError),+ "permissions": [+ ["id": "screen", "granted": screen, "settingsUrl": orNull(PermissionGuide.settingsURL(for: .screenRecording))],+ ["id": "accessibility", "granted": accessibility, "settingsUrl": orNull(PermissionGuide.settingsURL(for: .accessibility))],+ ],+ "activity": [Any](),+ "canPause": true,+ ]+ status["apps"] = orNull(await driverApps(driver))+ return status+ }++ /// The coding agents on this Mac and whether each runs this driver.+ private func driverApps(_ driver: EmbeddedDriver) async -> [[String: Any]]? {+ guard let setup = model.agentSetup else { return nil }+ var apps: [[String: Any]] = []+ for s in await setup.statuses() where driverAgents.contains(s.id) && s.installed {+ let entry = s.mcpConfig.flatMap { EmbeddedDriver.entry(named: driver.serverName, inConfig: $0) }+ let on = entry.map { driver.isOurs(command: $0.command, args: $0.args) } ?? false+ apps.append(["id": s.id, "name": s.name, "on": on, "own": entry != nil && !on, "bringsOwn": false])+ }+ let t3 = ["/Applications/T3 Code.app", NSHomeDirectory() + "/Applications/T3 Code.app"]+ if t3.contains(where: { FileManager.default.fileExists(atPath: $0) }) {+ apps.append(["id": "t3-code", "name": "T3 Code", "on": false, "own": false, "bringsOwn": true])+ }+ return apps+ }++ /// Both permissions, the screen read, and one agent-pointer move (the+ /// real pointer stays put): `DriverLiveTest`, kept as the last test.+ func driverLiveTest(_ driver: EmbeddedDriver) async -> [String: Any] {+ let started = Date()+ let failure: String? = await Task.detached { () -> String? in+ do {+ let p = try driver.call("check_permissions", ["prompt": false]) as? [String: Any] ?? [:]+ for (key, name) in [("accessibility", "Accessibility"), ("screen_recording", "Screen Recording")] where !Self.granted(p, key) {+ return "\(name) is off for Cua Spaces"+ }+ _ = 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 {+ return "\(error)"+ }+ }.value+ let test: [String: Any] = [+ "passed": failure == nil,+ "atMs": (started.timeIntervalSince1970 * 1000).rounded(),+ "failure": orNull(failure),+ "tookMs": (Date().timeIntervalSince(started) * 1000).rounded(),+ ]+ DriverPageState.shared.lastTest = test+ return test+ }++ /// `check_permissions` reports `key` granted, as a boolean or `{granted}`.+ nonisolated static func granted(_ permissions: [String: Any], _ key: String) -> Bool {+ if let b = permissions[key] as? Bool { return b }+ return (permissions[key] as? [String: Any])?["granted"] as? Bool ?? false+ }++ /// 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.+ private func restartDriverIfStale(_ driver: EmbeddedDriver, force: Bool) async {+ let state = DriverPageState.shared+ if !force, let last = state.lastRestart, Date().timeIntervalSince(last) < 60 { return }+ let stale: Int32? = await Task.detached { () -> Int32? in+ guard let meta = driver.metadata(), meta.pid > 0,+ let p = try? driver.call("check_permissions", ["prompt": false]) as? [String: Any] else { return nil }+ return Self.granted(p, "accessibility") && Self.granted(p, "screen_recording") ? nil : meta.pid+ }.value+ guard let pid = stale else { return }+ let granted = await PermissionGuide.readGranted()+ 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).+ 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 }+ }+ }++ /// "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 {+ let marker = driver.pausedMarker+ if paused {+ try FileManager.default.createDirectory(atPath: (marker as NSString).deletingLastPathComponent, withIntermediateDirectories: true)+ guard FileManager.default.createFile(atPath: marker, contents: Data("1\n".utf8)) else {+ throw Failure(code: "failed", message: "Couldn't pause agents")+ }+ } else if FileManager.default.fileExists(atPath: marker) {+ try FileManager.default.removeItem(atPath: marker)+ }+ }++ /// Set up and Repair: each agent's MCP entry runs this driver through+ /// its embedded proxy, and the cua-driver skill is installed.+ private func setUpDriverAgents(_: EmbeddedDriver, agents: [String]) async throws {+ guard let setup = model.agentSetup else { throw Failure.unsupported("Agent setup is not available in this build") }+ let installed = await setup.statuses().filter { agents.contains($0.id) && $0.installed }.map(\.id)+ guard !installed.isEmpty else { throw Failure(code: "failed", message: "Install Claude Code or Codex first") }+ let outcomes = try await setup.setUpCuaDriver(agents: installed)+ if let failed = outcomes.first(where: { $0.change == "failed" }) {+ throw Failure(code: "failed", message: failed.detail.isEmpty ? "Couldn't set up \(failed.agents.joined(separator: ", "))" : failed.detail)+ }+ }+}++/// A JSON value, or JSON null.+private func orNull(_ value: Any?) -> Any { value ?? NSNull() }++/// Tool arguments are plain JSON values, safe to hand to a detached task.+private struct SendableArgs: @unchecked Sendable {+ let value: [String: Any]+ init(_ value: [String: Any]) { self.value = value }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 7afb167eaf..26fc5890e7 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -145,6 +145,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"thread.read", "thread.post", "thread.members", "thread.setRights","thread.agentAdd", "thread.agentRemove","thread.joinCodeCreate", "thread.joinCodeList", "thread.joinCodeCancel", "thread.settings",+ // Cua Driver inside Cua Spaces: the embedded driver's page (WebUIBridge+Driver.swift).+ "driver.status", "driver.list", "driver.config", "driver.setConfig", "driver.test", "driver.pause",+ "driver.setup", "driver.setApp",]let model: AppModel@@ -548,6 +551,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {if let result = try routeNudges(method, args) { return result }if let result = try await routeCli(method, args) { return result }if let result = try await routeCi(method, args) { return result }+ if let result = try await routeDriver(method, args) { return result }throw Failure.unimplemented(method)}}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex 4dde9f6c3c..02b99c69e4 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -336,6 +336,9 @@ struct BridgeContractTests {("window.setDragRegions", ["rects": [["x": 78, "y": 0, "width": 400, "height": 48]]]),("window.setDropTargets", ["targets": [["spaceId": space, "x": 20, "y": 60, "width": 232, "height": 180]]]),("startup.get", [:]),+ // A test runner carries no Cua Driver: null and an empty list.+ ("driver.status", [:]),+ ("driver.list", [:]),]}@@ -399,6 +402,12 @@ struct BridgeContractTests {"thread.joinCodeList": "answers the daemon's thread_join_code_list as-is (the page maps it); ThreadBridgeTests covers the arguments","thread.joinCodeCancel": "answers the daemon's thread_join_code_cancel as-is (the page ignores it); ThreadBridgeTests covers the arguments","thread.settings": "answers the daemon's thread_settings as-is (the page maps it); ThreadBridgeTests covers the arguments",+ "driver.config": "needs the bundled Cua Driver running (embedded-driver-vm-check.sh); EmbeddedDriverTests covers the socket",+ "driver.setConfig": "as driver.config",+ "driver.test": "as driver.config (it moves the agent pointer)",+ "driver.pause": "as driver.config (it stops the driver); EmbeddedDriverTests covers the marker path",+ "driver.setup": "writes the coding agents' configs and restarts the driver",+ "driver.setApp": "as driver.setup, for one agent",]static func shapes() throws -> [String: Any] {diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swiftnew file mode 100644index 0000000000..806ee2e1a7--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/EmbeddedDriverTests.swift@@ -0,0 +1,156 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Darwin+import Foundation+import Testing+@testable import CuaSpacesMacKit++struct EmbeddedDriverTests {+ @Test func pathsFollowTheChannel() throws {+ let stable = try #require(EmbeddedDriver.make(binary: "/A/Contents/Helpers/cua-driver", info: [:],+ 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.serverName == "cua-driver")+ #expect(stable.mcpArguments == ["mcp", "--embedded", "--socket", "/Users/ada/.cua/run/cua-driver.sock",+ "--host-bundle-id", "com.trycua.spaces.macos"])++ let local = try #require(EmbeddedDriver.make(binary: "/L/Contents/Helpers/cua-driver",+ info: ["CuaHome": "~/.cua-local", "CuaChannel": "local"],+ bundleId: "com.trycua.spaces.macos.local", home: "/Users/ada"))+ #expect(local.socket == "/Users/ada/.cua-local/run/cua-driver.sock")+ #expect(local.serverName == "cua-driver-local")+ #expect(local.hostBundleId == "com.trycua.spaces.macos.local")+ // A Local bundle without its home never falls back to the released app's.+ #expect(EmbeddedDriver.make(binary: "/x", info: ["CuaChannel": "local"], bundleId: "x.local", home: "/Users/ada") == nil)+ }++ @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))+ #expect(!d.isOurs(command: d.binary, args: ["mcp"]))+ #expect(!d.isOurs(command: "/Applications/CuaDriver.app/Contents/MacOS/cua-driver", args: d.mcpArguments))+ }++ @Test func readsClaudeCodesAndCodexsEntries() throws {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("driver-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ let claude = dir.appendingPathComponent("claude.json")+ let json: [String: Any] = ["mcpServers": ["cua-driver": ["type": "stdio", "command": "/A/cua-driver",+ "args": ["mcp", "--embedded", "--socket", "/s"]]]]+ try JSONSerialization.data(withJSONObject: json).write(to: claude)+ #expect(EmbeddedDriver.entry(named: "cua-driver", inConfig: claude.path)+ == .init(command: "/A/cua-driver", args: ["mcp", "--embedded", "--socket", "/s"]))+ #expect(EmbeddedDriver.entry(named: "cua", inConfig: claude.path) == nil)++ let codex = dir.appendingPathComponent("config.toml")+ try """+ model = "gpt"++ [mcp_servers.cua]+ command = "/x/cua"+ args = ["mcp"]++ [mcp_servers."cua-driver"]+ command = "/A/Contents/Helpers/cua-driver"+ args = ["mcp", "--embedded", "--socket", "/Users/a b/.cua/run/cua-driver.sock"]++ [profiles.x]+ command = "nope"+ """.write(to: codex, atomically: true, encoding: .utf8)+ #expect(EmbeddedDriver.entry(named: "cua-driver", inConfig: codex.path)+ == .init(command: "/A/Contents/Helpers/cua-driver",+ args: ["mcp", "--embedded", "--socket", "/Users/a b/.cua/run/cua-driver.sock"]))+ #expect(EmbeddedDriver.entry(named: "cua", inConfig: codex.path) == .init(command: "/x/cua", args: ["mcp"]))+ #expect(EmbeddedDriver.entry(named: "missing", inConfig: codex.path) == nil)+ }++ @Test func talksToTheDriversSocket() throws {+ let dir = URL(fileURLWithPath: "/tmp").appendingPathComponent("ed-\(UUID().uuidString.prefix(8))")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ let socket = dir.appendingPathComponent("d.sock").path+ let server = try FakeDriver(path: socket) { request in+ switch request["method"] as? String {+ case "metadata":+ return ["ok": true, "result": ["driver_version": "0.38.0", "pid": 42, "embedded": true,+ "host_bundle_id": "com.trycua.spaces.macos"]]+ case "call" where request["name"] as? String == "check_permissions":+ return ["ok": true, "result": ["content": [["type": "text", "text": "ok"]],+ "structuredContent": ["accessibility": true, "screen_recording": ["granted": false]]]]+ case "call":+ return ["ok": true, "result": ["isError": true, "content": [["type": "text", "text": "no such window"]]]]+ default:+ return ["ok": false, "error": "unknown"]+ }+ }+ defer { server.stop() }+ let d = EmbeddedDriver(binary: "/x", socket: socket, hostBundleId: "com.trycua.spaces.macos", serverName: "cua-driver")+ #expect(d.metadata() == .init(version: "0.38.0", pid: 42, embedded: true, hostBundleId: "com.trycua.spaces.macos"))+ let p = try #require(try d.call("check_permissions", ["prompt": false]) as? [String: Any])+ #expect(WebUIBridge.granted(p, "accessibility"))+ #expect(!WebUIBridge.granted(p, "screen_recording"))+ #expect(throws: EmbeddedDriver.CallError.self) { try d.call("click", [:]) }++ let gone = EmbeddedDriver(binary: "/x", socket: dir.appendingPathComponent("none.sock").path,+ hostBundleId: "x", serverName: "cua-driver")+ #expect(gone.metadata(timeout: 0.5) == nil)+ do {+ _ = try gone.call("get_config")+ Issue.record("expected an error")+ } catch let error as EmbeddedDriver.CallError {+ #expect(error.message == "Cua Driver isn't running")+ }+ }+}++/// A one-thread Unix socket server answering one JSON line per connection.+private final class FakeDriver: @unchecked Sendable {+ let fd: Int32+ let path: String+ private var thread: Thread?++ init(path: String, answer: @escaping @Sendable ([String: Any]) -> [String: Any]) throws {+ self.path = path+ let sock = socket(AF_UNIX, SOCK_STREAM, 0)+ fd = sock+ var addr = sockaddr_un()+ addr.sun_family = sa_family_t(AF_UNIX)+ let bytes = Array(path.utf8)+ withUnsafeMutableBytes(of: &addr.sun_path) { raw in+ raw.copyBytes(from: bytes)+ raw[bytes.count] = 0+ }+ let bound = withUnsafePointer(to: &addr) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(sock, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }+ }+ guard bound == 0, listen(sock, 8) == 0 else { throw EmbeddedDriver.CallError(message: "bind \(errno)") }+ thread = Thread {+ while true {+ let c = accept(sock, nil, nil)+ if c < 0 { return }+ var data = Data()+ var buf = [UInt8](repeating: 0, count: 4096)+ while !data.contains(0x0A) {+ let n = recv(c, &buf, buf.count, 0)+ if n <= 0 { break }+ data.append(contentsOf: buf[0..<n])+ }+ let request = (try? JSONSerialization.jsonObject(with: data.prefix { $0 != 0x0A })) as? [String: Any] ?? [:]+ var out = (try? JSONSerialization.data(withJSONObject: answer(request))) ?? Data()+ out.append(0x0A)+ _ = out.withUnsafeBytes { send(c, $0.baseAddress, $0.count, 0) }+ close(c)+ }+ }+ thread?.start()+ }++ func stop() {+ shutdown(fd, SHUT_RDWR)+ close(fd)+ unlink(path)+ }+}diff --git a/apps/cua-spaces-macos/scripts/tests/embedded-driver-vm-check.sh b/apps/cua-spaces-macos/scripts/tests/embedded-driver-vm-check.shnew file mode 100755index 0000000000..69d6e63533--- /dev/null+++ b/apps/cua-spaces-macos/scripts/tests/embedded-driver-vm-check.sh@@ -0,0 +1,121 @@+#!/usr/bin/env bash+# 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).+#+# 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.+# 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.+# 5. Only Cua Spaces (no CuaDriver) is in the permission lists, when the+# TCC databases are readable (needs sudo with Full Disk Access).+#+# Done by the person or agent running it, from the host side (VNC):+# - during step 3, a screenshot shows the agent cursor near (200,200) and+# then (900,500), and the real pointer did not move;+# - only one agent cursor is drawn per agent (cua-spacesd's own overlay+# and the driver's overlay don't double up or flicker);+# - opening Cua Spaces from Finder still opens its window (the driver in+# Contents/Helpers didn't take over the app's launch).+# ok/fail never fail, so `test && ok || fail` is an if/else here.+# shellcheck disable=SC2015+set -uo pipefail+app="${1:-/Applications/Cua Spaces.app}"+helpers="$app/Contents/Helpers"+bundle_id="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist")"+case "$bundle_id" in+ com.trycua.spaces.macos.local) home="$HOME/.cua-local" ;;+ *) home="$HOME/.cua" ;;+esac+socket="$home/run/cua-driver.sock"+spec="$home/helper/service.json"+fails=0+ok() { echo "ok: $*"; }+fail() { echo "FAIL: $*"; fails=$((fails + 1)); }++# 1. Bundle layout and signatures.+for f in cua-driver cua-cursor-theme; do+ if codesign --verify --strict -R='anchor apple generic and certificate leaf[subject.OU] = "YCK386LBJ7"' "$helpers/$f" 2>/dev/null; then+ ok "$f is in Contents/Helpers, signed by the Cua team"+ else+ fail "$helpers/$f is missing or not signed by the Cua team"+ fi+done+[ ! -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+driver_pid=""+for _ in $(seq 1 30); do+ driver_pid="$(pgrep -f "^$helpers/cua-driver serve --embedded" | head -1)"+ [ -n "$driver_pid" ] && break+ sleep 1+done+if [ -z "$driver_pid" ]; then+ fail "no 'cua-driver serve --embedded' from Contents/Helpers within 30 s"+else+ parent="$(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" ;;+ esac+ ps -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"+fi+[ -S "$socket" ] && ok "socket $socket" || fail "no socket at $socket"++# 3. The coding-agent route.+out="$(mktemp)"+{+ printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"vm-check","version":"1"}}}'+ printf '%s\n' '{"jsonrpc":"2.0","method":"notifications/initialized"}'+ printf '%s\n' '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"check_permissions","arguments":{"prompt":false}}}'+ printf '%s\n' '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"move_cursor","arguments":{"x":200,"y":200,"session":"vm-check"}}}'+ sleep 2+ printf '%s\n' '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"move_cursor","arguments":{"x":900,"y":500,"session":"vm-check"}}}'+ sleep 3+} | "$helpers/cua-driver" mcp --embedded --socket "$socket" --host-bundle-id "$bundle_id" >"$out" 2>"$out.err"+grep -q '"id":1,"result"' "$out" && ok "the agent route answers initialize" || fail "no initialize answer ($(tail -2 "$out.err"))"+perms="$(grep '"id":2' "$out")"+for key in accessibility screen_recording; do+ echo "$perms" | grep -Eq "\\\\?\"$key\\\\?\": *true" && ok "$key is on (as Cua Spaces)" || fail "$key is not on: $perms"+done+grep '"id":4' "$out" | grep -q '"isError":true' && fail "move_cursor failed: $(grep '"id":4' "$out")" || ok "move_cursor answered (check the screenshots)"+rm -f "$out" "$out.err"++# 4. Restart after a crash.+if [ -n "$driver_pid" ]; then+ kill -9 "$driver_pid"+ new=""+ for _ in $(seq 1 10); do+ sleep 1+ new="$(pgrep -f "^$helpers/cua-driver serve --embedded" | head -1)"+ [ -n "$new" ] && [ "$new" != "$driver_pid" ] && break+ done+ [ -n "$new" ] && [ "$new" != "$driver_pid" ] && ok "restarted after a crash (pid $new)" || fail "not restarted within 10 s"+fi++# 5. Permission lists (best effort).+for db in "/Library/Application Support/com.apple.TCC/TCC.db" "$HOME/Library/Application Support/com.apple.TCC/TCC.db"; do+ rows="$(sudo -n sqlite3 "$db" "select service, client from access where service in ('kTCCServiceAccessibility','kTCCServiceScreenCapture') and auth_value = 2" 2>/dev/null)" || continue+ echo "$rows" | grep -qi "cuadriver\|com.trycua.driver" && fail "a CuaDriver entry is allowed in $db: $rows" || ok "no CuaDriver entry in $db"+done++echo "$fails check(s) failed"+[ "$fails" = 0 ]diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex 6a68b21f73..adf0510bce 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -236,6 +236,15 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"host.openSettings": { url: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" },"startup.get": {},"startup.act": { action: "allowAccess" },+ "driver.status": {},+ "driver.list": {},+ "driver.config": {},+ "driver.setConfig": { changes: { "cursor.float": "off" } },+ "driver.test": {},+ "driver.pause": { paused: false },+ "driver.setApp": { app: "codex", on: true },+ "driver.setup": {},+ "driver.update": {},};/** Operations the demo host refuses on purpose, and why. */diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 6d2b2db11d..8492e11241 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -28,6 +28,7 @@ import { PRESENCE_ARGS } from "../ops/presence";import { CLOUD_APPROVE_ARGS } from "../ops/cloud-approve";import { AGENT_THREADS_ARGS } from "../ops/agent-threads";import { RUNTIME_FIX_ARGS } from "../ops/runtime-fix";+import { DRIVER_ARGS } from "../ops/driver";import type { HostWindow } from "../detect";import { ELECTRON_BRIDGE_CHANNEL } from "../electron-channels";import { OPERATIONS, type OpArgs, type OpName } from "../protocol";@@ -185,6 +186,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {...CLOUD_APPROVE_ARGS,...AGENT_THREADS_ARGS,...RUNTIME_FIX_ARGS,+ ...DRIVER_ARGS,};const unsupportedOn = (op: OpName, host: "webkit" | "tauri") =>diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 0c4a4f9219..7e41409798 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -61,6 +61,7 @@ import { demoSpaceDetailHandlers, demoSpaceDetailState, type DemoSpaceDetailStatimport { demoTelemetryHandlers, demoTelemetryState, type DemoTelemetryState } from "./demo/telemetry";import { demoLinksHandlers, demoLinksState, type DemoLinksState, type DemoSharesPreset } from "./demo/links";import { demoResourcesHandlers, demoResourcesState, type DemoResourcesState } from "./demo/resources";+import { demoDriverHandlers, demoDriverState, type DemoDriverState } from "./demo/driver";import { demoRelayUsageHandlers, demoRelayUsageNamed, demoRelayUsageState, type DemoRelayUsageState } from "./demo/relay-usage";import { demoStartupHandlers, demoStartupState, type DemoStartupState } from "./demo/startup";import { createChildrenStore } from "../children";@@ -437,6 +438,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...demoNewSpaceState(Boolean(options.macHost), options.clouds ?? null),...demoKeyvaultSetupState(!options.noVault),...demoKeyvaultManageState(),+ ...demoDriverState(now(), options.onboarded === false),};if (state.platform.os !== "macos") state.host = { ...state.host, name: demoMachine(state.platform).name };@@ -1078,6 +1080,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...demoKeyvaultSetupHandlers(ctx),...demoKeyvaultManageHandlers(ctx, overview),...demoStartupHandlers(ctx),+ ...demoDriverHandlers(ctx),...unsupportedStreamOps("demo"),...unsupportedChecklistOps("demo"),...demoCiHandlers({ state: ciState, now, wait, stepMs: step, signedIn: () => Boolean(state.identity) }),@@ -1116,7 +1119,7 @@ interface DemoLinksStateField {links: DemoLinksState;}-export interface DemoState extends DemoLinksStateField, DemoTelemetryState, DemoRelayUsageState, DemoResourcesState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {+export interface DemoState extends DemoDriverState, DemoLinksStateField, DemoTelemetryState, DemoRelayUsageState, DemoResourcesState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {rows: SpaceRow[];items: KvItem[];keyvaultLocked: boolean;diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/driver.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/driver.tsnew file mode 100644index 0000000000..538c63d912--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/driver.ts@@ -0,0 +1,176 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The demo host's Cua Driver (`ops/driver.ts`): the driver this Mac's Cua+ * Spaces runs for coding agents, with Claude Code connected and Codex not+ * yet. Its permissions are This machine's (`state.host`), as the embedded+ * driver's are Cua Spaces' own grants, so allowing one allows both.+ */++import { HostError } from "../../adapter";+import type { DriverApp, DriverConfig, DriverLiveTest, DriverMachine, DriverPermission, DriverStatus } from "../../ops/driver";+import type { DemoContext, DemoHandlers } from "./context";++export interface DemoDriverState {+ driver: {+ version: string;+ update: { version: string; note: string | null } | null;+ paused: boolean;+ lastTest: DriverLiveTest | null;+ config: DriverConfig;+ apps: DriverApp[];+ /** The account's other computers with a Cua Driver. */+ others: DriverMachine[];+ };+}++const APPS: DriverApp[] = [+ { id: "claude-code", name: "Claude Code", on: true, own: false, bringsOwn: false },+ { id: "codex", name: "Codex", on: false, own: false, bringsOwn: false },+ { id: "t3-code", name: "T3 Code", on: true, own: false, bringsOwn: true },+];++/** `get_config` as the 0.38 driver answers it, with trycua/cua#6142's cursor keys. */+const CONFIG: DriverConfig = {+ version: "0.38.0",+ platform: "macos",+ agent_cursor: { enabled: true },+ cursor: { badges: "minimal", float: true, marks: false, rotate: false, motion: { style: "signature_arc", timing: "steady", effects: {} } },+ max_image_dimension: 1366,+};++const OTHERS: DriverMachine[] = [+ { machineId: "mac-mini", name: "Mac mini", os: "macos", thisMachine: false, state: "ready", version: "0.37.2", update: "0.38.1" },+ { machineId: "linux-box", name: "Linux box", os: "linux", thisMachine: false, state: "ready", version: "0.38.1", update: null },+];++export const demoDriverState = (now: number, firstRun: boolean): DemoDriverState => ({+ driver: {+ version: "0.38.0",+ update: null,+ paused: false,+ lastTest: firstRun ? null : { passed: true, atMs: now - 2 * 60_000, failure: null, tookMs: 4_000 },+ config: structuredClone(CONFIG),+ apps: APPS.map((a) => ({ ...a })),+ others: [],+ },+});++/** The account's other computers, for a demo that shows the page's list. */+export const demoDriverOthers = (): DriverMachine[] => OTHERS.map((m) => ({ ...m }));++/** A dotted `set_config` key into the nested `get_config` object. */+function setPath(config: DriverConfig, key: string, value: unknown): void {+ const parts = key.split(".");+ let at = config as Record<string, unknown>;+ for (const p of parts.slice(0, -1)) {+ if (typeof at[p] !== "object" || at[p] === null) at[p] = {};+ at = at[p] as Record<string, unknown>;+ }+ at[parts.at(-1)!] = value === "on" ? true : value === "off" ? false : value;+}++export function demoDriverHandlers({ state, now, wait, emit, stepMs }: DemoContext): DemoHandlers<+ "driver.status" | "driver.list" | "driver.config" | "driver.setConfig" | "driver.test" | "driver.pause" | "driver.setApp" | "driver.setup" | "driver.update"+> {+ const d = () => state.driver;+ const permissions = (): DriverPermission[] =>+ (["screen-recording", "accessibility"] as const).map((id) => {+ const p = state.host.permissions.find((x) => x.id === id);+ return { id: id === "screen-recording" ? "screen" : "accessibility", granted: p ? Boolean(p.granted) : true, settingsUrl: p?.settingsUrl ?? null };+ });+ const remote = (machine: string | null | undefined) => (machine && machine !== "this-mac" ? d().others.find((m) => m.machineId === machine) : undefined);+ const status = (): DriverStatus => {+ const perms = permissions();+ const allowed = perms.every((p) => p.granted);+ return {+ machineId: "this-mac",+ machineName: "This Mac",+ thisMachine: true,+ state: d().paused ? "paused" : !allowed ? "needs-permission" : "ready",+ version: d().version,+ update: d().update ? { ...d().update! } : null,+ lastTest: d().lastTest ? { ...d().lastTest! } : null,+ lastError: null,+ permissions: perms,+ apps: d().apps.map((a) => ({ ...a })),+ activity: allowed && !d().paused && d().lastTest ? [{ app: "Claude Code", target: "Xcode" }] : [],+ canPause: true,+ };+ };+ const runTest = async (): Promise<DriverLiveTest> => {+ const started = now();+ await wait(stepMs * 3);+ const missing = permissions().find((p) => !p.granted);+ const test: DriverLiveTest = {+ passed: !missing && !d().paused,+ atMs: now(),+ failure: missing ? (missing.id === "screen" ? "Screen Recording is off for Cua Spaces" : "Accessibility is off for Cua Spaces") : d().paused ? "Cua Driver isn't running" : null,+ tookMs: Math.max(now() - started, 4_000),+ };+ d().lastTest = test;+ emit({ type: "machines.changed" });+ return { ...test };+ };+ return {+ "driver.status": ({ machine }) => {+ const other = remote(machine);+ if (!other) return status();+ return {+ machineId: other.machineId,+ machineName: other.name,+ thisMachine: false,+ state: other.state,+ version: other.version,+ update: other.update ? { version: other.update, note: null } : null,+ lastTest: { passed: true, atMs: now() - 3 * 60 * 60_000, failure: null },+ lastError: null,+ permissions: [],+ apps: null,+ activity: [],+ canPause: false,+ };+ },+ "driver.list": () => {+ const s = status();+ return [{ machineId: "this-mac", name: "This Mac", os: "macos", thisMachine: true, state: s.state, version: s.version, update: s.update?.version ?? null }, ...d().others.map((m) => ({ ...m }))];+ },+ "driver.config": () => structuredClone(d().config),+ "driver.setConfig": ({ changes }) => {+ for (const [k, v] of Object.entries(changes)) setPath(d().config, k, v);+ return structuredClone(d().config);+ },+ "driver.test": () => runTest(),+ "driver.pause": ({ paused }) => {+ d().paused = paused;+ return null;+ },+ "driver.setApp": ({ app, on }) => {+ const a = d().apps.find((x) => x.id === app);+ if (!a) throw new HostError(`No coding app ${app}`, "not_found");+ a.on = on;+ return null;+ },+ "driver.setup": async () => {+ for (const a of d().apps) if (!a.bringsOwn) a.on = true;+ await runTest();+ return status();+ },+ "driver.update": async ({ machine }) => {+ const other = remote(machine);+ await wait(stepMs * 4);+ if (other) {+ other.version = other.update ?? other.version;+ other.update = null;+ return null;+ }+ if (!d().update) return null;+ d().version = d().update!.version;+ (d().config as Record<string, unknown>).version = d().version;+ d().update = null;+ d().lastTest = { passed: true, atMs: now(), failure: null, tookMs: 4_000 };+ return null;+ },+ };+}diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex da0e4c8450..6d894de114 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -70,6 +70,7 @@ import { THREAD_OPERATIONS } from "../ops/thread";import { PRESENCE_OPERATIONS } from "../ops/presence";import { cloudApproveTauriOps } from "../ops/cloud-approve";import { RUNTIME_FIX_OPERATIONS } from "../ops/runtime-fix";+import { DRIVER_OPERATIONS } from "../ops/driver";import { tauriTelemetryOps } from "../ops/telemetry";import { tauriStartupOps } from "../ops/startup";@@ -137,6 +138,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = ["crashReporting.config",...PRESENCE_OPERATIONS,...RUNTIME_FIX_OPERATIONS,+ ...DRIVER_OPERATIONS,];/** `persistent_agent_list`'s snake_case agents, as `PersistentAgent`s (as `src/native/persistent.ts` maps them). */diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex e91081a492..ebd3337eaa 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -75,6 +75,7 @@ import type { LinkCreate, ShareLink, ShareSettings } from "../ops/links";import { unsupportedPresenceOps, type PresenceJoinInfo } from "../ops/presence";import { cloudApproveWebkitOps } from "../ops/cloud-approve";import { unsupportedRuntimeFixOps } from "../ops/runtime-fix";+import { webkitDriverOps } from "../ops/driver";import type { CliInstallPlan } from "../contracts/first-run";import type { BulkResult } from "../contracts/spaces-page";import type { CreatingElsewhere, ListStatus, SpaceAccess, SpaceRow, SpaceSharingFacts } from "../contracts/spaces";@@ -836,6 +837,8 @@ export function createWebkitAdapter(...(electron? { "spaces.fixRuntime": (args: OpArgs<"spaces.fixRuntime">) => request<null>("spaces.fixRuntime", { ...args }) }: unsupportedRuntimeFixOps("webkit")),+ // Cua Driver inside Cua Spaces: the Mac app's embedded driver (ops/driver.ts).+ ...webkitDriverOps(request),};const onEvent = (detail: WebkitEventDetail) => {diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex 4ac1d8da9b..bd26662488 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -2001,6 +2001,197 @@"method"]},+ "DriverLiveTest": {+ "type": "object",+ "properties": {+ "passed": {+ "type": "boolean"+ },+ "atMs": {+ "type": "number"+ },+ "failure": {+ "type": [+ "string",+ "null"+ ]+ },+ "tookMs": {+ "type": [+ "number",+ "null"+ ]+ }+ },+ "required": [+ "passed",+ "atMs",+ "failure"+ ]+ },+ "DriverStatus": {+ "type": "object",+ "properties": {+ "machineId": {+ "type": "string"+ },+ "machineName": {+ "type": "string"+ },+ "thisMachine": {+ "type": "boolean"+ },+ "state": {+ "enum": [+ "ready",+ "starting",+ "stopped",+ "paused",+ "needs-permission",+ "failed"+ ]+ },+ "version": {+ "type": [+ "string",+ "null"+ ]+ },+ "update": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "version": {+ "type": "string"+ },+ "note": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "version",+ "note"+ ]+ },+ "lastTest": {+ "anyOf": [+ {+ "$ref": "#/$defs/DriverLiveTest"+ },+ {+ "type": "null"+ }+ ]+ },+ "lastError": {+ "type": [+ "string",+ "null"+ ]+ },+ "permissions": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "enum": [+ "screen",+ "accessibility"+ ]+ },+ "granted": {+ "type": "boolean"+ },+ "settingsUrl": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "id",+ "granted",+ "settingsUrl"+ ]+ }+ },+ "apps": {+ "type": [+ "array",+ "null"+ ],+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "on": {+ "type": "boolean"+ },+ "own": {+ "type": "boolean"+ },+ "bringsOwn": {+ "type": "boolean"+ }+ },+ "required": [+ "id",+ "name",+ "on",+ "own",+ "bringsOwn"+ ]+ }+ },+ "activity": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "app": {+ "type": "string"+ },+ "target": {+ "type": "string"+ }+ },+ "required": [+ "app",+ "target"+ ]+ }+ },+ "canPause": {+ "type": "boolean"+ }+ },+ "required": [+ "machineId",+ "machineName",+ "thisMachine",+ "state",+ "version",+ "update",+ "lastTest",+ "lastError",+ "permissions",+ "apps",+ "activity",+ "canPause"+ ]+ },"DriveStorageInput": {"type": "object","properties": {@@ -8986,6 +9177,101 @@"devices.revokePairingCode": {"type": "null"},+ "driver.config": {+ "type": "object",+ "additionalProperties": {}+ },+ "driver.list": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "machineId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "os": {+ "enum": [+ "macos",+ "windows",+ "linux"+ ]+ },+ "thisMachine": {+ "type": "boolean"+ },+ "state": {+ "enum": [+ "ready",+ "starting",+ "stopped",+ "paused",+ "needs-permission",+ "failed"+ ]+ },+ "version": {+ "type": [+ "string",+ "null"+ ]+ },+ "update": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "machineId",+ "name",+ "os",+ "thisMachine",+ "state",+ "version",+ "update"+ ]+ }+ },+ "driver.pause": {+ "type": "null"+ },+ "driver.setApp": {+ "type": "null"+ },+ "driver.setConfig": {+ "type": "object",+ "additionalProperties": {}+ },+ "driver.setup": {+ "anyOf": [+ {+ "$ref": "#/$defs/DriverStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "driver.status": {+ "anyOf": [+ {+ "$ref": "#/$defs/DriverStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "driver.test": {+ "$ref": "#/$defs/DriverLiveTest"+ },+ "driver.update": {+ "type": "null"+ },"experiments.get": {"$ref": "#/$defs/Experiments"},@@ -12398,6 +12684,90 @@"devices.revokePairingCode": {"type": "null"},+ "driver.list": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "machineId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "os": {+ "enum": [+ "macos",+ "windows",+ "linux"+ ]+ },+ "thisMachine": {+ "type": "boolean"+ },+ "state": {+ "enum": [+ "ready",+ "starting",+ "stopped",+ "paused",+ "needs-permission",+ "failed"+ ]+ },+ "version": {+ "type": [+ "string",+ "null"+ ]+ },+ "update": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "machineId",+ "name",+ "os",+ "thisMachine",+ "state",+ "version",+ "update"+ ]+ }+ },+ "driver.pause": {+ "type": "null"+ },+ "driver.setApp": {+ "type": "null"+ },+ "driver.setup": {+ "anyOf": [+ {+ "$ref": "#/$defs/DriverStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "driver.status": {+ "anyOf": [+ {+ "$ref": "#/$defs/DriverStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "driver.test": {+ "$ref": "#/$defs/DriverLiveTest"+ },"github.enable": {"type": "object","properties": {@@ -14646,6 +15016,8 @@"webkitUnshaped": {"agents.recentThreads": "the daemon tool's JSON as-is (agent_threads, agent_thread_read); ops/agent-threads.ts maps it for every host","agents.threadHistory": "the daemon tool's JSON as-is (agent_threads, agent_thread_read); ops/agent-threads.ts maps it for every host",+ "driver.config": "the driver's get_config JSON as-is; bridge/driver.ts reads only the keys it knows",+ "driver.setConfig": "the driver's get_config JSON as-is, after the change","thread.agentAdd": "the daemon tool's JSON as-is (thread_read, thread_post, agent_members, agent_set_rights, agent_add, agent_remove, thread_join_code_create, thread_join_code_list, thread_join_code_cancel, thread_settings); ops/thread.ts maps it for every host","thread.agentRemove": "the daemon tool's JSON as-is (thread_read, thread_post, agent_members, agent_set_rights, agent_add, agent_remove, thread_join_code_create, thread_join_code_list, thread_join_code_cancel, thread_settings); ops/thread.ts maps it for every host","thread.joinCodeCancel": "the daemon tool's JSON as-is (thread_read, thread_post, agent_members, agent_set_rights, agent_add, agent_remove, thread_join_code_create, thread_join_code_list, thread_join_code_cancel, thread_settings); ops/thread.ts maps it for every host",diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex b19a7e59fb..5108848488 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -68,6 +68,7 @@ import type { GithubAccount, GithubHost, GithubReport, GithubSourceRow } from ".import type { TelemetryLinkNotice } from "../ops/telemetry";import type { SentFileInfo, SpaceThumbnail, SpaceUsage, SpaceWindows } from "../ops/space-detail";import type { RelayUsage } from "../ops/relay-usage";+import type { DriverActivity, DriverApp, DriverLiveTest, DriverMachine, DriverPermission, DriverStatus, DriverUpdate } from "../ops/driver";import type { RiskyRequest } from "../ops/nudges";import type { PastMessage, PastThread, RecentThread } from "../ops/agent-threads";import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SharedBase, SpaceResources } from "../ops/resources";@@ -93,6 +94,24 @@ const RecentThreadShape = ref("RecentThread",obj<RecentThread>()({ agent: oneOf("claude-code", "openai-codex", "hermes"), id: str, title: str, cwd: nullable(str), lastActiveMs: num, resume: strings }),);+const DriverLiveTestShape = ref("DriverLiveTest", obj<DriverLiveTest>()({ passed: bool, atMs: num, failure: nullable(str), tookMs: optNull(num) }));+const DriverStatusShape = ref(+ "DriverStatus",+ obj<DriverStatus>()({+ machineId: str,+ machineName: str,+ thisMachine: bool,+ state: oneOf("ready", "starting", "stopped", "paused", "needs-permission", "failed"),+ version: nullable(str),+ update: nullable(obj<DriverUpdate>()({ version: str, note: nullable(str) })),+ lastTest: nullable(DriverLiveTestShape),+ lastError: nullable(str),+ permissions: list(obj<DriverPermission>()({ id: oneOf("screen", "accessibility"), granted: bool, settingsUrl: nullable(str) })),+ apps: nullable(list(obj<DriverApp>()({ id: str, name: str, on: bool, own: bool, bringsOwn: bool }))),+ activity: list(obj<DriverActivity>()({ app: str, target: str })),+ canPause: bool,+ }),+);/* ---- Spaces and machines --------------------------------------------------- */@@ -1582,6 +1601,25 @@ export const OP_SHAPES: Record<OpName, Schema> = {earlierOmitted: num,}),"nudges.answer": nul,+ "driver.status": nullable(DriverStatusShape),+ "driver.setup": nullable(DriverStatusShape),+ "driver.list": list(+ obj<DriverMachine>()({+ machineId: str,+ name: str,+ os: oneOf("macos", "windows", "linux"),+ thisMachine: bool,+ state: oneOf("ready", "starting", "stopped", "paused", "needs-permission", "failed"),+ version: nullable(str),+ update: nullable(str),+ }),+ ),+ "driver.config": dict(any),+ "driver.setConfig": dict(any),+ "driver.test": DriverLiveTestShape,+ "driver.pause": nul,+ "driver.setApp": nul,+ "driver.update": nul,"relay.usage": nullable(obj<RelayUsage>()({metered: bool,@@ -2048,6 +2086,12 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"agents.signInStart": SignInStartShape,"agents.signInWait": SignInWaitShape,"agents.setupDriver": OP_SHAPES["agents.setupDriver"],+ "driver.status": OP_SHAPES["driver.status"],+ "driver.list": OP_SHAPES["driver.list"],+ "driver.test": OP_SHAPES["driver.test"],+ "driver.pause": OP_SHAPES["driver.pause"],+ "driver.setup": OP_SHAPES["driver.setup"],+ "driver.setApp": OP_SHAPES["driver.setApp"],"agents.detail": AgentDetailShape,"agents.readFile": AgentOpenFileShape,"agents.restoreFile": nul,@@ -2208,6 +2252,8 @@ export const WEBKIT_UNSHAPED: Partial<Record<WebkitMethod, string>> = {"thread.settings": THREAD_TOOL_JSON,"agents.recentThreads": AGENT_THREADS_TOOL_JSON,"agents.threadHistory": AGENT_THREADS_TOOL_JSON,+ "driver.config": "the driver's get_config JSON as-is; bridge/driver.ts reads only the keys it knows",+ "driver.setConfig": "the driver's get_config JSON as-is, after the change",};/** The exported document (`bridge-shapes.json`): `ops` and `webkit` mapdiff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 3a1464e1f7..906d421b44 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -55,6 +55,7 @@ import { AGENT_THREADS_COVERAGE } from "./ops/agent-threads";import { RUNTIME_FIX_COVERAGE } from "./ops/runtime-fix";import { TELEMETRY_COVERAGE } from "./ops/telemetry";import { STARTUP_COVERAGE } from "./ops/startup";+import { DRIVER_COVERAGE } from "./ops/driver";export interface OpCoverage {webkit: { methods: readonly WebkitMethod[]; byDesign?: string };@@ -238,6 +239,7 @@ export const HOST_COVERAGE = {...CLOUD_APPROVE_COVERAGE,...AGENT_THREADS_COVERAGE,...RUNTIME_FIX_COVERAGE,+ ...DRIVER_COVERAGE,} as const satisfies Record<OpName, OpCoverage>;/**diff --git a/apps/cua-spaces-web/src/bridge/driver.ts b/apps/cua-spaces-web/src/bridge/driver.tsnew file mode 100644index 0000000000..277953022f--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/driver.ts@@ -0,0 +1,261 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Cua Driver inside Cua Spaces, for its page and sidebar entry+ * (`ops/driver.ts`). One store per computer reads `driver.status` while+ * something shows it: at once, every few seconds, and when the app comes+ * to the front. A host without the operations, or a Cua Spaces that+ * carries no driver, reads as "not here", and nothing about the driver is+ * drawn.+ */++import { useCallback, useContext, useEffect, useState, useSyncExternalStore } from "react";++import { HostError, isUnsupported, type DataAdapter } from "./adapter";+import { BridgeContext } from "./BridgeProvider";+import type { DriverConfig, DriverConfigValue, DriverLiveTest, DriverMachine, DriverStatus } from "./ops/driver";++export type { DriverActivity, DriverApp, DriverConfig, DriverLiveTest, DriverMachine, DriverPermission, DriverStatus, DriverUpdate } from "./ops/driver";++export const DRIVER_POLL_MS = 5_000;++interface Snapshot {+ status: DriverStatus | null;+ config: DriverConfig | null;+ /** The host has no driver operations. */+ unsupported: boolean;+ /** The first read hasn't answered. */+ loading: boolean;+ error: string | null;+}++const INITIAL: Snapshot = { status: null, config: null, unsupported: false, loading: true, error: null };+const NONE: Snapshot = { ...INITIAL, loading: false, unsupported: true };++class DriverStore {+ snap: Snapshot = INITIAL;+ private listeners = new Set<() => void>();+ private stop: (() => void) | null = null;+ private reading = false;++ constructor(+ private readonly adapter: DataAdapter,+ readonly machine: string | null,+ ) {}++ subscribe = (l: () => void) => {+ this.listeners.add(l);+ if (this.listeners.size === 1) this.start();+ return () => {+ this.listeners.delete(l);+ if (this.listeners.size === 0) {+ this.stop?.();+ this.stop = null;+ }+ };+ };++ snapshot = () => this.snap;++ set(patch: Partial<Snapshot>) {+ this.snap = { ...this.snap, ...patch };+ for (const l of [...this.listeners]) l();+ }++ private get args() {+ return this.machine ? { machine: this.machine } : {};+ }++ async read(withConfig = false): Promise<void> {+ if (this.snap.unsupported || this.reading) return;+ this.reading = true;+ try {+ const status = await this.adapter.call("driver.status", this.args);+ const config = status && (withConfig || !this.snap.config) ? await this.adapter.call("driver.config", this.args).catch(() => this.snap.config) : this.snap.config;+ this.set({ status, config, loading: false, error: null });+ } catch (e) {+ // A host without the methods (the Electron shell, an older app) is "not here" too.+ if (isUnsupported(e) || (e instanceof HostError && e.code === "unimplemented")) this.set({ ...NONE });+ else this.set({ loading: false, error: e instanceof Error ? e.message : String(e) });+ } finally {+ this.reading = false;+ }+ }++ async call<T>(run: () => Promise<T>): Promise<T> {+ const out = await run();+ await this.read();+ return out;+ }++ private start() {+ void this.read(true);+ const timer = setInterval(() => void this.read(), DRIVER_POLL_MS);+ const win = typeof window !== "undefined" ? window : null;+ const onFocus = () => void this.read(true);+ win?.addEventListener("focus", onFocus);+ const off = this.adapter.subscribe((e) => {+ if (e.type === "machines.changed") void this.read();+ });+ this.stop = () => {+ clearInterval(timer);+ win?.removeEventListener("focus", onFocus);+ off();+ };+ }++ setConfig(changes: Record<string, DriverConfigValue>) {+ return this.adapter.call("driver.setConfig", { ...this.args, changes }).then((config) => {+ this.set({ config });+ return config;+ });+ }+}++const stores = new WeakMap<DataAdapter, Map<string, DriverStore>>();++function storeFor(adapter: DataAdapter, machine: string | null): DriverStore {+ let byMachine = stores.get(adapter);+ if (!byMachine) stores.set(adapter, (byMachine = new Map()));+ const key = machine ?? "";+ let s = byMachine.get(key);+ if (!s) byMachine.set(key, (s = new DriverStore(adapter, machine)));+ return s;+}++const noop = () => () => {};+const none = () => NONE;++export interface DriverHook extends Snapshot {+ /** The page and its sidebar entry may show. */+ available: boolean;+ refresh(): Promise<void>;+ setConfig(changes: Record<string, DriverConfigValue>): Promise<DriverConfig>;+ test(): Promise<DriverLiveTest>;+ pause(paused: boolean): Promise<null>;+ setApp(app: string, on: boolean): Promise<null>;+ /** Set up and Repair: connects the coding agents and tests the driver. */+ setup(): Promise<DriverStatus | null>;+ update(): Promise<null>;+}++/** This Mac's driver (`machine` null), or another computer's. */+export function useDriver(machine: string | null = null): DriverHook {+ const adapter = useContext(BridgeContext)?.adapter ?? null;+ const store = adapter ? storeFor(adapter, machine) : null;+ const snap = useSyncExternalStore(store?.subscribe ?? noop, store?.snapshot ?? none, none);+ const args = machine ? { machine } : {};+ const need = () => {+ if (!store || !adapter) throw new Error("Cua Driver isn't available here");+ return { store, adapter };+ };+ return {+ ...snap,+ available: Boolean(store && !snap.unsupported && snap.status),+ refresh: () => store?.read(true) ?? Promise.resolve(),+ setConfig: (changes) => need().store.setConfig(changes),+ test: () => need().store.call(() => need().adapter.call("driver.test", args)),+ pause: (paused) => need().store.call(() => need().adapter.call("driver.pause", { ...args, paused })),+ setApp: (app, on) => need().store.call(() => need().adapter.call("driver.setApp", { app, on })),+ setup: () => need().store.call(() => need().adapter.call("driver.setup", {})),+ update: () => need().store.call(() => need().adapter.call("driver.update", args)),+ };+}++/** The account's computers with a Cua Driver (this one first); empty where the host can't list them. */+export function useDriverMachines(enabled: boolean): DriverMachine[] {+ const adapter = useContext(BridgeContext)?.adapter ?? null;+ const [list, setList] = useState<DriverMachine[]>([]);+ const read = useCallback(() => {+ if (!adapter || !enabled) return;+ adapter+ .call("driver.list", {})+ .then(setList)+ .catch(() => setList([]));+ }, [adapter, enabled]);+ useEffect(() => {+ read();+ const t = setInterval(read, DRIVER_POLL_MS * 6);+ return () => clearInterval(t);+ }, [read]);+ return list;+}++/* ---- The pointer settings, from `get_config` ---------------------------- */++/** One driver setting the page can draw; null when this driver doesn't have it (the row hides). */+export interface PointerSettings {+ /** `agent_cursor.enabled`. */+ show: boolean | null;+ /** `cursor.motion.style`. */+ style: string | null;+ /** `cursor.float` (trycua/cua#6142). */+ float: boolean | null;+ /** `cursor.marks`. */+ marks: boolean | null;+ /** `cursor.rotate`. */+ rotate: boolean | null;+ /** `cursor.badges`: `minimal`, `verbose` or `off`. */+ nameTag: "minimal" | "verbose" | "off" | null;+}++const at = (config: DriverConfig | null, path: string): unknown =>+ path.split(".").reduce<unknown>((o, k) => (o && typeof o === "object" ? (o as Record<string, unknown>)[k] : undefined), config ?? undefined);++function onOff(v: unknown): boolean | null {+ if (typeof v === "boolean") return v;+ if (v === "on") return true;+ if (v === "off") return false;+ return null;+}++/** What the page draws from the driver's settings. A key the driver doesn't report is null. */+export function pointerSettings(config: DriverConfig | null): PointerSettings {+ const style = at(config, "cursor.motion.style");+ const badges = at(config, "cursor.badges");+ return {+ show: onOff(at(config, "agent_cursor.enabled")),+ style: typeof style === "string" ? style : null,+ float: onOff(at(config, "cursor.float")),+ marks: onOff(at(config, "cursor.marks")),+ rotate: onOff(at(config, "cursor.rotate")),+ nameTag: badges === "minimal" || badges === "verbose" || badges === "off" ? badges : null,+ };+}++/** The `set_config` key and value for one pointer setting. */+export function pointerChange<K extends keyof PointerSettings>(key: K, value: NonNullable<PointerSettings[K]>): Record<string, DriverConfigValue> {+ switch (key) {+ case "show":+ return { "agent_cursor.enabled": value as boolean };+ case "style":+ return { "cursor.motion.style": value as string };+ case "nameTag":+ return { "cursor.badges": value as string };+ default:+ return { [`cursor.${key}`]: value ? "on" : "off" };+ }+}++/** How the pointer travels, in plain words (`cursor.motion.style`). */+export const POINTER_STYLES: { value: string; label: string }[] = [+ { value: "signature_arc", label: "Smooth arc" },+ { value: "spring_settle", label: "Springy" },+ { value: "comet_swoop", label: "Swoop" },+ { value: "magnetic", label: "Snap to targets" },+ { value: "adaptive", label: "Adaptive" },+ { value: "classic", label: "Straight glide" },+];++/** "2 minutes ago", for the last test. */+export function sinceText(atMs: number, now = Date.now()): string {+ const s = Math.max(0, Math.round((now - atMs) / 1000));+ if (s < 45) return "just now";+ const m = Math.round(s / 60);+ if (m < 60) return m === 1 ? "a minute ago" : `${m} minutes ago`;+ const h = Math.round(m / 60);+ if (h < 24) return h === 1 ? "an hour ago" : `${h} hours ago`;+ const d = Math.round(h / 24);+ return d === 1 ? "yesterday" : `${d} days ago`;+}diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex ded8ecb0e3..041504757e 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -183,6 +183,25 @@ export {} from "./relay-usage";export { dataWords, linkEnds, needsRelaySetup, useLinks, useShareSettings, type LinksHook, type ShareSettingsHook } from "./links";+export {+ pointerChange,+ pointerSettings,+ sinceText,+ useDriver,+ useDriverMachines,+ DRIVER_POLL_MS,+ POINTER_STYLES,+ type DriverActivity,+ type DriverApp,+ type DriverConfig,+ type DriverHook,+ type DriverLiveTest,+ type DriverMachine,+ type DriverPermission,+ type DriverStatus,+ type DriverUpdate,+ type PointerSettings,+} from "./driver";export { chatKey, mergeChats, useAgentChats, useAgentDm, type AgentChat, type AgentChats, type AgentChatSpace, type AgentDm, type ChatAttempt, type ChatNeed, type ChatTone, type DmItem } from "./agents-dm";export { foldThread, readSeqFrom, useSpaceThread, type SpaceThread, type SpaceThreadStatus, type ThreadAnswer, type ThreadItem, type ThreadQuote } from "./thread";export {diff --git a/apps/cua-spaces-web/src/bridge/ops/driver.ts b/apps/cua-spaces-web/src/bridge/ops/driver.tsnew file mode 100644index 0000000000..1bfee0222b--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/ops/driver.ts@@ -0,0 +1,196 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Cua Driver inside Cua Spaces (CUA-2706): the driver this Mac's Cua Spaces+ * carries in `Contents/Helpers`, which `cua-spacesd` runs as its own child+ * (`embedded_driver.rs`), so it uses Cua Spaces' permissions. The SwiftUI+ * app reads it over the driver's socket (`WebUIBridge+Driver.swift`).+ *+ * | Operation | SwiftUI | Tauri |+ * |---|---|---|+ * | `driver.status`, `driver.list` | the host methods of the same names | unsupported |+ * | `driver.config`, `driver.setConfig` | `get_config` / `set_config` on the driver | unsupported |+ * | `driver.test`, `driver.pause`, `driver.setup`, `driver.setApp` | the host methods of the same names | unsupported |+ * | `driver.update` | fails by design: the driver updates with Cua Spaces | unsupported |+ *+ * The Electron shell (Windows, Linux) runs the driver in-process in+ * `cua-spacesd` and routes none of these methods: its "unimplemented"+ * reads as "not here", so the page doesn't show there.+ *+ * `driver.status` answers null when this Cua Spaces carries no driver; the+ * page and its sidebar entry then don't show. A field the host can't answer+ * is null or absent, and the page hides the part that needs it.+ *+ * `driver.pause` is "Let agents use apps on this Mac" turned off: the host+ * writes `<CuaHome>/run/cua-driver.off` and `cua-spacesd` stops the driver+ * until it is gone. `driver.setup` (Set up and Repair) writes the embedded+ * proxy (`cua-driver mcp --embedded --socket …`) into Claude Code's and+ * Codex's MCP configs, starts a driver whose permission answer is stale+ * again, runs the live test, and answers the new status.+ *+ * Settings are the driver's own `get_config` JSON as-is (`driver.config`);+ * `driver.setConfig` takes `set_config` keys (`cursor.float`,+ * `cursor.marks`, `cursor.rotate`, `cursor.motion.style`, `cursor.badges`).+ * `agent_cursor.enabled` is the one key that isn't `set_config`'s: the host+ * turns it into `set_agent_cursor_enabled`.+ */++import { HostError } from "../adapter";+import type { OpCoverage } from "../coverage";+import type { WebkitMethod } from "../webkit-protocol";++/** One of the two switches in System Settings, as the driver sees them (Cua Spaces' grants). */+export interface DriverPermission {+ /** `screen` (Screen Recording) or `accessibility`. */+ id: "screen" | "accessibility";+ granted: boolean;+ /** The System Settings pane (`x-apple.systempreferences:`); `host.openSettings` guides it. */+ settingsUrl: string | null;+}++/** `embedded_driver::LiveTest`: both permissions, the screen read, and one agent-pointer move. */+export interface DriverLiveTest {+ passed: boolean;+ /** When it ran (ms since the epoch). */+ atMs: number;+ /** Which step failed, in plain words. */+ failure: string | null;+ /** How long it took (ms), when the host timed it. */+ tookMs?: number | null;+}++/** A newer driver the host has ready (CUA-2776). Absent: no Update button. */+export interface DriverUpdate {+ version: string;+ /** One plain line on what's better ("Faster clicks in Chrome"). */+ note: string | null;+}++/** A coding app the driver is registered with. */+export interface DriverApp {+ /** `claude-code`, `codex`, `t3-code`. */+ id: string;+ name: string;+ /** It uses this Cua Driver. */+ on: boolean;+ /** The person's own `cua-driver` entry, left in place: the switch is read-only. */+ own: boolean;+ /** Brings its own driver (T3 Code): nothing for Cua Spaces to register. */+ bringsOwn: boolean;+}++/** An agent using the driver right now. */+export interface DriverActivity {+ /** The coding app ("Claude Code"). */+ app: string;+ /** The app it is working in ("Xcode"). */+ target: string;+}++/** `embedded_driver::DriverStatus`, plus what the app adds around it. */+export interface DriverStatus {+ machineId: string;+ machineName: string;+ thisMachine: boolean;+ /**+ * `ready`: running, permissions on. `starting`, `stopped`. `paused`: the+ * person paused agents. `needs-permission`: a System Settings switch is+ * off. `failed`: it keeps exiting (`lastError` says why).+ */+ state: "ready" | "starting" | "stopped" | "paused" | "needs-permission" | "failed";+ version: string | null;+ update: DriverUpdate | null;+ lastTest: DriverLiveTest | null;+ lastError: string | null;+ permissions: DriverPermission[];+ /** Null: the host can't say which apps use it (the section hides). */+ apps: DriverApp[] | null;+ activity: DriverActivity[];+ /** The host can pause agents (`driver.pause`). */+ canPause: boolean;+}++/** One computer on the account with a Cua Driver, for the page's list of computers. */+export interface DriverMachine {+ machineId: string;+ name: string;+ os: "macos" | "windows" | "linux";+ thisMachine: boolean;+ state: DriverStatus["state"];+ version: string | null;+ update: string | null;+}++/** The driver's `get_config` JSON, as-is. */+export type DriverConfig = Record<string, unknown>;++/** A `set_config` value: on/off switches and named choices are strings; `agent_cursor.enabled` is a boolean. */+export type DriverConfigValue = string | boolean;++type Machine = { machine?: string | null };++export interface DriverOps {+ "driver.status": { args: Machine; result: DriverStatus | null };+ "driver.list": { args: Record<string, never>; result: DriverMachine[] };+ "driver.config": { args: Machine; result: DriverConfig };+ "driver.setConfig": { args: Machine & { changes: Record<string, DriverConfigValue> }; result: DriverConfig };+ "driver.test": { args: Machine; result: DriverLiveTest };+ "driver.pause": { args: Machine & { paused: boolean }; result: null };+ /** Connects one coding agent (`on: true`); turning one off is that agent's own setting. */+ "driver.setApp": { args: { app: string; on: boolean }; result: null };+ /** Set up and Repair: the agents' MCP entries, a fresh driver, the live test. */+ "driver.setup": { args: Record<string, never>; result: DriverStatus | null };+ "driver.update": { args: Machine; result: null };+}++export const DRIVER_OPERATIONS = [+ "driver.status",+ "driver.list",+ "driver.config",+ "driver.setConfig",+ "driver.test",+ "driver.pause",+ "driver.setApp",+ "driver.setup",+ "driver.update",+] as const satisfies readonly (keyof DriverOps)[];++const TAURI = "the Tauri shell is not the shipped app and runs no embedded driver";+const UPDATE = "the driver updates with Cua Spaces (a new pin in cua-driver.release.json), so the page never offers its own update";++const viaHost = (op: keyof DriverOps): OpCoverage =>+ op === "driver.update"+ ? { webkit: { methods: [], byDesign: UPDATE }, tauri: [], unsupported: { tauri: TAURI } }+ : { webkit: { methods: [op as WebkitMethod] }, tauri: [], unsupported: { tauri: TAURI } };++export const DRIVER_COVERAGE = Object.fromEntries(DRIVER_OPERATIONS.map((op) => [op, viaHost(op)])) as Record<keyof DriverOps, OpCoverage>;++/** The SwiftUI app's methods (`WebUIBridge+Driver.swift`). */+export function webkitDriverOps(request: <T>(method: WebkitMethod, args?: Record<string, unknown>) => Promise<T>): { [K in keyof DriverOps]: (args: DriverOps[K]["args"]) => Promise<DriverOps[K]["result"]> } {+ const machine = (a: Machine) => (a.machine ? { machine: a.machine } : {});+ return {+ "driver.status": (a) => request<DriverStatus | null>("driver.status", machine(a)),+ "driver.list": () => request<DriverMachine[]>("driver.list"),+ "driver.config": (a) => request<DriverConfig>("driver.config", machine(a)),+ "driver.setConfig": (a) => request<DriverConfig>("driver.setConfig", { ...machine(a), changes: a.changes }),+ "driver.test": (a) => request<DriverLiveTest>("driver.test", machine(a)),+ "driver.pause": (a) => request<null>("driver.pause", { ...machine(a), paused: a.paused }),+ "driver.setApp": (a) => request<null>("driver.setApp", { app: a.app, on: a.on }),+ "driver.setup": () => request<DriverStatus | null>("driver.setup"),+ "driver.update": () => Promise.reject(new HostError(UPDATE, "by_design")),+ };+}++/** Arguments that take each down its usual path (coverage and contract tests). */+export const DRIVER_ARGS = {+ "driver.status": {},+ "driver.list": {},+ "driver.config": {},+ "driver.setConfig": { changes: { "cursor.float": "off" } },+ "driver.test": {},+ "driver.pause": { paused: false },+ "driver.setApp": { app: "codex", on: true },+ "driver.setup": {},+ "driver.update": {},+};diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex 3ac6dc5151..fd391fa0f7 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -60,6 +60,7 @@ import { PRESENCE_OPERATIONS, type PresenceOps } from "./ops/presence";import { CLOUD_APPROVE_OPERATIONS, type CloudApproveOps } from "./ops/cloud-approve";import { AGENT_THREADS_OPERATIONS, type AgentThreadsOps } from "./ops/agent-threads";import { RUNTIME_FIX_OPERATIONS, type RuntimeFixOps } from "./ops/runtime-fix";+import { DRIVER_OPERATIONS, type DriverOps } from "./ops/driver";import { TELEMETRY_OPERATIONS, type TelemetryOps } from "./ops/telemetry";import type { TipsState } from "./contracts/spaces-page";import { STARTUP_EVENTS, STARTUP_OPERATIONS, type StartupHostEvent, type StartupOps } from "./ops/startup";@@ -254,7 +255,8 @@ export interface HostOperationsPresenceOps,CloudApproveOps,AgentThreadsOps,- RuntimeFixOps {+ RuntimeFixOps,+ DriverOps {"spaces.list": { args: Record<string, never>; result: SpaceRow[] };/** `os`: the plan's OS, for a host that draws its own pending row (the SwiftUI app's notch).* `config.children` and `config.labels` (an agent home, CUA-2630) are forwarded to@@ -559,6 +561,7 @@ export const OPERATIONS = [...CLOUD_APPROVE_OPERATIONS,...AGENT_THREADS_OPERATIONS,...RUNTIME_FIX_OPERATIONS,+ ...DRIVER_OPERATIONS,...SETTINGS_OPERATIONS,...NOTIFICATIONS_OPERATIONS,...TELEMETRY_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 8f1a984c31..1203eda126 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -199,6 +199,14 @@ export const WEBKIT_METHODS = ["relay.usage","nudges.pending","nudges.answer",+ "driver.status",+ "driver.list",+ "driver.config",+ "driver.setConfig",+ "driver.test",+ "driver.pause",+ "driver.setup",+ "driver.setApp","resources.get","machines.rename","machines.remove",diff --git a/apps/cua-spaces-web/src/components/__tests__/driver.test.tsx b/apps/cua-spaces-web/src/components/__tests__/driver.test.tsxnew file mode 100644index 0000000000..eca969fbfd--- /dev/null+++ b/apps/cua-spaces-web/src/components/__tests__/driver.test.tsx@@ -0,0 +1,153 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { createMemoryHistory, createRootRoute, createRouter, RouterProvider } from "@tanstack/react-router";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it } from "vitest";++import { BridgeProvider, pointerChange, pointerSettings } from "@/bridge";+import { UnsupportedOperationError, type DataAdapter } from "@/bridge/adapter";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import { unavailableCore } from "@/bridge/core";+import { DriverPage } from "@/components/driver/driver-page";+import { useNavItems } from "@/components/shell/nav";+import { ToastProvider } from "@/components/ui/toast";++afterEach(() => cleanup());++function mount(adapter: DataAdapter, ui: () => ReactNode) {+ const router = createRouter({ routeTree: createRootRoute({ component: () => <>{ui()}</> }), history: createMemoryHistory({ initialEntries: ["/"] }) });+ return render(+ <BridgeProvider adapter={adapter} core={unavailableCore("test: no core")}>+ <ToastProvider>+ <RouterProvider router={router} />+ </ToastProvider>+ </BridgeProvider>,+ );+}++/** A host with no driver operations (Electron, Tauri). */+function withoutDriver(): DataAdapter {+ const base = createDemoAdapter({ latencyMs: 0, stepMs: 0 });+ return Object.assign(Object.create(base) as DataAdapter, {+ call: ((op: string, args: unknown) =>+ op.startsWith("driver.") ? Promise.reject(new UnsupportedOperationError("webkit", op)) : (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args)) as DataAdapter["call"],+ });+}++function NavLabels() {+ return <div data-nav="">{useNavItems().map((n) => n.label).join(",")}</div>;+}++describe("pointer settings from the driver's get_config", () => {+ it("hide every setting the driver doesn't report", () => {+ expect(pointerSettings({ agent_cursor: { enabled: true }, cursor: { badges: "minimal", motion: { style: "signature_arc" } } })).toEqual({+ show: true,+ style: "signature_arc",+ float: null,+ marks: null,+ rotate: null,+ nameTag: "minimal",+ });+ expect(pointerSettings({ cursor: { float: "on", marks: "off", rotate: false } })).toMatchObject({ show: null, float: true, marks: false, rotate: false });+ expect(pointerSettings(null)).toEqual({ show: null, style: null, float: null, marks: null, rotate: null, nameTag: null });+ });++ it("map each change to its set_config key", () => {+ expect(pointerChange("float", false)).toEqual({ "cursor.float": "off" });+ expect(pointerChange("marks", true)).toEqual({ "cursor.marks": "on" });+ expect(pointerChange("style", "magnetic")).toEqual({ "cursor.motion.style": "magnetic" });+ expect(pointerChange("nameTag", "off")).toEqual({ "cursor.badges": "off" });+ expect(pointerChange("show", false)).toEqual({ "agent_cursor.enabled": false });+ });+});++describe("Cua Driver in the app", () => {+ it("shows the sidebar item under Machines only where the host runs the driver", async () => {+ mount(createDemoAdapter({ latencyMs: 0, stepMs: 0 }), () => <NavLabels />);+ await waitFor(() => expect(document.querySelector("[data-nav]")?.textContent).toContain("Machines,Cua Driver,Agents"));+ cleanup();++ mount(withoutDriver(), () => <NavLabels />);+ await act(async () => {+ await new Promise((r) => setTimeout(r, 20));+ });+ expect(document.querySelector("[data-nav]")?.textContent).not.toContain("Cua Driver");+ });++ it("draws the page: state, version, Repair, Test now, the switch, pointer rows, agents and permissions", async () => {+ mount(createDemoAdapter({ latencyMs: 0, stepMs: 0 }), () => <DriverPage machine={null} />);+ expect(await screen.findByText("Working on this Mac.")).toBeTruthy();+ expect(screen.getByText("Lets agents see and use the apps on this Mac.")).toBeTruthy();+ expect(document.querySelector("[data-driver-version]")?.textContent).toBe("Version 0.38.0.");+ expect(screen.queryByRole("button", { name: /Update/ })).toBeNull();+ expect(screen.getByRole("button", { name: "Repair" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Test now" })).toBeTruthy();+ expect((screen.getByLabelText("Let agents use apps on this Mac") as HTMLElement).getAttribute("aria-checked")).toBe("true");+ await waitFor(() => expect(screen.getByLabelText("Float while it thinks")).toBeTruthy());+ expect(document.querySelector("[data-driver-app=claude-code]")?.textContent).toContain("Uses Cua Driver in Cua Spaces.");+ expect(document.querySelector("[data-driver-app=codex]")?.textContent).toContain("Not connected. Set up connects it.");+ expect(document.querySelector("[data-driver-app=t3-code]")?.textContent).toContain("Brings its own Cua Driver");+ expect(document.querySelector("[data-driver-permission=screen]")?.textContent).toContain("On");+ expect(document.querySelector("[data-driver-computers]")).toBeNull();+ });++ it("hides a pointer setting the driver lacks", async () => {+ const demo = createDemoAdapter({ latencyMs: 0, stepMs: 0 });+ delete (demo.state.driver.config.cursor as Record<string, unknown>).rotate;+ mount(demo, () => <DriverPage machine={null} />);+ expect(await screen.findByText("Working on this Mac.")).toBeTruthy();+ await waitFor(() => expect(screen.getByLabelText("Float while it thinks")).toBeTruthy());+ expect(screen.queryByLabelText("Tilt while moving")).toBeNull();+ });++ it("changes a pointer setting through set_config", async () => {+ const demo = createDemoAdapter({ latencyMs: 0, stepMs: 0 });+ mount(demo, () => <DriverPage machine={null} />);+ const float = await screen.findByLabelText("Float while it thinks");+ fireEvent.click(float);+ await waitFor(() => expect((demo.state.driver.config.cursor as Record<string, unknown>).float).toBe(false));+ });++ it("turns agents off and on with the switch", async () => {+ const demo = createDemoAdapter({ latencyMs: 0, stepMs: 0 });+ mount(demo, () => <DriverPage machine={null} />);+ const allow = await screen.findByLabelText("Let agents use apps on this Mac");+ fireEvent.click(allow);+ await waitFor(() => expect(demo.state.driver.paused).toBe(true));+ expect(await screen.findByText("Off. Agents can't use apps on this Mac.")).toBeTruthy();+ fireEvent.click(screen.getByLabelText("Let agents use apps on this Mac"));+ await waitFor(() => expect(demo.state.driver.paused).toBe(false));+ });++ it("Set up connects every coding agent and tests the driver", async () => {+ const demo = createDemoAdapter({ latencyMs: 0, stepMs: 0 });+ for (const a of demo.state.driver.apps) a.on = false;+ mount(demo, () => <DriverPage machine={null} />);+ fireEvent.click(await screen.findByRole("button", { name: "Set up" }));+ await waitFor(() => expect(document.querySelector("[data-driver-app=codex]")?.textContent).toContain("Uses Cua Driver in Cua Spaces."));+ expect(demo.state.driver.apps.find((a) => a.id === "t3-code")?.on).toBe(false);+ expect(demo.state.driver.lastTest?.passed).toBe(true);+ expect(await screen.findByRole("button", { name: "Repair" })).toBeTruthy();+ });++ it("says a permission is missing, and Allow opens Cua Spaces' guide", async () => {+ const demo = createDemoAdapter({ latencyMs: 0, stepMs: 0 });+ demo.state.host.permissions = [+ { id: "screen-recording", label: "Screen Recording", instructions: "", settingsUrl: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture", granted: false },+ ];+ const calls: string[] = [];+ const spy = Object.assign(Object.create(demo) as DataAdapter, {+ call: ((op: string, args: unknown) => {+ calls.push(op);+ return (demo.call as (o: string, a: unknown) => Promise<unknown>).call(demo, op, args);+ }) as DataAdapter["call"],+ });+ mount(spy, () => <DriverPage machine={null} />);+ expect(await screen.findByText("A permission is missing. Allow it below.")).toBeTruthy();+ expect(document.querySelector("[data-driver-permission=screen]")?.textContent).toContain("Missing");+ fireEvent.click(screen.getByRole("button", { name: "Allow" }));+ await waitFor(() => expect(calls).toContain("host.openSettings"));+ });+});diff --git a/apps/cua-spaces-web/src/components/driver/copy.ts b/apps/cua-spaces-web/src/components/driver/copy.tsnew file mode 100644index 0000000000..37d86e5a58--- /dev/null+++ b/apps/cua-spaces-web/src/components/driver/copy.ts@@ -0,0 +1,48 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/** The Cua Driver page's words. Plain words only. */++import { sinceText, type DriverStatus } from "@/bridge";++export const DRIVER_LINE = "Lets agents see and use the apps on this Mac.";++const place = (s: DriverStatus) => (s.thisMachine ? "this Mac" : s.machineName);++/** "Working on this Mac." and friends: the status in one sentence. */+export function stateText(s: DriverStatus): string {+ switch (s.state) {+ case "ready":+ return `Working on ${place(s)}.`;+ case "paused":+ return "Off. Agents can't use apps on this Mac.";+ case "needs-permission":+ return "A permission is missing. Allow it below.";+ case "starting":+ return "Starting.";+ case "stopped":+ return "Not running.";+ case "failed":+ return "Not answering.";+ }+}++/** "Last test passed 2 minutes ago." / "Last test failed: …" / null. */+export function testText(s: DriverStatus, now = Date.now()): string | null {+ const t = s.lastTest;+ if (!t) return null;+ if (t.passed) return `Last test passed ${sinceText(t.atMs, now)}.`;+ return `Last test failed: ${t.failure ?? "no reason given"}.`;+}++/** "Version 0.38.0. Version 0.38.1 is ready: faster clicks in Chrome." */+export function versionText(s: DriverStatus): string | null {+ if (!s.version) return null;+ const update = s.update ? ` Version ${s.update.version} is ready${s.update.note ? `: ${lowerFirst(s.update.note)}` : "."}` : "";+ return `Version ${s.version}.${update}`;+}++const lowerFirst = (s: string) => (s ? s[0]!.toLowerCase() + s.slice(1) : s);++/** The app mark id for a coding app (`components/agents/harness-mark.tsx`). */+export const markFor = (app: string) => (app === "t3-code" ? "t3code" : app);diff --git a/apps/cua-spaces-web/src/components/driver/driver-page.tsx b/apps/cua-spaces-web/src/components/driver/driver-page.tsxnew file mode 100644index 0000000000..d18696a51c--- /dev/null+++ b/apps/cua-spaces-web/src/components/driver/driver-page.tsx@@ -0,0 +1,318 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { Link } from "@tanstack/react-router";+import { CheckIcon, ChevronRightIcon, MousePointer2Icon } from "lucide-react";+import { useState } from "react";++import { pointerChange, pointerSettings, POINTER_STYLES, useBridge, useDriver, useDriverMachines, type DriverApp, type DriverHook, type DriverPermission, type DriverStatus, type PointerSettings } from "@/bridge";+import { AppMarkImage } from "@/components/agents/harness-mark";+import { CuaKey } from "@/components/cua-key";+import { OsIcon } from "@/components/os-icon";+import { EmptyState, Page } from "@/components/page";+import { Button } from "@/components/ui/button";+import { GroupedSection, PlainList, plainRowClass, SettingRow } from "@/components/ui/grouped";+import { Segmented } from "@/components/ui/segmented";+import { Select } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { toast, toastError } from "@/components/ui/toast";+import { cn } from "@/lib/utils";+import { DRIVER_LINE, markFor, stateText, testText, versionText } from "./copy";+import { PointerPreview } from "./pointer-preview";++/**+ * The Cua Driver page (CUA-2706, design A): what it is in one line, its+ * state and version, Set up or Repair and Test now, the switch that lets+ * agents use this Mac, a live preview of the agent pointer and its+ * settings, the coding agents connected to it, and the two permissions it+ * uses (Cua Spaces' own). A part the host can't answer hides.+ */+export function DriverPage({ machine }: { machine: string | null }) {+ const driver = useDriver(machine);+ if (driver.loading) return <Page className="max-w-5xl">{null}</Page>;+ if (!driver.available || !driver.status) {+ return (+ <Page className="max-w-3xl">+ <EmptyState icon={<MousePointer2Icon />} title="Cua Driver isn't on this computer yet">+ It comes with Cua Spaces for Mac.+ </EmptyState>+ </Page>+ );+ }+ return <DriverBody driver={driver} status={driver.status} />;+}++function DriverBody({ driver, status }: { driver: DriverHook; status: DriverStatus }) {+ const settings = pointerSettings(driver.config);+ const hasPointer = status.thisMachine && Object.values(settings).some((v) => v !== null);+ const apps = status.thisMachine ? status.apps : null;+ return (+ <Page className="max-w-5xl">+ <div data-driver-page={status.machineId} />+ <Hero driver={driver} status={status} settings={settings} />+ {status.thisMachine && status.canPause ? <AllowSection driver={driver} status={status} /> : null}+ <div className="grid gap-x-6 [@media(min-width:900px)]:grid-cols-2">+ {hasPointer ? <PointerSection driver={driver} settings={settings} /> : null}+ <div className="min-w-0">+ {apps ? <AppsSection apps={apps} /> : null}+ {status.permissions.length > 0 ? <PermissionsSection permissions={status.permissions} /> : null}+ {!status.thisMachine ? (+ <GroupedSection title="On that computer" className="mb-8">+ <SettingRow label="Pointer and coding apps" help={`Open Cua Spaces on ${status.machineName} to change them.`} />+ </GroupedSection>+ ) : null}+ </div>+ </div>+ <Computers current={status.machineId} />+ </Page>+ );+}++/* ---- The top: keycap, the line, state, version, actions, preview ---------------- */++function Hero({ driver, status, settings }: { driver: DriverHook; status: DriverStatus; settings: PointerSettings }) {+ const [busy, setBusy] = useState<"test" | "setup" | null>(null);+ const run = async (what: "test" | "setup", work: () => Promise<void>) => {+ setBusy(what);+ try {+ await work();+ } finally {+ setBusy(null);+ }+ };+ const test = () =>+ run("test", async () => {+ const t = await driver.test().catch((e) => {+ toastError("Couldn't run the test")(e);+ return null;+ });+ if (t && !t.passed) toast("The test didn't pass", { description: t.failure ?? undefined, type: "error" });+ });+ const connected = (status.apps ?? []).some((a) => a.on);+ const setup = () =>+ run("setup", async () => {+ const after = await driver.setup().catch((e) => {+ toastError(connected ? "Couldn't repair Cua Driver" : "Couldn't set up Cua Driver")(e);+ return undefined;+ });+ if (after === undefined) return;+ const t = after?.lastTest;+ if (t && !t.passed) toast("Set up, but the test didn't pass", { description: t.failure ?? undefined, type: "error" });+ else toast("Cua Driver is ready", { description: "Start a new Claude Code or Codex session to use it." });+ });+ const ok = status.state === "ready";+ const tested = testText(status);+ const version = versionText(status);+ const problem = (status.state === "failed" || status.state === "stopped") && status.lastError ? status.lastError : null;+ return (+ <section className="grid items-center gap-8 [@media(min-width:900px)]:grid-cols-[1fr_minmax(0,400px)]" data-driver-hero="">+ <div className="flex min-w-0 gap-5">+ <CuaKey size={56} className="mt-1 size-14 self-start" />+ <div className="min-w-0">+ <h1 className="font-display text-[28px] leading-tight font-semibold tracking-[-0.02em]">Cua Driver</h1>+ <p className="mt-1 text-[14px] text-muted-foreground">{status.thisMachine ? DRIVER_LINE : `Lets agents see and use the apps on ${status.machineName}.`}</p>+ <p className="mt-4 flex items-start gap-2 text-[13px]" data-driver-state={status.state}>+ {ok ? (+ <span className="mt-px flex size-4 shrink-0 items-center justify-center rounded-full bg-[#1f9d55] text-white" aria-hidden>+ <CheckIcon className="size-2.5" strokeWidth={3} />+ </span>+ ) : null}+ <span>+ <span className="font-medium">{stateText(status)}</span>+ {busy === "test" ? <span className="text-muted-foreground"> Testing now.</span> : tested ? <span className="text-muted-foreground"> {tested}</span> : null}+ </span>+ </p>+ {problem ? (+ <p className="mt-1 text-[13px] text-muted-foreground" data-driver-problem="">+ {problem}+ </p>+ ) : null}+ {version ? (+ <p className="mt-1 text-[13px] text-muted-foreground" data-driver-version="">+ {version}+ </p>+ ) : null}+ {status.thisMachine ? (+ <div className="mt-5 flex flex-wrap items-center gap-2">+ <Button disabled={busy !== null} onClick={() => void setup()} data-driver-setup={connected ? "repair" : "setup"}>+ {busy === "setup" ? (connected ? "Repairing…" : "Setting up…") : connected ? "Repair" : "Set up"}+ </Button>+ <Button variant="outline" disabled={busy !== null || status.state === "paused"} onClick={() => void test()} data-driver-test="">+ {busy === "test" ? "Testing…" : "Test now"}+ </Button>+ </div>+ ) : null}+ {status.thisMachine ? (+ <p className="mt-2 text-xs text-muted-foreground">{connected ? "Repair connects your coding agents again, restarts Cua Driver and tests it." : "Set up connects Claude Code and Codex to Cua Driver and tests it."}</p>+ ) : null}+ </div>+ </div>+ {status.thisMachine ? <PointerPreview settings={settings} caption="Live: the agent pointer as it looks on this Mac" /> : null}+ </section>+ );+}++/* ---- Let agents use this Mac ---------------------------------------------------- */++function AllowSection({ driver, status }: { driver: DriverHook; status: DriverStatus }) {+ const on = status.state !== "paused";+ return (+ <GroupedSection title="Agents" className="mt-8 mb-8" data-driver-allow="">+ <SettingRow+ label="Let agents use apps on this Mac"+ help={on ? "Coding agents you connect can see your screen and use your apps. Your own pointer never moves." : "Off. Agents can't see your screen or use your apps until you turn this on."}+ control={<Switch checked={on} onCheckedChange={(next) => void driver.pause(!next).catch(toastError(next ? "Couldn't turn agents on" : "Couldn't turn agents off"))} aria-label="Let agents use apps on this Mac" />}+ />+ </GroupedSection>+ );+}++/* ---- Agent pointer --------------------------------------------------------------- */++function PointerSection({ driver, settings }: { driver: DriverHook; settings: PointerSettings }) {+ const change = <K extends keyof PointerSettings>(key: K, value: NonNullable<PointerSettings[K]>) =>+ void driver.setConfig(pointerChange(key, value)).catch(toastError("Couldn't change the pointer"));+ const off = settings.show === false;+ return (+ <GroupedSection title="Agent pointer" className="mb-8 min-w-0" data-driver-pointer="" footer="Applies to every agent on this Mac.">+ {settings.show !== null ? (+ <SettingRow+ label="Show the agent's pointer"+ help="A second pointer shows where an agent is working. Yours never moves."+ control={<Switch checked={settings.show} onCheckedChange={(on) => change("show", on)} aria-label="Show the agent's pointer" />}+ />+ ) : null}+ {settings.style !== null ? (+ <SettingRow+ label="Style"+ help="How it travels between clicks."+ dim={off}+ control={<Select aria-label="Pointer style" value={settings.style} options={POINTER_STYLES.some((s) => s.value === settings.style) ? POINTER_STYLES : [...POINTER_STYLES, { value: settings.style, label: settings.style }]} onValueChange={(v) => change("style", v)} disabled={off} />}+ />+ ) : null}+ {settings.float !== null ? (+ <SettingRow label="Float while it thinks" help="A slow bob while the agent pauses." dim={off} control={<Switch checked={settings.float} disabled={off} onCheckedChange={(on) => change("float", on)} aria-label="Float while it thinks" />} />+ ) : null}+ {settings.marks !== null ? (+ <SettingRow label="Show what it's doing" help="A small sign next to it: moving, clicking, typing." dim={off} control={<Switch checked={settings.marks} disabled={off} onCheckedChange={(on) => change("marks", on)} aria-label="Show what it's doing" />} />+ ) : null}+ {settings.rotate !== null ? (+ <SettingRow label="Tilt while moving" help="The arrow leans the way it's going." dim={off} control={<Switch checked={settings.rotate} disabled={off} onCheckedChange={(on) => change("rotate", on)} aria-label="Tilt while moving" />} />+ ) : null}+ {settings.nameTag !== null ? (+ <SettingRow+ label="Name tag"+ help="Which app is moving it."+ dim={off}+ control={+ <Segmented+ aria-label="Name tag"+ value={settings.nameTag}+ disabled={off}+ options={[+ { value: "minimal", label: "When needed" },+ { value: "verbose", label: "Always" },+ { value: "off", label: "Never" },+ ]}+ onValueChange={(v) => change("nameTag", v)}+ />+ }+ />+ ) : null}+ </GroupedSection>+ );+}++/* ---- Coding apps and permissions --------------------------------------------- */++function appLine(a: DriverApp): string {+ if (a.bringsOwn) return "Brings its own Cua Driver, with its own permission.";+ if (a.on) return "Uses Cua Driver in Cua Spaces.";+ if (a.own) return "Uses another Cua Driver. Set up switches it to this one.";+ return "Not connected. Set up connects it.";+}++function AppsSection({ apps }: { apps: DriverApp[] }) {+ return (+ <GroupedSection title="Connected agents" className="mb-8" data-driver-apps="">+ {apps.length === 0 ? <SettingRow label="No coding agents yet" help="Install Claude Code or Codex, then choose Set up." /> : null}+ {apps.map((a) => (+ <SettingRow+ key={a.id}+ data-driver-app={a.id}+ data-driver-app-on={a.on ? "" : undefined}+ label={+ <span className="flex items-center gap-2.5">+ <AppMarkImage agent={markFor(a.id)} className="size-4" />+ {a.name}+ </span>+ }+ help={appLine(a)}+ value={a.bringsOwn ? undefined : a.on ? "Connected" : undefined}+ />+ ))}+ </GroupedSection>+ );+}++const PERMISSION_WORDS: Record<DriverPermission["id"], { label: string; help: string }> = {+ screen: { label: "See the screen", help: "Screen Recording, given to Cua Spaces." },+ accessibility: { label: "Use the mouse and keyboard", help: "Accessibility, given to Cua Spaces." },+};++function PermissionsSection({ permissions }: { permissions: DriverPermission[] }) {+ const { data: adapter } = useBridge();+ return (+ <GroupedSection title="Permissions" className="mb-8" data-driver-permissions="" footer="Cua Driver uses the permissions you give Cua Spaces. It never asks for its own.">+ {permissions.map((p) => (+ <SettingRow+ key={p.id}+ data-driver-permission={p.id}+ data-driver-permission-granted={p.granted ? "" : undefined}+ label={PERMISSION_WORDS[p.id].label}+ help={PERMISSION_WORDS[p.id].help}+ value={p.granted ? "On" : "Missing"}+ control={+ p.granted || !p.settingsUrl ? undefined : (+ <Button variant="outline" size="sm" onClick={() => void adapter?.call("host.openSettings", { url: p.settingsUrl! }).catch(toastError("Couldn't open System Settings"))}>+ Allow+ </Button>+ )+ }+ />+ ))}+ </GroupedSection>+ );+}++/* ---- The account's other computers -------------------------------------------- */++function Computers({ current }: { current: string }) {+ const machines = useDriverMachines(true);+ if (machines.length < 2) return null;+ return (+ <section data-driver-computers="">+ <GroupedSection title="Your computers" className="mb-8">+ <PlainList className="p-1">+ {machines.map((m) => {+ const line = m.update ? `Cua Driver ${m.version ?? ""}, ${m.update} ready` : m.version ? `Cua Driver ${m.version}` : "No Cua Driver yet";+ return (+ <Link+ key={m.machineId}+ to="/driver"+ search={m.thisMachine ? {} : { machine: m.machineId }}+ className={cn(plainRowClass(m.machineId === current))}+ data-driver-computer={m.machineId}+ >+ <OsIcon os={m.os} className="size-4 text-muted-foreground" />+ <span className="flex-1 truncate">{m.thisMachine ? "This Mac" : m.name}</span>+ <span className="truncate text-xs text-muted-foreground">{line}</span>+ <ChevronRightIcon className="size-3.5 text-muted-foreground" />+ </Link>+ );+ })}+ </PlainList>+ </GroupedSection>+ </section>+ );+}diff --git a/apps/cua-spaces-web/src/components/driver/pointer-preview.tsx b/apps/cua-spaces-web/src/components/driver/pointer-preview.tsxnew file mode 100644index 0000000000..1ea9a69081--- /dev/null+++ b/apps/cua-spaces-web/src/components/driver/pointer-preview.tsx@@ -0,0 +1,169 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useEffect, useRef, useState } from "react";++import type { PointerSettings } from "@/bridge";+import { cn } from "@/lib/utils";++/**+ * The agent pointer as it looks on this Mac, played in a small window: it+ * travels to Continue the way `cursor.motion.style` says, clicks, and rests+ * (bobbing while `cursor.float` is on). It follows the page's settings live+ * (tilt, marks, the name tag). A drawing of the driver's pointer, not a+ * screenshot of macOS; the real one moves during Test now.+ */++const W = 360;+const H = 200;+const START = { x: 36, y: 184 };+const END = { x: 296, y: 162 };+const LOOP_MS = 4200;+/** The agent's colour (Claude Code's in the driver's default theme). */+const FILL = "#2bb5d8";++type Pt = { x: number; y: number };++const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);++function quad(a: Pt, c: Pt, b: Pt, t: number): Pt {+ const u = 1 - t;+ return { x: u * u * a.x + 2 * u * t * c.x + t * t * b.x, y: u * u * a.y + 2 * u * t * c.y + t * t * b.y };+}++/** Where the pointer is `t` (0..1) along the trip, for a motion style. */+function along(style: string, t: number): Pt {+ switch (style) {+ case "classic":+ return quad(START, { x: (START.x + END.x) / 2, y: (START.y + END.y) / 2 }, END, ease(t));+ case "magnetic": {+ // Quick most of the way, then pulled onto the target.+ const k = t < 0.7 ? 0.85 * ease(t / 0.7) : 0.85 + 0.15 * (1 - (1 - (t - 0.7) / 0.3) ** 3);+ return quad(START, { x: 170, y: 150 }, END, k);+ }+ case "spring_settle": {+ const k = 1 - Math.cos(t * Math.PI * 2.5) * Math.exp(-5 * t);+ return quad(START, { x: 160, y: 110 }, END, Math.min(1.08, k));+ }+ case "comet_swoop":+ return quad(START, { x: 250, y: 20 }, END, ease(t));+ case "adaptive":+ return quad(START, { x: 160, y: 90 }, END, ease(t));+ default:+ return quad(START, { x: 160, y: 30 }, END, ease(t));+ }+}++/** The dashed trail, for the style. */+function trail(style: string): string {+ const pts = Array.from({ length: 25 }, (_, i) => along(style, i / 24));+ return pts.map((p, i) => `${i ? "L" : "M"}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ");+}++function useReducedMotion(): boolean {+ const [reduced, setReduced] = useState(() => typeof window !== "undefined" && Boolean(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches));+ useEffect(() => {+ const m = window.matchMedia?.("(prefers-reduced-motion: reduce)");+ if (!m) return;+ const on = () => setReduced(m.matches);+ m.addEventListener?.("change", on);+ return () => m.removeEventListener?.("change", on);+ }, []);+ return reduced;+}++/** Milliseconds into the loop, ticking while on screen. `fixedMs` pins it (screenshots, tests). */+function useLoopClock(fixedMs: number | undefined, still: boolean): number {+ const [t, setT] = useState(0);+ const start = useRef<number | null>(null);+ useEffect(() => {+ if (fixedMs !== undefined || still) return;+ let raf = 0;+ const tick = (now: number) => {+ start.current ??= now;+ setT((now - start.current) % LOOP_MS);+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ }, [fixedMs, still]);+ return fixedMs ?? (still ? LOOP_MS * 0.8 : t);+}++export function PointerPreview({+ settings,+ caption,+ agent = "Claude Code",+ fixedMs,+ className,+}: {+ settings: PointerSettings;+ caption?: string;+ agent?: string;+ fixedMs?: number;+ className?: string;+}) {+ const reduced = useReducedMotion();+ const ms = useLoopClock(fixedMs, reduced);+ const style = settings.style ?? "signature_arc";+ const p = ms / LOOP_MS;+ // 0-12%: waiting at the start; 12-56%: the trip; 56-66%: the click; then resting on Continue.+ const travel = Math.min(1, Math.max(0, (p - 0.12) / 0.44));+ const clicking = p >= 0.56 && p < 0.66;+ const resting = p >= 0.66 || p < 0.12;+ const pos = p < 0.12 ? START : travel < 1 ? along(style, travel) : END;+ const bob = settings.float !== false && resting && !reduced ? Math.sin(((ms % 2000) / 2000) * Math.PI * 2) * 2.5 : 0;+ const ahead = along(style, Math.min(1, travel + 0.03));+ const heading = settings.rotate && !resting ? (Math.atan2(ahead.y - pos.y, ahead.x - pos.x) * 180) / Math.PI + 90 - 25 : 0;+ const shown = settings.show !== false;+ const mark = settings.marks ? (clicking ? "Clicking" : resting ? null : "Moving") : null;+ const tag = settings.nameTag === "verbose" || (settings.nameTag === "minimal" && clicking);+ return (+ <figure className={cn("flex flex-col gap-2", className)} data-pointer-preview={style} data-float={String(settings.float !== false)}>+ <div className="relative overflow-hidden rounded-lg bg-muted p-4 dark:bg-white/[0.04]">+ <svg viewBox={`0 0 ${W} ${H}`} className="block w-full" role="img" aria-label={caption ?? "The agent pointer moving to Continue and clicking it"}>+ <rect x="0" y="0" width={W} height={H} rx="10" className="fill-background" />+ <circle cx="16" cy="14" r="4" fill="#ff5f57" />+ <circle cx="30" cy="14" r="4" fill="#febc2e" />+ <circle cx="44" cy="14" r="4" fill="#28c840" />+ <text x="16" y="44" className="fill-foreground" fontSize="12" fontWeight="500">+ New document+ </text>+ <rect x="16" y="54" width={W - 32} height="24" rx="5" className="fill-muted" />+ <text x="26" y="70" className="fill-foreground" fontSize="11">+ Quarterly report+ </text>+ <g transform={`translate(${END.x - 40} ${END.y - 13})`}>+ <rect width="80" height="26" rx="6" fill="#2563eb" opacity={clicking ? 0.82 : 1} />+ <text x="40" y="17" textAnchor="middle" fill="white" fontSize="11" fontWeight="500">+ Continue+ </text>+ </g>+ {shown ? (+ <>+ <path d={trail(style)} fill="none" className="stroke-foreground/35" strokeWidth="1.2" strokeDasharray="3 4" />+ <g transform={`translate(${pos.x} ${pos.y + bob}) rotate(${heading}) scale(${clicking ? 0.88 : 1})`} data-agent-pointer="">+ {/* Upright like the system arrow (trycua/cua#6142); the tip is the click point. */}+ <path d="M0,0 L0,20 L5,15.5 L8.6,23.5 L12,22 L8.5,14.2 L14.5,14.2 Z" fill={FILL} stroke="white" strokeWidth="1.5" strokeLinejoin="round" style={{ filter: `drop-shadow(0 0 3px ${FILL})` }} />+ </g>+ {mark ? (+ <text x={pos.x + 18} y={pos.y + bob + 30} className="fill-muted-foreground" fontSize="10">+ {mark}+ </text>+ ) : null}+ {tag ? (+ <g transform={`translate(${pos.x + 14} ${pos.y + bob - 20})`}>+ <rect width={agent.length * 6 + 12} height="16" rx="4" fill={FILL} />+ <text x="6" y="11.5" fill="white" fontSize="10" fontWeight="500">+ {agent}+ </text>+ </g>+ ) : null}+ </>+ ) : null}+ </svg>+ </div>+ {caption ? <figcaption className="px-1 text-xs text-muted-foreground">{caption}</figcaption> : null}+ </figure>+ );+}diff --git a/apps/cua-spaces-web/src/components/shell/nav.ts b/apps/cua-spaces-web/src/components/shell/nav.tsindex 252ab23825..1b2ce29389 100644--- a/apps/cua-spaces-web/src/components/shell/nav.ts+++ b/apps/cua-spaces-web/src/components/shell/nav.ts@@ -1,13 +1,13 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { BellIcon, BotIcon, HardDriveIcon, HouseIcon, KeyRoundIcon, LayoutGridIcon, ServerIcon, SettingsIcon, WorkflowIcon, type LucideIcon } from "lucide-react";+import { BellIcon, BotIcon, HardDriveIcon, HouseIcon, KeyRoundIcon, LayoutGridIcon, MousePointer2Icon, ServerIcon, SettingsIcon, WorkflowIcon, type LucideIcon } from "lucide-react";-import { useExperimentFlags, useFlag } from "@/bridge";+import { useDriver, useExperimentFlags, useFlag } from "@/bridge";import type { KeybindingCommand } from "@/lib/keybindings";export interface NavItem {- to: "/home" | "/spaces" | "/machines" | "/ci" | "/agents" | "/volume" | "/keyvault" | "/notifications" | "/settings";+ to: "/home" | "/spaces" | "/machines" | "/driver" | "/ci" | "/agents" | "/volume" | "/keyvault" | "/notifications" | "/settings";label: string;icon: LucideIcon;/** Its keyboard shortcut, when it has one. */@@ -32,14 +32,22 @@ const CI_ITEM: NavItem = { to: "/ci", label: "CI Runners", icon: WorkflowIcon };/** The "Ask first" Home, first while its experiment flag is on (`spaces_ask_first_home`). */const HOME_ITEM: NavItem = { to: "/home", label: "Home", icon: HouseIcon };-/** The nav, with Volume while the Cua Volume experiment is on, CI Runners while its experiment is, and Home while the Ask-first flag is. */+/** Cua Driver, under Machines, while this Mac's Cua Spaces carries the driver (CUA-2706). */+const DRIVER_ITEM: NavItem = { to: "/driver", label: "Cua Driver", icon: MousePointer2Icon };++/** The nav, with Cua Driver while this Mac has it, Volume while the Cua Volume experiment is on, CI Runners while its experiment is, and Home while the Ask-first flag is. */export function useNavItems(): NavItem[] {const experiments = useExperimentFlags();const home = useFlag("spaces_ask_first_home");+ const driver = useDriver().available;let items = NAV_ITEMS;+ if (driver) {+ const i = items.findIndex((n) => n.to === "/machines") + 1;+ items = [...items.slice(0, i), DRIVER_ITEM, ...items.slice(i)];+ }if (experiments?.cuaVolume) {- const i = NAV_ITEMS.findIndex((n) => n.to === "/agents") + 1;- items = [...NAV_ITEMS.slice(0, i), VOLUME_ITEM, ...NAV_ITEMS.slice(i)];+ const i = items.findIndex((n) => n.to === "/agents") + 1;+ items = [...items.slice(0, i), VOLUME_ITEM, ...items.slice(i)];}if (experiments?.ciRunners) {const i = items.findIndex((n) => n.to === "/machines") + 1;diff --git a/apps/cua-spaces-web/src/components/volume/driver-card.tsx b/apps/cua-spaces-web/src/components/volume/driver-card.tsxindex a0c25ecca3..e46b2360c3 100644--- a/apps/cua-spaces-web/src/components/volume/driver-card.tsx+++ b/apps/cua-spaces-web/src/components/volume/driver-card.tsx@@ -56,7 +56,7 @@ export function DriverSummaries({ summaries }: { summaries: AgentSetupSummary[]</span>) : null}{s.failed.map((f) => (- <span key={f} className="block truncate text-xs text-destructive" data-summary-failed="">+ <span key={f} className="block text-xs text-pretty break-words text-destructive select-text" data-summary-failed="">{f}</span>))}diff --git a/apps/cua-spaces-web/src/routeTree.gen.ts b/apps/cua-spaces-web/src/routeTree.gen.tsindex 67c553d7ac..3a4570fe31 100644--- a/apps/cua-spaces-web/src/routeTree.gen.ts+++ b/apps/cua-spaces-web/src/routeTree.gen.ts@@ -17,6 +17,7 @@ import { Route as SettingsRouteRouteImport } from './routes/settings/route'import { Route as AgentsIndexRouteImport } from './routes/agents/index'import { Route as AgentsAllRouteImport } from './routes/agents/all'import { Route as CiIndexRouteImport } from './routes/ci/index'+import { Route as DriverIndexRouteImport } from './routes/driver/index'import { Route as HomeIndexRouteImport } from './routes/home/index'import { Route as HomeTaskIdRouteImport } from './routes/home/$taskId'import { Route as KeyvaultIndexRouteImport } from './routes/keyvault/index'@@ -64,6 +65,11 @@ const CiIndexRoute = CiIndexRouteImport.update({path: '/ci/',getParentRoute: () => rootRouteImport,} as any)+const DriverIndexRoute = DriverIndexRouteImport.update({+ id: '/driver/',+ path: '/driver/',+ getParentRoute: () => rootRouteImport,+} as any)const HomeIndexRoute = HomeIndexRouteImport.update({id: '/home/',path: '/home/',@@ -187,6 +193,7 @@ export interface FileRoutesByFullPath {'/spaces/$spaceId': typeof SpacesSpaceIdRoute'/agents/': typeof AgentsIndexRoute'/ci/': typeof CiIndexRoute+ '/driver/': typeof DriverIndexRoute'/home/': typeof HomeIndexRoute'/keyvault/': typeof KeyvaultIndexRoute'/machines/': typeof MachinesIndexRoute@@ -214,6 +221,7 @@ export interface FileRoutesByTo {'/spaces/$spaceId': typeof SpacesSpaceIdRoute'/agents': typeof AgentsIndexRoute'/ci': typeof CiIndexRoute+ '/driver': typeof DriverIndexRoute'/home': typeof HomeIndexRoute'/keyvault': typeof KeyvaultIndexRoute'/machines': typeof MachinesIndexRoute@@ -243,6 +251,7 @@ export interface FileRoutesById {'/spaces/$spaceId': typeof SpacesSpaceIdRoute'/agents/': typeof AgentsIndexRoute'/ci/': typeof CiIndexRoute+ '/driver/': typeof DriverIndexRoute'/home/': typeof HomeIndexRoute'/keyvault/': typeof KeyvaultIndexRoute'/machines/': typeof MachinesIndexRoute@@ -273,6 +282,7 @@ export interface FileRouteTypes {| '/spaces/$spaceId'| '/agents/'| '/ci/'+ | '/driver/'| '/home/'| '/keyvault/'| '/machines/'@@ -300,6 +310,7 @@ export interface FileRouteTypes {| '/spaces/$spaceId'| '/agents'| '/ci'+ | '/driver'| '/home'| '/keyvault'| '/machines'@@ -328,6 +339,7 @@ export interface FileRouteTypes {| '/spaces/$spaceId'| '/agents/'| '/ci/'+ | '/driver/'| '/home/'| '/keyvault/'| '/machines/'@@ -348,6 +360,7 @@ export interface RootRouteChildren {SpacesSpaceIdRoute: typeof SpacesSpaceIdRouteAgentsIndexRoute: typeof AgentsIndexRouteCiIndexRoute: typeof CiIndexRoute+ DriverIndexRoute: typeof DriverIndexRouteHomeIndexRoute: typeof HomeIndexRouteKeyvaultIndexRoute: typeof KeyvaultIndexRouteMachinesIndexRoute: typeof MachinesIndexRoute@@ -394,6 +407,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CiIndexRouteImportparentRoute: typeof rootRouteImport}+ '/driver/': {+ id: '/driver/'+ path: '/driver'+ fullPath: '/driver/'+ preLoaderRoute: typeof DriverIndexRouteImport+ parentRoute: typeof rootRouteImport+ }'/home/': {id: '/home/'path: '/home'@@ -604,6 +624,7 @@ const rootRouteChildren: RootRouteChildren = {SpacesSpaceIdRoute: SpacesSpaceIdRoute,AgentsIndexRoute: AgentsIndexRoute,CiIndexRoute: CiIndexRoute,+ DriverIndexRoute: DriverIndexRoute,HomeIndexRoute: HomeIndexRoute,KeyvaultIndexRoute: KeyvaultIndexRoute,MachinesIndexRoute: MachinesIndexRoute,diff --git a/apps/cua-spaces-web/src/routes/driver/index.tsx b/apps/cua-spaces-web/src/routes/driver/index.tsxnew file mode 100644index 0000000000..20182c62e2--- /dev/null+++ b/apps/cua-spaces-web/src/routes/driver/index.tsx@@ -0,0 +1,20 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { createFileRoute } from "@tanstack/react-router";++import { DriverPage } from "@/components/driver/driver-page";++/**+ * Cua Driver (CUA-2706): this Mac's, or another computer's with+ * `?machine=<id>`. The page says so when this Cua Spaces carries no driver.+ */+export const Route = createFileRoute("/driver/")({+ validateSearch: (s: Record<string, unknown>): { machine?: string } => (typeof s.machine === "string" && s.machine ? { machine: s.machine } : {}),+ component: DriverRoute,+});++function DriverRoute() {+ const { machine } = Route.useSearch();+ return <DriverPage key={machine ?? ""} machine={machine ?? null} />;+}diff --git a/apps/cua-spaces/src-tauri/src/installer.rs b/apps/cua-spaces/src-tauri/src/installer.rsindex a4549428c0..a68de6f4bb 100644--- a/apps/cua-spaces/src-tauri/src/installer.rs+++ b/apps/cua-spaces/src-tauri/src/installer.rs@@ -533,7 +533,11 @@ mod tests {let bin = d.path().join(".local/bin");std::fs::create_dir_all(&bin).unwrap();let driver = bin.join("cua-driver");- std::fs::write(&driver, "#!/bin/sh\n").unwrap();+ std::fs::write(+ &driver,+ "#!/bin/sh\nread line\nprintf '%s\\n' '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"serverInfo\":{\"name\":\"cua-driver\",\"version\":\"9.9.9\"}}}'\n",+ )+ .unwrap();std::fs::set_permissions(&driver, std::fs::Permissions::from_mode(0o755)).unwrap();let b = SdkAgentSetup::new(cua_agent_setup::AgentSetup::new(cua_agent_setup::HostEnv::isolated(d.path())),diff --git a/libs/cua-spacesd/Cargo.lock b/libs/cua-spacesd/Cargo.lockindex ce9648bd88..d3c15f7d55 100644--- a/libs/cua-spacesd/Cargo.lock+++ b/libs/cua-spacesd/Cargo.lock@@ -2206,6 +2206,8 @@ dependencies = ["bytes","clap","cua-driver-core",+ "cua-driver-sdk",+ "cua-home","cua-logging","cua-media-codec","cua-media-protocol",diff --git a/libs/cua-spacesd/crates/cua-spacesd/Cargo.toml b/libs/cua-spacesd/crates/cua-spacesd/Cargo.tomlindex fd798d1cc0..5aa6ccbd4e 100644--- a/libs/cua-spacesd/crates/cua-spacesd/Cargo.toml+++ b/libs/cua-spacesd/crates/cua-spacesd/Cargo.toml@@ -62,6 +62,10 @@ cua-spacesd-doctor = { path = "../cua-spacesd-doctor" }platform-macos = { path = "../../../cua-driver/rust/crates/platform-macos" }# The guest end of a macOS VM's vsock host channel (`vsock_agent`).libc = "0.2"+# Cua Driver for the coding agents on this Mac, run as cua-spacesd's own+# child so its permissions are Cua Spaces' (src/embedded_driver.rs).+cua-driver-sdk = { path = "../../../cua-driver/rust/crates/cua-driver-sdk", default-features = false }+cua-home = { path = "../../../cua/crates/cua-home" }[target.'cfg(all(target_os = "linux", not(target_env = "musl")))'.dependencies]# The cua-driver tool registry behind DriverService and /mcp.diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/embedded_driver.rs b/libs/cua-spacesd/crates/cua-spacesd/src/embedded_driver.rsnew file mode 100644index 0000000000..45ade99495--- /dev/null+++ b/libs/cua-spacesd/crates/cua-spacesd/src/embedded_driver.rs@@ -0,0 +1,538 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Cua Driver for the coding agents on this Mac, run by cua-spacesd as its+//! own child (macOS).+//!+//! The Cua Spaces app runs cua-spacesd from `Contents/Helpers`, and macOS+//! holds the app responsible for it. A `cua-driver serve --embedded` that+//! cua-spacesd spawns directly stays in that chain (embedded mode never+//! disclaims responsibility), so Accessibility and Screen Recording are Cua+//! Spaces' and there is no second app to allow. Coding agents reach it+//! through `cua-driver mcp --embedded --socket <socket> --host-bundle-id+//! <id>`, which Set up writes into their configs.+//!+//! [`EmbeddedDriver`] owns that child through the SDK's+//! [`EmbeddedCuaDriverHost`] (arguments, readiness, generations, shutdown+//! when cua-spacesd's end of its stdin closes), restarts it when it exits,+//! 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.+//! `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"+//! switch writes [`paused_marker`] (`<CuaHome>/run/cua-driver.off`). While+//! it exists the driver is stopped and its socket is gone, so agents get the+//! proxy's plain "open Cua Spaces" message; removing it starts the driver+//! again within a couple of seconds.+//!+//! **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+//! windows coexist cleanly is part of the VM check.++use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use cua_driver_sdk::{+ CuaDriver, EmbeddedCuaDriverHost, EmbeddedDriverConnection, EmbeddedDriverHostOptions,+ EmbeddedDriverHostState,+};+use cua_home::channel::CuaChannel;+use serde::Serialize;+use serde_json::Value;+use tokio_util::sync::CancellationToken;++/// Turns the embedded driver off (`0`); it is on otherwise.+pub const ENABLE_VAR: &str = "CUA_SPACESD_EMBEDDED_DRIVER";+/// A cua-driver to run instead of the bundled one (development).+pub const BINARY_VAR: &str = "CUA_SPACESD_DRIVER_BIN";++/// What to run, where it listens and whose permissions it uses.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct EmbeddedDriverConfig {+ pub binary: PathBuf,+ pub socket: PathBuf,+ pub host_bundle_id: String,+ /// While this file exists the person has paused agents: no driver runs.+ pub paused_marker: PathBuf,+}++/// The file the app writes while agents are paused: beside the socket.+pub fn paused_marker(socket: &Path) -> PathBuf {+ socket.with_file_name("cua-driver.off")+}++/// How often the supervisor looks at [`paused_marker`].+const PAUSE_POLL: Duration = Duration::from_secs(1);++impl EmbeddedDriverConfig {+ /// The configuration from the environment, or `None` (with the reason)+ /// when the embedded driver is off or there is no driver to run.+ pub fn from_env() -> Result<Self, String> {+ let get = |name: &str| std::env::var(name).ok();+ let exe = std::env::current_exe().map_err(|e| format!("this executable's path: {e}"))?;+ Self::resolve(+ get(ENABLE_VAR),+ get(BINARY_VAR),+ &exe,+ CuaChannel::current(),+ )+ }++ /// [`Self::from_env`] with its inputs explicit (testable).+ pub fn resolve(+ enable: Option<String>,+ binary_override: Option<String>,+ exe: &Path,+ channel: CuaChannel,+ ) -> Result<Self, String> {+ if enable.as_deref().map(str::trim) == Some("0") {+ return Err(format!("off ({ENABLE_VAR}=0)"));+ }+ let binary = match binary_override.filter(|v| !v.trim().is_empty()) {+ Some(path) => PathBuf::from(path),+ None => bundled_driver_beside(exe).ok_or_else(|| {+ format!(+ "no cua-driver next to {} (Cua Spaces carries it in Contents/Helpers)",+ exe.display()+ )+ })?,+ };+ let socket = channel.embedded_driver_socket();+ Ok(Self {+ binary,+ paused_marker: paused_marker(&socket),+ socket,+ host_bundle_id: channel.bundle_id().to_string(),+ })+ }+}++/// The `cua-driver` in the same folder as `exe`: in the app, cua-spacesd+/// and cua-driver are both in `Contents/Helpers`.+pub fn bundled_driver_beside(exe: &Path) -> Option<PathBuf> {+ let candidate = exe.parent()?.join("cua-driver");+ is_executable(&candidate).then_some(candidate)+}++fn is_executable(path: &Path) -> bool {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::metadata(path)+ .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)+ .unwrap_or(false)+}++/// How long to wait before restart number `attempt` (1-based) after the+/// driver exited: 1 s, doubling, at most a minute. A driver that stayed up+/// for [`STABLE_UPTIME`] starts again from 1 s.+pub fn restart_delay(attempt: u32) -> Duration {+ let secs = 1u64 << attempt.saturating_sub(1).min(6);+ Duration::from_secs(secs.min(60))+}++/// Uptime after which an exit counts as a fresh failure, not a crash loop.+pub const STABLE_UPTIME: Duration = Duration::from_secs(120);++/// The result of the last live test ([`EmbeddedDriver::live_test`]).+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+pub struct LiveTest {+ pub passed: bool,+ /// Seconds since the Unix epoch.+ pub at: u64,+ /// Which step failed and why, in plain words.+ pub failure: Option<String>,+}++/// What the app shows about the driver.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct DriverStatus {+ /// `stopped`, `starting`, `ready` or `stopping`.+ pub state: &'static str,+ pub version: Option<String>,+ pub pid: Option<u32>,+ pub generation: Option<String>,+ pub binary: String,+ pub socket: String,+ pub host_bundle_id: String,+ /// Restarts after an unexpected exit since cua-spacesd started.+ pub restarts: u32,+ pub last_error: Option<String>,+ pub last_test: Option<LiveTest>,+ /// The person paused agents ([`paused_marker`]).+ pub paused: bool,+}++#[derive(Default)]+struct Tracked {+ restarts: u32,+ last_error: Option<String>,+ last_test: Option<LiveTest>,+}++/// The driver cua-spacesd runs for coding agents.+pub struct EmbeddedDriver {+ config: EmbeddedDriverConfig,+ host: Arc<EmbeddedCuaDriverHost>,+ tracked: Mutex<Tracked>,+}++impl EmbeddedDriver {+ pub fn new(config: EmbeddedDriverConfig) -> Result<Arc<Self>, String> {+ let host = EmbeddedCuaDriverHost::with_options(EmbeddedDriverHostOptions {+ binary_path: config.binary.display().to_string(),+ host_bundle_id: config.host_bundle_id.clone(),+ socket_path: Some(config.socket.display().to_string()),+ startup_timeout_ms: None,+ shutdown_timeout_ms: None,+ permission_mode: None,+ capability_manifest_path: None,+ approve_capability_manifest: false,+ session_policy_path: None,+ approve_session_policy: false,+ dangerously_bypass_approvals: false,+ environment: Vec::new(),+ inherit_stderr: true,+ // The child draws coding agents' cursors (see the module docs).+ no_overlay: false,+ // Its stderr goes to cua-spacesd's log (inherit_stderr).+ capture_stderr: false,+ })+ .map_err(|e| e.to_string())?;+ Ok(Arc::new(Self {+ config,+ host,+ tracked: Mutex::new(Tracked::default()),+ }))+ }++ /// Keeps the driver running until `shutdown`: starts it, waits for it+ /// to exit, restarts it after [`restart_delay`], and stops it (and+ /// removes its socket) on shutdown.+ pub async fn supervise(self: Arc<Self>, shutdown: CancellationToken) {+ if let Some(dir) = self.config.socket.parent() {+ if let Err(error) = create_private_dir(dir) {+ self.note_error(format!("can't create {}: {error}", dir.display()));+ return;+ }+ }+ let mut attempt = 0u32;+ loop {+ // Paused by the person: nothing runs until the marker goes.+ if self.paused() {+ tokio::select! {+ _ = shutdown.cancelled() => break,+ _ = tokio::time::sleep(PAUSE_POLL) => continue,+ }+ }+ let started = std::time::Instant::now();+ let connection = tokio::select! {+ _ = shutdown.cancelled() => break,+ result = self.host.clone().start() => result,+ };+ match connection {+ Ok(connection) => {+ tracing::info!(+ pid = connection.pid,+ version = %connection.driver_version,+ socket = %connection.socket_path,+ "Cua Driver for coding agents is running"+ );+ let exit = tokio::select! {+ _ = shutdown.cancelled() => break,+ _ = self.until_paused() => {+ tracing::info!("agents paused: stopping Cua Driver for coding agents");+ if let Err(error) = self.host.clone().stop().await {+ tracing::warn!(%error, "stopping Cua Driver for coding agents");+ }+ attempt = 0;+ continue;+ }+ exit = self.host.clone().wait_for_exit(connection.generation.clone()) => exit,+ };+ let reason = match exit {+ Ok(exit) => format!("Cua Driver stopped (exit code {:?})", exit.code),+ Err(error) => error.to_string(),+ };+ tracing::warn!(%reason, "Cua Driver for coding agents stopped; restarting");+ self.note_error(reason);+ }+ Err(error) => {+ tracing::warn!(%error, "Cua Driver for coding agents did not start");+ self.note_error(error.to_string());+ }+ }+ if started.elapsed() >= STABLE_UPTIME {+ attempt = 0;+ }+ attempt += 1;+ self.tracked.lock().unwrap().restarts += 1;+ tokio::select! {+ _ = shutdown.cancelled() => break,+ _ = tokio::time::sleep(restart_delay(attempt)) => {}+ }+ }+ if let Err(error) = self.host.clone().stop().await {+ tracing::warn!(%error, "stopping Cua Driver for coding agents");+ }+ }++ /// Whether the person paused agents ([`paused_marker`]).+ pub fn paused(&self) -> bool {+ self.config.paused_marker.exists()+ }++ async fn until_paused(&self) {+ while !self.paused() {+ tokio::time::sleep(PAUSE_POLL).await;+ }+ }++ fn note_error(&self, error: String) {+ self.tracked.lock().unwrap().last_error = Some(error);+ }++ fn connection(&self) -> Option<EmbeddedDriverConnection> {+ self.host.connection()+ }++ pub fn status(&self) -> DriverStatus {+ let connection = self.connection();+ let tracked = self.tracked.lock().unwrap();+ DriverStatus {+ state: match self.host.state() {+ EmbeddedDriverHostState::Stopped => "stopped",+ EmbeddedDriverHostState::Starting => "starting",+ EmbeddedDriverHostState::Ready => "ready",+ EmbeddedDriverHostState::Stopping => "stopping",+ },+ version: connection.as_ref().map(|c| c.driver_version.clone()),+ pid: connection.as_ref().map(|c| c.pid),+ generation: connection.as_ref().map(|c| c.generation.clone()),+ binary: self.config.binary.display().to_string(),+ socket: self.config.socket.display().to_string(),+ host_bundle_id: self.config.host_bundle_id.clone(),+ restarts: tracked.restarts,+ last_error: tracked.last_error.clone(),+ last_test: tracked.last_test.clone(),+ paused: self.paused(),+ }+ }++ /// One tool call on the running driver; Err is a plain reason.+ async fn call(&self, tool: &str, arguments: Value) -> Result<Value, String> {+ let connection = self+ .connection()+ .ok_or_else(|| "Cua Driver isn't running".to_string())?;+ let client = CuaDriver::connect(Some(connection.socket_path)).map_err(|e| e.to_string())?;+ let result = client+ .call_tool(tool.to_string(), arguments.to_string())+ .await+ .map_err(|e| e.to_string())?;+ if result.is_error {+ return Err(if result.text.is_empty() {+ format!("{tool} failed")+ } else {+ result.text+ });+ }+ Ok(result+ .structured_json+ .as_deref()+ .and_then(|json| serde_json::from_str(json).ok())+ .unwrap_or(Value::String(result.text)))+ }++ /// The driver's settings (`get_config`).+ pub async fn get_config(&self) -> Result<Value, String> {+ self.call("get_config", serde_json::json!({})).await+ }++ /// Changes some of the driver's settings (`set_config` with only the+ /// given keys) and returns the settings after the change.+ pub async fn set_config(+ &self,+ changes: serde_json::Map<String, Value>,+ ) -> Result<Value, String> {+ self.call("set_config", Value::Object(changes)).await+ }++ /// Accessibility and Screen Recording as the driver sees them. In+ /// embedded mode these are Cua Spaces' grants. Never shows a prompt.+ pub async fn permissions(&self) -> Result<Value, String> {+ self.call("check_permissions", serde_json::json!({ "prompt": false }))+ .await+ }++ /// Proves the driver works: both permissions granted, a screenshot,+ /// and one agent-cursor move (the real pointer stays put). Kept as the+ /// last test in [`Self::status`].+ pub async fn live_test(&self) -> LiveTest {+ let failure = self.run_live_test().await.err();+ let test = LiveTest {+ passed: failure.is_none(),+ at: SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0),+ failure,+ };+ self.tracked.lock().unwrap().last_test = Some(test.clone());+ test+ }++ async fn run_live_test(&self) -> Result<(), String> {+ let permissions = self.permissions().await?;+ for (key, name) in [+ ("accessibility", "Accessibility"),+ ("screen_recording", "Screen Recording"),+ ] {+ if !granted(&permissions, key) {+ return Err(format!("{name} is off for Cua Spaces"));+ }+ }+ self.call("get_screen_size", serde_json::json!({}))+ .await+ .map_err(|e| format!("couldn't read the screen: {e}"))?;+ self.call(+ "move_cursor",+ serde_json::json!({+ "x": 200,+ "y": 200,+ "scope": "window",+ "cursor_id": "cua-spaces-setup-test",+ "session": "cua-spaces-setup-test",+ }),+ )+ .await+ .map_err(|e| format!("couldn't move the agent cursor: {e}"))?;+ Ok(())+ }+}++/// Whether `check_permissions` reports `key` as granted. Accepts the+/// boolean form (`"accessibility": true`) and the object form+/// (`"accessibility": {"granted": true}`).+pub fn granted(permissions: &Value, key: &str) -> bool {+ match permissions.get(key) {+ Some(Value::Bool(b)) => *b,+ Some(Value::Object(o)) => o.get("granted").and_then(Value::as_bool).unwrap_or(false),+ _ => false,+ }+}++fn create_private_dir(dir: &Path) -> std::io::Result<()> {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::create_dir_all(dir)?;+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))+}++/// Starts the embedded driver when it is on, under `shutdown`. Returns the+/// handle the app's status and settings calls go through.+pub fn spawn(shutdown: CancellationToken) -> Option<Arc<EmbeddedDriver>> {+ let config = match EmbeddedDriverConfig::from_env() {+ Ok(config) => config,+ Err(reason) => {+ tracing::debug!(%reason, "no embedded Cua Driver");+ return None;+ }+ };+ match EmbeddedDriver::new(config) {+ Ok(driver) => {+ tokio::spawn(driver.clone().supervise(shutdown));+ Some(driver)+ }+ Err(error) => {+ tracing::warn!(%error, "Cua Driver for coding agents is misconfigured");+ None+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn exe_with_driver() -> (tempfile::TempDir, PathBuf) {+ use std::os::unix::fs::PermissionsExt as _;+ let dir = tempfile::tempdir().unwrap();+ let helpers = dir.path().join("Cua Spaces.app/Contents/Helpers");+ std::fs::create_dir_all(&helpers).unwrap();+ let driver = helpers.join("cua-driver");+ std::fs::write(&driver, "#!/bin/sh\n").unwrap();+ std::fs::set_permissions(&driver, std::fs::Permissions::from_mode(0o755)).unwrap();+ let exe = helpers.join("cua-spacesd");+ (dir, exe)+ }++ #[test]+ fn on_unless_turned_off() {+ let (_dir, exe) = exe_with_driver();+ for enable in [None, Some("1".to_string()), Some("yes".to_string())] {+ assert!(EmbeddedDriverConfig::resolve(enable, None, &exe, CuaChannel::Stable).is_ok());+ }+ let r = EmbeddedDriverConfig::resolve(Some(" 0 ".into()), None, &exe, CuaChannel::Stable);+ assert!(r.unwrap_err().starts_with("off"));+ }++ #[test]+ fn the_pause_marker_sits_beside_the_socket() {+ let (_dir, exe) = exe_with_driver();+ let c = EmbeddedDriverConfig::resolve(None, None, &exe, CuaChannel::Local).unwrap();+ assert_eq!(c.paused_marker, c.socket.with_file_name("cua-driver.off"));+ assert_eq!(c.paused_marker.parent(), c.socket.parent());+ }++ #[test]+ fn uses_the_bundled_driver_and_the_channels_names() {+ let (_dir, exe) = exe_with_driver();+ let c = EmbeddedDriverConfig::resolve(None, None, &exe, CuaChannel::Stable).unwrap();+ assert_eq!(c.binary, exe.parent().unwrap().join("cua-driver"));+ assert_eq!(c.host_bundle_id, "com.trycua.spaces.macos");+ assert_eq!(c.socket, CuaChannel::Stable.embedded_driver_socket());+ let l = EmbeddedDriverConfig::resolve(None, None, &exe, CuaChannel::Local).unwrap();+ assert_eq!(l.host_bundle_id, "com.trycua.spaces.macos.local");+ assert_eq!(l.socket, CuaChannel::Local.embedded_driver_socket());+ }++ #[test]+ fn an_override_wins_and_a_missing_driver_says_where_it_looked() {+ let (_dir, exe) = exe_with_driver();+ let c = EmbeddedDriverConfig::resolve(+ None,+ Some("/opt/dev/cua-driver".into()),+ &exe,+ CuaChannel::Stable,+ )+ .unwrap();+ assert_eq!(c.binary, PathBuf::from("/opt/dev/cua-driver"));+ let empty = tempfile::tempdir().unwrap();+ let err = EmbeddedDriverConfig::resolve(+ None,+ None,+ &empty.path().join("cua-spacesd"),+ CuaChannel::Stable,+ )+ .unwrap_err();+ assert!(err.contains("Contents/Helpers"), "{err}");+ }++ #[test]+ fn restarts_back_off_to_a_minute() {+ let secs: Vec<u64> = (1..=9).map(|a| restart_delay(a).as_secs()).collect();+ assert_eq!(secs, [1, 2, 4, 8, 16, 32, 60, 60, 60]);+ }++ #[test]+ fn permissions_read_both_shapes() {+ let v = serde_json::json!({+ "accessibility": true,+ "screen_recording": {"granted": false},+ });+ assert!(granted(&v, "accessibility"));+ assert!(!granted(&v, "screen_recording"));+ assert!(!granted(&v, "missing"));+ }+}diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs b/libs/cua-spacesd/crates/cua-spacesd/src/main.rsindex 6fd335fd0f..0758355e06 100644--- a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs+++ b/libs/cua-spacesd/crates/cua-spacesd/src/main.rs@@ -7,6 +7,11 @@#[cfg(not(cua_headless))]mod doctor;+#[cfg(all(target_os = "macos", not(cua_headless)))]+// The app reads the driver's status, settings and permissions from the+// driver's own socket; only `spawn` and the supervisor run here.+#[allow(dead_code)]+mod embedded_driver;#[cfg(not(cua_headless))]mod legacy;mod phone;@@ -950,6 +955,14 @@ async fn serve(args: ServeArgs, join: Option<JoinArgs>) -> Result<Exit, BoxError// block on the host).#[cfg(target_os = "macos")]cua_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).+ #[cfg(all(target_os = "macos", not(cua_headless)))]+ let _embedded_driver = if no_desktop {+ None+ } else {+ 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/crates/cua-agent-setup/src/driver.rs b/libs/cua/crates/cua-agent-setup/src/driver.rsnew file mode 100644index 0000000000..1598f5828e--- /dev/null+++ b/libs/cua/crates/cua-agent-setup/src/driver.rs@@ -0,0 +1,326 @@+//! cua-driver, the background computer-use server agents launch as+//! `cua-driver mcp`: find the installed binary, check that it runs and+//! answers an MCP `initialize`, and install it with its own signed release+//! installer (`cua.ai/driver/install.sh`, which verifies each archive and,+//! on macOS, the CuaDriver.app signature) when it is missing.+//!+//! cua-driver is not bundled with cua or the Spaces apps: on macOS it is+//! its own app (`/Applications/CuaDriver.app`), which is what Accessibility+//! and Screen Recording are granted to.++use crate::{HostEnv, Os, is_executable};+use std::{+ io::{BufRead, BufReader, Write},+ path::{Path, PathBuf},+ process::{Command, Stdio},+ sync::mpsc,+ time::{Duration, Instant},+};++/// cua-driver's release installer for macOS and Linux.+pub const INSTALL_URL: &str = "https://cua.ai/driver/install.sh";++/// cua-driver's release installer for Windows.+pub const INSTALL_URL_WINDOWS: &str = "https://cua.ai/driver/install.ps1";++/// How long `cua-driver mcp` may take to answer `initialize`.+const CHECK_TIMEOUT: Duration = Duration::from_secs(30);++/// How long the release installer may run.+const INSTALL_TIMEOUT: Duration = Duration::from_secs(15 * 60);++/// The command a person runs to install cua-driver themselves.+pub fn install_command(os: Os) -> String {+ if os == Os::Windows {+ format!("& ([scriptblock]::Create((irm {INSTALL_URL_WINDOWS})))")+ } else {+ format!("/bin/bash -c \"$(curl -fsSL {INSTALL_URL})\"")+ }+}++fn exe_name(os: Os) -> &'static str {+ if os == Os::Windows {+ "cua-driver.exe"+ } else {+ "cua-driver"+ }+}++/// Where an installed cua-driver is, in order: on `env`'s PATH (which+/// includes `~/.local/bin`, where the installer links it), `~/.local/bin`,+/// then inside `CuaDriver.app` in the app folders (macOS).+pub fn locate(env: &HostEnv) -> Option<PathBuf> {+ let exe = exe_name(env.os);+ let mut candidates: Vec<PathBuf> = env.which("cua-driver").into_iter().collect();+ candidates.push(env.home.join(".local").join("bin").join(exe));+ if env.os == Os::Windows+ && let Some(local) = env.var("LOCALAPPDATA")+ {+ candidates.push(+ Path::new(local)+ .join("Programs")+ .join("Cua")+ .join("cua-driver")+ .join("bin")+ .join(exe),+ );+ }+ if env.os == Os::MacOs {+ for d in &env.app_dirs {+ candidates.push(d.join("CuaDriver.app/Contents/MacOS").join(exe));+ }+ }+ candidates.into_iter().find(|p| is_executable(p))+}++/// The absolute path `command` launches: itself when absolute, else the+/// match on `env`'s PATH. GUI agents (VS Code, Claude Desktop) start+/// servers without the user's shell PATH, so a bare name is not enough.+pub fn resolve(env: &HostEnv, command: &str) -> Option<PathBuf> {+ let p = Path::new(command);+ if p.is_absolute() {+ Some(p.to_path_buf())+ } else if command == "cua-driver" || command == "cua-driver.exe" {+ locate(env)+ } else {+ env.which(command)+ }+}++/// Checks that `command` runs and that `command mcp` answers an MCP+/// `initialize`. Ok carries the server's reported version (may be empty);+/// Err is a plain reason.+pub fn check(command: &Path) -> Result<String, String> {+ if !command.exists() {+ return Err(format!(+ "cua-driver isn't installed ({} doesn't exist)",+ command.display()+ ));+ }+ if !is_executable(command) {+ return Err(format!(+ "cua-driver at {} isn't an executable file",+ command.display()+ ));+ }+ let mut cmd = Command::new(command);+ no_window(&mut cmd);+ let mut child = cmd+ .arg("mcp")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .map_err(|e| format!("cua-driver at {} doesn't run: {e}", command.display()))?;+ let init = serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "cua-agent-setup", "version": env!("CARGO_PKG_VERSION")},+ },+ });+ let mut stdin = child.stdin.take();+ let wrote = stdin+ .as_mut()+ .map(|s| writeln!(s, "{init}").and_then(|_| s.flush()))+ .unwrap_or(Ok(()));+ let (tx, rx) = mpsc::channel();+ if let Some(out) = child.stdout.take() {+ std::thread::spawn(move || {+ for line in BufReader::new(out).lines() {+ let Ok(line) = line else { break };+ let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {+ continue;+ };+ if v.get("id") == Some(&serde_json::json!(1)) {+ let _ = tx.send(v);+ break;+ }+ }+ });+ }+ let answer = rx.recv_timeout(CHECK_TIMEOUT);+ drop(stdin);+ let _ = child.kill();+ let _ = child.wait();+ let answer = match answer {+ Ok(v) => v,+ Err(_) => {+ let early = wrote+ .err()+ .map(|e| format!(" (it exited early: {e})"))+ .unwrap_or_default();+ return Err(format!(+ "`{} mcp` didn't answer an MCP initialize{early}",+ command.display()+ ));+ }+ };+ if let Some(e) = answer.get("error") {+ let msg = e.get("message").and_then(|m| m.as_str()).unwrap_or("error");+ return Err(format!(+ "`{} mcp` refused an MCP initialize: {msg}",+ command.display()+ ));+ }+ let result = answer.get("result").ok_or_else(|| {+ format!(+ "`{} mcp` sent an MCP answer without a result",+ command.display()+ )+ })?;+ Ok(result+ .pointer("/serverInfo/version")+ .and_then(|v| v.as_str())+ .unwrap_or_default()+ .to_string())+}++/// Runs cua-driver's release installer (the same one `cua.ai/install.sh+/// --only cua-driver` runs) for `env`'s home. Err is a plain reason.+pub fn install(env: &HostEnv) -> Result<(), String> {+ let log_dir = env.cua_home().join("logs");+ let _ = std::fs::create_dir_all(&log_dir);+ let log_path = log_dir.join("cua-driver-install.log");+ let log = std::fs::File::create(&log_path)+ .map_err(|e| format!("can't write {}: {e}", log_path.display()))?;+ let log2 = log+ .try_clone()+ .map_err(|e| format!("can't write {}: {e}", log_path.display()))?;+ let mut script = None;+ let mut cmd = if env.os == Os::Windows {+ let mut c = Command::new("powershell");+ c.args([+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-Command",+ &install_command(Os::Windows),+ ]);+ c+ } else {+ // Download first, then run: a failed download never runs a partial+ // script (the shape cua.ai/install.sh uses).+ let file = std::env::temp_dir().join(format!(+ "cua-driver-install-{}-{}.sh",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or_default()+ ));+ let mut dl = Command::new("curl");+ dl.args(["-fsSL", "--retry", "2", "-o"])+ .arg(&file)+ .arg(INSTALL_URL)+ .stdin(Stdio::null());+ let got = dl+ .output()+ .map_err(|e| format!("couldn't run curl to download the cua-driver installer: {e}"))?;+ if !got.status.success() {+ let _ = std::fs::remove_file(&file);+ return Err(format!(+ "couldn't download the cua-driver installer from {INSTALL_URL}: {}",+ String::from_utf8_lossy(&got.stderr).trim()+ ));+ }+ let mut c = Command::new("/bin/bash");+ c.arg(&file);+ script = Some(file);+ c+ };+ no_window(&mut cmd);+ cmd.env("HOME", &env.home)+ .stdin(Stdio::null())+ .stdout(Stdio::from(log))+ .stderr(Stdio::from(log2));+ let result = run_bounded(cmd, INSTALL_TIMEOUT);+ if let Some(f) = script {+ let _ = std::fs::remove_file(f);+ }+ match result {+ Ok(true) => Ok(()),+ Ok(false) => Err(format!(+ "the cua-driver installer failed{} (log: {})",+ last_error_line(&log_path)+ .map(|l| format!(": {l}"))+ .unwrap_or_default(),+ log_path.display()+ )),+ Err(e) => Err(format!("{e} (log: {})", log_path.display())),+ }+}++/// A usable cua-driver: the installed one when it passes [`check`], else+/// (when `install`) a fresh install from the release, checked again. Err is+/// a plain reason.+pub fn ensure(env: &HostEnv, install: bool) -> Result<PathBuf, String> {+ let first = match locate(env) {+ Some(p) => match check(&p) {+ Ok(_) => return Ok(p),+ Err(e) => e,+ },+ None => "cua-driver isn't installed".to_string(),+ };+ if !install {+ return Err(first);+ }+ self::install(env)?;+ let p = locate(env).ok_or_else(|| {+ "the cua-driver installer finished, but no cua-driver was found".to_string()+ })?;+ check(&p)?;+ Ok(p)+}++fn run_bounded(mut cmd: Command, limit: Duration) -> Result<bool, String> {+ let mut child = cmd+ .spawn()+ .map_err(|e| format!("couldn't start the cua-driver installer: {e}"))?;+ let start = Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(status)) => return Ok(status.success()),+ Ok(None) if start.elapsed() > limit => {+ let _ = child.kill();+ let _ = child.wait();+ return Err(format!(+ "the cua-driver installer didn't finish within {} minutes",+ limit.as_secs() / 60+ ));+ }+ Ok(None) => std::thread::sleep(Duration::from_millis(250)),+ Err(e) => return Err(format!("the cua-driver installer: {e}")),+ }+ }+}++/// The installer's last `error:` line, else its last line.+fn last_error_line(log: &Path) -> Option<String> {+ let text = std::fs::read_to_string(log).ok()?;+ let lines: Vec<&str> = text+ .lines()+ .map(str::trim)+ .filter(|l| !l.is_empty())+ .collect();+ lines+ .iter()+ .rev()+ .find(|l| l.to_ascii_lowercase().starts_with("error"))+ .or(lines.last())+ .map(|l| l.chars().take(200).collect())+}++fn no_window(_cmd: &mut Command) {+ // The app runs this from a GUI process: no console window.+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;+ _cmd.creation_flags(CREATE_NO_WINDOW);+ }+}diff --git a/libs/cua/crates/cua-agent-setup/src/lib.rs b/libs/cua/crates/cua-agent-setup/src/lib.rsindex c9986b22dc..302812d131 100644--- a/libs/cua/crates/cua-agent-setup/src/lib.rs+++ b/libs/cua/crates/cua-agent-setup/src/lib.rs@@ -18,6 +18,7 @@pub mod claude_login;pub mod config;pub mod connection;+pub mod driver;mod edit;mod fsutil;pub mod registry;@@ -438,21 +439,13 @@ impl McpServer {}}- /// `cua-driver mcp`, with `cua-driver` resolved to an absolute path on- /// `env`'s PATH, else in `~/.local/bin` (where cua-driver's installer- /// puts it; GUI apps often run without the user's shell PATH), else the- /// bare name.+ /// `cua-driver mcp`, with `cua-driver` resolved to an absolute path+ /// ([`driver::locate`]: `env`'s PATH, `~/.local/bin` where cua-driver's+ /// installer links it, then `CuaDriver.app`; GUI apps often run without+ /// the user's shell PATH), else the bare name, which+ /// [`AgentSetup::setup_cua_driver`] refuses to write.pub fn driver_for(env: &HostEnv) -> Self {- let bin = if env.os == Os::Windows {- "cua-driver.exe"- } else {- "cua-driver"- };- let cmd = env- .which("cua-driver")- .or_else(|| {- Some(env.home.join(".local").join("bin").join(bin)).filter(|p| is_executable(p))- })+ let cmd = driver::locate(env).map(|p| p.display().to_string()).unwrap_or_else(|| "cua-driver".into());McpServer::driver(cmd)@@ -1496,17 +1489,53 @@ impl AgentSetup {out.extend(self.install_skills(agents, &[DRIVER_SKILL.to_string()], force)?);}if parts.mcp {- let with_mcp: Vec<String> = self- .specs(agents)?- .iter()- .filter(|a| a.mcp.is_some())- .map(|a| a.id.to_string())- .collect();- out.extend(self.configure_mcp(&with_mcp, server)?);+ // Only a cua-driver that runs and answers MCP is written, by+ // absolute path: a bare or missing command would leave every+ // agent with a server that fails to start (ENOENT).+ let checked = driver::resolve(&self.env, &server.command)+ .ok_or_else(|| "cua-driver isn't installed".to_string())+ .and_then(|p| driver::check(&p).map(|_| p));+ match checked {+ Ok(path) => {+ let server = McpServer {+ command: path.display().to_string(),+ ..server.clone()+ };+ let with_mcp: Vec<String> = self+ .specs(agents)?+ .iter()+ .filter(|a| a.mcp.is_some())+ .map(|a| a.id.to_string())+ .collect();+ out.extend(self.configure_mcp(&with_mcp, &server)?);+ }+ Err(why) => out.extend(self.driver_unavailable(agents, &why)?),+ }}Ok(out)}+ /// One failed `cua-driver` MCP row per agent in `agents` that supports+ /// MCP, saying `why`; no config is touched.+ pub fn driver_unavailable(&self, agents: &[String], why: &str) -> Result<Vec<Outcome>> {+ Ok(self+ .specs(agents)?+ .iter()+ .filter_map(|a| {+ let m = a.mcp.as_ref()?;+ Some(Outcome {+ agents: vec![a.id.into()],+ target: Target::Mcp,+ item: DRIVER_MCP_SERVER_NAME.into(),+ path: self.mcp_file(m),+ change: Change::Failed,+ detail: why.to_string(),+ backup: None,+ })+ })+ .collect())+ }+/// Refreshes every skill folder cua installed to this build's content/// (edited folders are skipped), and re-points every MCP entry cua/// manages that still holds its recorded value to `server`.diff --git a/libs/cua/crates/cua-agent-setup/tests/agents.rs b/libs/cua/crates/cua-agent-setup/tests/agents.rsindex 3d16059fe1..f4968e102f 100644--- a/libs/cua/crates/cua-agent-setup/tests/agents.rs+++ b/libs/cua/crates/cua-agent-setup/tests/agents.rs@@ -140,6 +140,26 @@ fn one(out: Vec<Outcome>) -> Outcome {out.into_iter().next().unwrap()}+/// A stand-in cua-driver at `path`: `mcp` answers one MCP `initialize`+/// (or, when `answers` is false, reads it and never answers).+#[cfg(unix)]+fn fake_driver(path: &Path, answers: bool) -> PathBuf {+ use std::os::unix::fs::PermissionsExt;+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ let body = if answers {+ "read line\nprintf '%s\\n' 'not json: a log line'\nprintf '%s\\n' '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"serverInfo\":{\"name\":\"cua-driver\",\"version\":\"9.9.9\"}}}'\n"+ } else {+ "read line\nexit 3\n"+ };+ std::fs::write(+ path,+ format!("#!/bin/sh\n[ \"$1\" = mcp ] || exit 2\n{body}"),+ )+ .unwrap();+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();+ path.to_path_buf()+}+/// A user config for `agent` holding one unrelated server (and comments/// where the format has them), plus the parsed path to the servers object.fn fixture(agent: &str) -> (&'static str, String) {@@ -875,6 +895,7 @@ fn state_file_records_what_cua_wrote() {assert!(o.detail.contains("does not support MCP"));}+#[cfg(unix)]#[test]fn cua_driver_setup_adds_its_skill_and_server_beside_cua_and_removes_both() {let t = T::new();@@ -884,7 +905,9 @@ fn cua_driver_setup_adds_its_skill_and_server_beside_cua_and_removes_both() {let agents = ids(&["claude-code", "codex", "pi"]);s.configure_mcp(&ids(&["claude-code"]), &server()).unwrap();- let driver = McpServer::driver("/opt/drv/bin/cua-driver");+ let exe = fake_driver(&t.home.join("opt/drv/bin/cua-driver"), true);+ let exe_s = exe.display().to_string();+ let driver = McpServer::driver(exe_s.as_str());assert_eq!(driver.name, cua_agent_setup::DRIVER_MCP_SERVER_NAME);assert_eq!(driver.args, ["mcp"]);let out = s@@ -911,7 +934,7 @@ fn cua_driver_setup_adds_its_skill_and_server_beside_cua_and_removes_both() {let after = t.read(&file);let m = registry::find("claude-code").unwrap().mcp.unwrap();let entry = cua_agent_setup_get(m.format, &file, &after, m.key_path, "cua-driver").unwrap();- assert_eq!(entry["command"], "/opt/drv/bin/cua-driver");+ assert_eq!(entry["command"], exe_s.as_str());assert!(cua_agent_setup_get(m.format, &file, &after, m.key_path, "cua").is_some());// Status sees both; idempotent.@@ -938,7 +961,7 @@ fn cua_driver_setup_adds_its_skill_and_server_beside_cua_and_removes_both() {assert_eq!(state["mcp"][&key]["name"], "cua");assert_eq!(state["servers"]["cua-driver"][&key]["value"]["command"],- "/opt/drv/bin/cua-driver"+ exe_s.as_str());// Plain remove undoes Cua Spaces' entry only: Cua Driver's server and@@ -1037,6 +1060,138 @@ fn the_driver_command_resolves_from_path_then_local_bin() {);}+/// The reported bug: no cua-driver on the machine. Set up must not write a+/// server agents can't start, and must say why.+#[test]+fn a_missing_cua_driver_fails_with_a_reason_and_leaves_configs_alone() {+ let t = T::new();+ let (rel, text) = fixture("claude-code");+ let file = t.write(rel, &text);+ let s = t.setup();+ let driver = McpServer::driver_for(&t.env);+ assert_eq!(driver.command, "cua-driver");+ let out = s+ .setup_cua_driver(&ids(&["claude-code", "pi"]), &driver, Parts::ALL, false)+ .unwrap();+ let mcp: Vec<&Outcome> = out.iter().filter(|o| o.target == Target::Mcp).collect();+ assert_eq!(mcp.len(), 1, "{mcp:#?}");+ assert_eq!(mcp[0].change, Change::Failed);+ assert_eq!(mcp[0].agents, ["claude-code"]);+ assert!(mcp[0].detail.contains("isn't installed"), "{mcp:#?}");+ assert_eq!(t.read(&file), text);+ // The skill still installs.+ assert!(t.home.join(".claude/skills/cua-driver/SKILL.md").is_file());+ // An absolute path that doesn't exist fails the same way.+ let gone = McpServer::driver(t.home.join("nope/cua-driver").display().to_string());+ let out = s+ .setup_cua_driver(+ &ids(&["claude-code"]),+ &gone,+ Parts {+ skills: false,+ mcp: true,+ },+ false,+ )+ .unwrap();+ assert_eq!(one(out).change, Change::Failed);+ assert_eq!(t.read(&file), text);+}++/// A cua-driver that never answers MCP is not "done" either.+#[cfg(unix)]+#[test]+fn a_cua_driver_that_does_not_answer_mcp_fails() {+ let t = T::new();+ let (rel, text) = fixture("claude-code");+ let file = t.write(rel, &text);+ let exe = fake_driver(&t.home.join(".local/bin/cua-driver"), false);+ let o = one(t+ .setup()+ .setup_cua_driver(+ &ids(&["claude-code"]),+ &McpServer::driver(exe.display().to_string()),+ Parts {+ skills: false,+ mcp: true,+ },+ false,+ )+ .unwrap());+ assert_eq!(o.change, Change::Failed);+ assert!(o.detail.contains("didn't answer"), "{o:#?}");+ assert_eq!(t.read(&file), text);+}++/// Re-running set up repairs an entry an older build wrote with the bare+/// `cua-driver` name: it now points at the installed binary's absolute path.+#[cfg(unix)]+#[test]+fn set_up_again_repairs_a_bare_cua_driver_entry() {+ let t = T::new();+ let (rel, text) = fixture("claude-code");+ let file = t.write(rel, &text);+ let s = t.setup();+ let m = registry::find("claude-code").unwrap().mcp.unwrap();+ // What 0.9.x wrote with no cua-driver installed.+ s.configure_mcp(&ids(&["claude-code"]), &McpServer::driver("cua-driver"))+ .unwrap();+ let before = t.read(&file);+ let entry = cua_agent_setup_get(m.format, &file, &before, m.key_path, "cua-driver").unwrap();+ assert_eq!(entry["command"], "cua-driver");++ let exe = fake_driver(&t.home.join(".local/bin/cua-driver"), true);+ let mut env = t.env.clone();+ env.path = vec![t.home.join(".local/bin")];+ let s = AgentSetup::new(env.clone());+ // The bare name resolves to the installed binary, checked, then written.+ for driver in [McpServer::driver("cua-driver"), McpServer::driver_for(&env)] {+ let o = one(s+ .setup_cua_driver(+ &ids(&["claude-code"]),+ &driver,+ Parts {+ skills: false,+ mcp: true,+ },+ false,+ )+ .unwrap());+ assert!(+ matches!(o.change, Change::Updated | Change::Unchanged),+ "{o:#?}"+ );+ let after = t.read(&file);+ let entry = cua_agent_setup_get(m.format, &file, &after, m.key_path, "cua-driver").unwrap();+ assert_eq!(entry["command"], exe.display().to_string());+ assert_eq!(entry["args"], json!(["mcp"]));+ }+ assert_eq!(cua_agent_setup::driver::check(&exe).unwrap(), "9.9.9");+}++/// On macOS the binary inside CuaDriver.app counts when no link exists.+#[test]+fn cua_driver_is_found_inside_its_app_on_macos() {+ let t = T::new();+ let mut env = t.env.clone();+ env.os = cua_agent_setup::Os::MacOs;+ let exe = t+ .home+ .join("Applications/CuaDriver.app/Contents/MacOS/cua-driver");+ std::fs::create_dir_all(exe.parent().unwrap()).unwrap();+ std::fs::write(&exe, "#!/bin/sh\n").unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ assert_eq!(cua_agent_setup::driver::locate(&env), Some(exe.clone()));+ assert_eq!(+ McpServer::driver_for(&env).command,+ exe.display().to_string()+ );+}+#[test]fn hermes_is_detected_from_its_bin_home_or_app() {let mut t = T::new();diff --git a/libs/cua/crates/cua-agent-setup/tests/common/mod.rs b/libs/cua/crates/cua-agent-setup/tests/common/mod.rsnew file mode 100644index 0000000000..f9fe19df8a--- /dev/null+++ b/libs/cua/crates/cua-agent-setup/tests/common/mod.rs@@ -0,0 +1,23 @@+//! Test helpers shared by the integration tests.+#![allow(dead_code)]++/// A stand-in cua-driver whose `mcp` answers one MCP `initialize`, made+/// once per test binary in a temporary folder. Set up writes the cua-driver+/// MCP server only for a driver that passes that check.+#[cfg(unix)]+pub fn answering_driver() -> &'static str {+ static PATH: std::sync::OnceLock<String> = std::sync::OnceLock::new();+ PATH.get_or_init(|| {+ use std::os::unix::fs::PermissionsExt;+ use std::path::PathBuf;+ let dir: PathBuf = tempfile::tempdir().unwrap().keep();+ let p = dir.join("cua-driver");+ std::fs::write(+ &p,+ "#!/bin/sh\nread line\nprintf '%s\\n' '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"serverInfo\":{\"name\":\"cua-driver\",\"version\":\"9.9.9\"}}}'\n",+ )+ .unwrap();+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();+ p.display().to_string()+ })+}diff --git a/libs/cua/crates/cua-agent-setup/tests/driver_skills.rs b/libs/cua/crates/cua-agent-setup/tests/driver_skills.rsindex 6298abf30a..5803400186 100644--- a/libs/cua/crates/cua-agent-setup/tests/driver_skills.rs+++ b/libs/cua/crates/cua-agent-setup/tests/driver_skills.rs@@ -4,6 +4,8 @@//! installers' `--no-skills`) leaves every skills folder untouched. Always in//! a temporary HOME, never the real one.+mod common;+use cua_agent_setup::{AGENTS, AgentSetup, Change, HostEnv, McpServer, Parts, Target};use std::path::{Path, PathBuf};@@ -146,15 +148,17 @@ fn skills_only_installs_the_skill_without_touching_mcp_config() {assert!(!home.path.join(".claude.json").exists());}+#[cfg(unix)]#[test]fn rerunning_the_setup_changes_nothing() {let home = Home::new();let setup = home.setup();+ let driver = McpServer::driver(common::answering_driver());setup- .setup_cua_driver(&ids("codex"), &driver(), Parts::ALL, false)+ .setup_cua_driver(&ids("codex"), &driver, Parts::ALL, false).unwrap();let again = setup- .setup_cua_driver(&ids("codex"), &driver(), Parts::ALL, false)+ .setup_cua_driver(&ids("codex"), &driver, Parts::ALL, false).unwrap();assert!(again.iter().all(|o| o.change == Change::Unchanged),diff --git a/libs/cua/crates/cua-agent-setup/tests/remove_keeps_cua_driver.rs b/libs/cua/crates/cua-agent-setup/tests/remove_keeps_cua_driver.rsindex 6c03af5d0c..d7d7c6357c 100644--- a/libs/cua/crates/cua-agent-setup/tests/remove_keeps_cua_driver.rs+++ b/libs/cua/crates/cua-agent-setup/tests/remove_keeps_cua_driver.rs@@ -8,6 +8,11 @@//! Configs in the formats of Claude Code (JSON), Codex (TOML) and Cursor//! (JSON), in a temporary HOME, never the real one.+// The stand-in cua-driver these tests set up is a shell script.+#![cfg(unix)]++mod common;+use cua_agent_setup::{AgentSetup, Change, CuaChannel, HostEnv, KEPT_CUA_DRIVER, McpServer, Outcome, Parts,RemoveOptions, Target, hash_dir, is_cua_driver_name,@@ -104,7 +109,7 @@ fn ids(v: &[&str]) -> Vec<String> {}fn driver() -> McpServer {- McpServer::driver("/opt/drv/bin/cua-driver")+ McpServer::driver(common::answering_driver())}/// Cua Spaces' setup (default skills + the `cua` server) and Cua Driver's@@ -206,7 +211,7 @@ fn remove_takes_cua_spaces_entries_and_leaves_cua_driver_in_every_agent() {for (a, before) in AGENTS.iter().zip(&driver_entry_before) {let after = mcp_text(&h, a);assert!(after.len() < before.len(), "{a}");- assert!(after.contains("/opt/drv/bin/cua-driver"), "{a}: {after}");+ assert!(after.contains(common::answering_driver()), "{a}: {after}");}for dir in [".claude/skills", ".agents/skills"] {for name in SPACES_SKILLS {diff --git a/libs/cua/crates/cua-cli/src/agents.rs b/libs/cua/crates/cua-cli/src/agents.rsindex 60a7e50284..dd7e7a5e9c 100644--- a/libs/cua/crates/cua-cli/src/agents.rs+++ b/libs/cua/crates/cua-cli/src/agents.rs@@ -4,9 +4,9 @@use crate::util::{self, internal, line};use clap::{Args, Subcommand};use cua_agent_setup::{- AgentSetup, AgentStatus, Change, ConnectionReport, ConnectionRow, ConnectionState, ImportState,- McpServer, McpState, Outcome, Parts, ProblemAction, RemoveOptions, SignedInState,- StatusOptions, Target, connection::ConnectParts,+ AgentSetup, AgentStatus, Change, ConnectionReport, ConnectionRow, ConnectionState,+ DRIVER_MCP_SERVER_NAME, ImportState, McpServer, McpState, Outcome, Parts, ProblemAction,+ RemoveOptions, SignedInState, StatusOptions, Target, connection::ConnectParts,};use cua_sdk::CuaError;use std::{@@ -924,7 +924,12 @@ pub fn run_driver_setup(),);}- if parts.mcp && server.command == "cua-driver" {+ // Nothing is written for a cua-driver that is missing or doesn't answer+ // MCP (the rows above say why).+ if outcomes+ .iter()+ .any(|o| o.failed() && o.target == Target::Mcp && o.item == DRIVER_MCP_SERVER_NAME)+ {let how = if cfg!(windows) {"& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Only cua-driver"} else {@@ -932,7 +937,7 @@ pub fn run_driver_setup(};line(out,- format!("cua-driver is not installed yet. Install it with: {how}"),+ format!("cua-driver is not installed or not working. Install it with: {how}"),);}line(diff --git a/libs/cua/crates/cua-cli/tests/agents_login.rs b/libs/cua/crates/cua-cli/tests/agents_login.rsindex 87c79c33e1..e7ce25286f 100644--- a/libs/cua/crates/cua-cli/tests/agents_login.rs+++ b/libs/cua/crates/cua-cli/tests/agents_login.rs@@ -501,13 +501,30 @@ async fn the_local_cli_registers_cua_local_beside_stables_cua() {assert!(stable_skill.join("SKILL.md").is_file() && !local_skill.exists());}+/// A stand-in cua-driver whose `mcp` answers one MCP `initialize`.+#[cfg(unix)]+fn fake_driver(h: &Home) -> String {+ use std::os::unix::fs::PermissionsExt;+ let p = h.dir.path().join("opt/drv/cua-driver");+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(+ &p,+ "#!/bin/sh\nread line\nprintf '%s\\n' '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"serverInfo\":{\"name\":\"cua-driver\",\"version\":\"9.9.9\"}}}'\n",+ )+ .unwrap();+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();+ p.display().to_string()+}+/// What `uninstall-local.sh` runs (`cua-local agents remove --yes`) removes/// Local's own MCP server and skills and nothing of the released app's: its/// `cua` and `cua-driver` entries and skills stay, also when Local was asked to/// set up `cua-driver` itself after Stable had (CUA-1776).+#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn the_local_cli_removes_only_its_own_entries_and_leaves_stables_cua_and_cua_driver() {let mut h = home();+ let drv = fake_driver(&h);mkdirs(&h, &[".cursor"]);let cursor = h.dir.path().join(".cursor/mcp.json");let root = h.dir.path().to_path_buf();@@ -543,7 +560,7 @@ async fn the_local_cli_removes_only_its_own_entries_and_leaves_stables_cua_and_c"cursor","--yes","--mcp-command",- "/opt/drv/cua-driver",+ &drv,]).await.ok();@@ -575,7 +592,7 @@ async fn the_local_cli_removes_only_its_own_entries_and_leaves_stables_cua_and_c"cursor","--yes","--mcp-command",- "/opt/drv/cua-driver",+ &drv,]).await.ok();@@ -605,9 +622,11 @@ async fn the_local_cli_removes_only_its_own_entries_and_leaves_stables_cua_and_c/// later set up the same command. Local's record still says it wrote the entry,/// but the name is Cua Driver's, so removing Local's setup leaves it, and the/// released app's `cua-driver` skill, alone.+#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn the_local_cli_leaves_cua_driver_alone_even_when_it_registered_it_first() {let mut h = home();+ let drv = fake_driver(&h);mkdirs(&h, &[".cursor"]);let cursor = h.dir.path().join(".cursor/mcp.json");let root = h.dir.path().to_path_buf();@@ -620,7 +639,7 @@ async fn the_local_cli_leaves_cua_driver_alone_even_when_it_registered_it_first("cursor","--yes","--mcp-command",- "/opt/drv/cua-driver",+ &drv,];let local_home = h.dir.path().join(".cua-local");@@ -651,7 +670,8 @@ async fn the_local_cli_leaves_cua_driver_alone_even_when_it_registered_it_first(serde_json::from_str(&std::fs::read_to_string(&cursor).unwrap()).unwrap();assert!(left["mcpServers"]["cua-local"].is_null(), "{left}");assert_eq!(- left["mcpServers"]["cua-driver"]["command"], "/opt/drv/cua-driver",+ left["mcpServers"]["cua-driver"]["command"],+ drv.as_str(),"Cua Driver's server stays: {left}");assert!(@@ -671,9 +691,11 @@ async fn the_local_cli_leaves_cua_driver_alone_even_when_it_registered_it_first();}+#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {let h = home();+ let drv = fake_driver(&h);mkdirs(&h, &[".codex", ".claude"]);agent_owned(&h, &[".codex/auth.json", ".claude/settings.json"]);std::fs::write(@@ -692,7 +714,7 @@ async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {"all","--yes","--mcp-command",- "/opt/drv/cua-driver",+ &drv,]).await;o.ok();@@ -709,9 +731,9 @@ async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {assert!(!o.stdout.contains("not installed yet"), "{o:?}");let codex = std::fs::read_to_string(h.dir.path().join(".codex/config.toml")).unwrap();assert!(- codex.contains(- "[mcp_servers.cua-driver]\ncommand = \"/opt/drv/cua-driver\"\nargs = [\"mcp\"]"- ),+ codex.contains(&format!(+ "[mcp_servers.cua-driver]\ncommand = \"{drv}\"\nargs = [\"mcp\"]"+ )),"{codex}");assert!(@@ -737,7 +759,7 @@ async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {"--agents","codex","--mcp-command",- "/opt/drv/cua-driver",+ &drv,]).await;o.ok();@@ -762,8 +784,28 @@ async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {assert_eq!(codex["cua_driver_configured"], true, "{codex}");assert_eq!(codex["cua_configured"], false, "{codex}");- // Without an installed cua-driver it points at the bare name and says how- // to install it.+ // Plain `cua agents remove` leaves it: it removes Cua Spaces' entries+ // only. `--include-cua-driver` undoes it.+ let o = h.run(&["agents", "remove", "--yes"]).await;+ o.ok();+ let codex = std::fs::read_to_string(h.dir.path().join(".codex/config.toml")).unwrap();+ assert!(codex.contains("[mcp_servers.cua-driver]"), "{codex}");+ assert!(h.dir.path().join(".claude/skills/cua-driver").is_dir());+ let o = h+ .run(&["agents", "remove", "--include-cua-driver", "--yes"])+ .await;+ o.ok();+ let codex = std::fs::read_to_string(h.dir.path().join(".codex/config.toml")).unwrap();+ assert_eq!(codex, "[mcp_servers.other]\ncommand = \"o\"\n");+ assert!(!h.dir.path().join(".claude/skills/cua-driver").exists());+}++/// Without an installed cua-driver nothing is written: the row fails with+/// the reason and the CLI says how to install it.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn agents_setup_cua_driver_without_cua_driver_writes_nothing() {+ let h = home();+ mkdirs(&h, &[".claude"]);let o = h.run(&["agents",@@ -775,7 +817,8 @@ async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {"--yes",]).await;- o.ok();+ assert_eq!(o.code, 1, "{o:?}");+ assert!(o.stdout.contains("isn't installed"), "{o:?}");// The install one-liner is PowerShell's `-Only` on Windows, sh's `--only`// elsewhere.let hint = if cfg!(windows) {@@ -784,30 +827,18 @@ async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {"--only cua-driver"};assert!(o.stdout.contains(hint), "{o:?}");-- // Plain `cua agents remove` leaves it: it removes Cua Spaces' entries- // only. `--include-cua-driver` undoes it.- let o = h.run(&["agents", "remove", "--yes"]).await;- o.ok();- let codex = std::fs::read_to_string(h.dir.path().join(".codex/config.toml")).unwrap();- assert!(codex.contains("[mcp_servers.cua-driver]"), "{codex}");- assert!(h.dir.path().join(".claude/skills/cua-driver").is_dir());- let o = h- .run(&["agents", "remove", "--include-cua-driver", "--yes"])- .await;- o.ok();- let codex = std::fs::read_to_string(h.dir.path().join(".codex/config.toml")).unwrap();- assert_eq!(codex, "[mcp_servers.other]\ncommand = \"o\"\n");- assert!(!h.dir.path().join(".claude/skills/cua-driver").exists());+ assert!(!h.dir.path().join(".claude.json").exists());}/// `cua agents remove` (what the uninstaller runs) takes Cua Spaces' `cua`/// server and skills and leaves Cua Driver's `cua-driver` server and skill,/// in the configs of Claude Code, Codex and Cursor; `--dry-run` lists exactly/// that and changes nothing; `--include-cua-driver` takes Cua Driver's too.+#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn agents_remove_keeps_cua_driver_and_dry_run_lists_what_it_removes() {let h = home();+ let drv = fake_driver(&h);mkdirs(&h, &[".claude", ".codex", ".cursor"]);let at = |rel: &str| h.dir.path().join(rel);std::fs::write(@@ -845,7 +876,7 @@ async fn agents_remove_keeps_cua_driver_and_dry_run_lists_what_it_removes() {agents,"--yes","--mcp-command",- "/opt/drv/cua-driver",+ &drv,]).await.ok();@@ -854,7 +885,7 @@ async fn agents_remove_keeps_cua_driver_and_dry_run_lists_what_it_removes() {for c in configs {let text = read(c);assert!(text.contains("/opt/cua/bin/cua"), "{c}: {text}");- assert!(text.contains("/opt/drv/cua-driver"), "{c}: {text}");+ assert!(text.contains(&drv), "{c}: {text}");}let state = at(".cua/agent-setup.json");let snapshot = || -> Vec<String> {@@ -937,7 +968,7 @@ async fn agents_remove_keeps_cua_driver_and_dry_run_lists_what_it_removes() {for c in configs {let text = read(c);assert!(!text.contains("/opt/cua/bin/cua"), "{c}: {text}");- assert!(text.contains("/opt/drv/cua-driver"), "{c}: {text}");+ assert!(text.contains(&drv), "{c}: {text}");assert!(text.contains("other"), "{c}: {text}");}assert!(!at(".claude/skills/cua-spaces").exists());@@ -972,9 +1003,11 @@ async fn agents_remove_keeps_cua_driver_and_dry_run_lists_what_it_removes() {assert!(!at(".claude/skills/cua-driver").exists());}+#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn agents_setup_cua_driver_says_where_the_skill_went_and_no_skills_skips_it() {let h = home();+ let drv = fake_driver(&h);mkdirs(&h, &[".codex", ".claude"]);let skill = |rel: &str| h.dir.path().join(rel).join("cua-driver/SKILL.md");@@ -988,7 +1021,7 @@ async fn agents_setup_cua_driver_says_where_the_skill_went_and_no_skills_skips_i"claude","--yes","--mcp-command",- "/opt/drv/cua-driver",+ &drv,]).await;o.ok();@@ -1013,7 +1046,7 @@ async fn agents_setup_cua_driver_says_where_the_skill_went_and_no_skills_skips_i"--no-skills","--yes","--mcp-command",- "/opt/drv/cua-driver",+ &drv,]).await;o.ok();diff --git a/libs/cua/crates/cua-home/src/channel.rs b/libs/cua/crates/cua-home/src/channel.rsindex 311667807d..2535ca3fa3 100644--- a/libs/cua/crates/cua-home/src/channel.rs+++ b/libs/cua/crates/cua-home/src/channel.rs@@ -24,6 +24,8 @@//! | Cua Volume | `~/Cua Volume` | `~/Cua Volume Local` |//! | Lume | `lume`, `com.trycua.lume_daemon`, `:7777`, `~/.lume` | `lume-local`, `com.trycua.lume_daemon.local`, `:7787`, `~/.lume-local` |//! | App data | `~/Library/Application Support/com.trycua.spaces.macos` | `.../com.trycua.spaces.macos.local` |+//! | Cua Driver socket | `~/.cua/run/cua-driver.sock` | `~/.cua-local/run/cua-driver.sock` |+//! | Cua Driver updates | `<App data>/driver/<version>/` | `<App data>/driver/<version>/` |//! | Agent MCP server | `cua` (launches `cua mcp`) | `cua-local` (launches `cua-local mcp`) |//! | Agent skills | `cua-spaces`, `cua-volume`, ... | `cua-spaces-local`, `cua-volume-local`, ... |//!@@ -372,6 +374,24 @@ impl CuaChannel {.join(self.app_support_dir_name())}+ /// The socket of the Cua Driver that Cua Spaces runs for coding agents+ /// on this Mac (`cua-spacesd` starts it as its own child, so its+ /// permissions are the app's): `~/.cua/run/cua-driver.sock` or+ /// `~/.cua-local/run/cua-driver.sock`. Agent configs name it, so it is+ /// per channel and the same in every environment (never below+ /// `envs/`), and never per launch. Not the standalone Cua Driver's+ /// socket, so the two never fight over one endpoint.+ pub fn embedded_driver_socket(self) -> PathBuf {+ self.home_dir().join("run").join("cua-driver.sock")+ }++ /// Where Cua Spaces keeps Cua Driver versions newer than the one in its+ /// bundle, one folder per version: `<app_support_dir>/driver`. Updates+ /// go here, never into the signed app bundle.+ pub fn driver_updates_dir(self) -> PathBuf {+ self.app_support_dir().join("driver")+ }+/// The URL scheme the app registers (`cua`, `cua-local`), without `://`.pub fn url_scheme(self) -> &'static str {match self {@@ -1022,6 +1042,18 @@ mod tests {l.app_support_dir(),user_home().join("Library/Application Support/com.trycua.spaces.macos.local"));+ assert_eq!(+ l.embedded_driver_socket(),+ user_home().join(".cua-local/run/cua-driver.sock")+ );+ assert_eq!(+ l.driver_updates_dir(),+ user_home().join("Library/Application Support/com.trycua.spaces.macos.local/driver")+ );+ assert_eq!(+ CuaChannel::Stable.embedded_driver_socket(),+ user_home().join(".cua/run/cua-driver.sock")+ );assert_eq!(l.cli_name(), "cua-local");assert_eq!(l.cli_path(), user_home().join(".local/bin/cua-local"));assert_eq!(l.home_dir(), user_home().join(".cua-local"));diff --git a/libs/cua/crates/cua-home/tests/app_agent_setup_names_test.rs b/libs/cua/crates/cua-home/tests/app_agent_setup_names_test.rsindex aaa0013cfa..0370c839f8 100644--- a/libs/cua/crates/cua-home/tests/app_agent_setup_names_test.rs+++ b/libs/cua/crates/cua-home/tests/app_agent_setup_names_test.rs@@ -71,6 +71,12 @@ fn the_swift_app_leaves_the_mcp_server_name_to_the_channel() {"no AgentMcpServer in the Swift app: did LiveAgentSetup move? Update this test");for (file, call) in &servers {+ // The Cua Driver entry (`EmbeddedDriver.serverName`) names itself for+ // the channel already: `cua-driver`, or `cua-driver-local` for Cua+ // Spaces Local, so Local never writes over the released app's entry.+ if call.contains("name: driver.serverName") {+ continue;+ }assert!(call.contains("name: \"\""),"{} builds `{call}`: pass `name: \"\"` so the SDK names the server for the channel \diff --git a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs b/libs/cua/crates/cua-sdk/src/native/agent_setup.rsindex d0bbb09358..8cc4456030 100644--- a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs+++ b/libs/cua/crates/cua-sdk/src/native/agent_setup.rs@@ -316,17 +316,44 @@ impl AgentSetup {skills: bool,mcp: bool,) -> Result<Vec<AgentSetupOutcome>> {- let server = match command {- Some(c) if !c.trim().is_empty() => cua_agent_setup::McpServer::driver(c),- _ => cua_agent_setup::McpServer::driver_for(self.inner.env()),- };+ // Without `command`, a missing or broken cua-driver is first+ // installed from its signed release (`cua.ai/driver/install.sh`, as+ // the installers' `cua-driver` item does). The server is written+ // only by absolute path and only after `cua-driver mcp` answers an+ // MCP `initialize`; otherwise each agent's `cua-driver` row fails+ // with the reason and how to fix it, and its config is left alone.+ let command = command.filter(|c| !c.trim().is_empty());self.blocking(move |s| {- Ok(outcomes(s.setup_cua_driver(- &agents,- &server,- cua_agent_setup::Parts { skills, mcp },- false,- )?))+ let server = match command {+ Some(c) => Ok(cua_agent_setup::McpServer::driver(c)),+ None if mcp => cua_agent_setup::driver::ensure(s.env(), true)+ .map(|p| cua_agent_setup::McpServer::driver(p.display().to_string())),+ None => Ok(cua_agent_setup::McpServer::driver_for(s.env())),+ };+ let parts = cua_agent_setup::Parts { skills, mcp };+ let mut out = match &server {+ Ok(server) => s.setup_cua_driver(&agents, server, parts, false)?,+ Err(_) => {+ let skills_only = cua_agent_setup::Parts { skills, mcp: false };+ let any = cua_agent_setup::McpServer::driver("cua-driver");+ s.setup_cua_driver(&agents, &any, skills_only, false)?+ }+ };+ if let Err(why) = &server {+ out.extend(s.driver_unavailable(&agents, why)?);+ }+ // A failed row says how to fix it.+ let fix = format!(+ "Set up again to retry, or install it with: {}",+ cua_agent_setup::driver::install_command(s.env().os)+ );+ for o in out+ .iter_mut()+ .filter(|o| o.failed() && o.item == cua_agent_setup::DRIVER_MCP_SERVER_NAME)+ {+ o.detail = format!("{}. {fix}", o.detail.trim_end_matches('.'));+ }+ Ok(outcomes(out))}).await}@@ -758,18 +785,28 @@ mod tests {assert!(!d.path().join(".agents/skills/cua-spaces").exists());}+ #[cfg(unix)]#[tokio::test]async fn sdk_cua_driver_setup_in_a_temp_home() {let d = tempfile::tempdir().unwrap();std::fs::create_dir_all(d.path().join(".codex")).unwrap();+ // Set up writes the MCP server only for a driver that answers+ // `initialize`, so use a stand-in that does.+ let drv = d.path().join("opt/drv/cua-driver");+ std::fs::create_dir_all(drv.parent().unwrap()).unwrap();+ std::fs::write(+ &drv,+ "#!/bin/sh\nread line\nprintf '%s\\n' '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"serverInfo\":{\"name\":\"cua-driver\",\"version\":\"9.9.9\"}}}'\n",+ )+ .unwrap();+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&drv, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let drv_path = drv.display().to_string();let s = AgentSetup::with_env(cua_agent_setup::HostEnv::isolated(d.path()));let out = s- .setup_cua_driver(- vec!["codex".into()],- Some("/opt/drv/cua-driver".into()),- true,- true,- )+ .setup_cua_driver(vec!["codex".into()], Some(drv_path.clone()), true, true).await.unwrap();assert!(@@ -786,6 +823,6 @@ mod tests {let codex = s.status().into_iter().find(|a| a.id == "codex").unwrap();assert!(codex.cua_driver_configured && !codex.cua_configured);let toml = std::fs::read_to_string(d.path().join(".codex/config.toml")).unwrap();- assert!(toml.contains("/opt/drv/cua-driver"), "{toml}");+ assert!(toml.contains(&drv_path), "{toml}");}}