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): run the host service as the Cua Spaces app itself, one name in System Settings (CUA-1885) (#5494)
Francesco Bonaccicd134c2431ee
diff --git a/.github/workflows/cd-cua-spaces.yml b/.github/workflows/cd-cua-spaces.ymlindex d7ad317b6e..b19eed4130 100644--- a/.github/workflows/cd-cua-spaces.yml+++ b/.github/workflows/cd-cua-spaces.yml@@ -490,6 +490,16 @@ jobs:--sign "$identity" --out "$RUNNER_TEMP/spaces-app" \--feed-url "https://github.com/$GITHUB_REPOSITORY/releases/download/cua-spaces-latest/cua-spaces-appcast.xml"+ # The symbols build-app.sh strips out of the shipped binaries, for+ # symbolicating crash reports. Not a release asset.+ - name: Keep the macOS dSYMs+ uses: actions/upload-artifact@v4+ with:+ name: cua-spaces-darwin-universal-dSYMs+ path: ${{ runner.temp }}/spaces-app/cua-spaces-*-dSYMs.zip+ if-no-files-found: error+ retention-days: 90+- name: Notarize and staple the appif: steps.signing.outputs.apple == 'true'env:diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.tsindex dcbce8c7fc..62a745cac5 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts@@ -1234,6 +1234,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_host_migrate_service": {+ args: [FfiType.Handle, FfiType.Int8, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_host_pause_signed_out": {args: [FfiType.Handle],ret: FfiType.Handle,@@ -3324,6 +3329,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_host_migrate_service": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_host_pause_signed_out": {args: [],ret: FfiType.UInt16,@@ -5154,6 +5164,7 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_method_guestdisplay_via(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_constructor_host_new(cuaHome: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_sdk_fn_method_host_configure(uniffiSelf: bigint, change: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_host_migrate_service(uniffiSelf: bigint, force: number, appVersion: Uint8Array): bigint;uniffi_cua_sdk_fn_method_host_pause_signed_out(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_host_remove(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_host_resume_signed_in(uniffiSelf: bigint, account: Uint8Array): bigint;@@ -5572,6 +5583,7 @@ interface NativeModuleInterface {uniffi_cua_sdk_checksum_method_guestdisplay_via(): number;uniffi_cua_sdk_checksum_constructor_host_new(): number;uniffi_cua_sdk_checksum_method_host_configure(): number;+ uniffi_cua_sdk_checksum_method_host_migrate_service(): number;uniffi_cua_sdk_checksum_method_host_pause_signed_out(): number;uniffi_cua_sdk_checksum_method_host_remove(): number;uniffi_cua_sdk_checksum_method_host_resume_signed_in(): number;diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.tsindex 743afe72be..bb2b4129b4 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts@@ -7703,6 +7703,67 @@ const FfiConverterTypeHostProvidedSpace = (() => {return new FFIConverter();})();+/**+ * What [`Host::migrate_service`] did.+ */+export type HostServiceMigration = {+ /**+ * `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or+ * `not-needed`.+ */+ outcome: string,+ /**+ * In words.+ */+ detail: string,+ /**+ * macOS will ask for Screen Recording and Accessibility for Cua Spaces+ * Helper.+ */+ permissionsNeeded: boolean+}++/**+ * Generated factory for {@link HostServiceMigration} record objects.+ */+export const HostServiceMigration = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<HostServiceMigration, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<HostServiceMigration>,+ });+})();++const FfiConverterTypeHostServiceMigration = (() => {+ type TypeName = HostServiceMigration;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ outcome: FfiConverterString.read(from),+ detail: FfiConverterString.read(from),+ permissionsNeeded: FfiConverterBool.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.outcome, into);+ FfiConverterString.write(value.detail, into);+ FfiConverterBool.write(value.permissionsNeeded, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.outcome) ++ FfiConverterString.allocationSize(value.detail) ++ FfiConverterBool.allocationSize(value.permissionsNeeded);++ }+ };+ return new FFIConverter();+})();+/*** A change to this machine's Spaces settings (`None` keeps a value).*/@@ -8078,7 +8139,16 @@ export type HostStatus = {/*** The owner's email, when the relay gave one.*/- ownerEmail?: string+ ownerEmail?: string,+ /**+ * macOS: a Cua Spaces app that can run the host service is+ * installed, so the host service can run as it.+ */+ helperAvailable: boolean,+ /**+ * macOS: the old hand-written LaunchAgent is still there.+ */+ legacyService: boolean}/**@@ -8097,7 +8167,9 @@ export const HostStatus = (() => {spacesAuditError: undefined,pausedSignedOut: false,owner: undefined,- ownerEmail: undefined+ ownerEmail: undefined,+ helperAvailable: false,+ legacyService: false});const create = (() => {return uniffiCreateRecord<HostStatus, ReturnType<typeof defaults>>(defaults);@@ -8141,7 +8213,9 @@ const FfiConverterTypeHostStatus = (() => {spacesAuditError: FfiConverterOptionalString.read(from),pausedSignedOut: FfiConverterBool.read(from),owner: FfiConverterOptionalString.read(from),- ownerEmail: FfiConverterOptionalString.read(from)+ ownerEmail: FfiConverterOptionalString.read(from),+ helperAvailable: FfiConverterBool.read(from),+ legacyService: FfiConverterBool.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -8173,6 +8247,8 @@ const FfiConverterTypeHostStatus = (() => {FfiConverterBool.write(value.pausedSignedOut, into);FfiConverterOptionalString.write(value.owner, into);FfiConverterOptionalString.write(value.ownerEmail, into);+ FfiConverterBool.write(value.helperAvailable, into);+ FfiConverterBool.write(value.legacyService, into);}allocationSize(value: TypeName): number {return FfiConverterBool.allocationSize(value.configured) +@@ -8202,7 +8278,9 @@ const FfiConverterTypeHostStatus = (() => {FfiConverterOptionalString.allocationSize(value.spacesAuditError) +FfiConverterBool.allocationSize(value.pausedSignedOut) +FfiConverterOptionalString.allocationSize(value.owner) +- FfiConverterOptionalString.allocationSize(value.ownerEmail);+ FfiConverterOptionalString.allocationSize(value.ownerEmail) ++ FfiConverterBool.allocationSize(value.helperAvailable) ++ FfiConverterBool.allocationSize(value.legacyService);}};@@ -34191,6 +34269,15 @@ export interface HostLike {* the desktop on or off restarts the host service.*/configure(change: HostSettingsChange, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HostStatus>;+/**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+ migrateService(force: boolean, appVersion: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HostServiceMigration>;/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -34297,6 +34384,46 @@ export class Host extends UniffiAbstractObject implements HostLike {}}+/**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+ async migrateService(force: boolean, appVersion: string, asyncOpts_?: { signal: AbortSignal }): Promise<HostServiceMigration> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_host_migrate_service(+ uniffiTypeHostObjectFactory.clonePointer(this),FfiConverterBool.lower(force, nativeModule().rustbuffer_alloc),FfiConverterString.lower(appVersion, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeHostServiceMigration.lift.bind(FfiConverterTypeHostServiceMigration),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -35740,6 +35867,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_host_configure() !== 36828) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_host_configure");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_host_migrate_service() !== 36386) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_host_migrate_service");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_host_pause_signed_out() !== 3338) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_host_pause_signed_out");}@@ -36720,6 +36850,7 @@ export default Object.freeze({FfiConverterTypeHostAccessRecord,FfiConverterTypeHostPermission,FfiConverterTypeHostProvidedSpace,+ FfiConverterTypeHostServiceMigration,FfiConverterTypeHostSettingsChange,FfiConverterTypeHostSetupOptions,FfiConverterTypeHostSpacesAuditRecord,diff --git a/apps/cua-spaces-desktop/test/fixtures.ts b/apps/cua-spaces-desktop/test/fixtures.tsindex 2297d13b7b..4d41acc22e 100644--- a/apps/cua-spaces-desktop/test/fixtures.ts+++ b/apps/cua-spaces-desktop/test/fixtures.ts@@ -305,6 +305,8 @@ export function unconfiguredHost(): HostStatus {pausedSignedOut: false,owner: undefined,ownerEmail: undefined,+ helperAvailable: false,+ legacyService: false,};}diff --git a/apps/cua-spaces-macos/Package.swift b/apps/cua-spaces-macos/Package.swiftindex 371ce5bc0f..897e3d796e 100644--- a/apps/cua-spaces-macos/Package.swift+++ b/apps/cua-spaces-macos/Package.swift@@ -14,7 +14,9 @@ import PackageDescription// notch panel and the menu bar extra. The notch's views are// CuaSpacesNotchUI (libs/spaces-notch-swift), shared with the Electron// app's notch helper.-// * CuaSpacesMac: the app entry point.+// * CuaSpacesMac: the app entry point, and the host service's login item+// (`--service-helper run`: the bundled cua-spacesd as its child, under+// the app's own identity).// * CuaSpacesMacTests: view-model, parity and snapshot tests (swift-testing).//// Sparkle (pinned; Package.resolved) is the macOS updater: a binarydiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swiftnew file mode 100644index 0000000000..cdc00df4dd--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift@@ -0,0 +1,199 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The host service (cua-spacesd) run by this app's own executable, so macOS+// asks for and keeps every permission under one name, "Cua Spaces" (bundle+// id com.trycua.spaces.macos, the Cua team):+//+// CuaSpacesMac --service-helper run the login item (SMAppService.agent,+// Contents/Library/LaunchAgents/+// com.trycua.spaces.helper.plist):+// reads ~/.cua/helper/service.json+// (written by cua-host: args, env,+// log, working directory) and runs+// Contents/MacOS/cua-spacesd with it+// CuaSpacesMac check-permissions `cua-spacesd check-permissions` with+// this terminal's stdio: the app's own+// permission state (cua-host's+// preflight runs it disclaimed)+//+// launchd starts this executable, so macOS holds it (the app's identity)+// responsible for its cua-spacesd child: Screen Recording, Accessibility+// and Local Network checks are all made against "Cua Spaces". A separate+// helper bundle would not do: macOS lists a login item's Accessibility+// under the helper's own name but its Screen Recording under the app's,+// which put two names in System Settings.+//+// No spec (the host is not set up, or was removed): exits 0, and launchd+// leaves it stopped until cua-host writes one and kickstarts it. Never+// touches AppKit, so it never shows in the Dock.++import ApplicationServices+import CoreGraphics+import Darwin+import Foundation++/// The spec file cua-host writes (`cua_host::service::helper_spec_path`).+private func specPath() -> String {+ var home = ProcessInfo.processInfo.environment["HOME"] ?? ""+ if home.isEmpty, let pw = getpwuid(getuid()), let dir = pw.pointee.pw_dir {+ home = String(cString: dir)+ }+ return home + "/.cua/helper/service.json"+}++/// `cua-spacesd` next to this executable (never a path from the spec: only+/// the code sealed in this app runs with the app's permissions).+private func daemonPath() -> String {+ let me = Bundle.main.executablePath ?? CommandLine.arguments[0]+ return URL(fileURLWithPath: me).resolvingSymlinksInPath()+ .deletingLastPathComponent().appendingPathComponent("cua-spacesd").path+}++private func log(_ message: String) {+ FileHandle.standardError.write(Data("cua-spaces service: \(message)\n".utf8))+}++/// What the service runs (`cua_host::service::ServiceSpec`, serde names).+private struct Spec {+ var args: [String]+ var env: [(String, String)]+ var logPath: String?+ var workingDir: String?++ static func load(_ path: String) -> Spec? {+ guard let data = FileManager.default.contents(atPath: path) else { return nil }+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ log("\(path) is not valid JSON")+ return nil+ }+ let args = (json["args"] as? [Any])?.compactMap { $0 as? String } ?? []+ var env: [(String, String)] = []+ for pair in json["env"] as? [Any] ?? [] {+ if let kv = pair as? [Any], kv.count == 2, let k = kv[0] as? String, let v = kv[1] as? String {+ env.append((k, v))+ }+ }+ return Spec(args: args, env: env,+ logPath: (json["log_path"] as? String).flatMap { $0.isEmpty ? nil : $0 },+ workingDir: (json["working_dir"] as? String).flatMap { $0.isEmpty ? nil : $0 })+ }+}++/// Spawns `cua-spacesd args` (stdio redirected to `logPath` when set) and+/// returns its pid.+private func spawn(_ args: [String], env extra: [(String, String)], logPath: String?, workingDir: String?) -> pid_t? {+ let program = daemonPath()+ guard FileManager.default.isExecutableFile(atPath: program) else {+ log("missing \(program)")+ return nil+ }+ var actions: posix_spawn_file_actions_t?+ posix_spawn_file_actions_init(&actions)+ defer { posix_spawn_file_actions_destroy(&actions) }+ if let logPath {+ let dir = (logPath as NSString).deletingLastPathComponent+ try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)+ posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0)+ posix_spawn_file_actions_addopen(&actions, 1, logPath, O_WRONLY | O_CREAT | O_APPEND, 0o600)+ posix_spawn_file_actions_adddup2(&actions, 1, 2)+ }+ if let workingDir {+ posix_spawn_file_actions_addchdir(&actions, workingDir)+ }+ var environment = ProcessInfo.processInfo.environment+ for (k, v) in extra { environment[k] = v }+ let argv: [UnsafeMutablePointer<CChar>?] = ([program] + args).map { strdup($0) } + [nil]+ let envp: [UnsafeMutablePointer<CChar>?] = environment.map { strdup("\($0.key)=\($0.value)") } + [nil]+ defer {+ argv.forEach { free($0) }+ envp.forEach { free($0) }+ }+ var pid: pid_t = 0+ let rc = posix_spawn(&pid, program, &actions, nil, argv, envp)+ guard rc == 0 else {+ log("could not start \(program): \(String(cString: strerror(rc)))")+ return nil+ }+ return pid+}++private func wait(_ pid: pid_t) -> Int32 {+ var status: Int32 = 0+ while waitpid(pid, &status, 0) < 0 {+ if errno != EINTR { return 1 }+ }+ // WIFEXITED / WEXITSTATUS (the macros are not imported into Swift).+ if status & 0x7f == 0 { return (status >> 8) & 0xff }+ return 128 + (status & 0x7f)+}+++// Stop (launchctl kill SIGTERM, logout, shutdown) reaches the child, and+// the service then exits 0 so launchd leaves it stopped. Any other end of+// the child is a failure launchd restarts (KeepAlive SuccessfulExit=false).+private var serviceChild: pid_t = 0+private var serviceStopping: sig_atomic_t = 0++enum ServiceLauncher {+ /// `CuaSpacesMac check-permissions` (and any other cua-spacesd command):+ /// runs it with this process's stdio and exits with its status.+ static func passthrough(_ args: [String]) -> Never {+ guard let pid = spawn(args, env: [], logPath: nil, workingDir: nil) else { exit(127) }+ exit(wait(pid))+ }++ /// `CuaSpacesMac --service-helper run`: the host service.+ static func serve() -> Never {+ guard let spec = Spec.load(specPath()) else {+ log("no host service set up (\(specPath())); nothing to run")+ exit(0)+ }+ guard !spec.args.isEmpty else {+ log("\(specPath()) has no arguments; nothing to run")+ exit(0)+ }+ for sig in [SIGTERM, SIGINT, SIGHUP] {+ signal(sig) { s in+ serviceStopping = 1+ if serviceChild > 0 { kill(serviceChild, s) }+ }+ }+ // Sharing the desktop needs Screen Recording and Accessibility. Ask+ // now, as "Cua Spaces" (macOS shows each prompt once and lists the+ // app in both panes); a background capture alone is refused without+ // a prompt.+ if !spec.args.contains("--no-desktop") {+ if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }+ let prompt = "AXTrustedCheckOptionPrompt" // kAXTrustedCheckOptionPrompt+ _ = AXIsProcessTrustedWithOptions([prompt: true] as CFDictionary)+ }+ guard let pid = spawn(spec.args, env: spec.env, logPath: spec.logPath, workingDir: spec.workingDir) else {+ exit(1)+ }+ serviceChild = pid+ // The app was replaced by one without the service (a downgrade) or+ // the host was removed: the files are gone while this process still+ // runs from them. Stop, so the service that replaced it can take the+ // port; launchd does not start a program that is gone.+ let specFile = specPath()+ let daemonFile = daemonPath()+ Thread.detachNewThread {+ var misses = 0+ while true {+ sleep(5)+ let gone = !FileManager.default.fileExists(atPath: daemonFile)+ || !FileManager.default.fileExists(atPath: specFile)+ misses = gone ? misses + 1 : 0+ if misses >= 2 {+ log("the app's cua-spacesd or its spec is gone; stopping")+ serviceStopping = 1+ kill(pid, SIGTERM)+ return+ }+ }+ }+ let code = wait(pid)+ exit(serviceStopping != 0 ? 0 : (code == 0 ? 1 : code))+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swiftindex df8d802fef..35c5560ce5 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift@@ -4,6 +4,7 @@import CuaSpacesFFIimport CuaSpacesMacKitimport Foundation+import ServiceManagement// `CuaSpacesMac --check-launch-only`: dyld has loaded every library the app// links (libcua_sdk.dylib, Sparkle.framework) and their signatures passed@@ -17,6 +18,26 @@ if CommandLine.arguments.dropFirst().first == "--check-launch-only" {exit(0)}+// The host service, run by this same executable so every permission is the+// app's ("Cua Spaces"; ServiceLauncher.swift), before anything else:+// * `--service-helper run`: the service itself (the login item launchd+// starts);+// * `check-permissions`: cua-spacesd's permission check, answered for the+// app;+// * `--service-helper register|unregister|status`: the login item+// (Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist) through+// SMAppService, which only this bundle's own code may register. cua-host's+// app-helper runner runs it (from the app's SDK and from the `cua` CLI);+// prints `{"status": ...}` (and `"error"`).+let launchArgs = Array(CommandLine.arguments.dropFirst()).filter { !$0.hasPrefix("-psn_") }+if launchArgs.first == "--service-helper" {+ if launchArgs.dropFirst().first == "run" { ServiceLauncher.serve() }+ exit(HelperService.run(Array(launchArgs.dropFirst())))+}+if launchArgs.first == "check-permissions" {+ ServiceLauncher.passthrough(launchArgs)+}+// `CUA_ENV=staging`: this process and the daemon use the staging home.TargetEnvironment.pin()diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swiftindex 0b9f9f5110..34f44f9a74 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift@@ -773,4 +773,7 @@ public final class PendingHost: HostRunning, @unchecked Sendable {public func configure(change: HostSettingsChange) async throws -> HostStatus {try await h().configure(change: change)}+ public func migrateService(force: Bool, appVersion: String) async throws -> HostServiceMigration {+ try await h().migrateService(force: force, appVersion: appVersion)+ }}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swiftindex 034e68c758..5c673a87fd 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift@@ -24,6 +24,17 @@ public protocol HostRunning: AnyObject, Sendable {/// Changes what this machine shares: its desktop, and Spaces for your/// other devices.func configure(change: HostSettingsChange) async throws -> HostStatus+ /// Moves the host service from the old LaunchAgent into this app, as+ /// its own login item ("Cua Spaces"), keeping this machine's id,+ /// registration and Spaces; the old one comes back if the helper does+ /// not take over (outcome `rolled-back`).+ func migrateService(force: Bool, appVersion: String) async throws -> HostServiceMigration+}++extension HostRunning {+ public func migrateService(force: Bool, appVersion: String) async throws -> HostServiceMigration {+ HostServiceMigration(outcome: "not-needed", detail: "", permissionsNeeded: false)+ }}extension CuaSDK.Host: HostRunning {}@@ -36,6 +47,8 @@ public final class FixtureHost: HostRunning, @unchecked Sendable {public var failSetup: String?/// The next `configure` fails with this (once).public var failConfigure: String?+ /// What `migrateService` answers (nil: moved, needing permissions).+ public var migration: HostServiceMigration?public init(status: HostStatus? = nil) {current = status ?? FixtureHost.unconfigured@@ -139,6 +152,34 @@ public final class FixtureHost: HostRunning, @unchecked Sendable {calls.append("remove")current = FixtureHost.unconfigured}++ public func migrateService(force: Bool, appVersion: String) async throws -> HostServiceMigration {+ calls.append("migrate:\(force)")+ let m = migration ?? HostServiceMigration(+ outcome: "migrated", detail: "the host service now runs inside the Cua Spaces app", permissionsNeeded: true)+ if m.outcome == "migrated" || m.outcome == "cleaned-up" {+ current.serviceKind = "app-helper"+ current.legacyService = false+ }+ return m+ }+}++/// The one-time move of the host service into this app, as its own login+/// item (Cua Spaces 0.9.4 and earlier, and `cua host setup`+/// without the app, ran it from a LaunchAgent of their own). Offered on the+/// main window, so a person is there for the one thing macOS asks again:+/// Screen Recording and Accessibility, now for "Cua Spaces". A login+/// launch nobody sees never moves it.+public enum HelperMove: Equatable {+ /// "Cua Spaces moved its background helper": Continue or Not now.+ case offer+ case moving+ /// Moved; `permissions`: macOS needs Screen Recording and Accessibility+ /// for the helper.+ case moved(permissions: Bool)+ /// It did not take over; the old one runs as before (the reason).+ case rolledBack(String)}/// "This machine": the host's state, its page and the host setup form.@@ -202,6 +243,22 @@ public final class HostModel {"Sign in to Cua in your browser to continue. Setup finishes on its own after that."/// Called whenever the state changes (the roster's entry follows it).public var onChange: (() -> Void)?+ /// The host's last status, as the SDK reported it.+ public private(set) var status: HostStatus?+ /// The move into the app's helper, while it shows.+ public private(set) var helperMove: HelperMove? {+ didSet { if oldValue != helperMove { onHelperMove?(helperMove) } }+ }+ /// Shows or hides the move's window (`HelperMoveWindow`).+ public var onHelperMove: ((HelperMove?) -> Void)?+ /// "Not now" this launch.+ private var helperMoveDeclined = false+ /// Restarts of a helper that should run but did not, this launch.+ private var helperRepairs = 0+ /// This app's version (a move that failed is not offered again by+ /// itself with the same version).+ public var appVersion = Bundle.main.infoDictionary?["CuaVersion"] as? String+ ?? Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0"public init(host: HostRunning?) {self.host = host@@ -213,6 +270,7 @@ public final class HostModel {public var summaryInput: AppHostSummaryInput? { state.map { appHostSummaryInput(state: $0) } }func apply(_ status: HostStatus) {+ self.status = statusvar next = appHostState(status: status)next.account = accountstate = next@@ -220,6 +278,7 @@ public final class HostModel {onChange?()}+public func refresh() async {guard let host else { return }do {@@ -227,6 +286,73 @@ public final class HostModel {} catch {self.error = LiveSpacesBackend.words(error)}+ await followHelper()+ }++ // MARK: - The app's login item (the host service, as "Cua Spaces")++ /// After each status: offer the move when the old LaunchAgent runs this+ /// machine and this app carries the helper; quietly remove what an+ /// interrupted move left of the old one.+ func followHelper() async {+ guard let host, let status, status.configured, status.helperAvailable else { return }+ // The helper should run but does not (launchd lost it after the app+ // was replaced): starting it again registers it from this copy.+ if status.serviceKind == "app-helper", !status.serviceRunning, status.sharing,+ !status.pausedSignedOut, helperRepairs < 3 {+ helperRepairs += 1+ if let s = try? await host.startSharing() { apply(s) }+ return+ }+ if status.serviceKind == "app-helper", status.legacyService {+ if let m = try? await host.migrateService(force: false, appVersion: appVersion),+ m.outcome == "cleaned-up" {+ await refreshStatusOnly()+ }+ return+ }+ if status.serviceKind == "launchd", helperMove == nil, !helperMoveDeclined {+ helperMove = .offer+ }+ }++ private func refreshStatusOnly() async {+ guard let host, let s = try? await host.status() else { return }+ apply(s)+ }++ /// Continue: move it now (the old one comes back if the helper does not+ /// take over).+ public func moveToHelper() async {+ guard let host, helperMove == .offer else { return }+ helperMove = .moving+ do {+ // The person asked for it: try again even after a failed move.+ let m = try await host.migrateService(force: true, appVersion: appVersion)+ switch m.outcome {+ case "migrated", "switched", "cleaned-up":+ helperMove = .moved(permissions: m.permissionsNeeded)+ case "not-needed":+ helperMove = nil+ default:+ helperMove = .rolledBack(m.detail)+ }+ } catch {+ helperMove = .rolledBack(LiveSpacesBackend.words(error))+ }+ await refreshStatusOnly()+ }++ /// Not now: asked again at the next launch.+ public func declineHelperMove() {+ helperMoveDeclined = true+ helperMove = nil+ }++ /// Done (or OK) on the last step.+ public func closeHelperMove() {+ helperMoveDeclined = true+ helperMove = nil}// MARK: - Formdiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swiftindex f13ae22071..5d8033a5db 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift@@ -84,3 +84,53 @@ public enum LoginLaunch {== OSType(keyAELaunchedAsLogInItem)}}++/// The host service's login item: this app's own executable+/// (`CuaSpacesMac --service-helper run`, so its permissions are the app's) run by+/// `SMAppService.agent` from Contents/Library/LaunchAgents/+/// com.trycua.spaces.helper.plist. cua-host (the `app-helper` runner, in+/// this app's SDK and in the `cua` CLI) drives it through+/// `CuaSpacesMac --service-helper register|unregister|status`, because only+/// this bundle's code may register it; it writes what the helper runs+/// (~/.cua/helper/service.json) and starts it with launchctl.+public enum HelperService {+ public static let plistName = "com.trycua.spaces.helper.plist"+ public static let label = "com.trycua.spaces.helper"++ static var service: SMAppService { SMAppService.agent(plistName: plistName) }++ public static func status() -> AppLoginItemStatus { MainAppLoginItem.map(service.status) }++ static func name(_ s: AppLoginItemStatus) -> String {+ switch s {+ case .enabled: return "enabled"+ case .notRegistered: return "not-registered"+ case .requiresApproval: return "requires-approval"+ case .notFound: return "not-found"+ }+ }++ /// The command line: prints one JSON object, returns the exit code.+ public static func run(_ args: [String]) -> Int32 {+ var failure: String?+ switch args.first {+ case "register":+ do { try service.register() } catch { failure = error.localizedDescription }+ case "unregister":+ // Not registered is already done.+ if service.status != .notRegistered {+ do { try service.unregister() } catch { failure = error.localizedDescription }+ }+ case "status": break+ default:+ FileHandle.standardError.write(Data("usage: CuaSpacesMac --service-helper register|unregister|status\n".utf8))+ return 2+ }+ var out: [String: String] = ["status": name(status())]+ if let failure { out["error"] = failure }+ if let data = try? JSONSerialization.data(withJSONObject: out, options: [.sortedKeys]) {+ FileHandle.standardOutput.write(data + Data("\n".utf8))+ }+ return failure == nil ? 0 : 1+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swiftindex a27a9c46a4..4ba44c999b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift@@ -324,6 +324,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {func start(_ model: AppModel) {guard !started else { return }started = true+ // The one-time move of the host service into this app (Cua Spaces+ // Helper): its own window, over whichever UI is up.+ HelperMoveWindow.follow(model.host, loginLaunch: Self.launchedAtLogin)// New Space opens New UI's wizard while its experiment is on.model.openWebNewSpace = { on in WebUIWindowController.showNewSpace(model: model, on: on) }// New UI on and off: one window, its frame kept, never two.diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/HelperMoveView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/HelperMoveView.swiftnew file mode 100644index 0000000000..fd362e4ab5--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/HelperMoveView.swift@@ -0,0 +1,189 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import AppKit+import SwiftUI++/// The one-time sheet that moves this Mac's sharing service into the app,+/// (run by the app's own executable, so macOS shows one name, "Cua+/// Spaces"), and walks through the one thing macOS asks again: Screen+/// Recording and Accessibility, each once (`HostModel.helperMove`).+public struct HelperMoveSheet: View {+ let host: HostModel++ public init(host: HostModel) {+ self.host = host+ }++ static let screenRecordingURL =+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"+ static let accessibilityURL =+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"++ public var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ switch host.helperMove {+ case .offer, nil:+ offer+ case .moving:+ HStack(spacing: 10) {+ ProgressView().controlSize(.small)+ Text("Moving the helper. This takes up to a minute.")+ }+ .frame(minHeight: 80)+ case .moved(let permissions):+ moved(permissions: permissions)+ case .rolledBack(let detail):+ rolledBack(detail)+ }+ }+ .padding(22)+ .frame(width: 460)+ }++ private var offer: some View {+ VStack(alignment: .leading, spacing: 14) {+ Label("Cua Spaces moved its background helper", systemImage: "arrow.triangle.2.circlepath")+ .font(.headline)+ Text("macOS needs you to allow it once more.")+ Text("The helper is what lets the people and agents you share this Mac with see the screen and use the mouse and keyboard. It is now part of Cua Spaces, so macOS lists it as \u{201C}Cua Spaces\u{201D} and remembers your answer after updates.")+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ HStack {+ Spacer()+ Button("Not now") { host.declineHelperMove() }+ .keyboardShortcut(.cancelAction)+ Button("Continue") { Task { await host.moveToHelper() } }+ .keyboardShortcut(.defaultAction)+ }+ }+ }++ @ViewBuilder+ private func moved(permissions: Bool) -> some View {+ VStack(alignment: .leading, spacing: 14) {+ Label("Allow Cua Spaces", systemImage: "checkmark.shield")+ .font(.headline)+ if permissions {+ Text("In System Settings, turn on \u{201C}Cua Spaces\u{201D} in these two lists:")+ step(1, "Screen Recording", "Open", Self.screenRecordingURL)+ step(2, "Accessibility", "Open", Self.accessibilityURL)+ Text("The old entry there is called \u{201C}cua-spacesd\u{201D}. You can remove it: click it, then click the minus (\u{2212}) button below the list.")+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ } else {+ Text("All set. Your Mac kept its name, its Spaces and who it is shared with.")+ }+ HStack {+ Spacer()+ Button("Done") { host.closeHelperMove() }+ .keyboardShortcut(.defaultAction)+ }+ }+ }++ private func step(_ n: Int, _ list: String, _ button: String, _ url: String) -> some View {+ HStack(alignment: .firstTextBaseline) {+ Text("\(n).").monospacedDigit()+ Text(list)+ Spacer()+ Button(button) {+ if let u = URL(string: url) { NSWorkspace.shared.open(u) }+ }+ }+ }++ private func rolledBack(_ detail: String) -> some View {+ VStack(alignment: .leading, spacing: 14) {+ Label("Nothing changed", systemImage: "arrow.uturn.backward")+ .font(.headline)+ Text("The helper could not move this time, so the old one keeps running and this Mac stays shared. Cua Spaces tries again after the next update.")+ .fixedSize(horizontal: false, vertical: true)+ DisclosureGroup("Details") {+ Text(detail).font(.caption).textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ HStack {+ Spacer()+ Button("OK") { host.closeHelperMove() }+ .keyboardShortcut(.defaultAction)+ }+ }+ }+}++/// The move's own window, over whichever UI is up (the New UI window or the+/// main one). At a login launch it waits until the app is brought to the+/// front, so it only ever shows to someone who is there.+@MainActor+public final class HelperMoveWindow: NSObject, NSWindowDelegate {+ private static var shared: HelperMoveWindow?+ private let host: HostModel+ private var window: NSWindow?+ private var waiting: NSObjectProtocol?++ private init(host: HostModel) { self.host = host }++ public static func follow(_ host: HostModel, loginLaunch: Bool) {+ let me = HelperMoveWindow(host: host)+ shared = me+ host.onHelperMove = { [weak me] move in+ guard let me else { return }+ if move == nil { me.close(); return }+ if move != .offer { me.window?.level = .normal }+ if loginLaunch && !NSApp.isActive {+ me.waitForFront()+ } else {+ me.show()+ }+ }+ }++ private func waitForFront() {+ guard waiting == nil else { return }+ waiting = NotificationCenter.default.addObserver(+ forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main+ ) { [weak self] _ in+ MainActor.assumeIsolated {+ guard let self else { return }+ if let w = self.waiting { NotificationCenter.default.removeObserver(w) }+ self.waiting = nil+ if self.host.helperMove != nil { self.show() }+ }+ }+ }++ private func show() {+ if let window { window.makeKeyAndOrderFront(nil); return }+ let w = NSWindow(contentViewController: NSHostingController(rootView: HelperMoveSheet(host: host)))+ w.title = "Cua Spaces"+ w.styleMask = [.titled, .closable]+ w.isReleasedWhenClosed = false+ w.delegate = self+ // Above the app's other windows while it asks (the New UI opens after+ // it); an ordinary window once System Settings needs the front.+ w.level = host.helperMove == .offer ? .floating : .normal+ w.setContentSize(NSSize(width: 460, height: 260))+ w.center()+ window = w+ NSApp.activate()+ w.makeKeyAndOrderFront(nil)+ w.orderFrontRegardless()+ }++ private func close() {+ window?.delegate = nil+ window?.close()+ window = nil+ }++ public func windowWillClose(_ notification: Notification) {+ window = nil+ // Closed with the button: as "Not now" (or Done).+ switch host.helperMove {+ case .moving: break+ case .offer: host.declineHelperMove()+ default: host.closeHelperMove()+ }+ }+}diff --git a/apps/cua-spaces-macos/Support/Helper/com.trycua.spaces.helper.plist b/apps/cua-spaces-macos/Support/Helper/com.trycua.spaces.helper.plistnew file mode 100644index 0000000000..04bb7b0c33--- /dev/null+++ b/apps/cua-spaces-macos/Support/Helper/com.trycua.spaces.helper.plist@@ -0,0 +1,44 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!--+ Cua Spaces.app/Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist:+ the host service as the app's login item, registered with+ SMAppService.agent(plistName:) (`CuaSpacesMac --service-helper register`;+ cua-host's app-helper runner). It runs the app's own executable+ (`--service-helper run`), so screen capture and input use the app's+ Screen Recording and Accessibility grants: one name, "Cua Spaces", in+ System Settings. It runs in the user's GUI (Aqua) session, reads+ ~/.cua/helper/service.json and exits 0 when there is none (nothing set+ up), which launchd leaves stopped; any other exit is restarted.+-->+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.trycua.spaces.helper</string>+ <key>BundleProgram</key>+ <string>Contents/MacOS/CuaSpacesMac</string>+ <key>ProgramArguments</key>+ <array>+ <string>CuaSpacesMac</string>+ <string>--service-helper</string>+ <string>run</string>+ </array>+ <key>AssociatedBundleIdentifiers</key>+ <array>+ <string>com.trycua.spaces.macos</string>+ </array>+ <key>LimitLoadToSessionType</key>+ <string>Aqua</string>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <dict>+ <key>SuccessfulExit</key>+ <false/>+ </dict>+ <key>ThrottleInterval</key>+ <integer>5</integer>+ <key>ProcessType</key>+ <string>Interactive</string>+</dict>+</plist>diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperMoveTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperMoveTests.swiftnew file mode 100644index 0000000000..ce8a45cb28--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperMoveTests.swift@@ -0,0 +1,89 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import CuaSDK+import CuaSpacesFFI+@testable import CuaSpacesMacKit+import Foundation+import Testing++/// The one-time move of the host service into the app (its own login item):+/// offered only when the old LaunchAgent runs it and this app carries the+/// helper, moved only when the person says Continue, and what went wrong+/// shown in words with the old service kept.+@MainActor+@Suite("Moving the host service into the app")+struct HelperMoveTests {+ /// A host set up as Cua Spaces 0.9.4 left it.+ func oldInstall(helperAvailable: Bool = true, kind: String = "launchd") -> FixtureHost {+ var s = FixtureHost.unconfigured+ s.configured = true+ s.mode = "relay"+ s.machineId = "0123abcd4567"+ s.sharing = true+ s.serviceInstalled = true+ s.serviceRunning = true+ s.serviceKind = kind+ s.helperAvailable = helperAvailable+ s.legacyService = true+ return FixtureHost(status: s)+ }++ @Test func anOldAgentWithTheHelperIsOfferedNotMoved() async {+ let host = oldInstall()+ let m = HostModel(host: host)+ var shown: [HelperMove?] = []+ m.onHelperMove = { shown.append($0) }+ await m.refresh()+ #expect(m.helperMove == .offer)+ #expect(shown == [.offer])+ #expect(!host.calls.contains { $0.hasPrefix("migrate") }, "never moved without Continue")+ }++ @Test func withoutTheHelperNothingIsOffered() async {+ let m = HostModel(host: oldInstall(helperAvailable: false))+ await m.refresh()+ #expect(m.helperMove == nil)+ }++ @Test func continueMovesItAndAsksForThePermissions() async {+ let host = oldInstall()+ let m = HostModel(host: host)+ await m.refresh()+ await m.moveToHelper()+ #expect(host.calls.contains("migrate:true"))+ #expect(m.helperMove == .moved(permissions: true))+ #expect(m.status?.serviceKind == "app-helper")+ m.closeHelperMove()+ await m.refresh()+ #expect(m.helperMove == nil, "moved: never offered again")+ }++ @Test func aMoveThatDidNotTakeOverSaysSoAndKeepsTheOldOne() async {+ let host = oldInstall()+ host.migration = HostServiceMigration(+ outcome: "rolled-back", detail: "the host service did not take over", permissionsNeeded: false)+ let m = HostModel(host: host)+ await m.refresh()+ await m.moveToHelper()+ #expect(m.helperMove == .rolledBack("the host service did not take over"))+ #expect(m.status?.serviceKind == "launchd")+ }++ @Test func notNowWaitsForTheNextLaunch() async {+ let m = HostModel(host: oldInstall())+ await m.refresh()+ m.declineHelperMove()+ await m.refresh()+ #expect(m.helperMove == nil)+ }++ @Test func leftoversOfTheOldAgentAreRemovedQuietly() async {+ let host = oldInstall(kind: "app-helper")+ host.migration = HostServiceMigration(outcome: "cleaned-up", detail: "", permissionsNeeded: false)+ let m = HostModel(host: host)+ await m.refresh()+ #expect(host.calls.contains("migrate:false"))+ #expect(m.helperMove == nil)+ }+}diff --git a/apps/cua-spaces-macos/scripts/build-app.sh b/apps/cua-spaces-macos/scripts/build-app.shindex 2579e8a53e..31c24ecc45 100755--- a/apps/cua-spaces-macos/scripts/build-app.sh+++ b/apps/cua-spaces-macos/scripts/build-app.sh@@ -12,8 +12,16 @@# (the app installs it onto PATH on first launch, like the Tauri app's# sidecar), Sparkle.framework (the updater, from the pinned SwiftPM# artifact, with its XPC services) in Contents/Frameworks and the-# third-party notices (Settings, About, Acknowledgements), then signs it-# ad hoc as com.trycua.spaces.macos.+# third-party notices (Settings, About, Acknowledgements), the host+# service (the pinned cua-spacesd from scripts/fetch-spacesd.sh, or+# $CUA_SPACESD_BIN, in Contents/MacOS; the app's own executable runs it as+# its login item, whose SMAppService plist is in+# Contents/Library/LaunchAgents), then signs it ad hoc as+# com.trycua.spaces.macos.+#+# A release build strips every binary it ships (local symbols from the SDK+# dylib, all but the dynamic ones from the executables) after writing their+# dSYMs to <out-dir>/dSYMs, which crash reports symbolicate against.## scripts/build-app.sh [debug|release] [out-dir]#@@ -109,8 +117,42 @@ for rp in $(otool -l "$app/Contents/MacOS/CuaSpacesMac" | awk '/LC_RPATH/ {getlidoneinstall_name_tool -add_rpath "@executable_path/../Frameworks" "$app/Contents/MacOS/CuaSpacesMac" 2>/dev/null || true+# The host service: cua-spacesd next to the app's executable, which runs it+# as the app's login item (SMAppService.agent; `CuaSpacesMac+# --service-helper run`), so macOS asks for and keeps its permissions under+# the app's own name, "Cua Spaces".+mkdir -p "$app/Contents/Library/LaunchAgents"+# shellcheck disable=SC2086 # one word per architecture+spacesd="$("$here/scripts/fetch-spacesd.sh" ${archs:-$(uname -m)})"+cp "$spacesd" "$app/Contents/MacOS/cua-spacesd"+chmod 0755 "$app/Contents/MacOS/cua-spacesd"+cp "$here/Support/Helper/com.trycua.spaces.helper.plist" "$app/Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist"+[ -x "$cli" ] && cp "$cli" "$app/Contents/MacOS/cua"++# Release: symbols go to dSYMs, not into the download (about 40% of each+# binary). Executables keep only what dynamic linking needs; the dylib keeps+# its exported (global) symbols, which the app links against.+if [ "$config" = release ]; then+ syms="$out/dSYMs"+ rm -rf "$syms"+ mkdir -p "$syms"+ for f in "$app/Contents/MacOS/CuaSpacesMac" "$app/Contents/MacOS/cua" "$app/Contents/MacOS/cua-spacesd" \+ "$app/Contents/Frameworks/libcua_sdk.dylib"; do+ [ -f "$f" ] || continue+ # A prebuilt binary (cua-spacesd) has no debug map: its dSYM still+ # carries the symbol table, which is what symbolication needs.+ dsymutil "$f" -o "$syms/$(basename "$f").dSYM" 2>/dev/null+ case "$f" in+ *.dylib) strip -x "$f" 2>/dev/null ;;+ *) strip "$f" 2>/dev/null ;;+ esac+ done+fi+# The daemon keeps a signature of its own (ad hoc here; build-release.sh+# signs it with the release identity).+codesign -s - -f -i com.trycua.cua-env-driver "$app/Contents/MacOS/cua-spacesd"+if [ -x "$cli" ]; then- cp "$cli" "$app/Contents/MacOS/cua"codesign -s - -f -i com.trycua.cua "$app/Contents/MacOS/cua"elseecho "note: no cua CLI at $cli (cargo build --release -p cua-spaces-cli); the app will not install one" >&2@@ -143,7 +185,7 @@ fi# only fail on the other kind of Mac).if [ -n "$archs" ]; thenfor f in "$app/Contents/MacOS/CuaSpacesMac" "$app/Contents/Frameworks/libcua_sdk.dylib" "$app/Contents/MacOS/cua" \- "$app/Contents/Frameworks/Sparkle.framework/Versions/B/Sparkle"; do+ "$app/Contents/Frameworks/Sparkle.framework/Versions/B/Sparkle" "$app/Contents/MacOS/cua-spacesd"; do[ -e "$f" ] || continuefor arch in $archs; dolipo "$f" -verify_arch "$arch" || { echo "$f has no $arch slice ($(lipo -archs "$f"))" >&2; exit 1; }diff --git a/apps/cua-spaces-macos/scripts/build-release.sh b/apps/cua-spaces-macos/scripts/build-release.shindex c3bf3df5ad..2f96f14abc 100755--- a/apps/cua-spaces-macos/scripts/build-release.sh+++ b/apps/cua-spaces-macos/scripts/build-release.sh@@ -15,6 +15,9 @@# Updater.app, then the framework# Contents/Frameworks/libcua_sdk.dylib (no entitlements)# Contents/MacOS/cua com.trycua.cua, Support/cua.entitlements+# Contents/MacOS/cua-spacesd com.trycua.cua-env-driver (the host service,+# which the app's own executable runs as its+# login item)# Cua Spaces.app com.trycua.spaces.macos, Support/CuaSpacesMac.entitlements## scripts/build-release.sh --version 0.2.0[-suffix] [--build-number N]@@ -144,6 +147,16 @@ if [ -n "$feed_url" ]; thencase "$feed_url" in https://*) ;; *) echo "--feed-url must be https" >&2; exit 2 ;; esac/usr/libexec/PlistBuddy -c "Set :SUFeedURL $feed_url" "$plist"fi+[ -x "$app/Contents/MacOS/cua-spacesd" ] || { echo "$app has no Contents/MacOS/cua-spacesd" >&2; exit 1; }+[ -f "$app/Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist" ] ||+ { echo "$app has no com.trycua.spaces.helper.plist" >&2; exit 1; }+# The symbols build-app.sh took out of the binaries, for symbolicating crash+# reports (the release workflow keeps it as an artifact; not shipped).+if [ -d "$out/dSYMs" ]; then+ rm -f "$out/cua-spaces-$version-dSYMs.zip"+ (cd "$out" && ditto -c -k --keepParent dSYMs "cua-spaces-$version-dSYMs.zip")+ rm -rf "$out/dSYMs"+fifor key in SUFeedURL SUPublicEDKey; do/usr/libexec/PlistBuddy -c "Print :$key" "$plist" >/dev/null 2>&1 || { echo "Info.plist has no $key" >&2; exit 1; }done@@ -175,6 +188,10 @@ done"${sign[@]}" "$app/Contents/Frameworks/libcua_sdk.dylib""${sign[@]}" --identifier com.trycua.cua \--entitlements "$here/Support/cua.entitlements" "$app/Contents/MacOS/cua"+# The host service. The app's own executable runs it, so its permissions+# are the app's (designated requirement: identifier and team, checked+# below), and they stay granted across updates.+"${sign[@]}" --identifier com.trycua.cua-env-driver "$app/Contents/MacOS/cua-spacesd"app_entitlements="$here/Support/CuaSpacesMac.entitlements"if [ "$identity" = "-" ]; thenapp_entitlements="$out/.adhoc.entitlements"@@ -185,7 +202,8 @@ fi[ "$identity" = "-" ] && rm -f "$app_entitlements"codesign --verify --deep --strict --verbose=2 "$app" >&2-for f in "$app" "$app/Contents/MacOS/cua" "$app/Contents/Frameworks/libcua_sdk.dylib" "${sparkle_parts[@]}"; do+for f in "$app" "$app/Contents/MacOS/cua" "$app/Contents/Frameworks/libcua_sdk.dylib" "${sparkle_parts[@]}" \+ "$app/Contents/MacOS/cua-spacesd"; doflags="$(codesign -dv "$f" 2>&1 | sed -n 's/^CodeDirectory.*flags=\([^ ]*\).*/\1/p')"case "$flags" in *runtime*) ;; *) echo "$f is not signed with the hardened runtime ($flags)" >&2; exit 1 ;; esacdone@@ -228,7 +246,7 @@ fi# A Developer ID build signs Sparkle with the same team (library# validation stays on: the app loads only its own team's code).if [ "$identity" != "-" ]; then- for f in "${sparkle_parts[@]}"; do+ for f in "${sparkle_parts[@]}" "$app/Contents/MacOS/cua-spacesd"; docodesign --verify -R="anchor apple generic and certificate leaf[subject.OU] = \"$team\"" "$f" ||{ echo "$f is not signed by team $team" >&2; exit 1; }donediff --git a/apps/cua-spaces-macos/scripts/check-launch.sh b/apps/cua-spaces-macos/scripts/check-launch.shindex 2ae0bc74d7..ca76857b10 100755--- a/apps/cua-spaces-macos/scripts/check-launch.sh+++ b/apps/cua-spaces-macos/scripts/check-launch.sh@@ -73,6 +73,12 @@ for b in sorted(binaries):bad.append(f"{os.path.relpath(b, app)} links {d} (outside the bundle and the OS)")continuefound = [c for c in candidates if os.path.isfile(c)]+ # An @rpath into the OS's Swift runtime (/usr/lib/swift: the+ # bundled cua-spacesd links it) is in the dyld shared cache, not on+ # disk.+ if not found and d.startswith("@rpath/") and any(+ r.startswith(("/usr/lib/", "/System/Library/")) for r in rpaths):+ continueif not found:bad.append(f"{os.path.relpath(b, app)}: {d} resolves to no file (run paths {rpaths})")elif not os.path.realpath(found[0]).startswith(app + os.sep):diff --git a/apps/cua-spaces-macos/scripts/dmg-settings.py b/apps/cua-spaces-macos/scripts/dmg-settings.pyindex 8610b321b6..caa4ceafa6 100644--- a/apps/cua-spaces-macos/scripts/dmg-settings.py+++ b/apps/cua-spaces-macos/scripts/dmg-settings.py@@ -8,8 +8,9 @@ alias = defines["alias"] # noqa: F821art = defines["art"] # noqa: F821app_name = os.path.basename(app)-format = "UDZO"-compression_level = 9+# LZMA (macOS 10.15+; the app needs 26): about 30% smaller than zlib+# (UDZO) for this app, whose binaries are mostly code.+format = "ULMO"filesystem = "HFS+"files = [app, alias]icon = os.path.join(app, "Contents", "Resources", "AppIcon.icns")diff --git a/apps/cua-spaces-macos/scripts/fetch-spacesd.sh b/apps/cua-spaces-macos/scripts/fetch-spacesd.shnew file mode 100755index 0000000000..459e267cbf--- /dev/null+++ b/apps/cua-spaces-macos/scripts/fetch-spacesd.sh@@ -0,0 +1,44 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Prints the path of the cua-spacesd the app bundles in Contents/MacOS (its host service):+# $CUA_SPACESD_BIN when set, else the pinned release (libs/cua-spacesd/VERSION,+# the version cua-host downloads for CLI-only installs), downloaded once into+# .build/spacesd/<version>/ and verified against its published sha256.+#+# scripts/fetch-spacesd.sh [arm64 x86_64]+#+# The release's macOS archives carry one universal binary, Developer ID+# signed by the Cua team; each requested architecture must be in it.+set -euo pipefail+here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+repo="$(cd "$here/../.." && pwd)"+archs="${*:-$(uname -m)}"+if [ -n "${CUA_SPACESD_BIN:-}" ]; then+ [ -x "$CUA_SPACESD_BIN" ] || { echo "CUA_SPACESD_BIN=$CUA_SPACESD_BIN is not an executable" >&2; exit 1; }+ bin="$CUA_SPACESD_BIN"+else+ version="$(tr -d '[:space:]' < "$repo/libs/cua-spacesd/VERSION")"+ release_repo="${CUA_RELEASE_REPOSITORY:-trycua/cua}"+ dir="$here/.build/spacesd/$version"+ bin="$dir/cua-spacesd"+ if [ ! -x "$bin" ]; then+ mkdir -p "$dir"+ base="https://github.com/$release_repo/releases/download/cua-spacesd-v$version"+ asset="cua-spacesd-macos-aarch64.tar.gz"+ tmp="$(mktemp -d)"+ trap 'rm -rf "$tmp"' EXIT+ curl -fsSL --retry 3 -o "$tmp/$asset" "$base/$asset"+ curl -fsSL --retry 3 -o "$tmp/$asset.sha256" "$base/$asset.sha256"+ want="$(awk '{print $1}' "$tmp/$asset.sha256")"+ got="$(shasum -a 256 "$tmp/$asset" | awk '{print $1}')"+ [ -n "$want" ] && [ "$want" = "$got" ] || { echo "cua-spacesd $version: checksum mismatch ($got, want $want)" >&2; exit 1; }+ tar -xzf "$tmp/$asset" -C "$tmp" cua-spacesd+ install -m 0755 "$tmp/cua-spacesd" "$bin"+ fi+fi+for arch in $archs; do+ lipo "$bin" -verify_arch "$arch" || { echo "$bin has no $arch slice ($(lipo -archs "$bin"))" >&2; exit 1; }+done+echo "$bin"diff --git a/apps/cua-spaces-macos/scripts/test-helper-upgrade.sh b/apps/cua-spaces-macos/scripts/test-helper-upgrade.shnew file mode 100755index 0000000000..11dd3c9a18--- /dev/null+++ b/apps/cua-spaces-macos/scripts/test-helper-upgrade.sh@@ -0,0 +1,158 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Upgrade test for the host service's move into the app ("Cua Spaces+# Helper"). Run it on a disposable Mac (a VM), never on a Mac you use: it+# replaces /Applications/Cua Spaces.app and moves this Mac's host service.+#+# Before: an older Cua Spaces (0.9.4 or earlier) in /Applications, signed+# in, and this Mac set up for access with its `cua host setup` (the+# LaunchAgent com.trycua.spacesd.host running ~/.cua/host/bin/cua-spacesd),+# online at the relay.+#+# scripts/test-helper-upgrade.sh upgrade NEW.app install NEW.app over the old app, `cua host migrate`+# scripts/test-helper-upgrade.sh update NEWER.app replace the app again (an update): the helper and+# its permissions stay+# scripts/test-helper-upgrade.sh downgrade OLD.app put the old app back: nothing left broken, and+# `cua host setup` brings the old service back with+# the same machine id+# scripts/test-helper-upgrade.sh remember record the machine before anything (the+# first upgrade does it too)+# scripts/test-helper-upgrade.sh check the checks alone (after the app moved it)+#+# Each check prints PASS or FAIL; the exit status is the number of FAILs.+# The state before the first step is kept in ~/.cua-helper-test.+set -uo pipefail+app="/Applications/Cua Spaces.app"+cua="$app/Contents/MacOS/cua"+state="$HOME/.cua-helper-test"+label_old=com.trycua.spacesd.host+label_new=com.trycua.spaces.helper+gui="gui/$(id -u)"+fails=0+export CUA_TELEMETRY=0++pass() { printf 'PASS %s\n' "$*"; }+fail() { printf 'FAIL %s\n' "$*"; fails=$((fails + 1)); }+check() { if eval "$2"; then pass "$1"; else fail "$1"; fi; }++status_json() { "$cua" host status --json 2>/dev/null; }+field() { python3 -c 'import json,sys; d=json.load(sys.stdin); v=d+for k in sys.argv[1].split("."): v=v.get(k) if isinstance(v,dict) else None+print("" if v is None else (str(v).lower() if isinstance(v,bool) else v))' "$1"; }++remember() {+ mkdir -p "$state"+ [ -f "$state/machine-id" ] && return 0+ status_json | field machineId > "$state/machine-id"+ shasum -a 256 "$HOME/.cua/host/machine-token" | awk '{print $1}' > "$state/token"+ "$cua" spaces ls 2>/dev/null | awk '{print $1}' | sort > "$state/spaces"+ echo "remembered machine $(cat "$state/machine-id")"+}++replace_app() {+ local src="$1"+ osascript -e 'quit app "Cua Spaces"' >/dev/null 2>&1 || true+ pkill -x CuaSpacesMac 2>/dev/null || true+ sleep 2+ rm -rf "$app"+ ditto "$src" "$app"+}++wait_online() {+ for _ in $(seq 1 30); do+ [ "$(status_json | field online)" = true ] && return 0+ sleep 2+ done+ return 1+}++same_machine_checks() {+ local s+ s="$(status_json)"+ check "same machine id ($(cat "$state/machine-id"))" \+ '[ "$(printf %s "$s" | field machineId)" = "$(cat "$state/machine-id")" ]'+ check "same machine token (not registered again)" \+ '[ "$(shasum -a 256 "$HOME/.cua/host/machine-token" | awk "{print \$1}")" = "$(cat "$state/token")" ]'+ check "relay reachable: online" 'wait_online'+ check "Spaces still listed" \+ '[ -z "$(comm -23 "$state/spaces" <("$cua" spaces ls 2>/dev/null | awk "{print \$1}" | sort))" ]'+ check "this Mac answers through the relay" \+ '"$cua" sandbox exec "relay:$(cat "$state/machine-id")" -- echo ok 2>/dev/null | grep -qx ok'+}++helper_checks() {+ local s+ s="$(status_json)"+ check "service kind is app-helper" '[ "$(printf %s "$s" | field service.kind)" = app-helper ]'+ check "the app's login item is running" 'launchctl print "$gui/$label_new" 2>/dev/null | grep -q "state = running"'+ check "the app's own executable runs it" 'pgrep -f "CuaSpacesMac --service-helper run" >/dev/null'+ check "cua-spacesd runs inside the app" \+ 'pgrep -fl "Cua Spaces.app/Contents/MacOS/cua-spacesd" >/dev/null'+ check "the old agent is gone from launchd" '! launchctl print "$gui/$label_old" >/dev/null 2>&1'+ check "the old plist is gone" '[ ! -e "$HOME/Library/LaunchAgents/$label_old.plist" ]'+ check "the old binary is gone" '[ ! -e "$HOME/.cua/host/bin/cua-spacesd" ]'+ check "no second cua-spacesd" '[ "$(pgrep -x cua-spacesd | wc -l | tr -d " ")" = 1 ]'+ check "the app is signed as com.trycua.spaces.macos with a stable requirement" \+ 'codesign -d -r- "$app" 2>&1 | grep -q "identifier \"com.trycua.spaces.macos\"" &&+ ! codesign -d -r- "$app" 2>&1 | grep -q cdhash'+ check "no separate helper bundle" '[ ! -e "$app/Contents/Library/LoginItems" ]'+}++permissions() { status_json | python3 -c 'import json,sys; print(",".join(p["id"] for p in json.load(sys.stdin).get("permissions",[])))'; }++case "${1:-}" in+upgrade)+ new="${2:?usage: upgrade NEW.app}"+ remember+ replace_app "$new"+ open -a "$app"+ sleep 15+ "$cua" host migrate; echo "migrate exit $?"+ same_machine_checks+ helper_checks+ echo "permissions still to allow for Cua Spaces: $(permissions)"+ ;;+update)+ newer="${2:?usage: update NEWER.app}"+ before="$(permissions)"+ replace_app "$newer"+ open -a "$app"+ sleep 15+ launchctl kickstart -k "$gui/$label_new" >/dev/null 2>&1+ sleep 5+ same_machine_checks+ helper_checks+ check "permissions unchanged by the update (before: '${before}')" '[ "$(permissions)" = "$before" ]'+ ;;+downgrade)+ old="${2:?usage: downgrade OLD.app}"+ replace_app "$old"+ # The service notices its cua-spacesd is gone within about 10 s and stops.+ check "no service left running" \+ 'for _ in $(seq 1 15); do pgrep -f "service-helper run" >/dev/null || break; sleep 2; done; ! pgrep -f "service-helper run" >/dev/null'+ check "the old app still reads this machine's setup" '[ "$(status_json | field configured)" = true ]'+ "$cua" host setup --name "$(status_json | field name)" >/dev/null 2>&1; echo "setup exit $?"+ open -a "$app"+ sleep 15+ check "the old agent runs again" 'launchctl print "$gui/$label_old" 2>/dev/null | grep -q "state = running"'+ check "same machine id after setup" '[ "$(status_json | field machineId)" = "$(cat "$state/machine-id")" ]'+ check "relay reachable: online" 'wait_online'+ check "this Mac answers through the relay" \+ '"$cua" sandbox exec "relay:$(cat "$state/machine-id")" -- echo ok 2>/dev/null | grep -qx ok'+ ;;+remember)+ remember+ ;;+check)+ same_machine_checks+ helper_checks+ ;;+*)+ sed -n '5,25p' "$0"+ exit 2+ ;;+esac+echo "$fails failed"+exit "$fails"diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdxindex 09ec280d47..b39ae8d5d9 100644--- a/docs/content/docs/cua-cli/reference/cli/index.mdx+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx@@ -25,7 +25,7 @@ Your Spaces and machines, unattended access on this machine, devices, teams, you| Command | Description | Subcommands || --- | --- | --- || <span id="cua-spaces"></span><span id="cua-spaces-ls"></span><span id="cua-spaces-add"></span><span id="cua-spaces-create"></span><span id="cua-spaces-cancel"></span><span id="cua-spaces-gpus"></span><span id="cua-spaces-delete"></span><span id="cua-spaces-stop"></span><span id="cua-spaces-start"></span><span id="cua-spaces-rm"></span><span id="cua-spaces-share"></span><span id="cua-spaces-unshare"></span><span id="cua-spaces-shares"></span><span id="cua-spaces-relay-register"></span><span id="cua-spaces-relay-unregister"></span>[`cua spaces`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces) | Spaces: registered ones and your computers on the relay. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-ls), [`add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-add), [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-create), [`cancel`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-cancel), [`gpus`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-gpus), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-delete), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-stop), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-start), [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rm), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-unshare), [`shares`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-shares), [`relay-register`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-register), [`relay-unregister`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-unregister) |-| <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/spaces-and-computers#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/spaces-and-computers#cua-host-setup), [`pair`](/cua-cli/reference/cli/spaces-and-computers#cua-host-pair), [`config`](/cua-cli/reference/cli/spaces-and-computers#cua-host-config), [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-status), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-host-stop), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-host-start), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-host-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-host-unshare), [`remove`](/cua-cli/reference/cli/spaces-and-computers#cua-host-remove) |+| <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-migrate"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/spaces-and-computers#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/spaces-and-computers#cua-host-setup), [`pair`](/cua-cli/reference/cli/spaces-and-computers#cua-host-pair), [`config`](/cua-cli/reference/cli/spaces-and-computers#cua-host-config), [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-status), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-host-stop), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-host-start), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-host-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-host-unshare), [`migrate`](/cua-cli/reference/cli/spaces-and-computers#cua-host-migrate), [`remove`](/cua-cli/reference/cli/spaces-and-computers#cua-host-remove) || <span id="cua-devices"></span><span id="cua-devices-status"></span><span id="cua-devices-enroll"></span><span id="cua-devices-approve"></span><span id="cua-devices-ls"></span><span id="cua-devices-rename"></span><span id="cua-devices-revoke"></span><span id="cua-devices-audit"></span>[`cua devices`](/cua-cli/reference/cli/spaces-and-computers#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. | [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-status), [`enroll`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-enroll), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-approve), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-ls), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-rename), [`revoke`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-revoke), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-audit) || <span id="cua-team"></span><span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/spaces-and-computers#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. | [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-team-create), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-team-ls), [`show`](/cua-cli/reference/cli/spaces-and-computers#cua-team-show), [`invite`](/cua-cli/reference/cli/spaces-and-computers#cua-team-invite), [`join`](/cua-cli/reference/cli/spaces-and-computers#cua-team-join), [`leave`](/cua-cli/reference/cli/spaces-and-computers#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/spaces-and-computers#cua-team-set-role), [`devices`](/cua-cli/reference/cli/spaces-and-computers#cua-team-devices), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-team-approve), [`deny`](/cua-cli/reference/cli/spaces-and-computers#cua-team-deny), [`request`](/cua-cli/reference/cli/spaces-and-computers#cua-team-request), [`add-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-team-audit), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-team-delete) || <span id="cua-usage"></span>[`cua usage`](/cua-cli/reference/cli/spaces-and-computers#cua-usage) | Your remote use this month: live sessions, remote hours, and your plan. | |diff --git a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdxindex ff1cf7c2e5..86887b30fc 100644--- a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx+++ b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx@@ -36,6 +36,7 @@ description: "Your Spaces and machines, unattended access on this machine, devic| [`cua host start`](#cua-host-start) | Start sharing again after `stop`. || [`cua host share`](#cua-host-share) | Share a relay computer (this one, or `--machine`) with people in your team (id or verified email). || [`cua host unshare`](#cua-host-unshare) | Stop sharing a relay computer with accounts; their open connections are cut. |+| [`cua host migrate`](#cua-host-migrate) | macOS: move the host service into the Cua Spaces app, as its "Cua Spaces Helper" login item, from the LaunchAgent that older versions installed. || [`cua host remove`](#cua-host-remove) | Unregister from the relay, uninstall the service and delete the host configuration (asks first). || [`cua devices`](#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. || [`cua devices status`](#cua-devices-status) | This device: enrolled, waiting for approval, or not enrolled. |@@ -425,7 +426,7 @@ cua host setup [OPTIONS]| <span id="cua-host-setup--name"></span>`--name` | string | | Display name (default: the host name). || <span id="cua-host-setup--allow"></span>`--allow` | string | | Also allow this account (id or email). Repeatable. || <span id="cua-host-setup--driver-bin"></span>`--driver-bin` | path | | cua-spacesd binary (default $CUA_SPACESD_BIN, a bundled one, or the release download). |-| <span id="cua-host-setup--runner"></span>`--runner` | string | `auto` | auto \| systemd \| launchd \| windows-task \| process. |+| <span id="cua-host-setup--runner"></span>`--runner` | string | `auto` | auto \| systemd \| launchd \| app-helper \| windows-task \| process. On a Mac with the Cua Spaces app, auto is app-helper: the service runs as the app's own login item ("Cua Spaces"). || <span id="cua-host-setup--profile"></span>`--profile` | `desktop` \| `spare` | `desktop` | What this computer is for: `desktop` (share this desktop; the default) or `spare` (do not share the desktop; provide Spaces). || <span id="cua-host-setup--max-spaces"></span>`--max-spaces` | integer | | Provided Spaces at once (default 4; 0: no limit). || <span id="cua-host-setup--remote"></span>`--remote` | boolean | `false` | When sign-in is needed, use a device code to approve it in a browser on another computer. The account session is not saved. |@@ -590,6 +591,27 @@ cua host unshare [OPTIONS] <WHO>...cua host unshare [email protected]```+### `cua host migrate`++macOS: move the host service into the Cua Spaces app, as its "Cua Spaces Helper" login item, from the LaunchAgent that older versions installed. This machine keeps its id, registration and Spaces; if the helper does not take over, the old service is put back. macOS then asks once for Screen Recording and Accessibility for Cua Spaces Helper.++```text output+cua host migrate [OPTIONS]+```++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| <span id="cua-host-migrate--force"></span>`--force` | boolean | `false` | Try again even if a move failed before with this version. |++**Examples**++```bash test="cli-shape" id="ref-cua-host-migrate"+cua host migrate++# Try again after a move that was rolled back+cua host migrate --force+```+### `cua host remove`Unregister from the relay, uninstall the service and delete the host configuration (asks first).diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdxindex 209e182b76..a9c44abb33 100644--- a/docs/content/docs/cua-sdk/reference/index.mdx+++ b/docs/content/docs/cua-sdk/reference/index.mdx@@ -81,4 +81,4 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th| --- | --- || [Protocol](/cua-sdk/reference/protocol) | The gRPC contracts of cua-spacesd (`cua.env.v1`) and the cua daemon (`cua.daemon.v1`). |-285 items, 357 methods. The [Types](/cua-sdk/reference/types) page lists them.+286 items, 358 methods. The [Types](/cua-sdk/reference/types) page lists them.diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdxindex 8f359174b3..03a2794133 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx@@ -18,7 +18,7 @@ The cua SDK: the only `#[uniffi::export]` crate of `libs/cua`.These are the objects, records, enums and functions the language bindings export, documented once in the [Cua SDK reference](/cua-sdk/reference), whose Rust tabs show each signature. Objects are `Arc<T>` handles whose methods are `async fn` returning `Result<_, CuaError>`, records are structs with public fields, and names are snake_case.-[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agents#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agents#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agents#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agents#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agents#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agents#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BundledSkill`](/cua-sdk/reference/agents#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd#replaymode-enum), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxRefParts`](/cua-sdk/reference/sandbox#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpacePowerReport`](/cua-sdk/reference/spaces#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/space#spacerelayregistration-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/space#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/space#spaceshares-record), [`SpacesHost`](/cua-sdk/reference/spaces/space#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/space#spaceshostlimit-record), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record).+[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agents#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agents#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agents#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agents#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agents#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agents#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BundledSkill`](/cua-sdk/reference/agents#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd#replaymode-enum), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxRefParts`](/cua-sdk/reference/sandbox#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpacePowerReport`](/cua-sdk/reference/spaces#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/space#spacerelayregistration-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/space#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/space#spaceshares-record), [`SpacesHost`](/cua-sdk/reference/spaces/space#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/space#spaceshostlimit-record), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record).## Typesdiff --git a/docs/content/docs/cua-sdk/reference/spaces/host.mdx b/docs/content/docs/cua-sdk/reference/spaces/host.mdxindex 5eb2ff974d..b749423f60 100644--- a/docs/content/docs/cua-sdk/reference/spaces/host.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/host.mdx@@ -22,6 +22,7 @@ This machine as an unattended-access host.| --- | --- || [`new`](#hostnew) | Host state under `cua_home` (default `$CUA_HOME` or `~/.cua`). || [`configure`](#hostconfigure) | Changes what this machine shares: its own desktop, and whether it creates Spaces for your other devices (and their limits). |+| [`migrate_service`](#hostmigrate_service) | macOS: moves the host service from the old LaunchAgent to the Cua Spaces app (its own login item, "Cua Spaces"), keeping this machine's registration, id and Spaces; puts the old one back if the helper does not take over (the outcome says so). || [`pause_signed_out`](#hostpause_signed_out) | Pause relay sharing while nobody is signed in to the owner's account: the host leaves the relay and stays off it (also across a restart) with its setup kept. || [`remove`](#hostremove) | Unregister, uninstall the service and delete the host state. || [`resume_signed_in`](#hostresume_signed_in) | Resume relay sharing paused by `Host.pause_signed_out` once `account` (the signed-in account's id or email) is signed in; refused when it is not the machine's owner. |@@ -129,6 +130,61 @@ pub async fn configure(&self, change: HostSettingsChange) -> Result<HostStatus,**Returns** [`HostStatus`](#hoststatus-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Host.migrate_service`++macOS: moves the host service from the old LaunchAgent to the Cua+Spaces app (its own login item, "Cua Spaces"), keeping this machine's+registration, id and Spaces; puts the old one back if the helper+does not take over (the outcome says so). `app_version`: a failed+move is not tried again by itself with the same version; `force`+tries anyway.++<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>+<Tab value="Python">++```python+async def migrate_service(self, force: bool, app_version: str) -> HostServiceMigration+```++</Tab>+<Tab value="TypeScript">++```ts+migrateService(force: boolean, appVersion: string, asyncOpts_?: { signal: AbortSignal }): Promise<HostServiceMigration>+```++</Tab>+<Tab value="Swift">++```swift+func migrateService(force: Bool, appVersion: String) async throws -> HostServiceMigration+```++</Tab>+<Tab value="Kotlin">++```kotlin+@Throws(CuaException::class)+suspend fun migrateService(force: Boolean, appVersion: String): HostServiceMigration+```++</Tab>+<Tab value="Rust">++```rust+pub async fn migrate_service(&self, force: bool, app_version: String) -> Result<HostServiceMigration, CuaError>+```++</Tab>+</Tabs>++| Parameter | Type | Default |+| --- | --- | --- |+| `force` | `bool` | required |+| `app_version` | `String` | required |++**Returns** [`HostServiceMigration`](#hostservicemigration-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Host.pause_signed_out`Pause relay sharing while nobody is signed in to the owner's@@ -806,6 +862,18 @@ A Space this machine provides to one of your devices.| `created_by` / `createdBy` | `String` | | Who created it. || `created_at_ms` / `createdAtMs` | `i64` | | Epoch ms. |+## `HostServiceMigration` record++What `Host.migrate_service` did.++Returned by [`Host.migrate_service`](#hostmigrate_service).++| Field | Type | Default | Description |+| --- | --- | --- | --- |+| `outcome` | `String` | | `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or `not-needed`. |+| `detail` | `String` | | In words. |+| `permissions_needed` / `permissionsNeeded` | `bool` | | macOS will ask for Screen Recording and Accessibility for Cua Spaces Helper. |+## `HostSettingsChange` recordA change to this machine's Spaces settings (`None` keeps a value).@@ -883,6 +951,8 @@ Returned by [`Host.configure`](#hostconfigure), [`Host.pause_signed_out`](#hostp| `paused_signed_out` / `pausedSignedOut` | `bool` | `false` | Relay sharing is paused until the owner signs in again (`Host.pause_signed_out`). || `owner` | `Option<String>` | `None` | The account this machine is registered to (relay mode): its id. || `owner_email` / `ownerEmail` | `Option<String>` | `None` | The owner's email, when the relay gave one. |+| `helper_available` / `helperAvailable` | `bool` | `false` | macOS: a Cua Spaces app that can run the host service is installed, so the host service can run as it. |+| `legacy_service` / `legacyService` | `bool` | `false` | macOS: the old hand-written LaunchAgent is still there. |## `PairingCode` recorddiff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdxindex 24190bd414..e132c48479 100644--- a/docs/content/docs/cua-sdk/reference/types.mdx+++ b/docs/content/docs/cua-sdk/reference/types.mdx@@ -48,7 +48,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f## All items-275 items. Methods are listed on their object.+276 items. Methods are listed on their object.The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/reference/spaces/resources#all-items).@@ -159,6 +159,7 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref| [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record) | record | One access to this machine. || [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record) | record | A macOS privacy pane the user must grant. || [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record) | record | A Space this machine provides to one of your devices. |+| [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record) | record | What `Host.migrate_service` did. || [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record) | record | A change to this machine's Spaces settings (`None` keeps a value). || [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record) | record | `cua host setup` options. || [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record) | record | One line of this machine's Spaces audit (remote creates, deletes, refusals and settings changes). |diff --git a/libs/cua/crates/cua-cli/src/doctor/host.rs b/libs/cua/crates/cua-cli/src/doctor/host.rsindex 5d39e44ada..184b14b05d 100644--- a/libs/cua/crates/cua-cli/src/doctor/host.rs+++ b/libs/cua/crates/cua-cli/src/doctor/host.rs@@ -87,8 +87,62 @@ pub fn defaults_checks() -> Vec<Check> {checks}+/// `host.service`: how this machine's host service (`cua host setup`)+/// runs, informational. On a Mac it says whether it is the Cua Spaces+/// app's own login item or the old LaunchAgent, and warns when both+/// are there or the app is gone. `None` when the machine is not+/// set up for access.+pub fn host_service_check(s: &cua_host::HostStatus) -> Option<Check> {+ if !s.configured {+ return None;+ }+ let state = if s.service.running {+ "running"+ } else if s.service.installed {+ "installed, not running"+ } else {+ "not installed"+ };+ let check = match s.service.kind.as_str() {+ "app-helper" if !s.helper_available => Check::new(+ "host.service",+ Status::Warn,+ "the host service is set up to run inside the Cua Spaces app, but the app is not installed",+ )+ .fix("install Cua Spaces again, or `cua host setup --runner launchd`"),+ "app-helper" if s.legacy_service => Check::new(+ "host.service",+ Status::Warn,+ format!("the Cua Spaces app's login item ({state}), and the old LaunchAgent is still there"),+ )+ .fix("`cua host migrate` removes the old LaunchAgent"),+ "app-helper" => Check::new(+ "host.service",+ Status::Pass,+ format!("the Cua Spaces app's login item ({state})"),+ ),+ "launchd" if s.helper_available => Check::new(+ "host.service",+ Status::Pass,+ format!("LaunchAgent com.trycua.spacesd.host ({state}); the Cua Spaces app can run it instead"),+ )+ .fix("`cua host migrate` (macOS then asks once for Screen Recording and Accessibility)"),+ kind => Check::new("host.service", Status::Pass, format!("{kind} ({state})")),+ };+ Some(with_severity(check, false))+}+pub async fn host_checks(cua: &Arc<Cua>, runtime_type: Option<&str>, arch: &str) -> Vec<Check> {let mut checks = defaults_checks();+ if let Ok(Ok(status)) = tokio::time::timeout(+ Duration::from_secs(15),+ cua_host::Host::new(crate::util::cua_home()).status(),+ )+ .await+ && let Some(check) = host_service_check(&status)+ {+ checks.push(check);+ }let needed = runtime_type.and_then(backend_for);let report = match tokio::time::timeout(Duration::from_secs(60), cua.local().doctor()).await {Ok(Ok(report)) => report,@@ -497,6 +551,48 @@ pub fn cross_runtime(runtime_type: &str, guest: &Report) -> Vec<Check> {)]}+#[cfg(test)]+mod host_service_tests {+ use super::*;++ fn status(kind: &str, helper: bool, legacy: bool) -> cua_host::HostStatus {+ cua_host::HostStatus {+ configured: true,+ service: cua_host::ServiceState {+ installed: true,+ running: true,+ kind: kind.into(),+ detail: String::new(),+ },+ helper_available: helper,+ legacy_service: legacy,+ ..Default::default()+ }+ }++ #[test]+ fn the_host_service_check_names_the_helper_and_warns_about_two() {+ assert!(host_service_check(&cua_host::HostStatus::default()).is_none());+ let c = host_service_check(&status("app-helper", true, false)).unwrap();+ assert_eq!(c.status, Status::Pass);+ assert!(+ c.message.contains("Cua Spaces app's login item"),+ "{}",+ c.message+ );+ let c = host_service_check(&status("app-helper", true, true)).unwrap();+ assert_eq!(c.status, Status::Warn);+ assert!(c.remediation.contains("cua host migrate"));+ let c = host_service_check(&status("app-helper", false, false)).unwrap();+ assert_eq!(c.status, Status::Warn);+ let c = host_service_check(&status("launchd", true, true)).unwrap();+ assert_eq!(c.status, Status::Pass);+ assert!(c.remediation.contains("cua host migrate"));+ let c = host_service_check(&status("systemd", false, false)).unwrap();+ assert_eq!(c.message, "systemd (running)");+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 1f0e9acc6e..79727eb817 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -57,7 +57,9 @@ pub enum HostCmd {/// one, or the release download).#[arg(long)]driver_bin: Option<PathBuf>,- /// auto | systemd | launchd | windows-task | process.+ /// auto | systemd | launchd | app-helper | windows-task | process.+ /// On a Mac with the Cua Spaces app, auto is app-helper: the+ /// service runs as the app's own login item ("Cua Spaces").#[arg(long, default_value = "auto")]runner: String,/// What this computer is for: `desktop` (share this desktop; the@@ -195,6 +197,21 @@ pub enum HostCmd {#[arg(long, hide = true)]relay: Option<String>,},+ /// macOS: move the host service into the Cua Spaces app, as its "Cua+ /// Spaces Helper" login item, from the LaunchAgent that older versions+ /// installed. This machine keeps its id, registration and Spaces; if+ /// the helper does not take over, the old service is put back. macOS+ /// then asks once for Screen Recording and Accessibility for Cua Spaces+ /// Helper.+ #[command(after_help = "Examples:+ cua host migrate+ # Try again after a move that was rolled back+ cua host migrate --force")]+ Migrate {+ /// Try again even if a move failed before with this version.+ #[arg(long)]+ force: bool,+ },/// Unregister from the relay, uninstall the service and delete the host/// configuration (asks first).#[command(after_help = "Examples:@@ -1102,6 +1119,17 @@ fn render(s: &HostStatus, out: &mut dyn Write) {}),);+ if s.service.kind == "app-helper" && s.legacy_service {+ line(+ out,+ " the old LaunchAgent (com.trycua.spacesd.host) is still there: run `cua host migrate` to remove it",+ );+ } else if s.service.kind == "launchd" && s.helper_available {+ line(+ out,+ " tip: `cua host migrate` moves this service into the Cua Spaces app (its login item)",+ );+ }line(out,format!(@@ -1454,6 +1482,36 @@ pub async fn run_host(.await.map_err(crate::team_cmd::err)?;}+ HostCmd::Migrate { force } => {+ let m = host+ .migrate_service(force, env!("CARGO_PKG_VERSION"))+ .await+ .map_err(host_err)?;+ if json {+ writeln!(+ out,+ "{}",+ serde_json::to_string_pretty(&m)+ .map_err(|e| CuaError::Internal(e.to_string()))?+ )+ .map_err(|e| CuaError::Internal(e.to_string()))?;+ } else {+ line(out, format!("{}: {}", m.outcome, m.detail));+ if m.permissions_needed {+ line(+ out,+ "macOS will ask you once more for Screen Recording and Accessibility, \+ now for Cua Spaces: allow both in System Settings > Privacy & \+ Security (`cua host status` lists them). The old \"cua-spacesd\" \+ entries there can be removed with the minus button.",+ );+ }+ }+ return Ok(match m.outcome.as_str() {+ "rolled-back" | "kept" => 1,+ _ => 0,+ });+ }HostCmd::Status => {let s = host.status().await.map_err(host_err)?;// This Mac's processor, memory and disk, with or without setup.diff --git a/libs/cua/crates/cua-host/src/helper_migration.rs b/libs/cua/crates/cua-host/src/helper_migration.rsnew file mode 100644index 0000000000..ea3e3d2854--- /dev/null+++ b/libs/cua/crates/cua-host/src/helper_migration.rs@@ -0,0 +1,303 @@+//! Moving a macOS host from the hand-written LaunchAgent (`cua host setup`+//! without the app, Cua Spaces 0.9.4 and earlier: `~/.cua/host/bin/cua-spacesd`+//! run by `~/Library/LaunchAgents/com.trycua.spacesd.host.plist`) to the Cua+//! Spaces app's own login item (the app's executable, "Cua Spaces")+//! ([`crate::service::AppHelper`]).+//!+//! The move keeps everything that makes the machine this machine: the host+//! config, the driver policy, the machine id, the machine token, the env+//! token, the Spaces it provides and Cua Volume. It never registers again.+//! It stops the old agent, starts the helper, and checks that the helper+//! keeps running and (in relay mode, when the old one was online) comes+//! online at the relay with a new session; only then does it delete the old+//! plist and binary. Anything else puts the old agent back as it was+//! ([`Host::migrate_service`](crate::Host::migrate_service)).+//!+//! [`plan`] is the decision, a pure function of [`MigrationFacts`], so every+//! case is unit tested; [`LegacyService`] is the seam over the old agent.++use crate::Result;+use crate::service::{Launchd, LegacyAgent, RunnerKind};+use serde::{Deserialize, Serialize};+use std::path::PathBuf;++/// `<host dir>/helper-migration.json`: the last move, so a failed one is not+/// tried again by itself with the same app version.+pub const RECORD_FILE: &str = "helper-migration.json";+/// Where the old agent's plist waits while the helper is checked.+pub const LEGACY_PLIST_BACKUP: &str = "legacy-agent.plist";++/// The last move ([`RECORD_FILE`]).+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MigrationRecord {+ /// `in-progress`, `done` or `rolled-back`.+ pub state: String,+ /// The app version that tried it.+ pub app_version: String,+ /// When (epoch ms).+ pub at_ms: u64,+ /// Why it was rolled back.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}++/// What [`plan`] decides from.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct MigrationFacts {+ /// A Cua Spaces app with the helper is installed.+ pub helper_available: bool,+ /// This cua home has a host config.+ pub configured: bool,+ /// The config's runner (`None`: not configured, or a name this build+ /// does not know).+ pub runner: Option<RunnerKind>,+ /// Relay sharing is paused while signed out (the service is+ /// uninstalled on purpose).+ pub paused: bool,+ /// What is left of the old LaunchAgent.+ pub legacy: LegacyAgent,+ /// `<host dir>/bin/cua-spacesd` exists.+ pub legacy_binary: bool,+ /// The last move.+ pub last: Option<MigrationRecord>,+ /// This app's version.+ pub app_version: String,+ /// Try again even after a failed move with this version+ /// (`cua host migrate --force`).+ pub force: bool,+}++/// What to do.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MigrationPlan {+ /// Nothing (why, in words).+ Nothing(&'static str),+ /// The helper is in use; remove what is left of the old agent.+ RemoveLeftovers,+ /// The service is uninstalled while signed out: switch the runner and+ /// remove the old agent; resuming starts the helper.+ SwitchPaused,+ /// Stop the old agent, start the helper, check it, keep it or roll+ /// back.+ Move,+ /// A move failed with this app version: keep the old agent.+ KeepAfterFailure,+}++/// The decision. A host that is not set up in this cua home is left alone,+/// even with an old agent around: the agent may belong to another cua home+/// (the staging channel's), and only `cua host remove` there may remove it.+pub fn plan(f: &MigrationFacts) -> MigrationPlan {+ if !f.helper_available {+ return MigrationPlan::Nothing("no Cua Spaces app with its helper is installed");+ }+ if !f.configured {+ return MigrationPlan::Nothing("this machine is not set up for access");+ }+ match f.runner {+ Some(RunnerKind::AppHelper) => {+ if f.legacy.present() || f.legacy_binary {+ MigrationPlan::RemoveLeftovers+ } else {+ MigrationPlan::Nothing("the host service already runs inside the Cua Spaces app")+ }+ }+ Some(RunnerKind::Launchd) => {+ if f.paused {+ return MigrationPlan::SwitchPaused;+ }+ let failed_here = f+ .last+ .as_ref()+ .is_some_and(|r| r.state == "rolled-back" && r.app_version == f.app_version);+ if failed_here && !f.force {+ MigrationPlan::KeepAfterFailure+ } else {+ MigrationPlan::Move+ }+ }+ _ => MigrationPlan::Nothing("the host service does not run from a LaunchAgent"),+ }+}++/// What [`Host::migrate_service`](crate::Host::migrate_service) did.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ServiceMigration {+ /// `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or+ /// `not-needed`.+ pub outcome: String,+ /// In words.+ pub detail: String,+ /// macOS will ask for Screen Recording and Accessibility for Cua Spaces+ /// Helper (this machine shares its desktop and they are not granted+ /// yet).+ pub permissions_needed: bool,+}++impl ServiceMigration {+ pub(crate) fn new(outcome: &str, detail: impl Into<String>, permissions_needed: bool) -> Self {+ Self {+ outcome: outcome.into(),+ detail: detail.into(),+ permissions_needed,+ }+ }+}++/// The old LaunchAgent, as the move needs it.+pub trait LegacyService: Send + Sync {+ /// What is left of it.+ fn found(&self) -> LegacyAgent;+ /// Its plist (`~/Library/LaunchAgents/com.trycua.spacesd.host.plist`).+ fn plist(&self) -> PathBuf;+ /// Stops it and takes it out of launchd (the plist stays).+ fn bootout(&self) -> Result<()>;+ /// Loads and starts it from its plist again.+ fn bootstrap(&self) -> Result<()>;+}++impl LegacyService for Launchd {+ fn found(&self) -> LegacyAgent {+ self.legacy()+ }+ fn plist(&self) -> PathBuf {+ self.plist_file()+ }+ fn bootout(&self) -> Result<()> {+ Launchd::bootout(self)+ }+ fn bootstrap(&self) -> Result<()> {+ crate::ServiceManager::start(self)+ }+}++/// How long the helper has to prove itself.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct VerifyTiming {+ /// Give up after this.+ pub timeout: std::time::Duration,+ /// It must run this long without a restart.+ pub stable: std::time::Duration,+ /// When the old agent was not online either, running this long is+ /// enough (the relay cannot tell more).+ pub offline_grace: std::time::Duration,+ /// Between checks.+ pub poll: std::time::Duration,+}++impl Default for VerifyTiming {+ fn default() -> Self {+ Self {+ timeout: std::time::Duration::from_secs(45),+ stable: std::time::Duration::from_secs(5),+ offline_grace: std::time::Duration::from_secs(15),+ poll: std::time::Duration::from_millis(500),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facts() -> MigrationFacts {+ MigrationFacts {+ helper_available: true,+ configured: true,+ runner: Some(RunnerKind::Launchd),+ legacy: LegacyAgent {+ plist: true,+ loaded: true,+ running: true,+ },+ legacy_binary: true,+ app_version: "0.10.0".into(),+ ..Default::default()+ }+ }++ #[test]+ fn an_old_agent_with_the_app_installed_moves() {+ assert_eq!(plan(&facts()), MigrationPlan::Move);+ // Even when the old agent is gone or broken: the helper replaces it.+ let mut f = facts();+ f.legacy = LegacyAgent::default();+ f.legacy_binary = false;+ assert_eq!(plan(&f), MigrationPlan::Move);+ }++ #[test]+ fn without_the_app_nothing_changes() {+ let mut f = facts();+ f.helper_available = false;+ assert!(matches!(plan(&f), MigrationPlan::Nothing(_)));+ }++ #[test]+ fn a_machine_that_is_not_set_up_is_left_alone_even_with_an_old_agent() {+ let mut f = facts();+ f.configured = false;+ f.runner = None;+ assert!(matches!(plan(&f), MigrationPlan::Nothing(_)));+ }++ #[test]+ fn a_paused_host_switches_without_starting_anything() {+ let mut f = facts();+ f.paused = true;+ assert_eq!(plan(&f), MigrationPlan::SwitchPaused);+ }++ #[test]+ fn a_failed_move_is_not_retried_with_the_same_version_unless_forced() {+ let mut f = facts();+ f.last = Some(MigrationRecord {+ state: "rolled-back".into(),+ app_version: "0.10.0".into(),+ at_ms: 1,+ reason: Some("did not come online".into()),+ });+ assert_eq!(plan(&f), MigrationPlan::KeepAfterFailure);+ f.force = true;+ assert_eq!(plan(&f), MigrationPlan::Move);+ // The next app version tries again by itself.+ f.force = false;+ f.app_version = "0.10.1".into();+ assert_eq!(plan(&f), MigrationPlan::Move);+ // A move that was interrupted (in progress) is tried again.+ f.app_version = "0.10.0".into();+ f.last.as_mut().unwrap().state = "in-progress".into();+ assert_eq!(plan(&f), MigrationPlan::Move);+ }++ #[test]+ fn the_helper_in_use_removes_leftovers_or_does_nothing() {+ let mut f = facts();+ f.runner = Some(RunnerKind::AppHelper);+ assert_eq!(plan(&f), MigrationPlan::RemoveLeftovers);+ f.legacy = LegacyAgent::default();+ assert_eq!(+ plan(&f),+ MigrationPlan::RemoveLeftovers,+ "the old binary is left"+ );+ f.legacy_binary = false;+ assert!(matches!(plan(&f), MigrationPlan::Nothing(_)));+ }++ #[test]+ fn other_runners_are_not_moved() {+ for r in [+ None,+ Some(RunnerKind::Process),+ Some(RunnerKind::Systemd),+ Some(RunnerKind::WindowsTask),+ ] {+ let mut f = facts();+ f.runner = r;+ assert!(matches!(plan(&f), MigrationPlan::Nothing(_)), "{r:?}");+ }+ }+}diff --git a/libs/cua/crates/cua-host/src/helper_migration_tests.rs b/libs/cua/crates/cua-host/src/helper_migration_tests.rsnew file mode 100644index 0000000000..6e8ab70e0e--- /dev/null+++ b/libs/cua/crates/cua-host/src/helper_migration_tests.rs@@ -0,0 +1,483 @@+//! Moving a host from the old LaunchAgent to the Cua Spaces app's helper,+//! against the fake relay, a fake old agent and a fake helper (temp homes;+//! nothing touches launchd).++use crate::helper_migration::{LegacyService, MigrationRecord, RECORD_FILE};+use crate::preflight::SessionProbe;+use crate::service::{FakeServiceManager, LegacyAgent, ServiceManager, ServiceSpec, ServiceState};+use crate::testing::FakeRelay;+use crate::*;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};+use std::time::Duration;++/// The old LaunchAgent: a plist file in the temp home, loaded or not.+struct FakeLegacy {+ plist: PathBuf,+ loaded: Mutex<bool>,+ calls: Mutex<Vec<&'static str>>,+}++impl FakeLegacy {+ fn new(dir: &Path) -> Arc<Self> {+ let plist = dir.join("LaunchAgents/com.trycua.spacesd.host.plist");+ std::fs::create_dir_all(plist.parent().unwrap()).unwrap();+ std::fs::write(&plist, "<plist/>").unwrap();+ Arc::new(Self {+ plist,+ loaded: Mutex::new(true),+ calls: Mutex::default(),+ })+ }+ fn calls(&self) -> Vec<&'static str> {+ self.calls.lock().unwrap().clone()+ }+}++impl LegacyService for FakeLegacy {+ fn found(&self) -> LegacyAgent {+ let loaded = *self.loaded.lock().unwrap();+ LegacyAgent {+ plist: self.plist.is_file(),+ loaded,+ running: loaded,+ }+ }+ fn plist(&self) -> PathBuf {+ self.plist.clone()+ }+ fn bootout(&self) -> Result<()> {+ self.calls.lock().unwrap().push("bootout");+ *self.loaded.lock().unwrap() = false;+ Ok(())+ }+ fn bootstrap(&self) -> Result<()> {+ self.calls.lock().unwrap().push("bootstrap");+ assert!(self.plist.is_file(), "bootstrapped without its plist");+ *self.loaded.lock().unwrap() = true;+ Ok(())+ }+}++/// How the fake helper behaves once started.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Helper {+ /// Runs and joins the relay with a new session.+ Works,+ /// Runs but never reaches the relay.+ NeverOnline,+ /// Exits right away (launchd would keep restarting it).+ Crashes,+ /// macOS refuses to register it.+ Refused,+}++struct FakeHelper {+ mode: Helper,+ relay: FakeRelay,+ machine: Mutex<Option<String>>,+ running: Mutex<bool>,+ spec: Mutex<Option<ServiceSpec>>,+ calls: Mutex<Vec<&'static str>>,+}++impl FakeHelper {+ fn new(mode: Helper, relay: &FakeRelay) -> Arc<Self> {+ Arc::new(Self {+ mode,+ relay: relay.clone(),+ machine: Mutex::default(),+ running: Mutex::default(),+ spec: Mutex::default(),+ calls: Mutex::default(),+ })+ }+ fn calls(&self) -> Vec<&'static str> {+ self.calls.lock().unwrap().clone()+ }+}++impl ServiceManager for FakeHelper {+ fn kind(&self) -> RunnerKind {+ RunnerKind::AppHelper+ }+ fn install(&self, spec: &ServiceSpec) -> Result<()> {+ self.calls.lock().unwrap().push("install");+ if self.mode == Helper::Refused {+ return Err(Error::Service("requires-approval".into()));+ }+ *self.spec.lock().unwrap() = Some(spec.clone());+ Ok(())+ }+ fn start(&self) -> Result<()> {+ self.calls.lock().unwrap().push("start");+ *self.running.lock().unwrap() = self.mode != Helper::Crashes;+ if self.mode == Helper::Works+ && let Some(id) = self.machine.lock().unwrap().as_deref()+ {+ self.relay.set_session(id, true, Some(1_800_000_000));+ }+ Ok(())+ }+ fn stop(&self) -> Result<()> {+ self.calls.lock().unwrap().push("stop");+ *self.running.lock().unwrap() = false;+ Ok(())+ }+ fn uninstall(&self) -> Result<()> {+ self.calls.lock().unwrap().push("uninstall");+ *self.running.lock().unwrap() = false;+ *self.spec.lock().unwrap() = None;+ Ok(())+ }+ fn state(&self) -> ServiceState {+ ServiceState {+ installed: self.spec.lock().unwrap().is_some(),+ running: *self.running.lock().unwrap(),+ kind: "app-helper".into(),+ detail: String::new(),+ }+ }+}++/// A GUI session, and permissions not granted (to the new identity).+struct Probe;++impl SessionProbe for Probe {+ fn gui_session(&self, _uid: u32) -> bool {+ true+ }+ fn console_user(&self) -> Option<String> {+ Some("ada".into())+ }+ fn permission_status(&self, _driver_bin: &Path) -> Option<(bool, bool)> {+ Some((false, false))+ }+}++struct Old {+ _dir: tempfile::TempDir,+ root: PathBuf,+ home: PathBuf,+ app: PathBuf,+ relay: FakeRelay,+ machine: String,+ token: String,+ legacy: Arc<FakeLegacy>,+}++fn quick() -> VerifyTiming {+ VerifyTiming {+ timeout: Duration::from_millis(600),+ stable: Duration::from_millis(50),+ offline_grace: Duration::from_millis(150),+ poll: Duration::from_millis(20),+ }+}++/// A host set up as Cua Spaces 0.9.4 / `cua host setup` left it: relay+/// mode, the launchd runner, `bin/cua-spacesd`, the old agent loaded and+/// online at the relay.+async fn old_install() -> Old {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path().to_path_buf();+ let home = root.join(".cua");+ let driver = root.join("downloaded-cua-spacesd");+ std::fs::write(&driver, b"#!/bin/sh\n").unwrap();+ let mut opts = SetupOptions::relay(&relay.url);+ opts.name = Some("studio".into());+ opts.driver_bin = Some(driver);+ let status = Host::new(&home)+ .with_service_manager(Arc::new(FakeServiceManager::default()))+ .setup(opts, &StaticToken("acct".into()))+ .await+ .unwrap();+ let machine = status.machine_id.unwrap();+ // What a launchd setup writes.+ let host = Host::new(&home);+ let mut config = host.config().unwrap().unwrap();+ config.runner = "launchd".into();+ std::fs::write(+ host.paths().config(),+ serde_json::to_string_pretty(&config).unwrap(),+ )+ .unwrap();+ assert!(host.paths().driver_bin().is_file());+ relay.set_session(&machine, true, Some(1_700_000_000));+ let token = std::fs::read_to_string(host.paths().machine_token()).unwrap();+ let app = root.join("Applications/Cua Spaces.app");+ Old {+ legacy: FakeLegacy::new(&root),+ _dir: dir,+ root,+ home,+ app,+ relay,+ machine,+ token,+ }+}++impl Old {+ fn host(&self, helper: &Arc<FakeHelper>) -> Host {+ *helper.machine.lock().unwrap() = Some(self.machine.clone());+ Host::new(&self.home)+ .with_app_helper(self.app.clone(), helper.clone(), self.legacy.clone())+ .with_preflight_probe(Arc::new(Probe))+ .with_verify_timing(quick())+ }+ fn record(&self) -> MigrationRecord {+ serde_json::from_slice(&std::fs::read(self.home.join("host").join(RECORD_FILE)).unwrap())+ .unwrap()+ }+}++#[tokio::test]+async fn an_old_install_moves_to_the_helper_and_keeps_the_machine() {+ let old = old_install().await;+ let registrations = old.relay.register_calls();+ let helper = FakeHelper::new(Helper::Works, &old.relay);+ let host = old.host(&helper);++ let before = host.status().await.unwrap();+ assert!(before.helper_available && before.legacy_service);+ assert_eq!(before.service.kind, "launchd", "the old runner until moved");++ let m = host.migrate_service(false, "0.10.0").await.unwrap();+ assert_eq!(m.outcome, "migrated", "{m:?}");+ // macOS asks the new identity once (only macOS has the panes).+ assert_eq!(m.permissions_needed, cfg!(target_os = "macos"));++ // Same machine: id, token, policy; never registered again.+ let config = host.config().unwrap().unwrap();+ assert_eq!(config.runner, "app-helper");+ assert_eq!(+ config.driver_bin,+ old.app.join("Contents/MacOS/CuaSpacesMac")+ );+ assert_eq!(config.machine_id.as_deref(), Some(old.machine.as_str()));+ assert_eq!(+ std::fs::read_to_string(host.paths().machine_token()).unwrap(),+ old.token+ );+ assert_eq!(old.relay.register_calls(), registrations);+ assert_eq!(+ std::fs::read_to_string(&host.paths().machine_id)+ .unwrap()+ .trim(),+ old.machine+ );+ // The helper runs `join` with the same files.+ let spec = helper.spec.lock().unwrap().clone().unwrap();+ assert!(spec.args.join(" ").starts_with("join --relay"), "{spec:?}");+ assert!(+ spec.args+ .contains(&host.paths().machine_token().to_string_lossy().into_owned())+ );++ // The old agent is gone: out of launchd, plist and binary deleted.+ assert_eq!(old.legacy.calls(), ["bootout"]);+ assert!(!old.legacy.plist.exists());+ assert!(!host.paths().driver_bin().exists());+ assert!(!host.paths().dir.join("legacy-agent.plist").exists());+ assert_eq!(old.record().state, "done");++ let after = host.status().await.unwrap();+ assert_eq!(after.service.kind, "app-helper");+ assert!(after.service.running);+ assert_eq!(after.online, Some(true));+ assert!(!after.legacy_service);+ assert!(+ after+ .permissions+ .iter()+ .all(|p| p.instructions.contains("Cua Spaces")+ && !p.instructions.contains("cua-spacesd")),+ "{:?}",+ after.permissions+ );++ // Done: a second run changes nothing.+ let again = host.migrate_service(false, "0.10.0").await.unwrap();+ assert_eq!(again.outcome, "not-needed");+}++async fn rolled_back(mode: Helper) -> (Old, Arc<FakeHelper>, ServiceMigration) {+ let old = old_install().await;+ let helper = FakeHelper::new(mode, &old.relay);+ let host = old.host(&helper);+ let m = host.migrate_service(false, "0.10.0").await.unwrap();+ (old, helper, m)+}++async fn assert_old_install_intact(old: &Old) {+ let host = Host::new(&old.home);+ let config = host.config().unwrap().unwrap();+ assert_eq!(config.runner, "launchd");+ assert_eq!(config.driver_bin, host.paths().driver_bin());+ assert!(host.paths().driver_bin().is_file(), "the old binary stays");+ assert!(old.legacy.plist.is_file(), "the old plist is back");+ assert!(+ *old.legacy.loaded.lock().unwrap(),+ "the old agent runs again"+ );+ assert_eq!(old.legacy.calls(), ["bootout", "bootstrap"]);+ assert_eq!(+ std::fs::read_to_string(host.paths().machine_token()).unwrap(),+ old.token+ );+ assert_eq!(old.record().state, "rolled-back");+}++#[tokio::test]+async fn a_helper_that_never_comes_online_is_rolled_back() {+ let (old, helper, m) = rolled_back(Helper::NeverOnline).await;+ assert_eq!(m.outcome, "rolled-back", "{m:?}");+ assert!(m.detail.contains("not online at the relay"), "{}", m.detail);+ assert!(m.detail.contains("The old host service runs as before"));+ assert_eq!(helper.calls().last(), Some(&"uninstall"));+ assert_old_install_intact(&old).await;+}++#[tokio::test]+async fn a_helper_that_crashes_is_rolled_back() {+ let (old, helper, m) = rolled_back(Helper::Crashes).await;+ assert_eq!(m.outcome, "rolled-back", "{m:?}");+ assert!(m.detail.contains("did not start"), "{}", m.detail);+ assert_eq!(helper.calls().last(), Some(&"uninstall"));+ assert_old_install_intact(&old).await;+}++#[tokio::test]+async fn a_helper_macos_refuses_is_rolled_back_and_not_retried_by_itself() {+ let (old, helper, m) = rolled_back(Helper::Refused).await;+ assert_eq!(m.outcome, "rolled-back", "{m:?}");+ assert!(m.detail.contains("requires-approval"), "{}", m.detail);+ assert_eq!(helper.calls(), ["install", "uninstall"]);+ assert_old_install_intact(&old).await;++ // The same version keeps the old agent; --force (or the next version)+ // tries again.+ let helper = FakeHelper::new(Helper::Works, &old.relay);+ let host = old.host(&helper);+ let kept = host.migrate_service(false, "0.10.0").await.unwrap();+ assert_eq!(kept.outcome, "kept");+ assert!(helper.calls().is_empty());+ let moved = host.migrate_service(true, "0.10.0").await.unwrap();+ assert_eq!(moved.outcome, "migrated", "{moved:?}");+}++#[tokio::test]+async fn an_old_agent_that_was_offline_only_has_to_keep_running() {+ let old = old_install().await;+ old.relay.set_session(&old.machine, false, None);+ // Runs, but the relay never sees it (as the old one did not).+ let helper = FakeHelper::new(Helper::NeverOnline, &old.relay);+ let m = old+ .host(&helper)+ .migrate_service(false, "0.10.0")+ .await+ .unwrap();+ assert_eq!(m.outcome, "migrated", "{m:?}");+}++#[tokio::test]+async fn a_paused_host_switches_without_starting_the_helper() {+ let old = old_install().await;+ let host = Host::new(&old.home);+ let mut config = host.config().unwrap().unwrap();+ config.paused_signed_out = true;+ std::fs::write(+ host.paths().config(),+ serde_json::to_string_pretty(&config).unwrap(),+ )+ .unwrap();+ let helper = FakeHelper::new(Helper::Works, &old.relay);+ let host = old.host(&helper);+ let m = host.migrate_service(false, "0.10.0").await.unwrap();+ assert_eq!(m.outcome, "switched", "{m:?}");+ assert!(helper.calls().is_empty(), "nothing starts while paused");+ assert_eq!(host.config().unwrap().unwrap().runner, "app-helper");+ assert!(!old.legacy.plist.exists() && !host.paths().driver_bin().exists());++ // Signing in again resumes it as the helper.+ host.resume_signed_in("user-1").await.unwrap();+ assert_eq!(helper.calls(), ["install", "start"]);+}++#[tokio::test]+async fn leftovers_of_an_interrupted_move_are_removed() {+ let old = old_install().await;+ let helper = FakeHelper::new(Helper::Works, &old.relay);+ let host = old.host(&helper);+ let mut config = host.config().unwrap().unwrap();+ config.runner = "app-helper".into();+ std::fs::write(+ host.paths().config(),+ serde_json::to_string_pretty(&config).unwrap(),+ )+ .unwrap();+ assert!(host.status().await.unwrap().legacy_service);+ let m = host.migrate_service(false, "0.10.0").await.unwrap();+ assert_eq!(m.outcome, "cleaned-up", "{m:?}");+ assert!(!old.legacy.plist.exists() && !host.paths().driver_bin().exists());+ assert!(!host.status().await.unwrap().legacy_service);+}++#[tokio::test]+async fn setup_with_the_app_installed_uses_the_helper_and_retires_the_old_agent() {+ let old = old_install().await;+ let registrations = old.relay.register_calls();+ let helper = FakeHelper::new(Helper::Works, &old.relay);+ let host = old.host(&helper);+ // `cua host setup` again (the runner is auto): it must not write the+ // old LaunchAgent, and needs no download.+ let mut opts = SetupOptions::relay(&old.relay.url);+ opts.driver_bin = Some(old.root.join("no-such-binary"));+ let s = host.setup(opts, &StaticToken("acct".into())).await.unwrap();+ assert_eq!(s.service.kind, "app-helper");+ assert_eq!(s.machine_id.as_deref(), Some(old.machine.as_str()));+ assert_eq!(old.relay.register_calls(), registrations + 1);+ assert_eq!(helper.calls(), ["install", "start"]);+ assert_eq!(old.legacy.calls(), ["bootout"]);+ assert!(!old.legacy.plist.exists() && !host.paths().driver_bin().exists());+ assert_eq!(host.config().unwrap().unwrap().runner, "app-helper");+}++#[tokio::test]+async fn without_the_app_nothing_moves() {+ let old = old_install().await;+ // No helper found (`CUA_SPACES_APP=none` is not needed: off macOS, and+ // on a Mac without the app, nothing is found; here no helper is wired).+ let host = Host::new(&old.home)+ .with_service_manager(Arc::new(FakeServiceManager::default()))+ .with_preflight_probe(Arc::new(Probe));+ if crate::service::find_app_helper().is_none() {+ let m = host.migrate_service(false, "0.10.0").await.unwrap();+ assert_eq!(m.outcome, "not-needed");+ assert_eq!(host.config().unwrap().unwrap().runner, "launchd");+ assert!(host.paths().driver_bin().is_file());+ }+}++#[test]+fn removing_the_host_removes_the_helper_and_old_leftovers() {+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(async {+ let old = old_install().await;+ let helper = FakeHelper::new(Helper::Works, &old.relay);+ let host = old.host(&helper);+ assert_eq!(+ host.migrate_service(false, "0.10.0").await.unwrap().outcome,+ "migrated"+ );+ // A plist an old app wrote again (a downgrade, then an upgrade).+ std::fs::write(&old.legacy.plist, "<plist/>").unwrap();+ host.remove().await.unwrap();+ assert_eq!(helper.calls().last(), Some(&"uninstall"));+ assert!(!old.legacy.plist.exists());+ assert!(!host.paths().dir.exists());+ });+}diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex a59ee00774..7054da8257 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -1,6 +1,10 @@//! [`Host`]: setup / status / stop / start / remove.use crate::driver::{self, DriverSource};+use crate::helper_migration::{+ self, LegacyService, MigrationFacts, MigrationPlan, MigrationRecord, ServiceMigration,+ VerifyTiming,+};use crate::preflight::{self, SessionProbe};use crate::relay::{AccountTokens, ConnectedClient, MachinePatch, RegisterRequest, RelayClient};use crate::service::{self, RunnerKind, ServiceManager, ServiceSpec, ServiceState};@@ -327,7 +331,9 @@ pub fn permission_hints(os: &str, driver: &Path) -> Vec<PermissionHint> {if os != "macos" {return vec![];}- let d = driver.display();+ let d = service_name(driver);+ // The app's executable runs the service: both are "Cua Spaces".+ let screen = d.clone();vec![PermissionHint {id: "screen-recording".into(),@@ -336,7 +342,7 @@ pub fn permission_hints(os: &str, driver: &Path) -> Vec<PermissionHint> {"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture".into(),instructions: format!(- "System Settings → Privacy & Security → Screen & System Audio Recording: turn on cua-spacesd ({d}), so people you share with can see this screen."+ "System Settings → Privacy & Security → Screen & System Audio Recording: turn on {screen}, so people you share with can see this screen."),},PermissionHint {@@ -346,12 +352,22 @@ pub fn permission_hints(os: &str, driver: &Path) -> Vec<PermissionHint> {"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility".into(),instructions: format!(- "System Settings → Privacy & Security → Accessibility: turn on cua-spacesd ({d}), so they can control the mouse and keyboard."+ "System Settings → Privacy & Security → Accessibility: turn on {d}, so they can control the mouse and keyboard."),},]}+/// How System Settings lists the host service: "Cua Spaces" when the app+/// runs it, else "cua-spacesd (<path>)".+fn service_name(driver: &Path) -> String {+ if crate::service::is_app_helper_launcher(driver) {+ crate::service::APP_HELPER_NAME.to_string()+ } else {+ format!("cua-spacesd ({})", driver.display())+ }+}+/// What a Mac that provides Spaces must allow in Local Network privacy, or/// `None` (another OS, or no Spaces provided). Its macOS Spaces are Lume/// VMs on vmnet (192.168.64.x), and the cua daemon that creates them must@@ -367,16 +383,21 @@ pub fn local_network_hint(os: &str, provide_spaces: bool, driver: &Path) -> Optiif os != "macos" || !provide_spaces {return None;}- let d = driver.display();+ let d = service_name(driver);+ let short = if crate::service::is_app_helper_launcher(driver) {+ crate::service::APP_HELPER_NAME+ } else {+ "cua-spacesd"+ };Some(PermissionHint {id: "local-network".into(),title: "Local Network".into(),settings_url:"x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork".into(),instructions: format!(- "macOS Spaces on this Mac need Local Network access for cua-spacesd ({d}). When \- macOS asks \"Allow cua-spacesd to find devices on local networks?\" on this Mac's \- screen, click Allow; or turn on cua-spacesd in System Settings → Privacy & \+ "macOS Spaces on this Mac need Local Network access for {d}. When \+ macOS asks \"Allow {short} to find devices on local networks?\" on this Mac's \+ screen, click Allow; or turn on {short} in System Settings → Privacy & \Security → Local Network. If the cua daemon was started from Terminal or over SSH, \run `cua daemon stop` so the host service starts it at the next create (over SSH \nothing can grant it). Without it, macOS Space creates fail with \"No route to \@@ -505,6 +526,14 @@ pub struct HostStatus {/// The owner's email, when the relay gave one.#[serde(default, skip_serializing_if = "Option::is_none")]pub owner_email: Option<String>,+ /// macOS: a Cua Spaces app that can run the host service is+ /// installed, so the host service can run as it.+ #[serde(default)]+ pub helper_available: bool,+ /// macOS: the old hand-written LaunchAgent+ /// (`com.trycua.spacesd.host`) is still there (loaded or its plist).+ #[serde(default)]+ pub legacy_service: bool,}/// Files under `<home>/host`.@@ -787,6 +816,13 @@ pub struct Host {paths: HostPaths,manager: Option<Arc<dyn ServiceManager>>,preflight: Option<Arc<dyn SessionProbe>>,+ /// The Cua Spaces app with the helper (tests; else found).+ helper_app: Option<PathBuf>,+ /// The helper's runner (tests; else [`service::AppHelper`]).+ helper: Option<Arc<dyn ServiceManager>>,+ /// The old LaunchAgent (tests; else [`service::Launchd`]).+ legacy: Option<Arc<dyn LegacyService>>,+ verify: VerifyTiming,}impl std::fmt::Debug for Host {@@ -804,6 +840,57 @@ impl Host {home,manager: None,preflight: None,+ helper_app: None,+ helper: None,+ legacy: None,+ verify: VerifyTiming::default(),+ }+ }++ /// Uses `app` as the installed Cua Spaces app with its helper, run by+ /// `helper`, and `legacy` as the old LaunchAgent (tests).+ pub fn with_app_helper(+ mut self,+ app: PathBuf,+ helper: Arc<dyn ServiceManager>,+ legacy: Arc<dyn LegacyService>,+ ) -> Self {+ self.helper_app = Some(app);+ self.helper = Some(helper);+ self.legacy = Some(legacy);+ self+ }++ /// How long a moved host service has to prove itself (tests).+ pub fn with_verify_timing(mut self, timing: VerifyTiming) -> Self {+ self.verify = timing;+ self+ }++ /// The installed Cua Spaces app with its helper.+ fn helper_app(&self) -> Option<PathBuf> {+ if self.helper.is_some() {+ return self.helper_app.clone();+ }+ service::find_app_helper()+ }++ /// The helper's runner for `app`.+ fn helper_manager(&self, app: &Path) -> Arc<dyn ServiceManager> {+ match &self.helper {+ Some(h) => h.clone(),+ None => Arc::new(service::AppHelper::for_current_user(+ app.to_path_buf(),+ &user_home(&self.home),+ )),+ }+ }++ /// The old LaunchAgent.+ fn legacy(&self) -> Arc<dyn LegacyService> {+ match &self.legacy {+ Some(l) => l.clone(),+ None => Arc::new(service::Launchd::for_current_user(&user_home(&self.home))),}}@@ -843,6 +930,11 @@ impl Host {}fn manager(&self, runner: RunnerKind) -> Arc<dyn ServiceManager> {+ if runner == RunnerKind::AppHelper+ && let (Some(h), Some(_)) = (&self.helper, &self.helper_app)+ {+ return h.clone();+ }if let Some(m) = &self.manager {return m.clone();}@@ -961,9 +1053,27 @@ impl Host {tokens: &dyn AccountTokens,stage: &mut SetupStage,) -> Result<HostStatus> {- let runner = match &self.manager {- Some(m) => m.kind(),- None => opts.runner.resolve(),+ let runner = match (&self.manager, opts.runner) {+ (_, RunnerKind::Auto) if self.helper.is_some() => RunnerKind::AppHelper,+ (Some(m), _) => m.kind(),+ (None, r) => r.resolve(),+ };+ // The app's helper runs the cua-spacesd sealed in the app; its+ // launcher is the driver the config names (and the permission+ // checks ask).+ let helper_launcher = match runner {+ RunnerKind::AppHelper => Some(+ self.helper_app()+ .map(|app| service::app_helper_launcher(&app))+ .ok_or_else(|| {+ Error::Service(+ "the host service runs inside the Cua Spaces app, which is not \+ installed; install it, or run `cua host setup --runner launchd`"+ .into(),+ )+ })?,+ ),+ _ => None,};let name = opts.name@@ -982,8 +1092,13 @@ impl Host {// (set up over ssh with nobody logged in at the console). Checked// first so a doomed setup never registers with the relay,// downloads the driver, or leaves a config file behind.- if runner == RunnerKind::Launchd {- preflight::check(self.preflight_probe().as_ref(), &self.paths.driver_bin())?;+ if runner == RunnerKind::Launchd || runner == RunnerKind::AppHelper {+ preflight::check(+ self.preflight_probe().as_ref(),+ helper_launcher+ .as_deref()+ .unwrap_or(&self.paths.driver_bin()),+ )?;}// Hosting Spaces on the plaintext direct listener: never on a// public address without --allow-any-address.@@ -1001,14 +1116,16 @@ impl Host {let mut config = HostConfig {name: name.clone(),runner: runner.as_str().into(),- driver_bin: self.paths.driver_bin(),+ driver_bin: helper_launcher+ .clone()+ .unwrap_or_else(|| self.paths.driver_bin()),sharing: true,share_desktop: opts.share_desktop,provide_spaces: opts.provide_spaces,mesh: mesh_env(),..Default::default()};- if opts.download_first {+ if opts.download_first && helper_launcher.is_none() {*stage = SetupStage::Download;install_driver(opts.driver_bin.as_deref(), &config.driver_bin).await?;}@@ -1084,12 +1201,17 @@ impl Host {write_json(&self.paths.policy(), &policy)?;}}- if !opts.download_first {+ if !opts.download_first && helper_launcher.is_none() {*stage = SetupStage::Download;install_driver(opts.driver_bin.as_deref(), &config.driver_bin).await?;}*stage = SetupStage::Service;write_json(&self.paths.config(), &config)?;+ if runner == RunnerKind::AppHelper {+ // Never two services: the old LaunchAgent (and its binary)+ // goes before the helper starts.+ self.retire_legacy()?;+ }let manager = self.manager(runner);manager.install(&self.service_spec(&config))?;manager.start()?;@@ -1314,6 +1436,10 @@ impl Host {status.owner_email = p.owner_email.clone();}status.paused_signed_out = config.paused_signed_out;+ if cfg!(target_os = "macos") || self.helper.is_some() {+ status.helper_available = self.helper_app().is_some();+ status.legacy_service = self.legacy().found().present();+ }if let (Some(url), Some(id)) = (&config.relay_url, &config.machine_id) {match recall_relay_view(url, id, self.relay_machine(url, id).await) {Ok(m) => {@@ -1647,6 +1773,258 @@ impl Host {crate::provided::load_provided(&self.paths.dir)}+ // ------------------------------------------------- the app's helper++ /// Moves the host service from the old hand-written LaunchAgent to the+ /// Cua Spaces app (its login item, under the app's own name), keeping the machine+ /// (config, machine id and token, policy, provided Spaces); see+ /// [`helper_migration`]. `app_version` is the app's (a failed move is+ /// not tried again by itself with the same version); `force` tries+ /// again anyway. Never fails for a move that did not work: the old+ /// agent is put back and the outcome says so (`rolled-back`).+ pub async fn migrate_service(+ &self,+ force: bool,+ app_version: &str,+ ) -> Result<ServiceMigration> {+ let config = self.config()?;+ let app = self.helper_app();+ let legacy = self.legacy();+ let facts = MigrationFacts {+ helper_available: app.is_some(),+ configured: config.is_some(),+ runner: config+ .as_ref()+ .and_then(|c| RunnerKind::parse(&c.runner).ok()),+ paused: config.as_ref().is_some_and(|c| c.paused_signed_out),+ legacy: legacy.found(),+ legacy_binary: self.paths.driver_bin().is_file(),+ last: read_json(&self.paths.dir.join(helper_migration::RECORD_FILE))+ .ok()+ .flatten(),+ app_version: app_version.to_string(),+ force,+ };+ let plan = helper_migration::plan(&facts);+ let (Some(app), Some(mut config)) = (app, config) else {+ if let MigrationPlan::Nothing(why) = plan {+ return Ok(ServiceMigration::new("not-needed", why, false));+ }+ return Ok(ServiceMigration::new(+ "not-needed",+ "nothing to move",+ false,+ ));+ };+ let launcher = service::app_helper_launcher(&app);+ match plan {+ MigrationPlan::Nothing(why) => Ok(ServiceMigration::new("not-needed", why, false)),+ MigrationPlan::KeepAfterFailure => Ok(ServiceMigration::new(+ "kept",+ "moving into the Cua Spaces app failed before with this version; the old host \+ service keeps running (`cua host migrate --force` tries again)",+ false,+ )),+ MigrationPlan::RemoveLeftovers => {+ self.retire_legacy()?;+ Ok(ServiceMigration::new(+ "cleaned-up",+ "removed what was left of the old host service",+ false,+ ))+ }+ MigrationPlan::SwitchPaused => {+ config.runner = RunnerKind::AppHelper.as_str().into();+ config.driver_bin = launcher;+ write_json(&self.paths.config(), &config)?;+ self.retire_legacy()?;+ self.record_migration("done", app_version, None);+ Ok(ServiceMigration::new(+ "switched",+ "the host service will run inside the Cua Spaces app when sharing resumes",+ config.share_desktop,+ ))+ }+ MigrationPlan::Move => self.move_to_helper(config, &app, legacy, app_version).await,+ }+ }++ async fn move_to_helper(+ &self,+ config: HostConfig,+ app: &Path,+ legacy: Arc<dyn LegacyService>,+ app_version: &str,+ ) -> Result<ServiceMigration> {+ let helper = self.helper_manager(app);+ let mut next = config.clone();+ next.runner = RunnerKind::AppHelper.as_str().into();+ next.driver_bin = service::app_helper_launcher(app);+ // Direct mode with sharing stopped keeps the service stopped.+ let run = config.mode == "relay" || config.sharing;+ let before = self.relay_session(&config).await;+ let found = legacy.found();+ self.record_migration("in-progress", app_version, None);++ // 1. The old agent out (its plist kept aside, so a restart in the+ // middle never runs two services).+ if let Err(e) = legacy.bootout() {+ let why = format!("the old host service did not stop: {e}");+ self.record_migration("rolled-back", app_version, Some(&why));+ return Ok(ServiceMigration::new("rolled-back", why, false));+ }+ let plist = legacy.plist();+ let backup = self.paths.dir.join(helper_migration::LEGACY_PLIST_BACKUP);+ let moved = plist.is_file() && move_file(&plist, &backup).is_ok();++ // 2. The helper in, and proved.+ let mut result = helper.install(&self.service_spec(&next));+ if result.is_ok() {+ result = if run { helper.start() } else { helper.stop() };+ }+ if result.is_ok() && run {+ result = self.verify_helper(helper.as_ref(), &next, before).await;+ }++ match result {+ Ok(()) => {+ write_json(&self.paths.config(), &next)?;+ let _ = std::fs::remove_file(&backup);+ self.remove_legacy_binary();+ self.record_migration("done", app_version, None);+ let _ = crate::provided::audit(+ &self.paths.dir,+ "config",+ "local",+ &next.name,+ "host service moved into the Cua Spaces app",+ );+ let needs = next.share_desktop && !self.missing_permissions(&next).is_empty();+ Ok(ServiceMigration::new(+ "migrated",+ "the host service now runs inside the Cua Spaces app; this machine kept its id, \+ its registration and its Spaces",+ needs,+ ))+ }+ Err(e) => {+ let _ = helper.uninstall();+ if moved {+ let _ = move_file(&backup, &plist);+ }+ let mut why = format!("the Cua Spaces app's host service did not take over: {e}");+ if found.loaded+ && let Err(e) = legacy.bootstrap()+ {+ why.push_str(&format!(+ "; restarting the old host service failed too: {e}"+ ));+ }+ self.record_migration("rolled-back", app_version, Some(&why));+ Ok(ServiceMigration::new(+ "rolled-back",+ format!("{why}. The old host service runs as before."),+ false,+ ))+ }+ }+ }++ /// The relay's view of this machine's session: `(online, connected_at)`+ /// (relay mode; `None` when it could not be read). Read fresh, never+ /// the remembered answer [`Host::status`] shows during a hiccup.+ async fn relay_session(&self, config: &HostConfig) -> Option<(bool, Option<u64>)> {+ let (Some(url), Some(id)) = (&config.relay_url, &config.machine_id) else {+ return None;+ };+ if config.mode != "relay" || config.paused_signed_out {+ return None;+ }+ self.relay_machine(url, id)+ .await+ .ok()+ .map(|m| (m.online, m.connected_at))+ }++ /// The helper keeps running, and, when the old service was online at+ /// the relay, a new session of this machine is online there.+ async fn verify_helper(+ &self,+ helper: &dyn ServiceManager,+ config: &HostConfig,+ before: Option<(bool, Option<u64>)>,+ ) -> Result<()> {+ let t = self.verify;+ let start = std::time::Instant::now();+ let mut stable_since: Option<std::time::Instant> = None;+ let was_online = matches!(before, Some((true, _)));+ let mut last = "it did not start".to_string();+ loop {+ if helper.state().running {+ let since = *stable_since.get_or_insert_with(std::time::Instant::now);+ if since.elapsed() >= t.stable {+ match self.relay_session(config).await {+ Some((true, at))+ if !was_online || at.is_none() || at != before.and_then(|b| b.1) =>+ {+ return Ok(());+ }+ _ if !was_online && start.elapsed() >= t.offline_grace => return Ok(()),+ Some(_) => last = "it is not online at the relay yet".into(),+ None if was_online => last = "the relay did not answer".into(),+ None => {}+ }+ }+ } else {+ if stable_since.is_some() {+ last = "it stopped after starting".into();+ }+ stable_since = None;+ }+ if start.elapsed() >= t.timeout {+ return Err(Error::Service(format!(+ "{last} (checked for {} s)",+ t.timeout.as_secs()+ )));+ }+ tokio::time::sleep(t.poll).await;+ }+ }++ /// Stops and removes the old LaunchAgent and its binary (the helper+ /// replaced them).+ fn retire_legacy(&self) -> Result<()> {+ let legacy = self.legacy();+ legacy.bootout()?;+ let plist = legacy.plist();+ if plist.is_file() {+ std::fs::remove_file(&plist)?;+ }+ self.remove_legacy_binary();+ Ok(())+ }++ fn remove_legacy_binary(&self) {+ let bin = self.paths.driver_bin();+ let _ = std::fs::remove_file(&bin);+ if let Some(dir) = bin.parent() {+ // Only when empty.+ let _ = std::fs::remove_dir(dir);+ }+ }++ fn record_migration(&self, state: &str, app_version: &str, reason: Option<&str>) {+ let _ = write_json(+ &self.paths.dir.join(helper_migration::RECORD_FILE),+ &MigrationRecord {+ state: state.into(),+ app_version: app_version.into(),+ at_ms: now_ms(),+ reason: reason.map(Into::into),+ },+ );+ }+async fn remove_inner(&self, uninstalling: bool) -> Result<()> {let Some(config) = self.config()? else {return Ok(());@@ -1695,6 +2073,10 @@ impl Host {note(e);}self.manager_for_config(&config).uninstall()?;+ if config.runner == RunnerKind::AppHelper.as_str() {+ // Whatever an interrupted move left of the old agent.+ let _ = self.retire_legacy();+ }remove_dir_retrying(&self.paths.dir).await?;match relay_error {Some(e) => Err(Error::Relay(format!(@@ -1705,6 +2087,20 @@ impl Host {}}+/// Renames `from` to `to`, copying across volumes.+fn move_file(from: &Path, to: &Path) -> std::io::Result<()> {+ if let Some(dir) = to.parent() {+ std::fs::create_dir_all(dir)?;+ }+ match std::fs::rename(from, to) {+ Ok(()) => Ok(()),+ Err(_) => {+ std::fs::copy(from, to)?;+ std::fs::remove_file(from)+ }+ }+}+/// How long [`Host::status`] keeps the relay's last answer about this/// machine while the relay is briefly unreachable, before it shows the/// failure ("Needs attention"). A relay deploy replaces its one pod, and@@ -1846,6 +2242,38 @@ mod tests {assert!(h.instructions.contains("`cua daemon stop`"));}+ #[test]+ fn permission_hints_name_the_app_helper() {+ let helper = Path::new("/Applications/Cua Spaces.app/Contents/MacOS/CuaSpacesMac");+ for h in permission_hints("macos", helper) {+ assert!(+ h.instructions.contains("turn on Cua Spaces,"),+ "{}",+ h.instructions+ );+ assert!(+ !h.instructions.contains("cua-spacesd"),+ "{}",+ h.instructions+ );+ }+ let ln = local_network_hint("macos", true, helper).unwrap();+ assert!(+ ln.instructions.contains("Allow Cua Spaces to find devices"),+ "{}",+ ln.instructions+ );+ let old = Path::new("/Users/ada/.cua/host/bin/cua-spacesd");+ for h in permission_hints("macos", old) {+ assert!(+ h.instructions+ .contains("cua-spacesd (/Users/ada/.cua/host/bin/cua-spacesd)"),+ "{}",+ h.instructions+ );+ }+ }+#[test]fn permission_hints_only_on_macos() {assert!(permission_hints("linux", Path::new("/x")).is_empty());diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex aa9aea8f6e..847d4240fe 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -35,6 +35,9 @@ pub mod access;pub mod device;pub mod direct;pub mod driver;+pub mod helper_migration;+#[cfg(test)]+mod helper_migration_tests;mod host;pub mod machine;pub mod pairing;@@ -51,6 +54,7 @@ pub mod testing;mod tests;pub use device::{DeviceAuth, DeviceKey, FileKeySlot, KeySlot, MemoryKeySlot, PendingCode};+pub use helper_migration::{ServiceMigration, VerifyTiming};pub use host::SetupStage;pub use host::{DirectHosting, Host, HostConfig, HostMode, HostPaths, HostPolicy, HostSettingsChange,diff --git a/libs/cua/crates/cua-host/src/service.rs b/libs/cua/crates/cua-host/src/service.rsindex f315d95757..70607c869f 100644--- a/libs/cua/crates/cua-host/src/service.rs+++ b/libs/cua/crates/cua-host/src/service.rs@@ -12,7 +12,12 @@//! - macOS: a LaunchAgent in the GUI (Aqua) session, so screen capture and//! accessibility run with the user's TCC grants. The user grants Screen//! Recording and Accessibility in System Settings; nothing here grants or-//! opens anything.+//! opens anything. With the Cua Spaces app installed, the agent is the+//! app's own login item ([`AppHelper`]): the app's executable in its+//! service mode, registered with `SMAppService`, so macOS shows and keeps+//! every permission under one name, "Cua Spaces", and the Team ID;+//! without the app, a hand-written LaunchAgent ([`Launchd`]) runs the+//! downloaded binary.//! - Windows: a scheduled task that starts at logon with the user's//! interactive token, which is the interactive-session helper: a Windows//! service lives in session 0 and cannot capture the desktop or inject@@ -31,6 +36,19 @@ pub const LAUNCHD_LABEL: &str = "com.trycua.spacesd.host";/// Windows task name.pub const WINDOWS_TASK_NAME: &str = "Cua\\SpacesdHost";+/// launchd label of the Cua Spaces app's login item ([`AppHelper`]).+pub const APP_HELPER_LABEL: &str = "com.trycua.spaces.helper";+/// What macOS shows for it (System Settings: Privacy & Security, Login+/// Items): the app's own name, since the app's executable runs it.+pub const APP_HELPER_NAME: &str = "Cua Spaces";+/// The cua-spacesd the app ships, inside the app (the service runs only+/// this one).+pub const APP_HELPER_DAEMON: &str = "Contents/MacOS/cua-spacesd";+/// The `SMAppService.agent` plist, inside the app.+pub const APP_HELPER_PLIST: &str = "Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist";+/// The app's own executable (which registers the helper), inside the app.+pub const APP_EXECUTABLE: &str = "Contents/MacOS/CuaSpacesMac";+/// The names installs made before the cua-spacesd rename used. `install` and/// `uninstall` remove a service left under them (best effort), so an upgrade/// never runs two copies.@@ -66,6 +84,9 @@ pub enum RunnerKind {Systemd,/// launchd LaunchAgent in the GUI session.Launchd,+ /// macOS: the Cua Spaces app's login item (the app's own executable)+ /// ([`AppHelper`]).+ AppHelper,/// Windows scheduled task at logon (interactive token).WindowsTask,/// A detached process with a pidfile (no init system, e.g. containers).@@ -73,11 +94,17 @@ pub enum RunnerKind {}impl RunnerKind {- /// The runner for this machine: launchd on macOS, the scheduled task on- /// Windows, systemd on Linux when it is PID 1, else a plain process.+ /// The runner for this machine: on macOS the Cua Spaces app's helper+ /// when the app (with one) is installed, else launchd; the scheduled+ /// task on Windows, systemd on Linux when it is PID 1, else a plain+ /// process.pub fn detect() -> Self {if cfg!(target_os = "macos") {- RunnerKind::Launchd+ if find_app_helper().is_some() {+ RunnerKind::AppHelper+ } else {+ RunnerKind::Launchd+ }} else if cfg!(windows) {RunnerKind::WindowsTask} else if Path::new("/run/systemd/system").is_dir() {@@ -102,6 +129,7 @@ impl RunnerKind {RunnerKind::Auto => "auto",RunnerKind::Systemd => "systemd",RunnerKind::Launchd => "launchd",+ RunnerKind::AppHelper => "app-helper",RunnerKind::WindowsTask => "windows-task",RunnerKind::Process => "process",}@@ -113,6 +141,7 @@ impl RunnerKind {"auto" | "" => RunnerKind::Auto,"systemd" => RunnerKind::Systemd,"launchd" => RunnerKind::Launchd,+ "app-helper" => RunnerKind::AppHelper,"windows-task" | "schtasks" => RunnerKind::WindowsTask,"process" => RunnerKind::Process,other => return Err(Error::InvalidArgument(format!("unknown runner {other:?}"))),@@ -128,7 +157,7 @@ pub struct ServiceState {pub installed: bool,/// The driver is running.pub running: bool,- /// `systemd`, `launchd`, `windows-task` or `process`.+ /// `systemd`, `launchd`, `app-helper`, `windows-task` or `process`.pub kind: String,/// Human detail (unit path, pid, runner output).pub detail: String,@@ -1173,6 +1202,358 @@ impl ServiceManager for ProcessRunner {}}+// ------------------------------------------------------------- app helper++/// `~/.cua/helper/service.json`: what the Cua Spaces app's helper runs (a+/// [`ServiceSpec`] as JSON, 0600). A fixed path under the user's home: the+/// helper's launchd plist is sealed in the app and cannot name a cua home.+pub fn helper_spec_path(user_home: &Path) -> PathBuf {+ user_home.join(".cua").join("helper").join("service.json")+}++/// The service's launcher inside `app`: the app's own executable (what+/// `config.driver_bin` names for the app-helper runner; `<launcher>+/// check-permissions` answers for the app's permissions).+pub fn app_helper_launcher(app: &Path) -> PathBuf {+ app.join(APP_EXECUTABLE)+}++/// Whether `app` is a Cua Spaces app that carries the helper.+pub fn has_app_helper(app: &Path) -> bool {+ app.join(APP_HELPER_PLIST).is_file()+ && app.join(APP_HELPER_DAEMON).is_file()+ && app.join(APP_EXECUTABLE).is_file()+}++/// Whether `launcher` is a Cua Spaces app's executable (a host set up with+/// the app-helper runner names it as its driver).+pub fn is_app_helper_launcher(launcher: &Path) -> bool {+ launcher.ends_with(APP_EXECUTABLE)+ && launcher+ .parent()+ .and_then(Path::parent)+ .and_then(Path::parent)+ .is_some_and(|app| app.extension().is_some_and(|e| e == "app"))+}++/// The installed Cua Spaces app that carries the helper, if any (macOS):+/// `CUA_SPACES_APP` when set (empty or `none`: no app), else the app this+/// process runs from (the app itself, or the `cua` it links onto PATH),+/// else `/Applications/Cua Spaces.app`, else `~/Applications/Cua Spaces.app`.+pub fn find_app_helper() -> Option<PathBuf> {+ if !cfg!(target_os = "macos") {+ return None;+ }+ if let Some(v) = std::env::var_os("CUA_SPACES_APP") {+ let p = PathBuf::from(&v);+ return (!v.is_empty() && v != "none" && has_app_helper(&p)).then_some(p);+ }+ let mut candidates = vec![];+ if let Ok(exe) = std::env::current_exe().and_then(|e| e.canonicalize()) {+ // .../X.app/Contents/MacOS/<exe>+ if let Some(app) = exe.parent().and_then(Path::parent).and_then(Path::parent)+ && app.extension().is_some_and(|e| e == "app")+ {+ candidates.push(app.to_path_buf());+ }+ }+ candidates.push(PathBuf::from("/Applications/Cua Spaces.app"));+ if let Some(home) = std::env::var_os("HOME") {+ candidates.push(PathBuf::from(home).join("Applications/Cua Spaces.app"));+ }+ candidates.into_iter().find(|a| has_app_helper(a))+}++/// What `CuaSpacesMac --service-helper <command>` reports: the+/// `SMAppService` status of the helper (`enabled`, `not-registered`,+/// `requires-approval`, `not-found`) and an error, if the command failed.+#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]+pub struct HelperRegistration {+ /// The status after the command.+ pub status: String,+ /// Why the command failed.+ #[serde(default)]+ pub error: Option<String>,+}++/// The Cua Spaces app's login item: the app's own executable+/// (`CuaSpacesMac --service-helper run`), registered with+/// `SMAppService.agent` by that executable. It reads [`helper_spec_path`]+/// and runs the cua-spacesd sealed in the app with it, in the GUI session;+/// macOS holds the app responsible for it, so Screen Recording and+/// Accessibility are granted to "Cua Spaces" (bundle id+/// `com.trycua.spaces.macos`, the Cua team), once, and survive app updates.+/// (A separate helper bundle got two names in System Settings: macOS lists+/// a login item's Screen Recording under the app that contains it.)+pub struct AppHelper {+ /// The app (`/Applications/Cua Spaces.app`).+ pub app: PathBuf,+ /// [`helper_spec_path`].+ pub spec_path: PathBuf,+ /// The user id (`gui/<uid>`).+ pub uid: u32,+}++impl AppHelper {+ /// The helper of `app` for the current user.+ pub fn for_current_user(app: PathBuf, user_home: &Path) -> Self {+ #[cfg(unix)]+ // SAFETY: getuid has no preconditions.+ let uid = unsafe { libc::getuid() };+ #[cfg(not(unix))]+ let uid = 0;+ Self {+ app,+ spec_path: helper_spec_path(user_home),+ uid,+ }+ }++ fn target(&self) -> String {+ format!("gui/{}/{APP_HELPER_LABEL}", self.uid)+ }++ /// `CuaSpacesMac --service-helper <command>`.+ pub fn registration(&self, command: &str) -> Result<HelperRegistration> {+ let exe = self.app.join(APP_EXECUTABLE);+ let out = Command::new(&exe)+ .args(["--service-helper", command])+ .output()+ .map_err(|e| Error::Service(format!("{}: {e}", exe.display())))?;+ let text = String::from_utf8_lossy(&out.stdout);+ let reg: HelperRegistration = text+ .lines()+ .rev()+ .find_map(|l| serde_json::from_str(l.trim()).ok())+ .ok_or_else(|| {+ Error::Service(format!(+ "Cua Spaces could not {command} its helper: {}{}",+ text.trim(),+ String::from_utf8_lossy(&out.stderr).trim()+ ))+ })?;+ Ok(reg)+ }++ fn loaded(&self) -> bool {+ run(Command::new("launchctl").args(["print", &self.target()])).is_ok()+ }++ /// launchd could not start the helper's program at its last try.+ fn spawn_failed(&self) -> bool {+ Command::new("launchctl")+ .args(["print", &self.target()])+ .output()+ .map(|o| {+ let p = String::from_utf8_lossy(&o.stdout);+ p.contains("spawn failed") || p.contains("last exit code = 78")+ })+ .unwrap_or(false)+ }+}++impl ServiceManager for AppHelper {+ fn kind(&self) -> RunnerKind {+ RunnerKind::AppHelper+ }+ fn install(&self, spec: &ServiceSpec) -> Result<()> {+ let mut spec = spec.clone();+ // The service runs only the app's own cua-spacesd; the spec says+ // which launcher it was written for.+ spec.program = app_helper_launcher(&self.app);+ let json =+ serde_json::to_string_pretty(&spec).map_err(|e| Error::Internal(e.to_string()))?;+ crate::host::write_secret(&self.spec_path, &json)?;+ // A registration made by another copy of the app (replaced since:+ // an update, a reinstall, a downgrade and back) can leave launchd+ // resolving the helper in a bundle that is gone ("Invalid or missing+ // Program", exit 78). Registering again from this app binds it here.+ if !self.state().running {+ let _ = self.registration("unregister");+ }+ let reg = self.registration("register")?;+ helper_registered(®)+ }+ fn start(&self) -> Result<()> {+ // A fresh registration can take a moment to reach launchd.+ let mut waited = std::time::Duration::ZERO;+ let step = std::time::Duration::from_millis(200);+ while !self.loaded() && waited < std::time::Duration::from_secs(5) {+ std::thread::sleep(step);+ waited += step;+ }+ let kick = || run(Command::new("launchctl").args(["kickstart", "-k", &self.target()]));+ let mut result = kick();+ // Started but gone at once with launchd's "could not find the+ // program" (a stale bundle): register from this app and try once more.+ std::thread::sleep(std::time::Duration::from_secs(2));+ if result.is_ok() && !self.state().running && self.spawn_failed() {+ let _ = self.registration("unregister");+ helper_registered(&self.registration("register")?)?;+ std::thread::sleep(std::time::Duration::from_millis(500));+ result = kick();+ }+ result.map(drop).map_err(|e| {+ Error::Service(format!(+ "macOS did not start {APP_HELPER_NAME} ({e}); if it keeps failing, turn on \+ Cua Spaces in System Settings > General > Login Items & Extensions"+ ))+ })+ }+ fn stop(&self) -> Result<()> {+ if !self.state().running {+ return Ok(());+ }+ // The launcher passes it on and exits 0, which launchd leaves+ // stopped (KeepAlive SuccessfulExit=false).+ run(Command::new("launchctl").args(["kill", "SIGTERM", &self.target()])).map(drop)+ }+ fn uninstall(&self) -> Result<()> {+ let _ = self.stop();+ let _ = std::fs::remove_file(&self.spec_path);+ // Unregistering also takes it out of Login Items.+ let _ = self.registration("unregister");+ Ok(())+ }+ fn state(&self) -> ServiceState {+ let printed = Command::new("launchctl")+ .args(["print", &self.target()])+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string());+ ServiceState {+ installed: self.spec_path.is_file() && printed.is_some(),+ running: printed+ .as_deref()+ .is_some_and(|p| p.contains("state = running")),+ kind: RunnerKind::AppHelper.as_str().into(),+ detail: format!("{APP_HELPER_NAME} in {}", self.app.display()),+ }+ }+}++/// A registration that did not leave the helper allowed to run, in words.+fn helper_registered(reg: &HelperRegistration) -> Result<()> {+ match (reg.status.as_str(), ®.error) {+ ("enabled", _) => Ok(()),+ ("requires-approval", _) => Err(Error::Service(format!(+ "macOS needs you to allow {APP_HELPER_NAME}: turn on Cua Spaces in System Settings > \+ General > Login Items & Extensions, then try again"+ ))),+ (status, Some(e)) => Err(Error::Service(format!(+ "Cua Spaces could not register {APP_HELPER_NAME} ({status}): {e}"+ ))),+ (status, None) => Err(Error::Service(format!(+ "Cua Spaces could not register {APP_HELPER_NAME} ({status})"+ ))),+ }+}++/// The app-helper runner on a Mac whose Cua Spaces app (with the helper)+/// is gone: nothing installed, nothing runs, and nothing can start.+pub struct MissingAppHelper;++impl ServiceManager for MissingAppHelper {+ fn kind(&self) -> RunnerKind {+ RunnerKind::AppHelper+ }+ fn install(&self, _: &ServiceSpec) -> Result<()> {+ Err(missing_app())+ }+ fn start(&self) -> Result<()> {+ Err(missing_app())+ }+ fn stop(&self) -> Result<()> {+ Ok(())+ }+ fn uninstall(&self) -> Result<()> {+ Ok(())+ }+ fn state(&self) -> ServiceState {+ ServiceState {+ installed: false,+ running: false,+ kind: RunnerKind::AppHelper.as_str().into(),+ detail: format!("{APP_HELPER_NAME}: the Cua Spaces app is not installed"),+ }+ }+}++fn missing_app() -> Error {+ Error::Service(format!(+ "{APP_HELPER_NAME} lives in the Cua Spaces app, which is not installed; install it \+ again, or run `cua host setup --runner launchd`"+ ))+}++/// The hand-written LaunchAgent an install made before the helper (`cua+/// host setup` without the app, or Cua Spaces 0.9.4 and earlier), as found+/// on this Mac.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]+pub struct LegacyAgent {+ /// `~/Library/LaunchAgents/com.trycua.spacesd.host.plist` exists.+ pub plist: bool,+ /// launchd has it loaded.+ pub loaded: bool,+ /// It runs now.+ pub running: bool,+}++impl LegacyAgent {+ /// Anything of it is left.+ pub fn present(&self) -> bool {+ self.plist || self.loaded+ }+}++impl Launchd {+ /// What is left of this LaunchAgent.+ pub fn legacy(&self) -> LegacyAgent {+ let printed = Command::new("launchctl")+ .args(["print", &self.target()])+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string());+ LegacyAgent {+ plist: self.plist_path().is_file(),+ loaded: printed.is_some(),+ running: printed+ .as_deref()+ .is_some_and(|p| p.contains("state = running")),+ }+ }++ /// The plist's path.+ pub fn plist_file(&self) -> PathBuf {+ self.plist_path()+ }++ /// Stops it and takes it out of launchd, leaving the plist in place.+ pub fn bootout(&self) -> Result<()> {+ let target = self.target();+ if !launchd_loaded(&target, &mut |args: &[&str]| {+ run(Command::new("launchctl").args(args))+ }) {+ return Ok(());+ }+ let _ = run(Command::new("launchctl").args(["bootout", &target]));+ // bootout returns before the teardown ends.+ for _ in 0..50 {+ if !launchd_loaded(&target, &mut |args: &[&str]| {+ run(Command::new("launchctl").args(args))+ }) {+ return Ok(());+ }+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ Err(Error::Service(format!(+ "launchd did not let go of {target}"+ )))+ }+}+/// Records calls; for tests of everything above the runner.#[derive(Default)]pub struct FakeServiceManager {@@ -1223,6 +1604,12 @@ pub fn manager_for(kind: RunnerKind, user_home: &Path, host_dir: &Path) -> Box<dmatch kind.resolve() {RunnerKind::Systemd => Box::new(Systemd::for_current_user(user_home)),RunnerKind::Launchd => Box::new(Launchd::for_current_user(user_home)),+ RunnerKind::AppHelper => match find_app_helper() {+ Some(app) => Box::new(AppHelper::for_current_user(app, user_home)),+ // The app was removed (or replaced by one without the helper):+ // nothing can run it; report it as not installed.+ None => Box::new(MissingAppHelper),+ },RunnerKind::WindowsTask => Box::new(WindowsTask::for_current_user(host_dir)),RunnerKind::Process | RunnerKind::Auto => Box::new(ProcessRunner {dir: host_dir.to_path_buf(),@@ -1471,6 +1858,7 @@ mod tests {RunnerKind::Auto,RunnerKind::Systemd,RunnerKind::Launchd,+ RunnerKind::AppHelper,RunnerKind::WindowsTask,RunnerKind::Process,] {@@ -1480,6 +1868,76 @@ mod tests {assert_ne!(RunnerKind::Auto.resolve(), RunnerKind::Auto);}+ #[test]+ fn the_app_helper_is_found_by_its_bundle_layout() {+ let dir = tempfile::tempdir().unwrap();+ let app = dir.path().join("Cua Spaces.app");+ assert!(!has_app_helper(&app));+ for f in [APP_HELPER_PLIST, APP_EXECUTABLE] {+ std::fs::create_dir_all(app.join(f).parent().unwrap()).unwrap();+ std::fs::write(app.join(f), "").unwrap();+ }+ assert!(+ !has_app_helper(&app),+ "an app without its own cua-spacesd (0.9.4)"+ );+ std::fs::write(app.join(APP_HELPER_DAEMON), "").unwrap();+ assert!(has_app_helper(&app));+ let launcher = app_helper_launcher(&app);+ assert_eq!(launcher, app.join(APP_EXECUTABLE));+ assert!(is_app_helper_launcher(&launcher));+ assert!(!is_app_helper_launcher(Path::new(+ "/usr/local/bin/CuaSpacesMac"+ )));+ assert!(!is_app_helper_launcher(Path::new(+ "/Users/ada/.cua/host/bin/cua-spacesd"+ )));+ assert_eq!(+ helper_spec_path(Path::new("/Users/ada")),+ Path::new("/Users/ada/.cua/helper/service.json")+ );+ }++ #[test]+ fn a_helper_registration_says_what_to_do_in_words() {+ let reg = |status: &str, error: Option<&str>| HelperRegistration {+ status: status.into(),+ error: error.map(Into::into),+ };+ assert!(helper_registered(®("enabled", None)).is_ok());+ let e = helper_registered(®("requires-approval", None))+ .unwrap_err()+ .to_string();+ assert!(e.contains("Login Items"), "{e}");+ let e = helper_registered(®("not-found", Some("Invalid argument")))+ .unwrap_err()+ .to_string();+ assert!(+ e.contains("Cua Spaces") && e.contains("Invalid argument"),+ "{e}"+ );+ // The JSON CuaSpacesMac --service-helper prints.+ let r: HelperRegistration = serde_json::from_str(+ r#"{"error":"Operation not permitted","status":"not-registered"}"#,+ )+ .unwrap();+ assert_eq!(r.status, "not-registered");+ }++ #[test]+ fn without_the_app_the_helper_runner_reports_and_refuses_in_words() {+ let m = MissingAppHelper;+ assert!(!m.state().installed && !m.state().running);+ assert_eq!(m.state().kind, "app-helper");+ assert!(+ m.start()+ .unwrap_err()+ .to_string()+ .contains("--runner launchd")+ );+ assert!(m.uninstall().is_ok());+ }+#[cfg(unix)]#[test]fn process_runner_starts_reports_and_stops_a_harmless_process() {diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rsindex a57ab6a449..65dff0c3db 100644--- a/libs/cua/crates/cua-host/src/testing.rs+++ b/libs/cua/crates/cua-host/src/testing.rs@@ -1191,6 +1191,15 @@ impl FakeRelay {}}+ /// Sets a machine's session: online since `connected_at` (Unix+ /// seconds), or offline (a new driver session gets a new time).+ pub fn set_session(&self, id: &str, online: bool, connected_at: Option<u64>) {+ if let Some(r) = self.state.lock().unwrap().machines.get_mut(id) {+ r.machine.online = online;+ r.machine.connected_at = if online { connected_at } else { None };+ }+ }+/// Adds a connected client to a machine.pub fn add_client(&self, id: &str, client: ConnectedClient) {if let Some(r) = self.state.lock().unwrap().machines.get_mut(id) {diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex e9ee3af897..e6886e77a8 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -421,6 +421,26 @@ pub struct HostStatus {/// The owner's email, when the relay gave one.#[uniffi(default = None)]pub owner_email: Option<String>,+ /// macOS: a Cua Spaces app that can run the host service is+ /// installed, so the host service can run as it.+ #[uniffi(default = false)]+ pub helper_available: bool,+ /// macOS: the old hand-written LaunchAgent is still there.+ #[uniffi(default = false)]+ pub legacy_service: bool,+}++/// What [`Host::migrate_service`] did.+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct HostServiceMigration {+ /// `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or+ /// `not-needed`.+ pub outcome: String,+ /// In words.+ pub detail: String,+ /// macOS will ask for Screen Recording and Accessibility for Cua Spaces+ /// Helper.+ pub permissions_needed: bool,}/// One access to this machine.@@ -508,6 +528,8 @@ impl From<cua_host::HostStatus> for HostStatus {paused_signed_out: s.paused_signed_out,owner: s.owner,owner_email: s.owner_email,+ helper_available: s.helper_available,+ legacy_service: s.legacy_service,}}}@@ -708,6 +730,31 @@ impl Host {.await}+ /// macOS: moves the host service from the old LaunchAgent to the Cua+ /// Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ /// registration, id and Spaces; puts the old one back if the helper+ /// does not take over (the outcome says so). `app_version`: a failed+ /// move is not tried again by itself with the same version; `force`+ /// tries anyway.+ pub async fn migrate_service(+ &self,+ force: bool,+ app_version: String,+ ) -> Result<HostServiceMigration> {+ let home = self.home.clone();+ run(async move {+ let m = cua_host::Host::new(home)+ .migrate_service(force, &app_version)+ .await?;+ Ok(HostServiceMigration {+ outcome: m.outcome,+ detail: m.detail,+ permissions_needed: m.permissions_needed,+ })+ })+ .await+ }+/// Unregister, uninstall the service and delete the host state.pub async fn remove(&self) -> Result<()> {let home = self.home.clone();diff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.inindex a0e821266a..6002405b41 100644--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in@@ -89,6 +89,7 @@"dump-docs","fleet","host.config",+ "host.migrate","host.pair","host.remove","host.setup",diff --git a/libs/cua/crates/cua-teleport/src/ux/window.rs b/libs/cua/crates/cua-teleport/src/ux/window.rsindex 7f523dfa41..0aaf4b0f69 100644--- a/libs/cua/crates/cua-teleport/src/ux/window.rs+++ b/libs/cua/crates/cua-teleport/src/ux/window.rs@@ -23,8 +23,10 @@//!//! [`WindowDragTracker`] is that state machine over any [`WindowSource`], so//! it is tested with fixture window lists. [`WindowDragMonitor`] runs it on-//! the real machine: macOS today (a listen-only `CGEventTap`, which needs-//! the Accessibility permission). Linux and Windows return+//! the real machine: macOS today (the left mouse button, polled, so it needs+//! no permission; a listen-only `CGEventTap` only when Input Monitoring is+//! already allowed, because creating one makes macOS ask for it). Linux and+//! Windows return//! [`UxError::Unsupported`]: Wayland does not let a client observe other//! apps' windows or the global pointer, and the X11 and Windows backends are//! not built yet.@@ -437,26 +439,21 @@ pub fn supported() -> bool {cfg!(target_os = "macos")}-/// Whether this process may observe global mouse events (macOS-/// Accessibility). `false` elsewhere.+/// Whether this process may observe global mouse events. On macOS the+/// monitor polls the left mouse button unless Input Monitoring is already+/// allowed, which needs no permission, so this is `true` there; `false`+/// elsewhere.pub fn permission_granted() -> bool {- #[cfg(target_os = "macos")]- {- super::window_macos::ax_trusted()- }- #[cfg(not(target_os = "macos"))]- {- false- }+ cfg!(target_os = "macos")}-/// Asks for the permission (opens System Settings on macOS). Returns the-/// state after asking.+/// Kept for callers that offer a button: nothing to ask on macOS (see+/// [`permission_granted`]), so it never prompts and returns the state.pub fn request_permission() -> Result<bool, UxError> {guard()?;#[cfg(target_os = "macos")]{- Ok(super::window_macos::request_ax_trust())+ Ok(true)}#[cfg(not(target_os = "macos"))]{@@ -507,27 +504,20 @@ pub fn capture_thumbnail_png(window_id: u32, max_width: usize) -> Result<Option<}/// Global window-drag detection on the real machine. Dropping it (or-/// [`Self::stop`]) removes the event tap.+/// [`Self::stop`]) removes the event tap or stops the polling.pub struct WindowDragMonitor {#[cfg(target_os = "macos")]inner: super::window_macos::Monitor,}impl WindowDragMonitor {- /// Starts watching; `on_event` runs on the monitor thread. Fails with- /// `PermissionDenied` without the Accessibility permission (macOS) and- /// `Unsupported` elsewhere.+ /// Starts watching; `on_event` runs on the monitor thread. Fails when+ /// macOS refuses the event tap (only tried with Input Monitoring+ /// allowed), and with `Unsupported` elsewhere.pub fn start(on_event: Box<dyn Fn(WindowDragEvent) + Send + 'static>) -> Result<Self, UxError> {guard()?;#[cfg(target_os = "macos")]{- if !super::window_macos::ax_trusted() {- return Err(UxError::PermissionDenied(- "window-drag detection needs the Accessibility permission \- (System Settings, Privacy & Security, Accessibility)"- .into(),- ));- }Ok(Self {inner: super::window_macos::Monitor::start(on_event)?,})diff --git a/libs/cua/crates/cua-teleport/src/ux/window_macos.rs b/libs/cua/crates/cua-teleport/src/ux/window_macos.rsindex e8163db282..4c6a82d248 100644--- a/libs/cua/crates/cua-teleport/src/ux/window_macos.rs+++ b/libs/cua/crates/cua-teleport/src/ux/window_macos.rs@@ -2,17 +2,19 @@// Copyright (c) 2026 Cua AI, Inc.//! macOS backend for [`super::window`]: CoreGraphics window lists, the-//! dragged window's image, and a listen-only `CGEventTap`.+//! dragged window's image, and the left mouse button: a listen-only+//! `CGEventTap` when Input Monitoring is already allowed, otherwise polling.//!//! Only reached through the guarded functions in [`super::window`], which//! refuse under `cfg(test)` or `CUA_ENV_TEST_SANDBOX=1`.use std::collections::HashMap;use std::ffi::c_void;+use std::sync::Arc;use std::sync::Mutex;+use std::sync::atomic::{AtomicBool, Ordering};use core_foundation::base::{CFType, TCFType};-use core_foundation::boolean::CFBoolean;use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};use core_foundation::number::CFNumber;use core_foundation::runloop::CFRunLoop;@@ -36,11 +38,18 @@ use super::window::{thumbnail_rgba,};-#[link(name = "ApplicationServices", kind = "framework")]+#[link(name = "CoreGraphics", kind = "framework")]unsafe extern "C" {- fn AXIsProcessTrusted() -> u8;- fn AXIsProcessTrustedWithOptions(options: CFDictionaryRef) -> u8;- static kAXTrustedCheckOptionPrompt: CFStringRef;+ /// Whether this process may capture the screen. Never prompts.+ fn CGPreflightScreenCaptureAccess() -> bool;+ /// Whether this process may listen to input events (Input Monitoring).+ /// Never prompts.+ fn CGPreflightListenEventAccess() -> bool;+ /// Whether a mouse button is down (state 0: combined session state).+ /// Needs no permission.+ fn CGEventSourceButtonState(state: i32, button: u32) -> bool;+ fn CGEventCreate(source: *const c_void) -> *const c_void;+ fn CGEventGetLocation(event: *const c_void) -> CGPoint;}#[link(name = "CoreFoundation", kind = "framework")]@@ -61,21 +70,6 @@ unsafe extern "C" {fn CGSWindowIsOrderedIn(cid: i32, wid: u32, out: *mut u8) -> i32;}-pub fn ax_trusted() -> bool {- unsafe { AXIsProcessTrusted() != 0 }-}--pub fn request_ax_trust() -> bool {- unsafe {- let key = CFString::wrap_under_get_rule(kAXTrustedCheckOptionPrompt);- let options = CFDictionary::from_CFType_pairs(&[(- key.as_CFType(),- CFBoolean::true_value().as_CFType(),- )]);- AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef()) != 0- }-}-fn num(dict: &CFDictionary<CFString, CFType>, key: CFStringRef) -> Option<CFNumber> {let key = unsafe { CFString::wrap_under_get_rule(key) };dict.find(&key).and_then(|v| v.downcast::<CFNumber>())@@ -241,7 +235,16 @@ pub fn display_union() -> Option<Rect> {/// only), downscaled and PNG-encoded in memory. Captured at the display's/// nominal (1x) resolution: a preview is at most a few hundred pixels wide,/// and the Retina capture was four times the pixels to copy and drop.+///+/// Only when this process already has Screen Recording: the app never asks+/// for it itself (a capture without it makes macOS prompt). The Cua Spaces+/// app's background service asks once, under the same "Cua Spaces" name,+/// and its grant covers this preview too.pub fn capture(window_id: u32, max_width: usize) -> Option<Vec<u8>> {+ // SAFETY: no arguments, no preconditions.+ if !unsafe { CGPreflightScreenCaptureAccess() } {+ return None;+ }let null_rect = CGRect::new(&CGPoint::new(f64::INFINITY, f64::INFINITY),&CGSize::new(0.0, 0.0),@@ -274,13 +277,80 @@ impl WindowSource for OnScreen {}}-/// A running event tap.+/// Watches the left mouse button: an event tap, or a polling thread.pub struct Monitor {run_loop: Mutex<Option<usize>>,+ stop_polling: Arc<AtomicBool>,+}++/// The cursor, in global display coordinates (top-left origin, as event+/// locations are).+fn cursor() -> Option<(f64, f64)> {+ // SAFETY: a NULL source is allowed; the event is released below.+ let event = unsafe { CGEventCreate(std::ptr::null()) };+ if event.is_null() {+ return None;+ }+ // SAFETY: `event` is a valid CGEventRef we own.+ let p = unsafe { CGEventGetLocation(event) };+ unsafe { core_foundation::base::CFRelease(event) };+ Some((p.x, p.y))}impl Monitor {pub fn start(on_event: Box<dyn Fn(WindowDragEvent) + Send + 'static>) -> Result<Self, UxError> {+ // A listen-only tap still makes macOS ask for Input Monitoring+ // ("would like to receive keystrokes"), which the app never asks+ // for. Unless it is already allowed, poll the button every 16 ms+ // instead: the same events, and no prompt.+ // SAFETY: no arguments; never prompts.+ if !unsafe { CGPreflightListenEventAccess() } {+ return Self::poll(on_event);+ }+ Self::tap(on_event)+ }++ fn poll(on_event: Box<dyn Fn(WindowDragEvent) + Send + 'static>) -> Result<Self, UxError> {+ let stop = Arc::new(AtomicBool::new(false));+ let stop2 = stop.clone();+ std::thread::Builder::new()+ .name("cua-window-drag".into())+ .spawn(move || {+ let mut tracker = WindowDragTracker::new(OnScreen, std::process::id() as i64);+ let mut was_down = false;+ let mut last = (f64::NAN, f64::NAN);+ while !stop2.load(Ordering::Relaxed) {+ std::thread::sleep(std::time::Duration::from_millis(16));+ // SAFETY: plain value arguments (combined session state,+ // left button).+ let down = unsafe { CGEventSourceButtonState(0, 0) };+ let Some(p) = cursor() else { continue };+ let m = match (was_down, down) {+ (false, true) => Some(MouseEvent::Down),+ (true, true) if p != last => Some(MouseEvent::Dragged),+ (true, false) => Some(MouseEvent::Up),+ _ => None,+ };+ was_down = down;+ last = p;+ if let Some(m) = m+ && let Some(mut ev) = tracker.handle(m, p.0, p.1)+ {+ if let Some(w) = ev.window.as_mut().filter(|w| w.bundle_path.is_none()) {+ w.bundle_path = bundle_path(w.pid, &mut HashMap::new());+ }+ on_event(ev);+ }+ }+ })+ .map_err(|e| UxError::Io(e.to_string()))?;+ Ok(Self {+ run_loop: Mutex::new(None),+ stop_polling: stop,+ })+ }++ fn tap(on_event: Box<dyn Fn(WindowDragEvent) + Send + 'static>) -> Result<Self, UxError> {let (tx, rx) = std::sync::mpsc::channel::<Result<usize, String>>();std::thread::Builder::new().name("cua-window-drag".into())@@ -340,6 +410,7 @@ impl Monitor {match rx.recv_timeout(std::time::Duration::from_secs(5)) {Ok(Ok(rl)) => Ok(Self {run_loop: Mutex::new(Some(rl)),+ stop_polling: Arc::new(AtomicBool::new(false)),}),Ok(Err(e)) => Err(UxError::PermissionDenied(e)),Err(_) => Err(UxError::Io("the event tap did not start".into())),@@ -347,6 +418,7 @@ impl Monitor {}pub fn stop(&self) {+ self.stop_polling.store(true, Ordering::Relaxed);if let Some(rl) = self.run_loop.lock()diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.ktindex 5a450351a2..65275e0599 100644--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt@@ -997,6 +997,8 @@ external fun uniffi_cua_sdk_checksum_method_devices_snapshot(): Shortexternal fun uniffi_cua_sdk_checksum_method_host_configure(): Short+external fun uniffi_cua_sdk_checksum_method_host_migrate_service(+): Shortexternal fun uniffi_cua_sdk_checksum_method_host_pause_signed_out(): Shortexternal fun uniffi_cua_sdk_checksum_method_host_remove(@@ -1794,6 +1796,8 @@ external fun uniffi_cua_sdk_fn_constructor_host_new(`cuaHome`: RustBuffer.ByValu): Longexternal fun uniffi_cua_sdk_fn_method_host_configure(`ptr`: Long,`change`: RustBuffer.ByValue,): Long+external fun uniffi_cua_sdk_fn_method_host_migrate_service(`ptr`: Long,`force`: Byte,`appVersion`: RustBuffer.ByValue,+): Longexternal fun uniffi_cua_sdk_fn_method_host_pause_signed_out(`ptr`: Long,): Longexternal fun uniffi_cua_sdk_fn_method_host_remove(`ptr`: Long,@@ -3060,6 +3064,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_method_host_configure() != 36828.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}+ if (lib.uniffi_cua_sdk_checksum_method_host_migrate_service() != 36386.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }if (lib.uniffi_cua_sdk_checksum_method_host_pause_signed_out() != 3338.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}@@ -8941,6 +8948,16 @@ public interface HostInterface {*/suspend fun `configure`(`change`: HostSettingsChange): HostStatus+ /**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+ suspend fun `migrateService`(`force`: kotlin.Boolean, `appVersion`: kotlin.String): HostServiceMigration+/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -9121,6 +9138,35 @@ open class Host: Disposable, AutoCloseable, HostInterface}+ /**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+ @Throws(CuaException::class)+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")+ override suspend fun `migrateService`(`force`: kotlin.Boolean, `appVersion`: kotlin.String) : HostServiceMigration {+ return uniffiRustCallAsync(+ callWithHandle { uniffiHandle ->+ UniffiLib.uniffi_cua_sdk_fn_method_host_migrate_service(+ uniffiHandle,+ FfiConverterBoolean.lower(`force`),FfiConverterString.lower(`appVersion`),+ )+ },+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },+ // lift function+ { FfiConverterTypeHostServiceMigration.lift(it) },+ // Error FFI converter+ CuaException.ErrorHandler,+ )+ }++/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -28348,6 +28394,63 @@ public object FfiConverterTypeHostProvidedSpace: FfiConverterRustBuffer<HostProv+/**+ * What [`Host::migrate_service`] did.+ */+data class HostServiceMigration (+ /**+ * `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or+ * `not-needed`.+ */+ var `outcome`: kotlin.String+ ,+ /**+ * In words.+ */+ var `detail`: kotlin.String+ ,+ /**+ * macOS will ask for Screen Recording and Accessibility for Cua Spaces+ * Helper.+ */+ var `permissionsNeeded`: kotlin.Boolean++){++++++ companion object+}++/**+ * @suppress+ */+public object FfiConverterTypeHostServiceMigration: FfiConverterRustBuffer<HostServiceMigration> {+ override fun read(buf: ByteBuffer): HostServiceMigration {+ return HostServiceMigration(+ FfiConverterString.read(buf),+ FfiConverterString.read(buf),+ FfiConverterBoolean.read(buf),+ )+ }++ override fun allocationSize(value: HostServiceMigration) = (+ FfiConverterString.allocationSize(value.`outcome`) ++ FfiConverterString.allocationSize(value.`detail`) ++ FfiConverterBoolean.allocationSize(value.`permissionsNeeded`)+ )++ override fun write(value: HostServiceMigration, buf: ByteBuffer) {+ FfiConverterString.write(value.`outcome`, buf)+ FfiConverterString.write(value.`detail`, buf)+ FfiConverterBoolean.write(value.`permissionsNeeded`, buf)+ }+}+++/*** A change to this machine's Spaces settings (`None` keeps a value).*/@@ -28742,6 +28845,17 @@ data class HostStatus (* The owner's email, when the relay gave one.*/var `ownerEmail`: kotlin.String? = null+ ,+ /**+ * macOS: a Cua Spaces app that can run the host service is+ * installed, so the host service can run as it.+ */+ var `helperAvailable`: kotlin.Boolean = false+ ,+ /**+ * macOS: the old hand-written LaunchAgent is still there.+ */+ var `legacyService`: kotlin.Boolean = false){@@ -28786,6 +28900,8 @@ public object FfiConverterTypeHostStatus: FfiConverterRustBuffer<HostStatus> {FfiConverterBoolean.read(buf),FfiConverterOptionalString.read(buf),FfiConverterOptionalString.read(buf),+ FfiConverterBoolean.read(buf),+ FfiConverterBoolean.read(buf),)}@@ -28817,7 +28933,9 @@ public object FfiConverterTypeHostStatus: FfiConverterRustBuffer<HostStatus> {FfiConverterOptionalString.allocationSize(value.`spacesAuditError`) +FfiConverterBoolean.allocationSize(value.`pausedSignedOut`) +FfiConverterOptionalString.allocationSize(value.`owner`) +- FfiConverterOptionalString.allocationSize(value.`ownerEmail`)+ FfiConverterOptionalString.allocationSize(value.`ownerEmail`) ++ FfiConverterBoolean.allocationSize(value.`helperAvailable`) ++ FfiConverterBoolean.allocationSize(value.`legacyService`))override fun write(value: HostStatus, buf: ByteBuffer) {@@ -28849,6 +28967,8 @@ public object FfiConverterTypeHostStatus: FfiConverterRustBuffer<HostStatus> {FfiConverterBoolean.write(value.`pausedSignedOut`, buf)FfiConverterOptionalString.write(value.`owner`, buf)FfiConverterOptionalString.write(value.`ownerEmail`, buf)+ FfiConverterBoolean.write(value.`helperAvailable`, buf)+ FfiConverterBoolean.write(value.`legacyService`, buf)}}diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.pyindex 2c962bceff..69a43c82e0 100644--- a/libs/cua/python/src/cua/_native.py+++ b/libs/cua/python/src/cua/_native.py@@ -731,6 +731,8 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_host_configure() != 36828:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_sdk_checksum_method_host_migrate_service() != 36386:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_host_pause_signed_out() != 3338:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_host_remove() != 63746:@@ -2614,6 +2616,12 @@ _UniffiLib.uniffi_cua_sdk_fn_method_host_configure.argtypes = (_UniffiRustBuffer,)_UniffiLib.uniffi_cua_sdk_fn_method_host_configure.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_sdk_fn_method_host_migrate_service.argtypes = (+ ctypes.c_uint64,+ ctypes.c_int8,+ _UniffiRustBuffer,+)+_UniffiLib.uniffi_cua_sdk_fn_method_host_migrate_service.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_sdk_fn_method_host_pause_signed_out.argtypes = (ctypes.c_uint64,)@@ -4538,6 +4546,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_constructor_host_new.restype = ctypes.c_uint1_UniffiLib.uniffi_cua_sdk_checksum_method_host_configure.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_host_configure.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_sdk_checksum_method_host_migrate_service.argtypes = (+)+_UniffiLib.uniffi_cua_sdk_checksum_method_host_migrate_service.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_sdk_checksum_method_host_pause_signed_out.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_host_pause_signed_out.restype = ctypes.c_uint16@@ -12332,6 +12343,51 @@ class _UniffiFfiConverterTypeHostProvidedSpace(_UniffiConverterRustBuffer):_UniffiFfiConverterString.write(value.created_by, buf)_UniffiFfiConverterInt64.write(value.created_at_ms, buf)+@dataclass+class HostServiceMigration:+ """+ What [`Host::migrate_service`] did.+"""+ def __init__(self, *, outcome:str, detail:str, permissions_needed:bool):+ self.outcome = outcome+ self.detail = detail+ self.permissions_needed = permissions_needed+++++ def __str__(self):+ return "HostServiceMigration(outcome={}, detail={}, permissions_needed={})".format(self.outcome, self.detail, self.permissions_needed)+ def __eq__(self, other):+ if self.outcome != other.outcome:+ return False+ if self.detail != other.detail:+ return False+ if self.permissions_needed != other.permissions_needed:+ return False+ return True++class _UniffiFfiConverterTypeHostServiceMigration(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return HostServiceMigration(+ outcome=_UniffiFfiConverterString.read(buf),+ detail=_UniffiFfiConverterString.read(buf),+ permissions_needed=_UniffiFfiConverterBoolean.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.outcome)+ _UniffiFfiConverterString.check_lower(value.detail)+ _UniffiFfiConverterBoolean.check_lower(value.permissions_needed)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.outcome, buf)+ _UniffiFfiConverterString.write(value.detail, buf)+ _UniffiFfiConverterBoolean.write(value.permissions_needed, buf)+@dataclassclass HostSettingsChange:"""@@ -12646,7 +12702,7 @@ class HostStatus:"""Host status."""- def __init__(self, *, configured:bool, mode:typing.Optional[str], relay_url:typing.Optional[str], direct_url:typing.Optional[str], env_token_path:typing.Optional[str], machine_id:typing.Optional[str], name:typing.Optional[str], sharing:bool, service_installed:bool, service_running:bool, service_kind:str, online:typing.Optional[bool], clients:typing.List[RelayClientInfo], allow:typing.List[str], permissions:typing.List[HostPermission], error:typing.Optional[str], recent_access:typing.List[HostAccessRecord] = _DEFAULT, access_log_error:typing.Optional[str] = _DEFAULT, share_desktop:bool = True, provide_spaces:bool = False, max_spaces:int = 0, max_macos_vms:int = 0, provided_spaces:typing.List[HostProvidedSpace] = _DEFAULT, spaces_audit:typing.List[HostSpacesAuditRecord] = _DEFAULT, spaces_audit_error:typing.Optional[str] = _DEFAULT, paused_signed_out:bool = False, owner:typing.Optional[str] = _DEFAULT, owner_email:typing.Optional[str] = _DEFAULT):+ def __init__(self, *, configured:bool, mode:typing.Optional[str], relay_url:typing.Optional[str], direct_url:typing.Optional[str], env_token_path:typing.Optional[str], machine_id:typing.Optional[str], name:typing.Optional[str], sharing:bool, service_installed:bool, service_running:bool, service_kind:str, online:typing.Optional[bool], clients:typing.List[RelayClientInfo], allow:typing.List[str], permissions:typing.List[HostPermission], error:typing.Optional[str], recent_access:typing.List[HostAccessRecord] = _DEFAULT, access_log_error:typing.Optional[str] = _DEFAULT, share_desktop:bool = True, provide_spaces:bool = False, max_spaces:int = 0, max_macos_vms:int = 0, provided_spaces:typing.List[HostProvidedSpace] = _DEFAULT, spaces_audit:typing.List[HostSpacesAuditRecord] = _DEFAULT, spaces_audit_error:typing.Optional[str] = _DEFAULT, paused_signed_out:bool = False, owner:typing.Optional[str] = _DEFAULT, owner_email:typing.Optional[str] = _DEFAULT, helper_available:bool = False, legacy_service:bool = False):self.configured = configuredself.mode = modeself.relay_url = relay_url@@ -12696,12 +12752,14 @@ class HostStatus:self.owner_email = Noneelse:self.owner_email = owner_email+ self.helper_available = helper_available+ self.legacy_service = legacy_servicedef __str__(self):- return "HostStatus(configured={}, mode={}, relay_url={}, direct_url={}, env_token_path={}, machine_id={}, name={}, sharing={}, service_installed={}, service_running={}, service_kind={}, online={}, clients={}, allow={}, permissions={}, error={}, recent_access={}, access_log_error={}, share_desktop={}, provide_spaces={}, max_spaces={}, max_macos_vms={}, provided_spaces={}, spaces_audit={}, spaces_audit_error={}, paused_signed_out={}, owner={}, owner_email={})".format(self.configured, self.mode, self.relay_url, self.direct_url, self.env_token_path, self.machine_id, self.name, self.sharing, self.service_installed, self.service_running, self.service_kind, self.online, self.clients, self.allow, self.permissions, self.error, self.recent_access, self.access_log_error, self.share_desktop, self.provide_spaces, self.max_spaces, self.max_macos_vms, self.provided_spaces, self.spaces_audit, self.spaces_audit_error, self.paused_signed_out, self.owner, self.owner_email)+ return "HostStatus(configured={}, mode={}, relay_url={}, direct_url={}, env_token_path={}, machine_id={}, name={}, sharing={}, service_installed={}, service_running={}, service_kind={}, online={}, clients={}, allow={}, permissions={}, error={}, recent_access={}, access_log_error={}, share_desktop={}, provide_spaces={}, max_spaces={}, max_macos_vms={}, provided_spaces={}, spaces_audit={}, spaces_audit_error={}, paused_signed_out={}, owner={}, owner_email={}, helper_available={}, legacy_service={})".format(self.configured, self.mode, self.relay_url, self.direct_url, self.env_token_path, self.machine_id, self.name, self.sharing, self.service_installed, self.service_running, self.service_kind, self.online, self.clients, self.allow, self.permissions, self.error, self.recent_access, self.access_log_error, self.share_desktop, self.provide_spaces, self.max_spaces, self.max_macos_vms, self.provided_spaces, self.spaces_audit, self.spaces_audit_error, self.paused_signed_out, self.owner, self.owner_email, self.helper_available, self.legacy_service)def __eq__(self, other):if self.configured != other.configured:return False@@ -12759,6 +12817,10 @@ class HostStatus:return Falseif self.owner_email != other.owner_email:return False+ if self.helper_available != other.helper_available:+ return False+ if self.legacy_service != other.legacy_service:+ return Falsereturn Trueclass _UniffiFfiConverterTypeHostStatus(_UniffiConverterRustBuffer):@@ -12793,6 +12855,8 @@ class _UniffiFfiConverterTypeHostStatus(_UniffiConverterRustBuffer):paused_signed_out=_UniffiFfiConverterBoolean.read(buf),owner=_UniffiFfiConverterOptionalString.read(buf),owner_email=_UniffiFfiConverterOptionalString.read(buf),+ helper_available=_UniffiFfiConverterBoolean.read(buf),+ legacy_service=_UniffiFfiConverterBoolean.read(buf),)@staticmethod@@ -12825,6 +12889,8 @@ class _UniffiFfiConverterTypeHostStatus(_UniffiConverterRustBuffer):_UniffiFfiConverterBoolean.check_lower(value.paused_signed_out)_UniffiFfiConverterOptionalString.check_lower(value.owner)_UniffiFfiConverterOptionalString.check_lower(value.owner_email)+ _UniffiFfiConverterBoolean.check_lower(value.helper_available)+ _UniffiFfiConverterBoolean.check_lower(value.legacy_service)@staticmethoddef write(value, buf):@@ -12856,6 +12922,8 @@ class _UniffiFfiConverterTypeHostStatus(_UniffiConverterRustBuffer):_UniffiFfiConverterBoolean.write(value.paused_signed_out, buf)_UniffiFfiConverterOptionalString.write(value.owner, buf)_UniffiFfiConverterOptionalString.write(value.owner_email, buf)+ _UniffiFfiConverterBoolean.write(value.helper_available, buf)+ _UniffiFfiConverterBoolean.write(value.legacy_service, buf)@dataclassclass HttpHeader:@@ -34642,6 +34710,16 @@ class HostProtocol(typing.Protocol):Changes what this machine shares: its own desktop, and whether itcreates Spaces for your other devices (and their limits). Turningthe desktop on or off restarts the host service.+"""+ raise NotImplementedError+ async def migrate_service(self, force: bool,app_version: str) -> HostServiceMigration:+ """+ macOS: moves the host service from the old LaunchAgent to the Cua+ Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ registration, id and Spaces; puts the old one back if the helper+ does not take over (the outcome says so). `app_version`: a failed+ move is not tried again by itself with the same version; `force`+ tries anyway."""raise NotImplementedErrorasync def pause_signed_out(self, ) -> HostStatus:@@ -34755,6 +34833,34 @@ class Host(HostProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def migrate_service(self, force: bool,app_version: str) -> HostServiceMigration:+ """+ macOS: moves the host service from the old LaunchAgent to the Cua+ Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ registration, id and Spaces; puts the old one back if the helper+ does not take over (the outcome says so). `app_version`: a failed+ move is not tried again by itself with the same version; `force`+ tries anyway.+"""++ _UniffiFfiConverterBoolean.check_lower(force)++ _UniffiFfiConverterString.check_lower(app_version)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ _UniffiFfiConverterBoolean.lower(force),+ _UniffiFfiConverterString.lower(app_version),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeHostServiceMigration.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_sdk_fn_method_host_migrate_service(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )async def pause_signed_out(self, ) -> HostStatus:"""Pause relay sharing while nobody is signed in to the owner's@@ -36325,6 +36431,7 @@ __all__ = ["HostAccessRecord","HostPermission","HostProvidedSpace",+ "HostServiceMigration","HostSettingsChange","HostSetupOptions","HostSpacesAuditRecord",diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swiftindex a99843b170..2526b494f3 100644--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift@@ -3466,6 +3466,16 @@ public protocol HostProtocol: AnyObject, Sendable {*/func configure(change: HostSettingsChange) async throws -> HostStatus+ /**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+ func migrateService(force: Bool, appVersion: String) async throws -> HostServiceMigration+/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -3596,6 +3606,31 @@ open func configure(change: HostSettingsChange)async throws -> HostStatus {)}+ /**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+open func migrateService(force: Bool, appVersion: String)async throws -> HostServiceMigration {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cua_sdk_fn_method_host_migrate_service(+ self.uniffiCloneHandle(),+ FfiConverterBool.lower(force),FfiConverterString.lower(appVersion)+ )+ },+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,+ liftFunc: FfiConverterTypeHostServiceMigration_lift,+ errorHandler: FfiConverterTypeCuaError_lift+ )+}+/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -20904,6 +20939,89 @@ public func FfiConverterTypeHostProvidedSpace_lower(_ value: HostProvidedSpace)}+/**+ * What [`Host::migrate_service`] did.+ */+public struct HostServiceMigration: Equatable, Hashable {+ /**+ * `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or+ * `not-needed`.+ */+ public var outcome: String+ /**+ * In words.+ */+ public var detail: String+ /**+ * macOS will ask for Screen Recording and Accessibility for Cua Spaces+ * Helper.+ */+ public var permissionsNeeded: Bool++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or+ * `not-needed`.+ */outcome: String,+ /**+ * In words.+ */detail: String,+ /**+ * macOS will ask for Screen Recording and Accessibility for Cua Spaces+ * Helper.+ */permissionsNeeded: Bool) {+ self.outcome = outcome+ self.detail = detail+ self.permissionsNeeded = permissionsNeeded+ }+++++}++#if compiler(>=6)+extension HostServiceMigration: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeHostServiceMigration: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> HostServiceMigration {+ return+ try HostServiceMigration(+ outcome: FfiConverterString.read(from: &buf),+ detail: FfiConverterString.read(from: &buf),+ permissionsNeeded: FfiConverterBool.read(from: &buf)+ )+ }++ public static func write(_ value: HostServiceMigration, into buf: inout [UInt8]) {+ FfiConverterString.write(value.outcome, into: &buf)+ FfiConverterString.write(value.detail, into: &buf)+ FfiConverterBool.write(value.permissionsNeeded, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeHostServiceMigration_lift(_ buf: RustBuffer) throws -> HostServiceMigration {+ return try FfiConverterTypeHostServiceMigration.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeHostServiceMigration_lower(_ value: HostServiceMigration) -> RustBuffer {+ return FfiConverterTypeHostServiceMigration.lower(value)+}++/*** A change to this machine's Spaces settings (`None` keeps a value).*/@@ -21366,6 +21484,15 @@ public struct HostStatus: Equatable, Hashable {* The owner's email, when the relay gave one.*/public var ownerEmail: String?+ /**+ * macOS: a Cua Spaces app that can run the host service is+ * installed, so the host service can run as it.+ */+ public var helperAvailable: Bool+ /**+ * macOS: the old hand-written LaunchAgent is still there.+ */+ public var legacyService: Bool// Default memberwise initializers are never public by default, so we// declare one manually.@@ -21455,7 +21582,14 @@ public struct HostStatus: Equatable, Hashable {*/owner: String? = nil,/*** The owner's email, when the relay gave one.- */ownerEmail: String? = nil) {+ */ownerEmail: String? = nil,+ /**+ * macOS: a Cua Spaces app that can run the host service is+ * installed, so the host service can run as it.+ */helperAvailable: Bool = false,+ /**+ * macOS: the old hand-written LaunchAgent is still there.+ */legacyService: Bool = false) {self.configured = configuredself.mode = modeself.relayUrl = relayUrl@@ -21484,6 +21618,8 @@ public struct HostStatus: Equatable, Hashable {self.pausedSignedOut = pausedSignedOutself.owner = ownerself.ownerEmail = ownerEmail+ self.helperAvailable = helperAvailable+ self.legacyService = legacyService}@@ -21529,7 +21665,9 @@ public struct FfiConverterTypeHostStatus: FfiConverterRustBuffer {spacesAuditError: FfiConverterOptionString.read(from: &buf),pausedSignedOut: FfiConverterBool.read(from: &buf),owner: FfiConverterOptionString.read(from: &buf),- ownerEmail: FfiConverterOptionString.read(from: &buf)+ ownerEmail: FfiConverterOptionString.read(from: &buf),+ helperAvailable: FfiConverterBool.read(from: &buf),+ legacyService: FfiConverterBool.read(from: &buf))}@@ -21562,6 +21700,8 @@ public struct FfiConverterTypeHostStatus: FfiConverterRustBuffer {FfiConverterBool.write(value.pausedSignedOut, into: &buf)FfiConverterOptionString.write(value.owner, into: &buf)FfiConverterOptionString.write(value.ownerEmail, into: &buf)+ FfiConverterBool.write(value.helperAvailable, into: &buf)+ FfiConverterBool.write(value.legacyService, into: &buf)}}@@ -39076,6 +39216,9 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_method_host_configure() != 36828) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_sdk_checksum_method_host_migrate_service() != 36386) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_sdk_checksum_method_host_pause_signed_out() != 3338) {return InitializationResult.apiChecksumMismatch}diff --git a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.hindex 09ddf4ad52..e24a7140dd 100644--- a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h+++ b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h@@ -777,6 +777,11 @@ uint64_t uniffi_cua_sdk_fn_constructor_host_new(RustBuffer cua_home, RustCallStauint64_t uniffi_cua_sdk_fn_method_host_configure(uint64_t ptr, RustBuffer change);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_HOST_MIGRATE_SERVICE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_HOST_MIGRATE_SERVICE+uint64_t uniffi_cua_sdk_fn_method_host_migrate_service(uint64_t ptr, int8_t force, RustBuffer app_version+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_HOST_PAUSE_SIGNED_OUT#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_HOST_PAUSE_SIGNED_OUTuint64_t uniffi_cua_sdk_fn_method_host_pause_signed_out(uint64_t ptr@@ -3747,6 +3752,12 @@ uint16_t uniffi_cua_sdk_checksum_method_devices_snapshot(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_HOST_CONFIGUREuint16_t uniffi_cua_sdk_checksum_method_host_configure(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_HOST_MIGRATE_SERVICE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_HOST_MIGRATE_SERVICE+uint16_t uniffi_cua_sdk_checksum_method_host_migrate_service(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_HOST_PAUSE_SIGNED_OUTdiff --git a/libs/cua/typescript/src/native/cua_sdk-ffi.ts b/libs/cua/typescript/src/native/cua_sdk-ffi.tsindex 233acfb436..f1db822d00 100644--- a/libs/cua/typescript/src/native/cua_sdk-ffi.ts+++ b/libs/cua/typescript/src/native/cua_sdk-ffi.ts@@ -1228,6 +1228,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_host_migrate_service": {+ args: [FfiType.Handle, FfiType.Int8, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_host_pause_signed_out": {args: [FfiType.Handle],ret: FfiType.Handle,@@ -3318,6 +3323,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_host_migrate_service": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_host_pause_signed_out": {args: [],ret: FfiType.UInt16,@@ -5148,6 +5158,7 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_method_guestdisplay_via(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_constructor_host_new(cuaHome: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_sdk_fn_method_host_configure(uniffiSelf: bigint, change: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_host_migrate_service(uniffiSelf: bigint, force: number, appVersion: Uint8Array): bigint;uniffi_cua_sdk_fn_method_host_pause_signed_out(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_host_remove(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_host_resume_signed_in(uniffiSelf: bigint, account: Uint8Array): bigint;@@ -5566,6 +5577,7 @@ interface NativeModuleInterface {uniffi_cua_sdk_checksum_method_guestdisplay_via(): number;uniffi_cua_sdk_checksum_constructor_host_new(): number;uniffi_cua_sdk_checksum_method_host_configure(): number;+ uniffi_cua_sdk_checksum_method_host_migrate_service(): number;uniffi_cua_sdk_checksum_method_host_pause_signed_out(): number;uniffi_cua_sdk_checksum_method_host_remove(): number;uniffi_cua_sdk_checksum_method_host_resume_signed_in(): number;diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.tsindex d65e250155..33b064dc77 100644--- a/libs/cua/typescript/src/native/cua_sdk.ts+++ b/libs/cua/typescript/src/native/cua_sdk.ts@@ -7697,6 +7697,67 @@ const FfiConverterTypeHostProvidedSpace = (() => {return new FFIConverter();})();+/**+ * What [`Host::migrate_service`] did.+ */+export type HostServiceMigration = {+ /**+ * `migrated`, `switched`, `cleaned-up`, `rolled-back`, `kept` or+ * `not-needed`.+ */+ outcome: string,+ /**+ * In words.+ */+ detail: string,+ /**+ * macOS will ask for Screen Recording and Accessibility for Cua Spaces+ * Helper.+ */+ permissionsNeeded: boolean+}++/**+ * Generated factory for {@link HostServiceMigration} record objects.+ */+export const HostServiceMigration = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<HostServiceMigration, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<HostServiceMigration>,+ });+})();++const FfiConverterTypeHostServiceMigration = (() => {+ type TypeName = HostServiceMigration;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ outcome: FfiConverterString.read(from),+ detail: FfiConverterString.read(from),+ permissionsNeeded: FfiConverterBool.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.outcome, into);+ FfiConverterString.write(value.detail, into);+ FfiConverterBool.write(value.permissionsNeeded, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.outcome) ++ FfiConverterString.allocationSize(value.detail) ++ FfiConverterBool.allocationSize(value.permissionsNeeded);++ }+ };+ return new FFIConverter();+})();+/*** A change to this machine's Spaces settings (`None` keeps a value).*/@@ -8072,7 +8133,16 @@ export type HostStatus = {/*** The owner's email, when the relay gave one.*/- ownerEmail?: string+ ownerEmail?: string,+ /**+ * macOS: a Cua Spaces app that can run the host service is+ * installed, so the host service can run as it.+ */+ helperAvailable: boolean,+ /**+ * macOS: the old hand-written LaunchAgent is still there.+ */+ legacyService: boolean}/**@@ -8091,7 +8161,9 @@ export const HostStatus = (() => {spacesAuditError: undefined,pausedSignedOut: false,owner: undefined,- ownerEmail: undefined+ ownerEmail: undefined,+ helperAvailable: false,+ legacyService: false});const create = (() => {return uniffiCreateRecord<HostStatus, ReturnType<typeof defaults>>(defaults);@@ -8135,7 +8207,9 @@ const FfiConverterTypeHostStatus = (() => {spacesAuditError: FfiConverterOptionalString.read(from),pausedSignedOut: FfiConverterBool.read(from),owner: FfiConverterOptionalString.read(from),- ownerEmail: FfiConverterOptionalString.read(from)+ ownerEmail: FfiConverterOptionalString.read(from),+ helperAvailable: FfiConverterBool.read(from),+ legacyService: FfiConverterBool.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -8167,6 +8241,8 @@ const FfiConverterTypeHostStatus = (() => {FfiConverterBool.write(value.pausedSignedOut, into);FfiConverterOptionalString.write(value.owner, into);FfiConverterOptionalString.write(value.ownerEmail, into);+ FfiConverterBool.write(value.helperAvailable, into);+ FfiConverterBool.write(value.legacyService, into);}allocationSize(value: TypeName): number {return FfiConverterBool.allocationSize(value.configured) +@@ -8196,7 +8272,9 @@ const FfiConverterTypeHostStatus = (() => {FfiConverterOptionalString.allocationSize(value.spacesAuditError) +FfiConverterBool.allocationSize(value.pausedSignedOut) +FfiConverterOptionalString.allocationSize(value.owner) +- FfiConverterOptionalString.allocationSize(value.ownerEmail);+ FfiConverterOptionalString.allocationSize(value.ownerEmail) ++ FfiConverterBool.allocationSize(value.helperAvailable) ++ FfiConverterBool.allocationSize(value.legacyService);}};@@ -34185,6 +34263,15 @@ export interface HostLike {* the desktop on or off restarts the host service.*/configure(change: HostSettingsChange, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HostStatus>;+/**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+ migrateService(force: boolean, appVersion: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HostServiceMigration>;/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -34291,6 +34378,46 @@ export class Host extends UniffiAbstractObject implements HostLike {}}+/**+ * macOS: moves the host service from the old LaunchAgent to the Cua+ * Spaces app (its own login item, "Cua Spaces"), keeping this machine's+ * registration, id and Spaces; puts the old one back if the helper+ * does not take over (the outcome says so). `app_version`: a failed+ * move is not tried again by itself with the same version; `force`+ * tries anyway.+ */+ async migrateService(force: boolean, appVersion: string, asyncOpts_?: { signal: AbortSignal }): Promise<HostServiceMigration> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_host_migrate_service(+ uniffiTypeHostObjectFactory.clonePointer(this),FfiConverterBool.lower(force, nativeModule().rustbuffer_alloc),FfiConverterString.lower(appVersion, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeHostServiceMigration.lift.bind(FfiConverterTypeHostServiceMigration),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** Pause relay sharing while nobody is signed in to the owner's* account: the host leaves the relay and stays off it (also across a@@ -35734,6 +35861,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_host_configure() !== 36828) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_host_configure");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_host_migrate_service() !== 36386) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_host_migrate_service");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_host_pause_signed_out() !== 3338) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_host_pause_signed_out");}@@ -36714,6 +36844,7 @@ export default Object.freeze({FfiConverterTypeHostAccessRecord,FfiConverterTypeHostPermission,FfiConverterTypeHostProvidedSpace,+ FfiConverterTypeHostServiceMigration,FfiConverterTypeHostSettingsChange,FfiConverterTypeHostSetupOptions,FfiConverterTypeHostSpacesAuditRecord,diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex 9a777fab60..ce59c737b8 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -9299,7 +9299,7 @@"aliases": [],"default_value": "auto","env": null,- "help": "auto | systemd | launchd | windows-task | process",+ "help": "auto | systemd | launchd | app-helper | windows-task | process. On a Mac with the Cua Spaces app, auto is app-helper: the service runs as the app's own login item (\"Cua Spaces\")","hidden": false,"is_optional": true,"multiple_values": false,@@ -9728,6 +9728,32 @@"subcommands": [],"usage": "cua host unshare [OPTIONS] <WHO>..."},+ {+ "abstract": "macOS: move the host service into the Cua Spaces app, as its \"Cua Spaces Helper\" login item, from the LaunchAgent that older versions installed. This machine keeps its id, registration and Spaces; if the helper does not take over, the old service is put back. macOS then asks once for Screen Recording and Accessibility for Cua Spaces Helper",+ "after_help": "Examples:\n cua host migrate\n # Try again after a move that was rolled back\n cua host migrate --force",+ "aliases": [],+ "arguments": [],+ "flags": [+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "Try again even if a move failed before with this version",+ "hidden": false,+ "name": "force",+ "repeatable": false,+ "short_name": null,+ "takes_value": false+ }+ ],+ "hidden": false,+ "hidden_aliases": [],+ "name": "migrate",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua host migrate [OPTIONS]"+ },{"abstract": "Unregister from the relay, uninstall the service and delete the host configuration (asks first)","after_help": "Examples:\n cua host remove\n # Without the prompt (required in scripts and agents)\n cua host remove --force",diff --git a/scripts/install/tests/test_uninstall.py b/scripts/install/tests/test_uninstall.pyindex 933835ae31..ce2cb12eb9 100644--- a/scripts/install/tests/test_uninstall.py+++ b/scripts/install/tests/test_uninstall.py@@ -290,6 +290,31 @@ class UninstallMacTest(unittest.TestCase):self.assertEqual(indexes, sorted(indexes))self.assertGreaterEqual(box.index("launchctl: bootout"), 0)+ def test_the_app_helper_goes_but_its_permissions_stay(self):+ box = self.box()+ installed_mac(box)+ # Cua Spaces 0.10+: the host service is the app's login item.+ box.put("Applications/Cua Spaces.app/Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist", "plist\n")+ write_executable(box.home / "Applications/Cua Spaces.app/Contents/MacOS/CuaSpacesMac",+ "#!/bin/sh\nprintf 'app: %s\\n' \"$*\" >>\"$FAKE_CALLS\"\n")+ box.put(".cua/helper/service.json", "{}\n")+ dry = box.run("--dry-run")+ self.assertEqual(dry.returncode, 0, dry.stdout + dry.stderr)+ self.assertIn("--service-helper unregister", dry.stdout)+ self.assertNotIn("tccutil", dry.stdout)+ self.assertEqual(box.index("tccutil"), -1)+ self.assertTrue(box.exists(".cua/helper/service.json"))+ result = box.run("--yes", "--prefix", str(box.home))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ # Unregistered by the app before the app goes, then stopped.+ self.assertGreaterEqual(box.index("app: --service-helper unregister"), 0)+ self.assertGreaterEqual(box.index("launchctl: bootout gui/1000/com.trycua.spaces.helper"), 0)+ self.assertEqual(box.index("tccutil"), -1)+ self.assertIn("minus button", result.stdout)+ for gone in (".cua/helper", "Applications/Cua Spaces.app",+ "Library/LaunchAgents/com.trycua.spacesd.host.plist", ".cua/host/bin/cua-spacesd"):+ self.assertFalse(box.exists(gone), gone)+def test_keep_data_keeps_the_cua_home_but_still_signs_out(self):box = self.box()installed_mac(box)diff --git a/scripts/install/uninstall.sh b/scripts/install/uninstall.shindex 03c9caea2a..7fa1eab208 100755--- a/scripts/install/uninstall.sh+++ b/scripts/install/uninstall.sh@@ -343,7 +343,7 @@ host_service_files() {case "$os" indarwin)printf '%s\n' "$HOME/Library/LaunchAgents/com.trycua.spacesd.host.plist" \- "$HOME/Library/LaunchAgents/com.trycua.env-driver.host.plist"+ "$HOME/Library/LaunchAgents/com.trycua.env-driver.host.plist" "$HOME/.cua/helper/service.json";;linux)printf '%s\n' "$config_home/systemd/user/cua-spacesd-host.service" \@@ -580,6 +580,8 @@ $(cua_homes)EOFcase "$os" indarwin)+ old_agent=0+ [ -f "$HOME/Library/LaunchAgents/com.trycua.spacesd.host.plist" ] && old_agent=1for label in com.trycua.spacesd.host com.trycua.env-driver.host; doplist="$HOME/Library/LaunchAgents/$label.plist"[ -f "$plist" ] || continue@@ -590,6 +592,33 @@ EOFfirm_path "$plist"done+ # The Cua Spaces app's own host service (the app's executable as its+ # login item, since 0.10): `cua host remove` above unregisters it when+ # it can; this covers an app whose cua could not run. What it ran+ # (~/.cua/helper) goes too.+ while IFS= read -r app; do+ [ -n "$app" ] || continue+ [ -f "$app/Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist" ] || continue+ [ -x "$app/Contents/MacOS/CuaSpacesMac" ] || continue+ if [ "$dry_run" = 1 ]; then+ say "[dry-run] $app/Contents/MacOS/CuaSpacesMac --service-helper unregister"+ else+ bounded 30 "$app/Contents/MacOS/CuaSpacesMac" --service-helper unregister >/dev/null 2>&1 || true+ fi+ done <<EOF+$(app_candidates)+EOF+ if [ "$dry_run" = 1 ]; then+ say "[dry-run] launchctl bootout gui/$(id -u)/com.trycua.spaces.helper"+ else+ launchctl bootout "gui/$(id -u)/com.trycua.spaces.helper" >/dev/null 2>&1 || true+ fi+ rm_path "$HOME/.cua/helper"+ # The privacy permissions macOS keeps for the app stay: an uninstall+ # never revokes them (see the driver uninstaller, 18 Oct 2026).+ if [ "$old_agent" = 1 ]; then+ info "System Settings may still list \"cua-spacesd\" under Privacy & Security (Screen Recording, Accessibility); select it and click the minus button to remove it"+ fi;;linux)for unit in cua-spacesd-host cua-env-driver-host; do