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): host setup that just works, your other Mac in Run on, and a built-in Lume (#4489)
ddupont5748bc5637b0
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swiftindex e1f63515f5..21507760a2 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift@@ -139,7 +139,7 @@ public final class AppModel {defaultLocation: settings.defaultLocation, cloudAvailable: false,localAvailable: true, localReason: nil, localBackends: nil, localDetails: nil,maxCpus: UInt32(max(2, min(16, ProcessInfo.processInfo.activeProcessorCount))),- hostArch: Self.hostArch, storage: nil, cloudPricing: nil, clouds: [], hosts: [],+ hostArch: Self.hostArch, lumeSource: nil, storage: nil, cloudPricing: nil, clouds: [], hosts: [],experiments: settings.experiments, gpus: nil))self.notch = NotchModel()// The notch tiles and the preview cover read one thumbnail store,@@ -382,6 +382,7 @@ public final class AppModel {async let gpusProbe = backend.gpuChoices()async let hostsProbe = backend.hosts()let cloud = await backend.cloudAvailable()+ lumeSource = await backend.lumeSource()await self.cloud.refresh()let (runtimes, storage, pricing, gpus) = await (runtimesProbe, storageProbe, pricingProbe, gpusProbe)hosts = await hostsProbe@@ -401,6 +402,30 @@ public final class AppModel {/// Your machines that provide Spaces, as New Space last read them.var hosts: [AppSpaceHost] = []+ /// Which Lume macOS Spaces run on (`runtime.lume`), once read.+ public private(set) var lumeSource: String?++ /// New Space's "Use built-in Lume": switches `runtime.lume`, then the+ /// open wizard reads the runtimes again (This Mac can run it now).+ public func applyRuntimeSwitch(_ change: AppRuntimeSwitch) async {+ do {+ try await backend.setLumeSource(change.value)+ } catch {+ show(error: LiveSpacesBackend.words(error))+ return+ }+ lumeSource = await backend.lumeSource() ?? change.value+ let runtimes = await backend.localRuntimes()+ var e = wizard.env+ let backends = runtimes?.ready+ e.localAvailable = backends.map { !$0.isEmpty } ?? true+ e.localReason = backends?.isEmpty == true ? "No local runtime found (Docker or Lume)." : nil+ e.localBackends = backends+ e.localDetails = runtimes?.details+ e.lumeSource = lumeSource+ wizard.update(env: e)+ }+private func wizardEnv(from e: AppWizardEnv) -> AppWizardEnv {var e = ee.clouds = cloud.clouds@@ -419,7 +444,7 @@ public final class AppModel {localAvailable: backends.map { !$0.isEmpty } ?? true,localReason: backends?.isEmpty == true ? "No local runtime found (Docker or Lume)." : nil,localBackends: backends, localDetails: runtimes?.details, maxCpus: wizard.env.maxCpus,- hostArch: Self.hostArch, storage: storage.map(Self.wizardStorage),+ hostArch: Self.hostArch, lumeSource: lumeSource, storage: storage.map(Self.wizardStorage),cloudPricing: available ? pricing : nil, clouds: [], hosts: [],experiments: settings.experiments, gpus: gpus))}@@ -656,7 +681,7 @@ public final class AppModel {experiments: settings.experiments, keyvaultAutoWipe: keyvault.autoWipe,keyvaultUnlockPrompt: keyvault.unlockPromptShows,keyvaultSiteIcons: settings.keyvaultSiteIcons, keyvaultProtection: keyvault.page.protection,- autoConnect: settings.autoConnect))+ autoConnect: settings.autoConnect, lumeSource: lumeSource))}/// Settings, General with Settings, Storage after General while the Cua@@ -748,6 +773,7 @@ public final class AppModel {/// Reads what Settings shows (telemetry, the coding agents).public func loadSettings() async {+ lumeSource = await backend.lumeSource()telemetryInput = telemetry?.status()readLoginItem()await storage.load()@@ -791,6 +817,13 @@ public final class AppModel {case "notch":settings.menuBar = option == "hide"saveSettings()+ case "macos-runtime":+ do {+ try await backend.setLumeSource(option)+ lumeSource = await backend.lumeSource() ?? option+ } catch {+ show(error: LiveSpacesBackend.words(error))+ }case "default-location":settings.defaultLocation = option == "cloud" ? .cloud : .localsaveSettings()diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swiftindex 7d46ce9558..bd0cbd8286 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift@@ -28,6 +28,8 @@ public final class FixtureHost: HostRunning, @unchecked Sendable {public private(set) var current: HostStatuspublic private(set) var calls: [String] = []public var failSetup: String?+ /// The next `configure` fails with this (once).+ public var failConfigure: String?public init(status: HostStatus? = nil) {current = status ?? FixtureHost.unconfigured@@ -68,6 +70,10 @@ public final class FixtureHost: HostRunning, @unchecked Sendable {public func configure(change: HostSettingsChange) async throws -> HostStatus {calls.append("configure:\(change.shareDesktop.map { "\($0)" } ?? "-"):\(change.provideSpaces.map { "\($0)" } ?? "-")")+ if let failConfigure {+ self.failConfigure = nil+ throw CuaError.Runtime(message: failConfigure)+ }if let d = change.shareDesktop { current.shareDesktop = d }if let p = change.provideSpaces { current.provideSpaces = p }return current@@ -104,6 +110,11 @@ public final class HostModel {public private(set) var form: AppHostFormState?public private(set) var busy = falsepublic private(set) var error: String?+ /// The last page button that failed (a setting, Stop sharing, ...), in+ /// plain words with Retry; cleared when any button succeeds.+ public private(set) var actionFailure: HostSetupFailure?+ /// What Retry runs again.+ private var failedAction: AppHostActionId?/// The last "Set up for access" failure, in plain words with the raw/// error as details. It stays while a retry runs (so Retry can show/// progress) and clears when setup succeeds or the form closes.@@ -266,22 +277,39 @@ public final class HostModel {error = nildefer { busy = false }do {- // The two settings: the core says what each switch changes.- if let change = appHostSettingChange(id: id) {- apply(try await host.configure(change: HostSettingsChange(- shareDesktop: change.shareDesktop, provideSpaces: change.provideSpaces)))- return- }- switch id {- case .stopSharing: apply(try await host.stopSharing())- case .resumeSharing: apply(try await host.startSharing())- case .remove:- try await host.remove()- apply(try await host.status())- case .setUp, .shareDesktop, .hideDesktop, .provideSpaces, .stopProvidingSpaces: break- }+ try await perform(id, on: host)+ actionFailure = nil+ failedAction = nil} catch {- self.error = LiveSpacesBackend.words(error)+ let raw = LiveSpacesBackend.words(error)+ actionFailure = HostSetupFailure.presenting(raw)+ failedAction = id+ // The page shows what the failure left behind (a stopped+ // service is offline), not the state before the button.+ await refresh()+ }+ }++ /// Runs the failed button again.+ public func retryFailedAction() async {+ guard let id = failedAction else { return }+ await run(id)+ }++ private func perform(_ id: AppHostActionId, on host: HostRunning) async throws {+ // The two settings: the core says what each switch changes.+ if let change = appHostSettingChange(id: id) {+ apply(try await host.configure(change: HostSettingsChange(+ shareDesktop: change.shareDesktop, provideSpaces: change.provideSpaces)))+ return+ }+ switch id {+ case .stopSharing: apply(try await host.stopSharing())+ case .resumeSharing: apply(try await host.startSharing())+ case .remove:+ try await host.remove()+ apply(try await host.status())+ case .setUp, .shareDesktop, .hideDesktop, .provideSpaces, .stopProvidingSpaces: break}}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swiftindex 66142ad6c8..d813cb69ca 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift@@ -16,6 +16,8 @@ public struct HostSetupFailure: Equatable, Sendable {case guiSession/// The Cua account is signed out or its session expired.case signedOut+ /// macOS did not start the host service (launchd).+ case servicecase other}@@ -70,6 +72,8 @@ public struct HostSetupFailure: Equatable, Sendable {if any(["aqua", "no gui session", "gui session", "not logged in at the console", "console user","no console"]) { return .guiSession }+ if any(["launchctl", "launchd", "host service", "bootstrap failed"]) { return .service }+if word("401") || any(["signed out", "not signed in", "sign in again", "please sign in", "unauthenticated", "unauthorized","login required", "not logged in", "session expired", "token expired", "invalid token",@@ -96,6 +100,10 @@ public struct HostSetupFailure: Equatable, Sendable {case .signedOut:return ("Sign in to Cua","Your Cua account isn\u{2019}t signed in on this Mac. Sign in, then try again.")+ case .service:+ return ("Couldn\u{2019}t start the Cua host service",+ "macOS didn\u{2019}t start the service your other devices connect to. Try again; "+ + "if it keeps failing, restart this Mac.")case .other:return ("Couldn\u{2019}t set up this Mac for access","Something went wrong. Try again, or open Details to see what happened.")diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swiftindex cb9286460b..aa5c0de010 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift@@ -44,6 +44,11 @@ public protocol SpacesBackend: AnyObject, Sendable {/// The local runtime doctor, when known: the ready backends and, for/// each one that is not, why (the check's detail).func localRuntimes() async -> (ready: [String], details: [String: String])?+ /// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ /// `system`), when known.+ func lumeSource() async -> String?+ /// Sets `runtime.lume`.+ func setLumeSource(_ value: String) async throws/// Free space where local Spaces are written and which images are/// pulled (`local().storage()`), when known.func localStorage() async -> LocalStorage?@@ -96,6 +101,8 @@ public extension SpacesBackend {func shares(id: String) async throws -> [AppShareEntryInput] { [] }func share(id: String, who: String, role: String) async throws -> [AppShareEntryInput] { [] }func unshare(id: String, who: String) async throws -> [AppShareEntryInput] { [] }+ func lumeSource() async -> String? { nil }+ func setLumeSource(_ value: String) async throws {}}/// The wizard's GPU choices from the SDK's `gpu_support`: the first option@@ -266,12 +273,24 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {try await cua.local().doctor()}guard case .success(let report) = result else { return nil }- let ready = report.checks.filter { $0.status == .ok }.map { $0.name.lowercased() }+ // Lume counts as ready when cua sets it up by itself on the first+ // macOS create (the built-in Lume): nothing for the person to do.+ let ready = report.checks+ .filter { $0.status == .ok || ($0.status == .installable && $0.name.lowercased() == "lume") }+ .map { $0.name.lowercased() }var details: [String: String] = [:]for check in report.checks where check.status != .ok { details[check.name.lowercased()] = check.detail }return (ready: ready, details: details)}+ public func lumeSource() async -> String? {+ (try? configGet(key: "runtime.lume"))?.value+ }++ public func setLumeSource(_ value: String) async throws {+ _ = try configSet(key: "runtime.lume", value: value)+ }+public func localStorage() async -> LocalStorage? {let result = await withTimeout(seconds: Self.probeSeconds) { [cua] intry await cua.local().storage()@@ -679,6 +698,13 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {/// The fixture Mac's ready local runtimes.public var fixtureBackends: [String] = ["docker"]+ /// The fixture account's other machines that provide Spaces.+ public var fixtureHosts: [AppSpaceHost] = []+ public func hosts() async -> [AppSpaceHost] { await MainActor.run { fixtureHosts } }+ /// The fixture Mac's `runtime.lume`.+ public var fixtureLumeSource: String? = "auto"+ public func lumeSource() async -> String? { await MainActor.run { fixtureLumeSource } }+ public func setLumeSource(_ value: String) async throws { await MainActor.run { fixtureLumeSource = value } }public func localBackends() async -> [String]? { await MainActor.run { fixtureBackends } }/// The fixture Mac's free space and pulled images (none: the wizard/// shows no room lines).diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swiftindex 24fe2490a0..e36181ace5 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift@@ -44,7 +44,8 @@ public struct MainWindow: View {try await model.addByAddress(url: url, token: token, name: name)},onCancel: { model.cancelNewSpace() },- cloud: model.cloud)+ cloud: model.cloud,+ onRuntimeSwitch: { await model.applyRuntimeSwitch($0) })}.sheet(item: approvalBinding) { _ inApprovalSheet(keyvault: model.keyvault)diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/NewSpaceWizardView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/NewSpaceWizardView.swiftindex f4dd86b280..0679e33bd9 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/NewSpaceWizardView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/NewSpaceWizardView.swift@@ -15,15 +15,20 @@ public struct NewSpaceWizardView: View {let onCancel: () -> Void/// "Connect a cloud": the sheet it opens (nil: the link does not show).let cloud: CloudModel?+ /// "Use built-in Lume" (the core's `runtimeSwitch`).+ let onRuntimeSwitch: ((AppRuntimeSwitch) async -> Void)?+ @State private var switchingRuntime = falsepublic init(wizard: WizardModel, onCreate: @escaping (AppCreatePlan) -> Void,onAdd: @escaping (String, String?, String?) async throws -> Void,- onCancel: @escaping () -> Void, cloud: CloudModel? = nil) {+ onCancel: @escaping () -> Void, cloud: CloudModel? = nil,+ onRuntimeSwitch: ((AppRuntimeSwitch) async -> Void)? = nil) {self.wizard = wizardself.onCreate = onCreateself.onAdd = onAddself.onCancel = onCancelself.cloud = cloud+ self.onRuntimeSwitch = onRuntimeSwitch}public var body: some View {@@ -116,18 +121,53 @@ public struct NewSpaceWizardView: View {Picker(field.label, selection: Binding(get: { v.placementId },set: { wizard.send(.choosePlacement(on: $0)) })) {- ForEach(Array(v.placements.enumerated()), id: \.element.id) { index, option in- if index > 0, v.placements[index - 1].group != option.group { Divider() }- Text(option.label)- .tag(option.id)- .selectionDisabled(!option.enabled)- .help(option.detail)+ // A Section per group draws the separators: a Divider among+ // the items shifts the menu's indices, so a machine of yours+ // chosen showed an empty "Run on".+ ForEach(Self.groups(v.placements), id: \.self) { group in+ Section {+ ForEach(v.placements.filter { $0.group == group }, id: \.id) { option in+ Text(option.label)+ .tag(option.id)+ .selectionDisabled(!option.enabled)+ .help(option.detail)+ }+ }}}.pickerStyle(.menu).accessibilityIdentifier("wizard-run-on")if let error = field.error {- Text(error).foregroundStyle(.red).font(.callout)+ HStack(alignment: .firstTextBaseline) {+ Text(error).foregroundStyle(.red).font(.callout)+ Spacer(minLength: 8)+ if let change = v.runtimeSwitch, let onRuntimeSwitch {+ Button {+ switchingRuntime = true+ Task {+ await onRuntimeSwitch(change)+ switchingRuntime = false+ }+ } label: {+ HStack(spacing: 6) {+ if switchingRuntime { ProgressView().controlSize(.small) }+ Text(change.label)+ }+ }+ .controlSize(.small)+ .disabled(switchingRuntime)+ .help(change.detail)+ .accessibilityIdentifier("wizard-runtime-switch")+ }+ }+ }+ if let hint = v.placementHint {+ // How another Mac of yours shows up here.+ Text(hint)+ .font(.callout)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityIdentifier("wizard-other-mac-hint")}case "kind":Picker(field.label, selection: Binding(@@ -160,6 +200,13 @@ public struct NewSpaceWizardView: View {}}+ /// The menu's groups, in order.+ static func groups(_ options: [AppPlacementOption]) -> [String] {+ options.reduce(into: [String]()) { out, o in+ if !out.contains(o.group) { out.append(o.group) }+ }+ }+private func field(_ v: AppWizardView, _ id: String) -> AppWizardField? {v.fields.first { $0.id == id }}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swiftindex 1ad8a33c5a..e69f6484af 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift@@ -124,7 +124,13 @@ struct ThisMachineView: View {PermissionRows(rows: panel.permissions, openLabel: panel.openSettingsLabel)}}- if let error = host.error {+ if let failure = host.actionFailure {+ // A button that failed: what happened in plain+ // words, Retry, and the raw error under Details.+ HostSetupFailureView(failure: failure, retrying: host.busy) {+ Task { await host.retryFailedAction() }+ }+ } else if let error = host.error {Text(error).foregroundStyle(.red).lineLimit(1).help(error)}if panel.setupChoices.isEmpty {@@ -154,7 +160,14 @@ struct ThisMachineView: View {}}.navigationTitle(host.form == nil ? panel.title : (host.formView?.title ?? panel.title))- .task { await host.refresh() }+ .task {+ // Followed while it shows: who is connected now, and a+ // permission granted in System Settings (no restart needed).+ while !Task.isCancelled {+ if host.form == nil { await host.refresh() }+ try? await Task.sleep(for: .seconds(5))+ }+ }.alert(confirming?.confirm?.title ?? "", isPresented: Binding(get: { confirming?.confirm != nil },set: { if !$0 { confirming = nil } })) {diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swiftindex 45f11672b9..a660c3471a 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift@@ -66,12 +66,27 @@ struct HostSetupFailureTests {#expect(f.message.contains("Sign in"))}+ /// The first post-launch user's error (raw), and the words the host+ /// now reports for it: a service that did not start, never the raw+ /// launchctl command line.+ @Test(arguments: [+ "local runtime: service: \"launchctl\" \"bootstrap\" \"gui/501\" \"/Users/u/Library/LaunchAgents/com.trycua.spacesd.host.plist\" failed: Bootstrap failed: 5: Input/output error",+ "local runtime: service: macOS did not start the Cua host service (launchd: Bootstrap failed: 5: Input/output error); try again",+ ])+ func serviceFailures(_ raw: String) {+ let f = HostSetupFailure.presenting(raw)+ #expect(f.kind == .service)+ #expect(f.title == "Couldn\u{2019}t start the Cua host service")+ #expect(!f.message.contains("launchctl"))+ #expect(f.details == raw)+ }+@Test func anythingElseIsGeneric() {- let f = HostSetupFailure.presenting("launchctl bootstrap failed\nmore")+ let f = HostSetupFailure.presenting("something odd failed\nmore")#expect(f.kind == .other)#expect(f.title == "Couldn\u{2019}t set up this Mac for access")#expect(f.message == "Something went wrong. Try again, or open Details to see what happened.")- #expect(f.details == "launchctl bootstrap failed\nmore")+ #expect(f.details == "something odd failed\nmore")}@Test func aPortNumberIsNotAStatusCode() {@@ -99,6 +114,26 @@ struct HostSetupFailureTests {#expect(model.showingHostForm)}+ /// A page button that fails (the first post-launch user turned a+ /// setting on and the service did not start) shows in words with+ /// Retry, and Retry runs the same button again.+ @MainActor @Test func aFailedPageButtonShowsWordsAndRetries() async {+ let host = FixtureHost()+ let model = HostModel(host: host)+ _ = try? await host.setupRequest(+ request: AppHostSetupRequest(+ mode: "relay", relayUrl: nil, direct: nil, name: "Studio", allow: nil, profile: "desktop",+ shareDesktop: nil, provideSpaces: nil),+ accountToken: "t")+ host.failConfigure = "local runtime: service: \"launchctl\" \"bootstrap\" \"gui/501\" \"/x.plist\" failed: Bootstrap failed: 5: Input/output error"+ await model.run(.provideSpaces)+ #expect(model.actionFailure?.kind == .service)+ #expect(model.actionFailure?.details.contains("launchctl") == true)+ await model.retryFailedAction()+ #expect(model.actionFailure == nil)+ #expect(host.calls.filter { $0.hasPrefix("configure:") }.count == 2, "Retry ran the same change")+ }+@MainActor @Test func retryRunsTheSameChoiceAndClearsOnSuccess() async {let host = FixtureHost()host.failSetup = Self.missingReleasediff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.pngindex 85487f6aba..8c549355af 100644Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png differdiff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swiftindex 6dceb63d8e..8ffe8900c0 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift@@ -362,7 +362,15 @@ struct ViewModelTests {let model = makeModel(account: account, agents: agents)await model.loadSettings()let page = model.settingsPage- #expect(page.sections.map(\.id) == ["account", "general", "privacy", "agents"])+ #expect(page.sections.map(\.id) == ["account", "general", "runtimes", "privacy", "agents"])+ // Settings, Runtimes: macOS VMs picks runtime.lume.+ let runtime = page.sections.first { $0.id == "runtimes" }!.rows[0]+ #expect(runtime.options.map(\.id) == ["auto", "builtin", "system"])+ #expect(runtime.options.first(where: \.active)?.id == "auto")+ await model.choose(row: "macos-runtime", option: "builtin")+ #expect(model.lumeSource == "builtin")+ #expect(model.settingsPage.sections.first { $0.id == "runtimes" }!.rows[0]+ .options.first(where: \.active)?.id == "builtin")#expect(model.chrome.signInLabel == "Sign in")await model.press(row: "sign-in")#expect(model.identity == "[email protected]")diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lockindex 7b4598c262..f1cf6ef314 100644--- a/apps/cua-spaces/src-tauri/Cargo.lock+++ b/apps/cua-spaces/src-tauri/Cargo.lock@@ -1750,6 +1750,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit 0.25.13+spec-1.1.0","tracing","vnc-rs","windows-sys 0.61.2",diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdxindex 63c0fd0f78..0c9c7bc40e 100644--- a/docs/content/docs/cua-sdk/reference/index.mdx+++ b/docs/content/docs/cua-sdk/reference/index.mdx@@ -139,4 +139,4 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b290 items, 379 methods. The [Types](/cua-sdk/reference/types) page lists them.-The Cua Spaces app export adds 712 items and 38 methods.+The Cua Spaces app export adds 713 items and 38 methods.diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdxindex 2d4510c51f..c296fb797f 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx@@ -1452,6 +1452,8 @@ pub fn plan_from_template(t: &Template) -> Result<LocalFleetPlan>pub fn pool_image(image: &str) -> Option<&str>/// Pool `pool`'s template image as an ...pub async fn pool_image_info(fleet: &FleetClient, pool: &str, creds: Option<&RegistryCredentials>) -> Result<Option<ImageInfo>>+/// Deletes the runtimes cua set up itself ...+pub fn remove_builtin_runtimes() -> Result<(), String>// mod byoc/// The error a cloud word without a ...@@ -1610,7 +1612,7 @@ pub const DEFAULT_PATH: &str = "/mcp";// mod settings/// Every setting, in display order.-pub const KEYS: [Key; 7] = _;+pub const KEYS: [Key; 8] = _;```## Type aliasesdiff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdxindex e7d7951264..eb41793b22 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx@@ -38,6 +38,7 @@ More of this crate: [client](/cua-sdk/reference/rust/cua-spaces-client), [agents- `presence`: Presence: who is looking at a Space and where their ...- `presence::art`: The shared presence cursor art (ass ...- `presence::view`: The presence netcode model every client draws from ...+- `reattach`: Keeping a host-served link to a Space alive across ...- `registry`: The persisted Spaces registry.- `relay`: `relay:<machine-id>`: machines of the signed-in cua.ai ...- `routines`: Routines: recurring tasks a Bot runs on a schedule.@@ -952,6 +953,54 @@ impl Provider {}```+### `reattach::Attempt`++What a re-attach attempt did.++```rust+pub enum Attempt {+ Attached,+ Unsupported,+}+```++### `reattach::Backoff`++Exponential backoff between failed attempts.++```rust+pub struct Backoff { /* private fields */ }+impl Backoff {+ fn new(policy: &Policy) -> Self;+ fn fail(&mut self) -> Duration;+ fn reset(&mut self);+}+```++### `reattach::Health`++What a link looks like right now.++```rust+pub enum Health {+ Healthy,+ Down,+ Gone,+}+```++### `reattach::Policy`++Timing of `supervise`.++```rust+pub struct Policy {+ pub poll: Duration,+ pub initial_backoff: Duration,+ pub max_backoff: Duration,+}+```+### `RecoveredCreate``container:ghcr.io/x:1` -> `ghcr.io/x:1` (the local ...@@ -2143,6 +2192,10 @@ pub fn cursor_art_svg(shape: CursorShape, color: &str, size: f64) -> String/// Opacity of a cursor idle for `idle_ms`.pub fn idle_alpha(idle_ms: f64) -> f64+// mod reattach+/// Checks a link every `policy.poll` and ...+pub async fn supervise<H, HF, R, RF>(policy: Policy, health: H, reattach: R) where H: FnMut() -> HF, HF: Future<Output = Health>, R: FnMut() -> RF, RF: Future<Output = Result<Attempt, String>>+// mod registry/// The cua home: `$CUA_HOME`, else ...pub fn cua_home() -> PathBufdiff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdxindex f7392d03dd..0ac895b80d 100644--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx@@ -43,6 +43,15 @@ pub fn cua_spaces_register()</Tab></Tabs>+## `AppRuntimeSwitch` record++| Field | Type | Default | Description |+| --- | --- | --- | --- |+| `setting` | `String` | | The `cua config` setting: `runtime.lume`. |+| `value` | `String` | | The value to set: `builtin`. |+| `label` | `String` | | The button: "Use built-in Lume". |+| `detail` | `String` | | One line on what that does. |+## `app_menu_input_from_json`The menu bar item's menu input from JSON (fixtures, parity).@@ -72,7 +81,7 @@ pub fn app_menu_input_from_json(json: String) -> Result<AppMenuInput, CuaError>## All items-595 items, across this page and its subpages, grouped by page. Methods are listed on their object.+596 items, across this page and its subpages, grouped by page. Methods are listed on their object.**About, updates and launch**: [`app_about_after_launch`](/cua-sdk/reference/spaces/app-core/about#app_about_after_launch), [`app_about_allowed_channels`](/cua-sdk/reference/spaces/app-core/about#app_about_allowed_channels), [`app_about_input_from_json`](/cua-sdk/reference/spaces/app-core/about#app_about_input_from_json), [`app_about_refresh_notice`](/cua-sdk/reference/spaces/app-core/about#app_about_refresh_notice), [`app_about_restart_daemon`](/cua-sdk/reference/spaces/app-core/about#app_about_restart_daemon), [`app_about_view`](/cua-sdk/reference/spaces/app-core/about#app_about_view), [`app_daemon_check_from_json`](/cua-sdk/reference/spaces/app-core/about#app_daemon_check_from_json), [`app_launch_input_from_json`](/cua-sdk/reference/spaces/app-core/about#app_launch_input_from_json), [`app_refresh_report_from_json`](/cua-sdk/reference/spaces/app-core/about#app_refresh_report_from_json), [`AppAboutInput`](/cua-sdk/reference/spaces/app-core/about#appaboutinput-record), [`AppAboutLink`](/cua-sdk/reference/spaces/app-core/about#appaboutlink-record), [`AppAboutLinkId`](/cua-sdk/reference/spaces/app-core/about#appaboutlinkid-enum), [`AppAboutUpdates`](/cua-sdk/reference/spaces/app-core/about#appaboutupdates-record), [`AppAboutView`](/cua-sdk/reference/spaces/app-core/about#appaboutview-record), [`AppCliInstaller`](/cua-sdk/reference/spaces/app-core/about#appcliinstaller), [`AppCliInstallPlan`](/cua-sdk/reference/spaces/app-core/about#appcliinstallplan-record), [`AppCliInstallRequest`](/cua-sdk/reference/spaces/app-core/about#appcliinstallrequest-record), [`AppDaemonCheck`](/cua-sdk/reference/spaces/app-core/about#appdaemoncheck-record), [`AppInstallMethod`](/cua-sdk/reference/spaces/app-core/about#appinstallmethod-enum), [`AppLaunchInput`](/cua-sdk/reference/spaces/app-core/about#applaunchinput-record), [`AppLaunchPlan`](/cua-sdk/reference/spaces/app-core/about#applaunchplan-record), [`AppRefreshReport`](/cua-sdk/reference/spaces/app-core/about#apprefreshreport-record), [`AppUpdateChannel`](/cua-sdk/reference/spaces/app-core/about#appupdatechannel-enum)@@ -102,7 +111,7 @@ pub fn app_menu_input_from_json(json: String) -> Result<AppMenuInput, CuaError>**This machine**: [`app_host_arch`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_arch), [`app_host_form_action_from_json`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_form_action_from_json), [`app_host_form_initial`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_form_initial), [`app_host_form_reduce`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_form_reduce), [`app_host_form_view`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_form_view), [`app_host_looks_like_listen`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_looks_like_listen), [`app_host_panel`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_panel), [`app_host_parse_allow_list`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_parse_allow_list), [`app_host_permission_rows`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_permission_rows), [`app_host_setting_change`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_setting_change), [`app_host_setup`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_setup), [`app_host_state`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_state), [`app_host_state_from_json`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_state_from_json), [`app_host_summary_input`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_summary_input), [`app_host_validate_setup`](/cua-sdk/reference/spaces/app-core/this-machine#app_host_validate_setup), [`app_with_this_machine`](/cua-sdk/reference/spaces/app-core/this-machine#app_with_this_machine), [`AppHostAccess`](/cua-sdk/reference/spaces/app-core/this-machine#apphostaccess-record), [`AppHostAccessRow`](/cua-sdk/reference/spaces/app-core/this-machine#apphostaccessrow-record), [`AppHostAction`](/cua-sdk/reference/spaces/app-core/this-machine#apphostaction-record), [`AppHostActionId`](/cua-sdk/reference/spaces/app-core/this-machine#apphostactionid-enum), [`AppHostClient`](/cua-sdk/reference/spaces/app-core/this-machine#apphostclient-record), [`AppHostConfirm`](/cua-sdk/reference/spaces/app-core/this-machine#apphostconfirm-record), [`AppHostFormAction`](/cua-sdk/reference/spaces/app-core/this-machine#apphostformaction-enum), [`AppHostFormChoice`](/cua-sdk/reference/spaces/app-core/this-machine#apphostformchoice-record), [`AppHostFormField`](/cua-sdk/reference/spaces/app-core/this-machine#apphostformfield-record), [`AppHostFormState`](/cua-sdk/reference/spaces/app-core/this-machine#apphostformstate-record), [`AppHostFormView`](/cua-sdk/reference/spaces/app-core/this-machine#apphostformview-record), [`AppHostLimit`](/cua-sdk/reference/spaces/app-core/this-machine#apphostlimit-record), [`AppHostPanelView`](/cua-sdk/reference/spaces/app-core/this-machine#apphostpanelview-record), [`AppHostPermissionInput`](/cua-sdk/reference/spaces/app-core/this-machine#apphostpermissioninput-record), [`AppHostProvidedSpace`](/cua-sdk/reference/spaces/app-core/this-machine#apphostprovidedspace-record), [`AppHostSettingChange`](/cua-sdk/reference/spaces/app-core/this-machine#apphostsettingchange-record), [`AppHostSetupChoice`](/cua-sdk/reference/spaces/app-core/this-machine#apphostsetupchoice-record), [`AppHostSetupRequest`](/cua-sdk/reference/spaces/app-core/this-machine#apphostsetuprequest-record), [`AppHostSpacesAudit`](/cua-sdk/reference/spaces/app-core/this-machine#apphostspacesaudit-record), [`AppHostState`](/cua-sdk/reference/spaces/app-core/this-machine#apphoststate-record), [`AppHostToggle`](/cua-sdk/reference/spaces/app-core/this-machine#apphosttoggle-record), [`AppPermissionRow`](/cua-sdk/reference/spaces/app-core/this-machine#apppermissionrow-record)-**Spaces app core**: [`app_menu_input_from_json`](#app_menu_input_from_json), [`cua_spaces_register`](#cua_spaces_register)+**Spaces app core**: [`app_menu_input_from_json`](#app_menu_input_from_json), [`AppRuntimeSwitch`](#appruntimeswitch-record), [`cua_spaces_register`](#cua_spaces_register)**Notch**: [`app_notch_estimated_progress`](/cua-sdk/reference/spaces/app-core/notch#app_notch_estimated_progress), [`app_notch_initial`](/cua-sdk/reference/spaces/app-core/notch#app_notch_initial), [`app_notch_layout`](/cua-sdk/reference/spaces/app-core/notch#app_notch_layout), [`app_notch_motion`](/cua-sdk/reference/spaces/app-core/notch#app_notch_motion), [`app_notch_radii`](/cua-sdk/reference/spaces/app-core/notch#app_notch_radii), [`app_notch_reduce`](/cua-sdk/reference/spaces/app-core/notch#app_notch_reduce), [`app_notch_tile_at`](/cua-sdk/reference/spaces/app-core/notch#app_notch_tile_at), [`app_notch_view`](/cua-sdk/reference/spaces/app-core/notch#app_notch_view), [`app_os_icon_svg`](/cua-sdk/reference/spaces/app-core/notch#app_os_icon_svg), [`app_os_icon_system_symbol`](/cua-sdk/reference/spaces/app-core/notch#app_os_icon_system_symbol), [`app_presence_name`](/cua-sdk/reference/spaces/app-core/notch#app_presence_name), [`app_presence_principal_id`](/cua-sdk/reference/spaces/app-core/notch#app_presence_principal_id), [`AppLogicalRect`](/cua-sdk/reference/spaces/app-core/notch#applogicalrect-record), [`AppNotchAccess`](/cua-sdk/reference/spaces/app-core/notch#appnotchaccess-record), [`AppNotchActivity`](/cua-sdk/reference/spaces/app-core/notch#appnotchactivity-record), [`AppNotchActivityKind`](/cua-sdk/reference/spaces/app-core/notch#appnotchactivitykind-enum), [`AppNotchButton`](/cua-sdk/reference/spaces/app-core/notch#appnotchbutton-record), [`AppNotchButtonId`](/cua-sdk/reference/spaces/app-core/notch#appnotchbuttonid-enum), [`AppNotchEffect`](/cua-sdk/reference/spaces/app-core/notch#appnotcheffect-enum), [`AppNotchEvent`](/cua-sdk/reference/spaces/app-core/notch#appnotchevent-enum), [`AppNotchHeader`](/cua-sdk/reference/spaces/app-core/notch#appnotchheader-record), [`AppNotchLayout`](/cua-sdk/reference/spaces/app-core/notch#appnotchlayout-record), [`AppNotchMotion`](/cua-sdk/reference/spaces/app-core/notch#appnotchmotion-record), [`AppNotchPermission`](/cua-sdk/reference/spaces/app-core/notch#appnotchpermission-record), [`AppNotchPhase`](/cua-sdk/reference/spaces/app-core/notch#appnotchphase-enum), [`AppNotchPreview`](/cua-sdk/reference/spaces/app-core/notch#appnotchpreview-record), [`AppNotchRadii`](/cua-sdk/reference/spaces/app-core/notch#appnotchradii-record), [`AppNotchState`](/cua-sdk/reference/spaces/app-core/notch#appnotchstate-record), [`AppNotchTab`](/cua-sdk/reference/spaces/app-core/notch#appnotchtab-record), [`AppNotchTile`](/cua-sdk/reference/spaces/app-core/notch#appnotchtile-record), [`AppNotchTransfer`](/cua-sdk/reference/spaces/app-core/notch#appnotchtransfer-record), [`AppNotchTransition`](/cua-sdk/reference/spaces/app-core/notch#appnotchtransition-record), [`AppNotchView`](/cua-sdk/reference/spaces/app-core/notch#appnotchview-record), [`AppScreenFacts`](/cua-sdk/reference/spaces/app-core/notch#appscreenfacts-record)diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdxindex 6165a12092..7329eb5c3b 100644--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdx@@ -308,6 +308,7 @@ Returned by [`app_wizard_env_from_json`](#app_wizard_env_from_json).| `local_details` / `localDetails` | `Option<HashMap<String, String>>` | | Why each local backend that is not ready is not (the runtime doctor's detail, by backend name), when known: the wizard names the reason instead of only "This Mac cannot run container Spaces." || `max_cpus` / `maxCpus` | `u32` | | Upper bound for the CPU slider. || `host_arch` / `hostArch` | `Option<String>` | | This machine's architecture (`arm64`, `amd64`), when known. |+| `lume_source` / `lumeSource` | `Option<String>` | | Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`, `system`), when known. || `storage` | [`Option<AppLocalStorage>`](#applocalstorage-record) | | Free space and pulled images here (the SDK's `Local.storage()`), when known. || `cloud_pricing` / `cloudPricing` | [`Option<AppCloudPricing>`](#appcloudpricing-record) | | This account's Cua Cloud rates, when known (no estimate without). || `clouds` | [`Vec<AppConnectedCloud>`](/cua-sdk/reference/spaces/app-core/cloud#appconnectedcloud-record) | | The user's connected clouds (`cloud_status`), for "Your cloud" (offered only while its experiment is on: `offered_clouds`). |@@ -388,6 +389,8 @@ Returned by [`app_wizard_view`](#app_wizard_view).| `cloud` | `Option<String>` | | The connected cloud "Your cloud" creates in (`aws`). || `host` | `Option<String>` | | The machine of yours it creates on (`SpaceHost.id`). || `placement_error` / `placementError` | `Option<String>` | | Why the chosen placement cannot be used. |+| `placement_hint` / `placementHint` | `Option<String>` | | One line under "Run on" when This Mac cannot run the Space and no machine of yours is listed: how another Mac joins. |+| `runtime_switch` / `runtimeSwitch` | [`Option<AppRuntimeSwitch>`](/cua-sdk/reference/spaces/app-core#appruntimeswitch-record) | | Switches This Mac to the built-in runtime the Space needs, when it is set to use its own and that is missing. || `advanced` | `bool` | | Advanced shown. || `kind_tiles` / `kindTiles` | [`Vec<AppTile>`](#apptile-record) | | Kind tiles. || `runtimes` | [`Vec<AppMenuOption>`](#appmenuoption-record) | | Runtime menu. |diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdxindex ca00acbe7e..13436a8314 100644--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx@@ -624,6 +624,7 @@ Returned by [`app_settings_input_from_json`](#app_settings_input_from_json).| `keyvault_site_icons` / `keyvaultSiteIcons` | `bool` | | Load site icons from Google when the browser had none (`AppSettings.keyvault_site_icons`). || `keyvault_protection` / `keyvaultProtection` | [`Vec<AppFact>`](#appfact-record) | | The Keyvault's protection facts (Touch ID, the daemon's signature), shown in the section. || `auto_connect` / `autoConnect` | `Option<bool>` | | "Connect to the desktop automatically" (none: no row; a shell without the preview cover leaves it out). |+| `lume_source` / `lumeSource` | `Option<String>` | | Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`, `system`); none: no Runtimes section. |## `AppSettingsOption` recorddiff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdxindex 97c5fd321c..7dd2f1b5b7 100644--- a/docs/content/docs/cua-sdk/reference/types.mdx+++ b/docs/content/docs/cua-sdk/reference/types.mdx@@ -50,7 +50,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f291 items. Methods are listed on their object.-The 712 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items).+The 713 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items).| Item | Kind | Summary || --- | --- | --- |diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lockindex 27bab2785b..124e31d236 100644--- a/examples/streaming/rust/Cargo.lock+++ b/examples/streaming/rust/Cargo.lock@@ -1547,6 +1547,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit","tracing","vnc-rs","windows-sys 0.61.2",diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lockindex 7be2d2cc4d..df19acfb41 100644--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock@@ -2721,6 +2721,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit","tracing","vnc-rs","windows-sys 0.61.2",diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex 4953b3ce74..dc8023d91e 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2942,6 +2942,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit","tracing","vnc-rs","windows-sys 0.61.2",diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex d790a9a166..ef7aebd6a4 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -327,6 +327,20 @@ pub fn permission_hints(os: &str, driver: &Path) -> Vec<PermissionHint> {]}+/// The relay machine meta key saying whether this machine provides Spaces+/// (`on` / `off`), as of its last setup. Your other devices list a machine+/// that provides Spaces in their "Run on" menu even while it is offline+/// (with why), instead of leaving it out.+pub const META_PROVIDES_SPACES: &str = "cua.host.spaces";++/// The meta a host registers with.+fn host_meta(provide_spaces: bool) -> std::collections::BTreeMap<String, String> {+ std::collections::BTreeMap::from([(+ META_PROVIDES_SPACES.to_string(),+ if provide_spaces { "on" } else { "off" }.to_string(),+ )])+}+/// What `status` reports (camelCase for the app).#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -869,7 +883,7 @@ impl Host {name: name.clone(),allow: opts.allow.clone(),host: None,- meta: Default::default(),+ meta: host_meta(opts.provide_spaces),},).await?;@@ -1066,8 +1080,11 @@ impl Host {}// The driver's flags change with the desktop, and in direct mode// with Spaces (it serves HostSpacesService only then).+ // A service that should run but is down (a start that failed+ // before) starts again too, so trying the change again repairs it.+ let down = config.sharing && !self.manager_for_config(&config).state().running;let restart =- desktop != config.share_desktop || (!relay && provide != config.provide_spaces);+ down || desktop != config.share_desktop || (!relay && provide != config.provide_spaces);config.share_desktop = desktop;config.provide_spaces = provide;if let Some(mut p) = policy {@@ -1132,7 +1149,7 @@ impl Host {.collect(),service: manager.state(),allow: policy.as_ref().map(|p| p.allow.clone()).unwrap_or_default(),- permissions: permission_hints(std::env::consts::OS, &config.driver_bin),+ permissions: self.missing_permissions(&config),..Default::default()};if config.mode == "direct" {@@ -1158,6 +1175,27 @@ impl Host {Ok(status)}+ /// The permissions left to grant: every one macOS needs, less the ones+ /// the driver reports granted (asked afresh on each status, so a grant+ /// shows without restarting anything). All of them when it cannot say.+ fn missing_permissions(&self, config: &HostConfig) -> Vec<PermissionHint> {+ let hints = permission_hints(std::env::consts::OS, &config.driver_bin);+ if hints.is_empty() {+ return hints;+ }+ match self.preflight_probe().permission_status(&config.driver_bin) {+ Some((screen, ax)) => hints+ .into_iter()+ .filter(|h| match h.id.as_str() {+ "screen-recording" => !screen,+ "accessibility" => !ax,+ _ => true,+ })+ .collect(),+ None => hints,+ }+ }+/// Fills the recent accesses from the driver's log and adds the callers/// active right now to `clients`: every one in direct mode (there is no/// relay presence), and in relay mode the ones the relay cannot see@@ -1231,6 +1269,13 @@ impl Host {let token = read_secret(&self.paths.machine_token())?;RelayClient::new(url)?.start_sharing(&token, id).await?;self.set_policy_sharing(true)?;+ // The service stays up while sharing is stopped; one that+ // went down (a failed start) is started again here.+ let manager = self.manager_for_config(&config);+ if !manager.state().running {+ manager.install(&self.service_spec(&config))?;+ manager.start()?;+ }}_ => {self.manager_for_config(&config).start()?;diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex 87e24db44d..baf7c1e92c 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -52,7 +52,7 @@ pub use device::{DeviceAuth, DeviceKey, FileKeySlot, KeySlot, MemoryKeySlot};pub use host::SetupStage;pub use host::{DirectHosting, Host, HostConfig, HostMode, HostPaths, HostPolicy, HostSettingsChange,- HostStatus, PermissionHint, SetupOptions, SpacesDaemon, permission_hints,+ HostStatus, META_PROVIDES_SPACES, PermissionHint, SetupOptions, SpacesDaemon, permission_hints,};pub use machine::machine_id;pub use provided::{diff --git a/libs/cua/crates/cua-host/src/preflight.rs b/libs/cua/crates/cua-host/src/preflight.rsindex fbce5ad5d3..2cc39ec95f 100644--- a/libs/cua/crates/cua-host/src/preflight.rs+++ b/libs/cua/crates/cua-host/src/preflight.rs@@ -95,18 +95,131 @@ impl SessionProbe for SystemProbe {if !driver_bin.is_file() {return None;}+ let stdout = check_permissions_output(driver_bin)?;+ let v: serde_json::Value = serde_json::from_slice(&stdout).ok()?;+ Some((+ v.get("screen_recording")?.as_bool()?,+ v.get("accessibility")?.as_bool()?,+ ))+ }+}++/// How long `<driver> check-permissions` may take.+const PERMISSION_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);++/// `<driver_bin> check-permissions`'s stdout, when it exits 0 in time.+///+/// On macOS the child disclaims responsibility: TCC answers for the+/// process macOS holds responsible, which for a plain child is its parent+/// (the app, or the terminal `cua` runs in), not the driver the+/// LaunchAgent runs. Disclaimed, the driver answers for itself, and a+/// fresh process each time sees a grant made a moment ago.+fn check_permissions_output(driver_bin: &Path) -> Option<Vec<u8>> {+ #[cfg(target_os = "macos")]+ {+ disclaimed::output(driver_bin, "check-permissions", PERMISSION_CHECK_TIMEOUT)+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = PERMISSION_CHECK_TIMEOUT;let out = std::process::Command::new(driver_bin).arg("check-permissions").output().ok()?;- if !out.status.success() {- return None;+ out.status.success().then_some(out.stdout)+ }+}++#[cfg(target_os = "macos")]+mod disclaimed {+ use std::ffi::CString;+ use std::io::Read as _;+ use std::os::fd::FromRawFd as _;+ use std::os::unix::ffi::OsStrExt as _;+ use std::path::Path;+ use std::time::Duration;++ unsafe extern "C" {+ // libsystem_secinit; used by Chromium, LLDB and Xcode for the same+ // reason. Present on every macOS cua supports.+ fn responsibility_spawnattrs_setdisclaim(+ attrs: *mut libc::posix_spawnattr_t,+ disclaim: libc::c_int,+ ) -> libc::c_int;+ }++ /// Runs `program arg` responsible for itself; its stdout when it exits+ /// 0 within `timeout` (killed otherwise).+ pub(super) fn output(program: &Path, arg: &str, timeout: Duration) -> Option<Vec<u8>> {+ let path = CString::new(program.as_os_str().as_bytes()).ok()?;+ let arg = CString::new(arg).ok()?;+ let devnull = CString::new("/dev/null").ok()?;+ let argv = [+ path.as_ptr() as *mut libc::c_char,+ arg.as_ptr() as *mut libc::c_char,+ std::ptr::null_mut(),+ ];+ let mut fds = [0 as libc::c_int; 2];+ // SAFETY: plain libc calls on locals; every resource is released+ // on every path below.+ unsafe {+ if libc::pipe(fds.as_mut_ptr()) != 0 {+ return None;+ }+ let (read_fd, write_fd) = (fds[0], fds[1]);+ let mut actions: libc::posix_spawn_file_actions_t = std::mem::zeroed();+ let mut attrs: libc::posix_spawnattr_t = std::mem::zeroed();+ libc::posix_spawn_file_actions_init(&mut actions);+ libc::posix_spawnattr_init(&mut attrs);+ libc::posix_spawn_file_actions_addopen(+ &mut actions,+ 0,+ devnull.as_ptr(),+ libc::O_RDONLY,+ 0,+ );+ libc::posix_spawn_file_actions_adddup2(&mut actions, write_fd, 1);+ libc::posix_spawn_file_actions_addopen(+ &mut actions,+ 2,+ devnull.as_ptr(),+ libc::O_WRONLY,+ 0,+ );+ libc::posix_spawn_file_actions_addclose(&mut actions, read_fd);+ libc::posix_spawn_file_actions_addclose(&mut actions, write_fd);+ responsibility_spawnattrs_setdisclaim(&mut attrs, 1);+ let mut pid: libc::pid_t = 0;+ let spawned = libc::posix_spawn(+ &mut pid,+ path.as_ptr(),+ &actions,+ &attrs,+ argv.as_ptr(),+ *libc::_NSGetEnviron(),+ );+ libc::posix_spawn_file_actions_destroy(&mut actions);+ libc::posix_spawnattr_destroy(&mut attrs);+ libc::close(write_fd);+ let reader = std::fs::File::from_raw_fd(read_fd);+ if spawned != 0 {+ return None;+ }+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut out = Vec::new();+ let _ = reader.take(64 * 1024).read_to_end(&mut out);+ let _ = tx.send(out);+ });+ let out = rx.recv_timeout(timeout).ok();+ if out.is_none() {+ libc::kill(pid, libc::SIGKILL);+ }+ let mut status = 0;+ libc::waitpid(pid, &mut status, 0);+ let ok = libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0;+ out.filter(|_| ok)}- let v: serde_json::Value = serde_json::from_slice(&out.stdout).ok()?;- Some((- v.get("screen_recording")?.as_bool()?,- v.get("accessibility")?.as_bool()?,- ))}}@@ -228,6 +341,28 @@ mod tests {assert_eq!(report.accessibility, Some(false));}+ #[cfg(target_os = "macos")]+ #[test]+ fn a_disclaimed_child_runs_and_its_stdout_is_read() {+ let d = std::time::Duration::from_secs(5);+ let out = super::disclaimed::output(Path::new("/bin/echo"), "hi", d).unwrap();+ assert_eq!(out, b"hi\n");+ // A non-zero exit is no answer.+ assert!(super::disclaimed::output(Path::new("/usr/bin/false"), "x", d).is_none());+ assert!(super::disclaimed::output(Path::new("/nonexistent/bin"), "x", d).is_none());+ // A child that does not answer in time is killed.+ let t = std::time::Instant::now();+ assert!(+ super::disclaimed::output(+ Path::new("/bin/sleep"),+ "30",+ std::time::Duration::from_millis(300)+ )+ .is_none()+ );+ assert!(t.elapsed() < std::time::Duration::from_secs(5));+ }+#[test]fn unknown_permission_status_is_not_a_failure() {let probe = FakeProbe {diff --git a/libs/cua/crates/cua-host/src/service.rs b/libs/cua/crates/cua-host/src/service.rsindex 3eec4ebfe0..c6057c0f58 100644--- a/libs/cua/crates/cua-host/src/service.rs+++ b/libs/cua/crates/cua-host/src/service.rs@@ -587,16 +587,24 @@ impl ServiceManager for Launchd {write_file(&self.plist_path(), &launchd_plist(spec))}fn start(&self) -> Result<()> {- let _ = run(Command::new("launchctl").args(["bootout", &self.target()]));- run(Command::new("launchctl").args([- "bootstrap",+ let plist = self.plist_path().to_string_lossy().into_owned();+ launchd_restart(&format!("gui/{}", self.uid),- &self.plist_path().to_string_lossy(),- ]))- .map(drop)+ &self.target(),+ &plist,+ &mut |args: &[&str]| run(Command::new("launchctl").args(args)),+ &mut |d| std::thread::sleep(d),+ )}fn stop(&self) -> Result<()> {- run(Command::new("launchctl").args(["bootout", &self.target()])).map(drop)+ let target = self.target();+ if !launchd_loaded(&target, &mut |args: &[&str]| {+ run(Command::new("launchctl").args(args))+ }) {+ // Already stopped: nothing to do (not an error).+ return Ok(());+ }+ run(Command::new("launchctl").args(["bootout", &target])).map(drop)}fn uninstall(&self) -> Result<()> {let _ = run(Command::new("launchctl").args(["bootout", &self.target()]));@@ -619,6 +627,79 @@ impl ServiceManager for Launchd {}}+/// How long [`launchd_restart`] waits for a bootout to finish.+const LAUNCHD_BOOTOUT_WAIT: std::time::Duration = std::time::Duration::from_secs(5);+/// Bootstrap attempts before [`launchd_restart`] gives up.+const LAUNCHD_BOOTSTRAP_ATTEMPTS: u32 = 3;++/// `launchctl print <target>` succeeds: the service is loaded.+fn launchd_loaded(target: &str, launchctl: &mut dyn FnMut(&[&str]) -> Result<String>) -> bool {+ launchctl(&["print", target]).is_ok()+}++/// (Re)starts a LaunchAgent so that running it twice, or while it is+/// loaded, never fails:+///+/// 1. `enable` clears a "disabled" override (left by turning the item off+/// in Login Items, or by an old `launchctl disable`), which otherwise+/// makes `bootstrap` fail with `5: Input/output error`.+/// 2. A loaded service is booted out, and this waits until launchd has+/// really let go of it: `bootout` returns before the teardown ends, and+/// a `bootstrap` in that window fails with `5: Input/output error` (or+/// `37: Operation already in progress`).+/// 3. `bootstrap`; when it fails but the service is loaded after all (a+/// race with launchd's own `RunAtLoad`/`KeepAlive`), `kickstart -k`+/// restarts it in place instead. Otherwise retried with a short backoff.+///+/// The error left after every attempt names the service in plain words,+/// with launchd's own message at the end.+pub(crate) fn launchd_restart(+ domain: &str,+ target: &str,+ plist: &str,+ launchctl: &mut dyn FnMut(&[&str]) -> Result<String>,+ sleep: &mut dyn FnMut(std::time::Duration),+) -> Result<()> {+ let step = std::time::Duration::from_millis(100);+ let _ = launchctl(&["enable", target]);+ if launchd_loaded(target, launchctl) {+ let _ = launchctl(&["bootout", target]);+ let mut waited = std::time::Duration::ZERO;+ while waited < LAUNCHD_BOOTOUT_WAIT && launchd_loaded(target, launchctl) {+ sleep(step);+ waited += step;+ }+ }+ let mut last = String::new();+ for attempt in 0..LAUNCHD_BOOTSTRAP_ATTEMPTS {+ if attempt > 0 {+ sleep(std::time::Duration::from_millis(500 * u64::from(attempt)));+ }+ match launchctl(&["bootstrap", domain, plist]) {+ Ok(_) => return Ok(()),+ Err(e) => last = e.to_string(),+ }+ if launchd_loaded(target, launchctl) {+ // Loaded after all: restart it in place.+ match launchctl(&["kickstart", "-k", target]) {+ Ok(_) => return Ok(()),+ Err(e) => last = e.to_string(),+ }+ }+ }+ let why = last+ .split_once(" failed: ")+ .map_or(last.as_str(), |(_, why)| why)+ .trim()+ .trim_start_matches("service: ")+ .to_string();+ Err(Error::Service(format!(+ "macOS did not start the Cua host service (launchd: {why}); \+ try again, and if it keeps failing turn on cua-spacesd in System Settings > \+ General > Login Items & Extensions, or restart this Mac"+ )))+}+/// Ends and deletes the pre-rename task, if any (best effort).fn remove_legacy_task() {let query = Command::new("schtasks")@@ -909,6 +990,115 @@ pub fn manager_for(kind: RunnerKind, user_home: &Path, host_dir: &Path) -> Box<d#[cfg(test)]mod tests {++ /// A scripted `launchctl`: `loaded` says whether `print` succeeds (by+ /// call), `bootstrap` whether each bootstrap succeeds.+ struct FakeLaunchctl {+ calls: Vec<String>,+ loaded: Box<dyn FnMut(usize) -> bool>,+ bootstraps: Vec<bool>,+ prints: usize,+ }++ impl FakeLaunchctl {+ fn new(loaded: impl FnMut(usize) -> bool + 'static, bootstraps: Vec<bool>) -> Self {+ Self {+ calls: vec![],+ loaded: Box::new(loaded),+ bootstraps,+ prints: 0,+ }+ }+ fn call(&mut self, args: &[&str]) -> Result<String> {+ self.calls.push(args[0].to_string());+ let fail = |m: &str| {+ Err(Error::Service(format!(+ "\"launchctl\" \"{}\" failed: {m}",+ args[0]+ )))+ };+ match args[0] {+ "print" => {+ self.prints += 1;+ if (self.loaded)(self.prints) {+ Ok("state = running".into())+ } else {+ fail("Could not find service")+ }+ }+ "bootstrap" => {+ if self.bootstraps.is_empty() || self.bootstraps.remove(0) {+ Ok(String::new())+ } else {+ fail("Bootstrap failed: 5: Input/output error")+ }+ }+ _ => Ok(String::new()),+ }+ }+ fn restart(&mut self) -> Result<()> {+ launchd_restart(+ "gui/501",+ "gui/501/x",+ "/p.plist",+ &mut |a: &[&str]| self.call(a),+ &mut |_| {},+ )+ }+ }++ #[test]+ fn launchd_start_when_not_loaded_bootstraps_once() {+ let mut lc = FakeLaunchctl::new(|_| false, vec![true]);+ lc.restart().unwrap();+ assert_eq!(lc.calls, ["enable", "print", "bootstrap"]);+ }++ #[test]+ fn launchd_start_waits_for_the_bootout_to_finish() {+ // Loaded for the first three prints: bootout is asynchronous.+ let mut lc = FakeLaunchctl::new(|n| n <= 3, vec![true]);+ lc.restart().unwrap();+ assert_eq!(+ lc.calls,+ [+ "enable",+ "print",+ "bootout",+ "print",+ "print",+ "print",+ "bootstrap"+ ]+ );+ }++ #[test]+ fn launchd_start_kickstarts_a_service_that_is_loaded_after_all() {+ // Not loaded at first; bootstrap fails (launchd loaded it itself).+ let mut lc = FakeLaunchctl::new(|n| n >= 2, vec![false]);+ lc.restart().unwrap();+ assert_eq!(+ lc.calls,+ ["enable", "print", "bootstrap", "print", "kickstart"]+ );+ }++ #[test]+ fn launchd_start_retries_then_says_what_failed_in_words() {+ let mut lc = FakeLaunchctl::new(|_| false, vec![false, false, true]);+ lc.restart().unwrap();+ assert_eq!(lc.calls.iter().filter(|c| *c == "bootstrap").count(), 3);++ let mut lc = FakeLaunchctl::new(|_| false, vec![false, false, false]);+ let e = lc.restart().unwrap_err().to_string();+ assert!(+ e.contains("macOS did not start the Cua host service"),+ "{e}"+ );+ assert!(e.contains("Bootstrap failed: 5: Input/output error"), "{e}");+ assert!(!e.contains("\"launchctl\""), "{e}");+ }use super::*;fn spec() -> ServiceSpec {diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex 87ad1c2a72..db0712afc8 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -1218,3 +1218,75 @@ async fn launchd_setup_proceeds_with_a_gui_session() {["install".to_string(), "start".to_string()]);}++// ------------------------------------------------- recovery and permissions++/// A start that failed leaves the service down. Trying the same change+/// again (the app's Retry), or Resume sharing, starts it again instead of+/// only rewriting the settings.+#[tokio::test]+async fn retrying_a_change_starts_a_service_that_is_down() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct-token", "user-1", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ host.setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))+ .await+ .unwrap();+ f.manager.stop().unwrap();+ assert!(!host.status().await.unwrap().service.running);+ // The desktop is already on: no change, but the service is down.+ let status = host+ .configure(HostSettingsChange {+ share_desktop: Some(true),+ ..Default::default()+ })+ .await+ .unwrap();+ assert!(status.service.running);++ f.manager.stop().unwrap();+ let status = host.start_sharing().await.unwrap();+ assert!(status.service.running);+}++/// A probe that reports the driver's permissions.+struct GrantsProbe(Option<(bool, bool)>);++impl SessionProbe for GrantsProbe {+ fn gui_session(&self, _uid: u32) -> bool {+ true+ }+ fn console_user(&self) -> Option<String> {+ None+ }+ fn permission_status(&self, _driver_bin: &Path) -> Option<(bool, bool)> {+ self.0+ }+}++/// "Grant in System Settings" lists only what the driver still lacks,+/// asked afresh on each status (a grant shows without a restart); when the+/// driver cannot say, every permission stays listed.+#[cfg(target_os = "macos")]+#[tokio::test]+async fn status_lists_only_the_permissions_still_missing() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct-token", "user-1", Some("[email protected]"));+ let f = fixture();+ f.host()+ .setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))+ .await+ .unwrap();+ let with = |grants| f.host().with_preflight_probe(Arc::new(GrantsProbe(grants)));+ let ids = |s: HostStatus| s.permissions.into_iter().map(|p| p.id).collect::<Vec<_>>();+ assert_eq!(+ ids(with(None).status().await.unwrap()),+ ["screen-recording", "accessibility"]+ );+ assert_eq!(+ ids(with(Some((true, false))).status().await.unwrap()),+ ["accessibility"]+ );+ assert!(ids(with(Some((true, true))).status().await.unwrap()).is_empty());+}diff --git a/libs/cua/crates/cua-sandbox-core/src/lib.rs b/libs/cua/crates/cua-sandbox-core/src/lib.rsindex bddcfb8fed..08c3ed97e0 100644--- a/libs/cua/crates/cua-sandbox-core/src/lib.rs+++ b/libs/cua/crates/cua-sandbox-core/src/lib.rs@@ -28,6 +28,13 @@ pub use cua_vmm::gpu;/// Create progress: what a create is doing (pulling, booting, waiting for/// the guest), reported to the [`progress::scope`] that started it.pub use cua_vmm::progress;++/// Deletes the runtimes cua set up itself (the built-in Lume under+/// `$CUA_HOME/runtimes`). A runtime the user installed is never touched;+/// the built-in one is set up again the next time a Space needs it.+pub fn remove_builtin_runtimes() -> std::result::Result<(), String> {+ cua_vmm::lume::builtin::remove().map_err(|e| e.to_string())+}/// Cancels a create ([`Sandboxes::create_cancellable`]).pub use tokio_util::sync::CancellationToken;pub mod pool_image;diff --git a/libs/cua/crates/cua-sandbox-core/src/settings.rs b/libs/cua/crates/cua-sandbox-core/src/settings.rsindex a3f9ea7842..ac135af2c2 100644--- a/libs/cua/crates/cua-sandbox-core/src/settings.rs+++ b/libs/cua/crates/cua-sandbox-core/src/settings.rs@@ -36,7 +36,7 @@ pub struct Key {}/// Every setting, in display order.-pub const KEYS: [Key; 7] = [+pub const KEYS: [Key; 8] = [Key {name: "default.on",env: "CUA_DEFAULT_ON",@@ -79,6 +79,12 @@ pub const KEYS: [Key; 7] = [default: "on",description: "anonymous usage telemetry (on, off; alias `telemetry`); DO_NOT_TRACK=1 also turns it off. See `cua telemetry status`",},+ Key {+ name: "runtime.lume",+ env: "CUA_RUNTIME_LUME",+ default: "auto",+ description: "the Lume macOS Spaces run on: auto (this Mac's own, else built-in), builtin (cua's pinned, signed Lume, set up on first use) or system (only this Mac's own; nothing is downloaded)",+ },];/// Short names `cua config` accepts for a setting.@@ -414,6 +420,14 @@ pub fn normalize(key: Key, value: &str) -> Result<String, SettingsError> {}v.to_string()}+ "runtime.lume" => cua_vmm::lume::builtin::LumeSource::parse(v)+ .ok_or_else(|| {+ SettingsError(format!(+ "runtime.lume: expected auto, builtin or system, got {v:?}"+ ))+ })?+ .as_str()+ .to_string(),"telemetry.enabled" => match v.to_ascii_lowercase().as_str() {"1" | "true" | "yes" | "on" => "on".into(),"0" | "false" | "no" | "off" => "off".into(),diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex e28043ea90..cf63609d43 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -608,7 +608,16 @@ impl Host {/// Unregister, uninstall the service and delete the host state.pub async fn remove(&self) -> Result<()> {let home = self.home.clone();- run(async move { Ok(cua_host::Host::new(home).remove().await?) }).await+ run(async move {+ cua_host::Host::new(home).remove().await?;+ // Then the runtimes cua set up itself (the built-in Lume, set up+ // again on the next create that needs it); the user's own stay.+ if let Err(e) = cua_sandbox_core::remove_builtin_runtimes() {+ tracing::warn!("could not remove the built-in runtimes: {e}");+ }+ Ok(())+ })+ .await}}diff --git a/libs/cua/crates/cua-spaces-app-core/src/settings.rs b/libs/cua/crates/cua-spaces-app-core/src/settings.rsindex 35ff726a49..6ee068fba1 100644--- a/libs/cua/crates/cua-spaces-app-core/src/settings.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/settings.rs@@ -271,6 +271,10 @@ pub struct SettingsInput {/// "Connect to the desktop automatically" (none: no row; a shell/// without the preview cover leaves it out).pub auto_connect: Option<bool>,+ /// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ /// `system`); none: no Runtimes section.+ #[serde(default)]+ pub lume_source: Option<String>,}impl Default for SettingsInput {@@ -295,6 +299,7 @@ impl Default for SettingsInput {keyvault_site_icons: true,keyvault_protection: vec![],auto_connect: None,+ lume_source: None,}}}@@ -659,6 +664,10 @@ pub fn page(input: &SettingsInput) -> SettingsPage {},];+ if let Some(source) = input.lume_source.as_deref() {+ sections.push(runtimes_section(source));+ }+if let Some(t) = &input.telemetry {let mut share = row("telemetry", Choice, "Share anonymous usage data");share.options = vec![opt("on", "On", t.enabled), opt("off", "Off", !t.enabled)];@@ -737,6 +746,37 @@ pub fn page(input: &SettingsInput) -> SettingsPage {}}+/// The help under Settings, Runtimes, macOS VMs.+pub const MACOS_RUNTIME_HELP: &str =+ "Built-in is Cua\u{2019}s signed Lume, downloaded the first time you need it (6 MB).";++/// Settings, Runtimes: one row per local runtime Cua can provide itself.+/// macOS VMs: Automatic, Built-in (Cua's signed Lume, set up on first use)+/// or System (this Mac's own Lume only). The row's id is `macos-runtime`;+/// its options are `runtime.lume`'s values.+pub fn runtimes_section(lume_source: &str) -> SettingsSection {+ use SettingsRowKind::*;+ let source = match lume_source {+ "builtin" | "system" => lume_source,+ _ => "auto",+ };+ let mut macos = row("macos-runtime", Choice, "macOS VMs");+ macos.options = vec![+ opt("auto", "Automatic", source == "auto"),+ opt("builtin", "Built-in", source == "builtin"),+ opt("system", "System", source == "system"),+ ];+ let note = row("macos-runtime-note", Note, MACOS_RUNTIME_HELP);+ SettingsSection {+ id: "runtimes".into(),+ title: "Runtimes".into(),+ button: None,+ button_enabled: false,+ button_help: None,+ rows: vec![macos, note],+ }+}+/// The Settings page with Settings, Storage (the Cua Volume's store,/// Finder volume and cache, [`crate::drive_settings::storage_section`])/// after General, while the Cua Volume experiment is on. Off, Storage is@@ -768,6 +808,35 @@ pub fn with_storage(mod tests {use super::*;+ #[test]+ fn the_runtimes_section_shows_the_lume_choice() {+ let p = page(&SettingsInput::default());+ assert!(+ !p.sections.iter().any(|s| s.id == "runtimes"),+ "not until read"+ );+ let page = page(&SettingsInput {+ lume_source: Some("system".into()),+ ..Default::default()+ });+ let r = &page+ .sections+ .iter()+ .find(|s| s.id == "runtimes")+ .unwrap()+ .rows[0];+ assert_eq!(r.id, "macos-runtime");+ let active: Vec<_> = r+ .options+ .iter()+ .filter(|o| o.active)+ .map(|o| o.id.as_str())+ .collect();+ assert_eq!(active, ["system"]);+ let ids: Vec<_> = r.options.iter().map(|o| o.label.as_str()).collect();+ assert_eq!(ids, ["Automatic", "Built-in", "System"]);+ }+#[test]fn hotkeys_need_a_modifier() {let c = KeyCombo {diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rsindex c3a5033adf..1234caaa8d 100644--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs@@ -885,6 +885,12 @@ pub fn deleting_space(space: &Space) -> Space {s}+/// Bytes move while the create is still preparing: the SDK is setting up+/// the local runtime it needs (downloaded once, on first use).+fn setting_up_runtime(p: &PendingCreate) -> bool {+ p.phase == "preparing" && p.bytes_total.is_some_and(|t| t > 0)+}+/// A pending create as a Space row.pub fn pending_space(p: &PendingCreate) -> Space {let failed = p.error.is_some();@@ -896,6 +902,14 @@ pub fn pending_space(p: &PendingCreate) -> Space {"Failed".to_string()} else if p.cancelling {"Cancelling\u{2026}".to_string()+ } else if setting_up_runtime(p) {+ // Bytes before the image: the runtime cua sets up on first use+ // (the built-in Lume for a macOS Space).+ if p.os == SpaceOs::Macos {+ "Setting up Lume\u{2026}".to_string()+ } else {+ "Setting up the runtime\u{2026}".to_string()+ }} else {phase_label(&p.phase).to_string()};@@ -929,7 +943,7 @@ pub fn pending_space(p: &PendingCreate) -> Space {label,error: p.error.clone(),credit_url: p.credit_url.clone(),- transfer: (!failed && !p.cancelling && p.phase == "pulling")+ transfer: (!failed && !p.cancelling && (p.phase == "pulling" || setting_up_runtime(p))).then(|| transfer_text(p.bytes_done, p.bytes_total, p.bytes_per_second)).flatten(),cancellable: !failed && !p.cancelling && p.space_id.is_none(),@@ -1039,6 +1053,39 @@ mod tests {}}+ /// The first macOS create on a Mac without Lume: the built-in Lume's+ /// download shows on the Space's own row, in words, with its bytes.+ #[test]+ fn the_runtime_set_up_on_first_use_shows_on_the_create() {+ let s = reduce(+ &CreatesState::default(),+ &start("pending:m", "", SpaceOs::Macos),+ );+ let s = reduce(+ &s,+ &CreateAction::Progress {+ id: "pending:m".into(),+ phase: "preparing".into(),+ fraction: Some(0.5),+ now: Some(2_000),+ bytes_done: Some(3 << 20),+ bytes_total: Some(6 << 20),+ bytes_per_second: Some((1 << 20) as f64),+ },+ );+ let row = pending_space(&s.pending[0]);+ let p = row.progress.unwrap();+ assert_eq!(p.label, "Setting up Lume\u{2026}");+ assert!(p.transfer.unwrap().contains("MB"));+ assert_eq!(row.detail, "This Mac \u{b7} Setting up Lume\u{2026}");+ // Then the image, as before.+ let s = reduce(&s, &bytes_at("pending:m", 1 << 30, 20 << 30, 5e7, 3_000));+ assert_eq!(+ pending_space(&s.pending[0]).progress.unwrap().label,+ "Downloading image\u{2026}"+ );+ }+#[test]fn a_download_shows_its_bytes_rate_and_time_left() {let s = reduce(diff --git a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs b/libs/cua/crates/cua-spaces-app-core/src/wizard.rsindex 5ea29b5c66..7df3d13e3a 100644--- a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs@@ -589,6 +589,21 @@ pub fn host_refusal(image: &SandboxImage, host: &SpaceHost) -> Option<(&'static))}+/// A setting that makes This Mac able to run the Space: shown when the+/// person chose to use only this Mac's own runtime and it is missing.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RuntimeSwitch {+ /// The `cua config` setting: `runtime.lume`.+ pub setting: String,+ /// The value to set: `builtin`.+ pub value: String,+ /// The button: "Use built-in Lume".+ pub label: String,+ /// One line on what that does.+ pub detail: String,+}+/// One entry of the "Run on" menu: a machine that can host the Space.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -767,6 +782,66 @@ fn local_engine_detail(image: &SandboxImage, env: &WizardEnv) -> Option<String>})}+/// This Mac can run `image` now: a local runtime answers, and (when the+/// doctor's list is known) one of the image's engines is among them.+fn local_ready(image: &SandboxImage, env: &WizardEnv) -> bool {+ env.local_available+ && env+ .local_backends+ .as_ref()+ .is_none_or(|b| local_runtime_ready(image, b))+}++/// The first machine of yours that can run `image` now (online, not at a+/// limit, the right OS).+fn usable_host<'a>(image: &SandboxImage, env: &'a WizardEnv) -> Option<&'a SpaceHost> {+ env.hosts.iter().find(|h| host_refusal(image, h).is_none())+}++/// Until the person picks where it runs: when This Mac cannot run the+/// image but one of your machines can, start there instead of on an error.+fn follow_to_host(state: &mut WizardState, env: &WizardEnv) {+ if state.picked || state.placement != Location::Local {+ return;+ }+ let image = image_of(state);+ if local_ready(&image, env) {+ return;+ }+ if let Some(h) = usable_host(&image, env) {+ state.placement = Location::Host;+ state.host = Some(h.id.clone());+ }+}++/// Switching to the built-in Lume, when macOS VMs are set to use this+/// Mac's own Lume (`runtime.lume = system`) and it is missing. Otherwise+/// cua sets up its built-in Lume by itself on the first macOS create.+fn runtime_switch(image: &SandboxImage, env: &WizardEnv) -> Option<RuntimeSwitch> {+ if image.local != Some(LocalEngine::Lume) || local_ready(image, env) {+ return None;+ }+ if env.lume_source.as_deref() != Some("system") {+ return None;+ }+ if env.host_arch.as_deref().is_some_and(|a| a != "arm64") {+ return None;+ }+ Some(RuntimeSwitch {+ setting: "runtime.lume".into(),+ value: "builtin".into(),+ label: "Use built-in Lume".into(),+ detail: "Cua sets up its own signed Lume (about 6 MB) the first time you create a \+ macOS Space."+ .into(),+ })+}++/// The one line under "Run on" when nothing can run the Space here and+/// none of your machines is listed: how another Mac of yours joins.+pub const OTHER_MAC_HINT: &str = "To use another Mac, open Cua Spaces on it, choose Set up for \+ access and turn on Spaces for your devices. It then shows up here.";+/// `host:port` or `http(s)://host:port`: a shape check only.pub fn looks_like_address(value: &str) -> bool {let v = value.trim();@@ -941,6 +1016,10 @@ pub struct WizardEnv {/// This machine's architecture (`arm64`, `amd64`), when known.#[serde(default)]pub host_arch: Option<String>,+ /// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ /// `system`), when known.+ #[serde(default)]+ pub lume_source: Option<String>,/// Free space and pulled images here (the SDK's `Local.storage()`),/// when known.#[serde(default)]@@ -1270,7 +1349,7 @@ pub fn initial(env: &WizardEnv) -> WizardState {.first().cloned().expect("at least one published image");- WizardState {+ let mut state = WizardState {mode: WizardMode::Create,step: 0,placement: offered_location(env.default_location, env),@@ -1291,7 +1370,9 @@ pub fn initial(env: &WizardEnv) -> WizardState {host: None,gpu: false,address: AddressForm::default(),- }+ };+ follow_to_host(&mut state, env);+ state}/// The preset the Space is based on.@@ -1419,10 +1500,12 @@ pub fn reduce(state: &WizardState, action: &WizardAction, env: &WizardEnv) -> Wiif let Some(r) = first {choose_image(&mut s, &r);}+ follow_to_host(&mut s, env);}WizardAction::ChooseImage { image_ref } => {choose_image(&mut s, image_ref);close_suggestions(&mut s);+ follow_to_host(&mut s, env);}// The same text is no edit (a field echoing its value on focus).WizardAction::SetImageText { text } if *text == s.image_text => {}@@ -1888,6 +1971,14 @@ pub struct WizardView {pub host: Option<String>,/// Why the chosen placement cannot be used.pub placement_error: Option<String>,+ /// One line under "Run on" when This Mac cannot run the Space and no+ /// machine of yours is listed: how another Mac joins.+ #[serde(default)]+ pub placement_hint: Option<String>,+ /// Switches This Mac to the built-in runtime the Space needs, when it+ /// is set to use its own and that is missing.+ #[serde(default)]+ pub runtime_switch: Option<RuntimeSwitch>,/// Advanced shown.pub advanced: bool,/// Kind tiles.@@ -2448,11 +2539,24 @@ pub fn view(state: &WizardState, env: &WizardEnv) -> WizardView {None => Some(YOUR_CLOUD_CONNECT_DETAIL.to_string()),};let placeable = can_place(&image, placement);- let local_ready = env.local_available- && env- .local_backends- .as_ref()- .is_none_or(|b| local_runtime_ready(&image, b));+ let local_ready = local_ready(&image, env);+ let runtime_switch = (placement == Location::Local)+ .then(|| runtime_switch(&image, env))+ .flatten();+ let placement_hint = (placement == Location::Local+ && !local_ready+ && image.local.is_some()+ && usable_host(&image, env).is_none())+ .then(|| match env.hosts.iter().find(|h| !h.online) {+ // Yours, but its service is down: how it comes back.+ Some(h) => format!(+ "{name} is offline. Open Cua Spaces on {name}; once it is back, choose it in Run on.",+ name = h.name+ ),+ None if env.hosts.is_empty() => OTHER_MAC_HINT.to_string(),+ None => String::new(),+ })+ .filter(|h| !h.is_empty());let placement_ready = match placement {Location::Cloud => env.cloud_available,Location::Local => local_ready,@@ -2513,6 +2617,9 @@ pub fn view(state: &WizardState, env: &WizardEnv) -> WizardView {Location::Host => host_why.clone().unwrap_or_else(|| "Choose a machine.".to_string()),+ Location::Local if runtime_switch.is_some() => {+ "This Mac\u{2019}s own Lume isn\u{2019}t installed.".to_string()+ }Location::Local => {if env.local_available {let what = match image.local {@@ -2766,6 +2873,8 @@ pub fn view(state: &WizardState, env: &WizardEnv) -> WizardView {cloud: cloud.map(|c| c.name.clone()),host: host.map(|h| h.id.clone()),placement_error,+ placement_hint,+ runtime_switch,advanced: state.advanced,kind_tiles,runtimes: engines@@ -2886,6 +2995,7 @@ mod tests {local_details: None,max_cpus: 8,host_arch: Some("arm64".into()),+ lume_source: None,storage: None,cloud_pricing: None,clouds: vec![],@@ -3677,6 +3787,116 @@ mod tests {.collect()}+ /// macOS is never a dead end. With the built-in Lume (set up on the+ /// first create) This Mac just runs it. Set to use only this Mac's own+ /// Lume and without one, the error says so, offers the built-in one in+ /// one click, and one line says how another Mac joins.+ #[test]+ fn macos_runs_on_the_builtin_lume_or_says_how_to_get_one() {+ // The app counts a Lume cua sets up itself as ready.+ let builtin = WizardEnv {+ local_backends: Some(vec!["lume".into()]),+ lume_source: Some("auto".into()),+ ..env()+ };+ let s = reduce(+ &initial(&builtin),+ &WizardAction::ChooseOs { os: SpaceOs::Macos },+ &builtin,+ );+ let v = view(&s, &builtin);+ assert_eq!(v.placement_id, "local");+ assert!(+ v.placement_error.is_none() && v.runtime_switch.is_none() && v.placement_hint.is_none()+ );+ assert!(v.can_continue);++ let system = WizardEnv {+ local_available: false,+ local_reason: Some("No local runtime found (Docker or Lume).".into()),+ local_backends: Some(vec![]),+ lume_source: Some("system".into()),+ ..env()+ };+ let v = view(&s, &system);+ assert_eq!(+ v.placement_error.as_deref(),+ Some("This Mac\u{2019}s own Lume isn\u{2019}t installed.")+ );+ let switch = v.runtime_switch.expect("built-in offered");+ assert_eq!(+ (+ switch.setting.as_str(),+ switch.value.as_str(),+ switch.label.as_str()+ ),+ ("runtime.lume", "builtin", "Use built-in Lume")+ );+ assert_eq!(v.placement_hint.as_deref(), Some(OTHER_MAC_HINT));+ assert!(!v.can_continue);+ // Not on an Intel Mac (Lume needs Apple silicon).+ let intel = WizardEnv {+ host_arch: Some("amd64".into()),+ ..system.clone()+ };+ assert!(view(&s, &intel).runtime_switch.is_none());+ }++ /// With your other Mac online and This Mac unable to run the image,+ /// New Space starts on that Mac, by name; a choice the person made+ /// stays.+ #[test]+ fn a_mac_that_cannot_run_it_starts_on_your_other_mac() {+ let e = WizardEnv {+ local_available: false,+ local_backends: Some(vec![]),+ hosts: vec![host("m-studio", "Studio", "relay", true)],+ ..env()+ };+ let s = reduce(+ &initial(&e),+ &WizardAction::ChooseOs { os: SpaceOs::Macos },+ &e,+ );+ let v = view(&s, &e);+ assert_eq!(v.placement_id, "host:m-studio");+ assert_eq!(v.host.as_deref(), Some("m-studio"));+ assert!(+ v.placement_error.is_none() && v.placement_hint.is_none() && v.runtime_switch.is_none()+ );+ assert!(v.can_continue);+ // Picked This Mac on purpose: it stays (with the install offered).+ let picked = reduce(+ &s,+ &WizardAction::ChoosePlacement { on: "local".into() },+ &e,+ );+ let picked = reduce(&picked, &WizardAction::ChooseOs { os: SpaceOs::Macos }, &e);+ let v = view(&picked, &e);+ assert_eq!(v.placement_id, "local");+ assert!(v.placement_error.is_some());+ assert!(v.placement_hint.is_none(), "your Mac is in the menu");+ // An offline Mac is listed but never chosen for you.+ let offline = WizardEnv {+ hosts: vec![host("m-studio", "Studio", "relay", false)],+ ..e+ };+ let s = reduce(+ &initial(&offline),+ &WizardAction::ChooseOs { os: SpaceOs::Macos },+ &offline,+ );+ let v = view(&s, &offline);+ assert_eq!(v.placement_id, "local");+ // One line says how it comes back.+ assert_eq!(+ v.placement_hint.as_deref(),+ Some(+ "Studio is offline. Open Cua Spaces on Studio; once it is back, choose it in Run on."+ )+ );+ }+/// The "Run on" menu lists This Mac and your machines; your clouds/// only with the "Your cloud" experiment. Disabled machines say why.#[test]diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rsindex 76d881552e..0e289ab143 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs@@ -3049,6 +3049,21 @@ pub struct AppSpaceHost {pub limits: Vec<AppHostLimit>,}+/// A setting that makes This Mac able to run the Space: shown when the+/// person chose to use only this Mac's own runtime and it is missing.+pub type AppRuntimeSwitch = core::wizard::RuntimeSwitch;+#[uniffi::remote(Record)]+pub struct AppRuntimeSwitch {+ /// The `cua config` setting: `runtime.lume`.+ pub setting: String,+ /// The value to set: `builtin`.+ pub value: String,+ /// The button: "Use built-in Lume".+ pub label: String,+ /// One line on what that does.+ pub detail: String,+}+/// One entry of the "Run on" menu: a machine that can host the Space.pub type AppPlacementOption = core::wizard::PlacementOption;#[uniffi::remote(Record)]@@ -3112,6 +3127,9 @@ pub struct AppWizardEnv {pub max_cpus: u32,/// This machine's architecture (`arm64`, `amd64`), when known.pub host_arch: Option<String>,+ /// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ /// `system`), when known.+ pub lume_source: Option<String>,/// Free space and pulled images here (the SDK's `Local.storage()`),/// when known.pub storage: Option<AppLocalStorage>,@@ -3610,6 +3628,12 @@ pub struct AppWizardView {pub host: Option<String>,/// Why the chosen placement cannot be used.pub placement_error: Option<String>,+ /// One line under "Run on" when This Mac cannot run the Space and no+ /// machine of yours is listed: how another Mac joins.+ pub placement_hint: Option<String>,+ /// Switches This Mac to the built-in runtime the Space needs, when it+ /// is set to use its own and that is missing.+ pub runtime_switch: Option<AppRuntimeSwitch>,/// Advanced shown.pub advanced: bool,/// Kind tiles.@@ -6280,6 +6304,9 @@ pub struct AppSettingsInput {/// "Connect to the desktop automatically" (none: no row; a shell/// without the preview cover leaves it out).pub auto_connect: Option<bool>,+ /// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ /// `system`); none: no Runtimes section.+ pub lume_source: Option<String>,}/// How a Settings row draws.diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rsindex 29d4509962..b470906d4a 100644--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs@@ -1480,7 +1480,8 @@ impl Spaces {/// (at most [`HOST_PROBE`] each, all at once). One that answers without/// providing Spaces is left out; one that does not answer is listed/// offline when it provided one of your Spaces before (relay) or was- /// added as a host (direct). Without a relay account, or when the relay+ /// added as a host (direct), or is yours and set up to provide Spaces+ /// (its relay meta, [`cua_host::META_PROVIDES_SPACES`]). Without a relay account, or when the relay/// cannot be asked, only the direct hosts are listed.pub async fn hosts(&self) -> Result<Vec<HostOffer>> {let relay: Vec<crate::relay::RelayMachine> = if self.relay_account().is_some() {@@ -1523,7 +1524,16 @@ impl Spaces {} else {None};- host_offer(m.id.clone(), name, "relay", answer, known.contains(&m.id))+ // Offline, it is listed (with why) when it provided one+ // of your Spaces before, or its setup said it provides+ // Spaces (or predates saying so): a Mac whose service+ // is down must not just vanish from "Run on".+ let offers_spaces = m+ .meta+ .get(cua_host::META_PROVIDES_SPACES)+ .is_none_or(|v| v != "off");+ let keep = known.contains(&m.id) || (m.role == "owner" && offers_spaces);+ host_offer(m.id.clone(), name, "relay", answer, keep)}),).await;diff --git a/libs/cua/crates/cua-spaces/tests/host_spaces.rs b/libs/cua/crates/cua-spaces/tests/host_spaces.rsindex d147720486..fd02b6348b 100644--- a/libs/cua/crates/cua-spaces/tests/host_spaces.rs+++ b/libs/cua/crates/cua-spaces/tests/host_spaces.rs@@ -885,3 +885,41 @@ async fn a_local_space_suspends_and_resumes_and_others_refuse() {(String::new(), String::new()));}++/// Your other Mac must not vanish from "Run on" while its service is down+/// (a failed setup, a restart): a machine of yours set up to provide+/// Spaces is listed offline, by name; one set up only to share its desktop+/// is not.+#[tokio::test]+async fn an_offline_machine_set_up_for_spaces_is_listed_by_name() {+ let relay = FakeRelay::start().await;+ relay.add_account("ada-token", "ada", Some("[email protected]"));+ let dir = tempfile::tempdir().unwrap();+ for (name, profile) in [+ ("Studio", HostProfile::Spare),+ ("Laptop", HostProfile::Desktop),+ ] {+ let home = dir.path().join(name);+ let driver = dir.path().join(format!("{name}-cua-spacesd"));+ std::fs::write(&driver, b"#!/bin/sh\n").unwrap();+ let mut opts = SetupOptions::relay(&relay.url).profile(profile);+ opts.name = Some(name.into());+ opts.driver_bin = Some(driver);+ Host::new(&home)+ .with_service_manager(Arc::new(FakeServiceManager::default()))+ .setup(opts, &StaticToken("ada-token".into()))+ .await+ .unwrap();+ }+ let other = tempfile::tempdir().unwrap();+ let spaces = Spaces::builder()+ .home(other.path())+ .relay(cua_spaces::RelayAccount::new(+ &relay.url,+ Arc::new(StaticToken("ada-token".into())),+ ))+ .build();+ let hosts = spaces.hosts().await.unwrap();+ let names: Vec<(&str, bool)> = hosts.iter().map(|h| (h.name.as_str(), h.online)).collect();+ assert_eq!(names, [("Studio", false)]);+}diff --git a/libs/cua/crates/cua-vmm/Cargo.toml b/libs/cua/crates/cua-vmm/Cargo.tomlindex fe2a5d044c..7be3d5729f 100644--- a/libs/cua/crates/cua-vmm/Cargo.toml+++ b/libs/cua/crates/cua-vmm/Cargo.toml@@ -25,6 +25,7 @@ futures = "0.3"reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"], optional = true }serde = { version = "1", features = ["derive"] }sha2 = "0.10"+toml_edit = "0.25"serde_json = "1"thiserror = "2"tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "process", "rt-multi-thread", "sync", "time"] }diff --git a/libs/cua/crates/cua-vmm/src/auto.rs b/libs/cua/crates/cua-vmm/src/auto.rsindex e09eb175e7..efd8ce1eca 100644--- a/libs/cua/crates/cua-vmm/src/auto.rs+++ b/libs/cua/crates/cua-vmm/src/auto.rs@@ -199,7 +199,7 @@ pub async fn doctor() -> DoctorReport {// Lume.let mut lume = LumeReport {supported_host: host_os == HostOs::Macos && host_arch == Arch::Aarch64,- binary: host::which("lume"),+ binary: lume_binary(),url: std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into()),..Default::default()};@@ -214,20 +214,28 @@ pub async fn doctor() -> DoctorReport {.map(|s| s.trim().to_string());}}+ // Without any Lume, the built-in one is set up on first use unless the+ // setting says to use only this Mac's own.+ let builtin_ok = lume_builtin_allowed();let lume_status = BackendStatus {backend: BackendKind::Lume,ready: lume.supported_host && lume.serving,- provisionable: lume.supported_host && !lume.serving,+ provisionable: lume.supported_host+ && !lume.serving+ && (lume.binary.is_some() || builtin_ok),detail: if !lume.supported_host {"Lume needs a macOS Apple Silicon host".into()} else if lume.serving {format!("lume serve answering at {}", lume.url)} else if lume.binary.is_some() {"lume installed but not serving".into()+ } else if builtin_ok {+ "built-in Lume, set up on first use".into()} else {- "lume not installed".into()+ "Lume is not installed on this Mac (macOS VMs are set to use this Mac's own Lume)"+ .into()},- missing: if lume.supported_host && lume.binary.is_none() {+ missing: if lume.supported_host && lume.binary.is_none() && !builtin_ok {vec!["lume".into()]} else {vec![]@@ -236,11 +244,13 @@ pub async fn doctor() -> DoctorReport {vec![]} else if lume.binary.is_some() {vec!["start `lume serve`".into()]- } else {+ } else if builtin_ok {vec![- "run the Lume installer (allow_install)".into(),+ "download the built-in Lume (about 6 MB, signed)".into(),"start `lume serve`".into(),]+ } else {+ vec![]},};@@ -412,6 +422,30 @@ pub fn select(req: &SelectRequest, report: &DoctorReport) -> Result<Selection> {}}+/// The Lume binary the setting picks (see [`crate::lume::builtin`]).+fn lume_binary() -> Option<PathBuf> {+ #[cfg(feature = "lume")]+ {+ crate::lume::lume_bin()+ }+ #[cfg(not(feature = "lume"))]+ {+ host::which("lume")+ }+}++/// Whether `runtime.lume` lets the built-in Lume be set up.+fn lume_builtin_allowed() -> bool {+ #[cfg(feature = "lume")]+ {+ crate::lume::builtin::LumeSource::current().allows_builtin()+ }+ #[cfg(not(feature = "lume"))]+ {+ false+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/libs/cua/crates/cua-vmm/src/lume/builtin.rs b/libs/cua/crates/cua-vmm/src/lume/builtin.rsnew file mode 100644index 0000000000..d59769c960--- /dev/null+++ b/libs/cua/crates/cua-vmm/src/lume/builtin.rs@@ -0,0 +1,352 @@+//! Built-in Lume: a pinned, signed Lume that cua downloads into its own+//! directory the first time a macOS Space needs one, so creating a macOS+//! Space never asks for Homebrew, a terminal or an installer.+//!+//! * **Which Lume.** [`LumeSource`] (`cua config set runtime.lume`, the+//! apps' Settings): `auto` (the default) uses a Lume already on this Mac+//! and the built-in one otherwise; `builtin` always the built-in one;+//! `system` only the one on this Mac, and never downloads anything.+//! * **Pinned and verified.** [`VERSION`] from the trycua/cua release, its+//! SHA-256 checked before anything is unpacked, then `codesign --verify`+//! and the Developer ID team ([`TEAM_ID`]) checked before it is used. A+//! new app (and cua) release moves the pin.+//! * **Cua's own directory.** `$CUA_HOME/runtimes/lume/<version>`+//! ([`dir`]); [`remove`] deletes it. A user's own Lume is never touched.+//! * **Lazy.** Nothing is downloaded until a create needs it+//! ([`super::LumeRuntime::ensure_serving`]), with the download reported as+//! the create's progress.++use std::path::{Path, PathBuf};++use crate::error::{Result, VmmError};+use crate::host;++/// The pinned Lume release.+pub const VERSION: &str = "0.6.0";+/// Its Apple silicon tarball (`lume` launcher + signed `lume.app`).+pub const URL: &str =+ "https://github.com/trycua/cua/releases/download/lume-v0.6.0/lume-0.6.0-darwin-arm64.tar.gz";+/// The tarball's SHA-256 (the release manifest's).+pub const SHA256: &str = "4d25c7c36ebd3fdf0e2f97f9e7a2c4ff2d0538ba9eb2d536f6dbb542d9d504a7";+/// The tarball's size, for progress and the disk check.+pub const SIZE: u64 = 6_114_070;+/// Cua AI, Inc.'s Developer ID team: the only signer accepted.+pub const TEAM_ID: &str = "YCK386LBJ7";++/// The setting that picks the Lume: `runtime.lume` in+/// `$CUA_HOME/config.toml`, overridden by `CUA_RUNTIME_LUME`.+pub const SETTING_ENV: &str = "CUA_RUNTIME_LUME";++/// Which Lume macOS Spaces run on.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum LumeSource {+ /// This Mac's Lume when there is one, else the built-in one.+ #[default]+ Auto,+ /// Always the built-in one.+ Builtin,+ /// Only this Mac's own Lume (nothing is downloaded).+ System,+}++impl LumeSource {+ /// `auto`, `builtin` or `system`.+ pub fn parse(word: &str) -> Option<Self> {+ match word.trim().to_ascii_lowercase().as_str() {+ "auto" | "" => Some(Self::Auto),+ "builtin" | "built-in" => Some(Self::Builtin),+ "system" => Some(Self::System),+ _ => None,+ }+ }++ /// The setting's word.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Auto => "auto",+ Self::Builtin => "builtin",+ Self::System => "system",+ }+ }++ /// The setting now: the environment, else the config file, else auto.+ /// Read on every use, so a change in Settings applies at once.+ pub fn current() -> Self {+ if let Some(s) = std::env::var(SETTING_ENV)+ .ok()+ .and_then(|v| Self::parse(&v))+ {+ return s;+ }+ Self::from_config(&host::cua_home().join("config.toml"))+ }++ /// `[runtime] lume = "..."` in `path` (auto when absent or unreadable).+ pub fn from_config(path: &Path) -> Self {+ std::fs::read_to_string(path)+ .ok()+ .and_then(|t| t.parse::<toml_edit::DocumentMut>().ok())+ .and_then(|d| {+ d.get("runtime")?+ .get("lume")?+ .as_str()+ .and_then(Self::parse)+ })+ .unwrap_or_default()+ }++ /// Whether the built-in Lume may be used (and downloaded).+ pub fn allows_builtin(self) -> bool {+ self != Self::System+ }+}++/// Where the built-in Lume lives.+pub fn dir() -> PathBuf {+ root().join(VERSION)+}++/// `$CUA_HOME/runtimes/lume`: every built-in Lume version.+pub fn root() -> PathBuf {+ host::cua_home().join("runtimes").join("lume")+}++/// The built-in Lume's executable, when it is installed and was verified.+pub fn installed() -> Option<PathBuf> {+ let d = dir();+ let bin = d.join("lume.app/Contents/MacOS/lume");+ (bin.is_file() && d.join(VERIFIED).is_file()).then_some(bin)+}++/// Written last, once the unpacked Lume passed every check.+const VERIFIED: &str = ".verified";++/// The Lume to run for `source`: this Mac's own (`system`, or `auto` when+/// it has one), else the built-in one when installed.+pub fn resolve(source: LumeSource) -> Option<PathBuf> {+ let system = || host::which("lume").filter(|p| !p.starts_with(root()));+ match source {+ LumeSource::System => system(),+ LumeSource::Builtin => installed(),+ LumeSource::Auto => system().or_else(installed),+ }+}++/// Deletes every built-in Lume (`$CUA_HOME/runtimes/lume`). A user's own+/// Lume is elsewhere and stays.+pub fn remove() -> Result<()> {+ match std::fs::remove_dir_all(root()) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),+ _ => Ok(()),+ }+}++/// One install at a time in this process (a second create waits for it).+static INSTALL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++/// Installs the built-in Lume when it is not there yet; its executable.+/// The download is reported as the running create's progress.+#[cfg(feature = "lume")]+pub async fn ensure() -> Result<PathBuf> {+ if let Some(bin) = installed() {+ return Ok(bin);+ }+ let _one = INSTALL.lock().await;+ if let Some(bin) = installed() {+ return Ok(bin);+ }+ if !(cfg!(target_os = "macos") && cfg!(target_arch = "aarch64")) {+ return Err(VmmError::missing(+ "Lume",+ "macOS Spaces need a Mac with Apple silicon",+ ));+ }+ std::fs::create_dir_all(root())?;+ crate::disk::ensure_space(&root(), SIZE * 5, "set up the built-in Lume")?;+ let staging = tempfile::Builder::new()+ .prefix(".install-")+ .tempdir_in(root())?;+ let tarball = staging.path().join("lume.tar.gz");+ download(URL, &tarball).await?;+ let got = sha256_file(&tarball)?;+ if got != SHA256 {+ return Err(VmmError::other(format!(+ "the built-in Lume download did not match its checksum (got {got}); try again"+ )));+ }+ let unpacked = staging.path().join("lume");+ std::fs::create_dir_all(&unpacked)?;+ host::run(+ "/usr/bin/tar",+ &[+ "-xzf",+ &tarball.to_string_lossy(),+ "-C",+ &unpacked.to_string_lossy(),+ ],+ )+ .await?;+ verify_signature(&unpacked.join("lume.app")).await?;+ std::fs::write(unpacked.join(VERIFIED), VERSION)?;+ let target = dir();+ let _ = std::fs::remove_dir_all(&target);+ std::fs::rename(&unpacked, &target)?;+ tracing::info!(version = VERSION, dir = %target.display(), "installed the built-in Lume");+ installed().ok_or_else(|| VmmError::other("the built-in Lume did not install"))+}++/// Streams `url` to `to`, reporting bytes as create progress.+#[cfg(feature = "lume")]+async fn download(url: &str, to: &Path) -> Result<()> {+ use crate::progress::{Meter, Phase, Progress, report};+ use tokio::io::AsyncWriteExt as _;+ let http = reqwest::Client::builder()+ .connect_timeout(std::time::Duration::from_secs(20))+ .timeout(std::time::Duration::from_secs(600))+ .build()+ .map_err(|e| VmmError::other(format!("download the built-in Lume: {e}")))?;+ let mut res = http+ .get(url)+ .send()+ .await+ .and_then(|r| r.error_for_status())+ .map_err(|e| VmmError::other(format!("download the built-in Lume: {e}")))?;+ let total = res.content_length().unwrap_or(SIZE);+ let mut file = tokio::fs::File::create(to).await?;+ let mut meter = Meter::new();+ let mut done = 0u64;+ let detail = format!("Setting up Lume {VERSION} for macOS Spaces");+ report(Progress::phase(Phase::Preparing).detail(detail.clone()));+ while let Some(chunk) = res+ .chunk()+ .await+ .map_err(|e| VmmError::other(format!("download the built-in Lume: {e}")))?+ {+ if done + chunk.len() as u64 > SIZE * 4 {+ return Err(VmmError::other("the built-in Lume download is too large"));+ }+ file.write_all(&chunk).await?;+ done += chunk.len() as u64;+ if let Some(t) = meter.sample_at(std::time::Instant::now(), done, total) {+ report(+ Progress::phase(Phase::Preparing)+ .detail(detail.clone())+ .bytes(t)+ .fraction(done as f64 / total.max(1) as f64),+ );+ }+ }+ file.flush().await?;+ Ok(())+}++fn sha256_file(path: &Path) -> Result<String> {+ use sha2::{Digest, Sha256};+ use std::io::Read as _;+ let mut f = std::fs::File::open(path)?;+ let mut h = Sha256::new();+ let mut buf = vec![0u8; 64 * 1024];+ loop {+ let n = f.read(&mut buf)?;+ if n == 0 {+ break;+ }+ h.update(&buf[..n]);+ }+ Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())+}++/// `codesign --verify --strict` passes and the signer is [`TEAM_ID`].+async fn verify_signature(app: &Path) -> Result<()> {+ let app = app.to_string_lossy();+ host::run(+ "/usr/bin/codesign",+ &["--verify", "--deep", "--strict", &app],+ )+ .await+ .map_err(|e| VmmError::other(format!("the built-in Lume is not validly signed: {e}")))?;+ let out = tokio::process::Command::new("/usr/bin/codesign")+ .args(["-dv", "--verbose=2", &app])+ .output()+ .await?;+ // codesign -d prints to stderr.+ let text = String::from_utf8_lossy(&out.stderr);+ if !team_matches(&text) {+ return Err(VmmError::other(+ "the built-in Lume is not signed by Cua AI, Inc.",+ ));+ }+ Ok(())+}++fn team_matches(codesign_display: &str) -> bool {+ codesign_display+ .lines()+ .any(|l| l.trim() == format!("TeamIdentifier={TEAM_ID}"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_setting_parses_and_defaults_to_auto() {+ assert_eq!(LumeSource::parse("Built-in"), Some(LumeSource::Builtin));+ assert_eq!(LumeSource::parse("system"), Some(LumeSource::System));+ assert_eq!(LumeSource::parse("nope"), None);+ let d = tempfile::tempdir().unwrap();+ let p = d.path().join("config.toml");+ assert_eq!(LumeSource::from_config(&p), LumeSource::Auto);+ std::fs::write(+ &p,+ "[default]\non = \"local\"\n\n[runtime]\nlume = \"system\"\n",+ )+ .unwrap();+ assert_eq!(LumeSource::from_config(&p), LumeSource::System);+ assert!(!LumeSource::System.allows_builtin());+ assert!(LumeSource::Auto.allows_builtin());+ }++ #[test]+ fn only_cua_s_team_is_accepted() {+ assert!(team_matches(+ "Identifier=com.trycua.lume\nTeamIdentifier=YCK386LBJ7\n"+ ));+ assert!(!team_matches("TeamIdentifier=ABCDE12345\n"));+ assert!(!team_matches("TeamIdentifier=not set\n"));+ }++ #[test]+ fn the_pin_is_a_sha256_and_a_release_url() {+ assert_eq!(SHA256.len(), 64);+ assert!(URL.contains(&format!(+ "lume-v{VERSION}/lume-{VERSION}-darwin-arm64.tar.gz"+ )));+ }++ /// Opt-in (network): downloads the pinned Lume into a temporary+ /// `CUA_HOME`, verifies it, and finds it as `builtin` and `auto`.+ /// `CUA_HOME=<tmp> cargo test -p cua-vmm --lib builtin -- --ignored`.+ #[cfg(all(feature = "lume", target_os = "macos", target_arch = "aarch64"))]+ #[tokio::test]+ #[ignore = "downloads the pinned Lume release (network)"]+ async fn downloads_and_verifies_the_pinned_lume() {+ let home = std::env::var("CUA_HOME").expect("set CUA_HOME to a temporary directory");+ assert!(+ !home.is_empty() && !home.ends_with("/.cua"),+ "never the real cua home"+ );+ let bin = ensure().await.unwrap();+ assert_eq!(installed(), Some(bin.clone()));+ assert_eq!(resolve(LumeSource::Builtin), Some(bin.clone()));+ let out = std::process::Command::new(&bin)+ .arg("--version")+ .output()+ .unwrap();+ assert!(String::from_utf8_lossy(&out.stdout).contains(VERSION));+ // Again: already there, nothing downloaded.+ assert_eq!(ensure().await.unwrap(), bin);+ remove().unwrap();+ assert!(installed().is_none());+ }+}diff --git a/libs/cua/crates/cua-vmm/src/lume/mod.rs b/libs/cua/crates/cua-vmm/src/lume/mod.rsindex b14c59b089..662bc2cf65 100644--- a/libs/cua/crates/cua-vmm/src/lume/mod.rs+++ b/libs/cua/crates/cua-vmm/src/lume/mod.rs@@ -11,9 +11,10 @@//! same NoCloud seed as the QEMU backend provisions SSH access.//!//! [`LumeRuntime::ensure_serving`] makes the backend zero-setup: if the API is-//! not reachable it starts `lume serve`, and when the binary is missing it runs-//! the official installer only if [`LumeConfig::allow_install`] is set.+//! not reachable it starts `lume serve`, and when the binary is missing it sets+//! up the built-in Lume ([`builtin`]) unless `runtime.lume` is `system`.+pub mod builtin;pub mod client;pub mod gpu;pub mod lease;@@ -108,9 +109,10 @@ pub fn base_vm_name(reference: &str) -> String {format!("cua-base-{}", &hex[..12])}-/// Locate the `lume` binary.+/// Locate the `lume` binary for the `runtime.lume` setting: this Mac's+/// own, or the built-in one ([`builtin`]) when installed.pub fn lume_bin() -> Option<PathBuf> {- host::which("lume")+ builtin::resolve(builtin::LumeSource::current())}/// Deletes a clone whose create was cut off (dropped) before its first@@ -251,8 +253,18 @@ impl LumeRuntime {"start it with `lume serve`",));}+ let source = builtin::LumeSource::current();let bin = match lume_bin() {Some(b) => b,+ // Nothing to ask: the pinned, signed Lume, into cua's own dir.+ None if source.allows_builtin() => builtin::ensure().await?,+ None if source == builtin::LumeSource::System && !self.cfg.allow_install => {+ return Err(VmmError::missing(+ "Lume",+ "macOS Spaces are set to use this Mac's own Lume, and it is not installed. \+ Choose Built-in for macOS VMs in Settings (or `cua config set runtime.lume builtin`)",+ ));+ }None if self.cfg.allow_install => {install_lume().await?;if self.client.reachable().await {diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.pyindex d800542962..4627836fae 100644--- a/libs/cua/scripts/generate-app-core-ffi.py+++ b/libs/cua/scripts/generate-app-core-ffi.py@@ -35,7 +35,7 @@ TYPES = [("teleport/grid.rs", "teleport::grid", ["PickerTileIcon", "PickerTileThumbnail", "PickerTile", "PickerTileSection", "PickerGrid", "PickerGridTab", "PickerGridTabItem", "PickerGridPrimary"]),("teleport/review.rs", "teleport::review", ["SendSource", "RememberedChoice", "ReviewDomain", "ReviewToggle", "VaultSource", "ReviewChoice"]),("teleport/flow.rs", "teleport::flow", ["Capability", "Move", "SensitiveGroup", "SensitiveOption", "CatalogEntry", "ConsentKind", "ConsentItem", "PlanStepView", "Plan", "RunPhase", "RunEvent", "RunReport", "Consent", "InstallCuaPrompt", "Step", "PickerState", "PickerEvent", "EntrySection", "ReviewView"]),- ("wizard.rs", "wizard", ["LocalEngine", "CloudEngine", "ImageTier", "ImageDistro", "PlatformSize", "ImageSizes", "SandboxImage", "ImageGroup", "KindOption", "StorageVolume", "LocalStorage", "CloudPricing", "CloudOffer", "ConnectedCloud", "HostLimit", "SpaceHost", "PlacementOption", "GpuChoice", "WizardEnv", "WizardMode", "AddressForm", "WizardState", "WizardAction", "StepState", "StepView", "Tile", "MenuOption", "CreatePlan", "CreateSpaceArgs", "AddressView", "AddressSubmit", "ImageSuggestion", "SuggestionGroup", "ImageFieldView", "WizardField", "WizardLabels", "WizardFact", "GpuRow", "WizardView"]),+ ("wizard.rs", "wizard", ["LocalEngine", "CloudEngine", "ImageTier", "ImageDistro", "PlatformSize", "ImageSizes", "SandboxImage", "ImageGroup", "KindOption", "StorageVolume", "LocalStorage", "CloudPricing", "CloudOffer", "ConnectedCloud", "HostLimit", "SpaceHost", "RuntimeSwitch", "PlacementOption", "GpuChoice", "WizardEnv", "WizardMode", "AddressForm", "WizardState", "WizardAction", "StepState", "StepView", "Tile", "MenuOption", "CreatePlan", "CreateSpaceArgs", "AddressView", "AddressSubmit", "ImageSuggestion", "SuggestionGroup", "ImageFieldView", "WizardField", "WizardLabels", "WizardFact", "GpuRow", "WizardView"]),("keyvault/wire.rs", "keyvault::wire", ["KvItemPolicy", "KvItem", "KvFavicon", "KvDomainCount", "KvInventory", "KvSigning", "KvCaller", "KvSelector", "KvAccessRequest", "KvPending", "KvGrant", "KvRuleCaller", "KvRule", "KvDelivery", "KvAuditEntry", "KvStatus", "KvVerification", "KeyvaultOverview", "KvCommand"]),("keyvault/view.rs", "keyvault::view", ["Tone", "SigningBadge", "Tri", "DecisionTone", "Decision", "PendingRow", "AccessKind", "AccessRow", "KvLabels", "KeyvaultPage"]),("keyvault/vault.rs", "keyvault::vault", ["KvKind", "KvLock", "VaultState", "VaultAction", "VaultRow", "VaultSite", "VaultFiles", "VaultApp", "VaultSelection", "VaultView", "UnlockPrompt", "KvDeleteConfirm", "KvVaultSource"]),diff --git a/libs/images/tools/cua-image-pack/Cargo.lock b/libs/images/tools/cua-image-pack/Cargo.lockindex 50283c23fe..7054a1d506 100644--- a/libs/images/tools/cua-image-pack/Cargo.lock+++ b/libs/images/tools/cua-image-pack/Cargo.lock@@ -389,6 +389,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit","tracing","vnc-rs","windows-sys 0.61.2",@@ -504,6 +505,12 @@ version = "1.0.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"+[[package]]name = "errno"version = "0.3.14"@@ -713,6 +720,12 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+[[package]]name = "heck"version = "0.5.0"@@ -1011,6 +1024,16 @@ dependencies = ["icu_properties",]+[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]+[[package]]name = "ipnet"version = "2.12.2"@@ -2156,6 +2179,43 @@ dependencies = ["tokio",]+[[package]]+name = "toml_datetime"+version = "1.1.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.25.15+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"+dependencies = [+ "indexmap",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_parser"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"+[[package]]name = "tower"version = "0.5.3"@@ -2622,6 +2682,15 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"+[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+dependencies = [+ "memchr",+]+[[package]]name = "writeable"version = "0.6.4"diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swiftindex 0fca15df05..176613a040 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift@@ -24614,6 +24614,92 @@ public func FfiConverterTypeAppRoutineInput_lower(_ value: AppRoutineInput) -> R}+public struct AppRuntimeSwitch: Equatable, Hashable {+ /**+ * The `cua config` setting: `runtime.lume`.+ */+ public var setting: String+ /**+ * The value to set: `builtin`.+ */+ public var value: String+ /**+ * The button: "Use built-in Lume".+ */+ public var label: String+ /**+ * One line on what that does.+ */+ public var detail: String++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * The `cua config` setting: `runtime.lume`.+ */setting: String,+ /**+ * The value to set: `builtin`.+ */value: String,+ /**+ * The button: "Use built-in Lume".+ */label: String,+ /**+ * One line on what that does.+ */detail: String) {+ self.setting = setting+ self.value = value+ self.label = label+ self.detail = detail+ }+++++}++#if compiler(>=6)+extension AppRuntimeSwitch: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeAppRuntimeSwitch: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppRuntimeSwitch {+ return+ try AppRuntimeSwitch(+ setting: FfiConverterString.read(from: &buf),+ value: FfiConverterString.read(from: &buf),+ label: FfiConverterString.read(from: &buf),+ detail: FfiConverterString.read(from: &buf)+ )+ }++ public static func write(_ value: AppRuntimeSwitch, into buf: inout [UInt8]) {+ FfiConverterString.write(value.setting, into: &buf)+ FfiConverterString.write(value.value, into: &buf)+ FfiConverterString.write(value.label, into: &buf)+ FfiConverterString.write(value.detail, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppRuntimeSwitch_lift(_ buf: RustBuffer) throws -> AppRuntimeSwitch {+ return try FfiConverterTypeAppRuntimeSwitch.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeAppRuntimeSwitch_lower(_ value: AppRuntimeSwitch) -> RustBuffer {+ return FfiConverterTypeAppRuntimeSwitch.lower(value)+}++public struct AppSandboxImage: Equatable, Hashable {/*** OCI ref.@@ -25349,6 +25435,11 @@ public struct AppSettingsInput: Equatable, Hashable {* without the preview cover leaves it out).*/public var autoConnect: Bool?+ /**+ * Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ * `system`); none: no Runtimes section.+ */+ public var lumeSource: String?// Default memberwise initializers are never public by default, so we// declare one manually.@@ -25415,7 +25506,11 @@ public struct AppSettingsInput: Equatable, Hashable {/*** "Connect to the desktop automatically" (none: no row; a shell* without the preview cover leaves it out).- */autoConnect: Bool?) {+ */autoConnect: Bool?,+ /**+ * Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ * `system`); none: no Runtimes section.+ */lumeSource: String?) {self.identity = identityself.apiKeyClient = apiKeyClientself.signIn = signIn@@ -25435,6 +25530,7 @@ public struct AppSettingsInput: Equatable, Hashable {self.keyvaultSiteIcons = keyvaultSiteIconsself.keyvaultProtection = keyvaultProtectionself.autoConnect = autoConnect+ self.lumeSource = lumeSource}@@ -25471,7 +25567,8 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {keyvaultUnlockPrompt: FfiConverterOptionBool.read(from: &buf),keyvaultSiteIcons: FfiConverterBool.read(from: &buf),keyvaultProtection: FfiConverterSequenceTypeAppFact.read(from: &buf),- autoConnect: FfiConverterOptionBool.read(from: &buf)+ autoConnect: FfiConverterOptionBool.read(from: &buf),+ lumeSource: FfiConverterOptionString.read(from: &buf))}@@ -25495,6 +25592,7 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {FfiConverterBool.write(value.keyvaultSiteIcons, into: &buf)FfiConverterSequenceTypeAppFact.write(value.keyvaultProtection, into: &buf)FfiConverterOptionBool.write(value.autoConnect, into: &buf)+ FfiConverterOptionString.write(value.lumeSource, into: &buf)}}@@ -30803,6 +30901,11 @@ public struct AppWizardEnv: Equatable, Hashable {* This machine's architecture (`arm64`, `amd64`), when known.*/public var hostArch: String?+ /**+ * Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ * `system`), when known.+ */+ public var lumeSource: String?/*** Free space and pulled images here (the SDK's `Local.storage()`),* when known.@@ -30861,6 +30964,10 @@ public struct AppWizardEnv: Equatable, Hashable {/*** This machine's architecture (`arm64`, `amd64`), when known.*/hostArch: String?,+ /**+ * Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,+ * `system`), when known.+ */lumeSource: String?,/*** Free space and pulled images here (the SDK's `Local.storage()`),* when known.@@ -30891,6 +30998,7 @@ public struct AppWizardEnv: Equatable, Hashable {self.localDetails = localDetailsself.maxCpus = maxCpusself.hostArch = hostArch+ self.lumeSource = lumeSourceself.storage = storageself.cloudPricing = cloudPricingself.clouds = clouds@@ -30923,6 +31031,7 @@ public struct FfiConverterTypeAppWizardEnv: FfiConverterRustBuffer {localDetails: FfiConverterOptionDictionaryStringString.read(from: &buf),maxCpus: FfiConverterUInt32.read(from: &buf),hostArch: FfiConverterOptionString.read(from: &buf),+ lumeSource: FfiConverterOptionString.read(from: &buf),storage: FfiConverterOptionTypeAppLocalStorage.read(from: &buf),cloudPricing: FfiConverterOptionTypeAppCloudPricing.read(from: &buf),clouds: FfiConverterSequenceTypeAppConnectedCloud.read(from: &buf),@@ -30941,6 +31050,7 @@ public struct FfiConverterTypeAppWizardEnv: FfiConverterRustBuffer {FfiConverterOptionDictionaryStringString.write(value.localDetails, into: &buf)FfiConverterUInt32.write(value.maxCpus, into: &buf)FfiConverterOptionString.write(value.hostArch, into: &buf)+ FfiConverterOptionString.write(value.lumeSource, into: &buf)FfiConverterOptionTypeAppLocalStorage.write(value.storage, into: &buf)FfiConverterOptionTypeAppCloudPricing.write(value.cloudPricing, into: &buf)FfiConverterSequenceTypeAppConnectedCloud.write(value.clouds, into: &buf)@@ -31540,6 +31650,16 @@ public struct AppWizardView: Equatable, Hashable {* Why the chosen placement cannot be used.*/public var placementError: String?+ /**+ * One line under "Run on" when This Mac cannot run the Space and no+ * machine of yours is listed: how another Mac joins.+ */+ public var placementHint: String?+ /**+ * Switches This Mac to the built-in runtime the Space needs, when it+ * is set to use its own and that is missing.+ */+ public var runtimeSwitch: AppRuntimeSwitch?/*** Advanced shown.*/@@ -31739,6 +31859,14 @@ public struct AppWizardView: Equatable, Hashable {/*** Why the chosen placement cannot be used.*/placementError: String?,+ /**+ * One line under "Run on" when This Mac cannot run the Space and no+ * machine of yours is listed: how another Mac joins.+ */placementHint: String?,+ /**+ * Switches This Mac to the built-in runtime the Space needs, when it+ * is set to use its own and that is missing.+ */runtimeSwitch: AppRuntimeSwitch?,/*** Advanced shown.*/advanced: Bool,@@ -31871,6 +31999,8 @@ public struct AppWizardView: Equatable, Hashable {self.cloud = cloudself.host = hostself.placementError = placementError+ self.placementHint = placementHint+ self.runtimeSwitch = runtimeSwitchself.advanced = advancedself.kindTiles = kindTilesself.runtimes = runtimes@@ -31939,6 +32069,8 @@ public struct FfiConverterTypeAppWizardView: FfiConverterRustBuffer {cloud: FfiConverterOptionString.read(from: &buf),host: FfiConverterOptionString.read(from: &buf),placementError: FfiConverterOptionString.read(from: &buf),+ placementHint: FfiConverterOptionString.read(from: &buf),+ runtimeSwitch: FfiConverterOptionTypeAppRuntimeSwitch.read(from: &buf),advanced: FfiConverterBool.read(from: &buf),kindTiles: FfiConverterSequenceTypeAppTile.read(from: &buf),runtimes: FfiConverterSequenceTypeAppMenuOption.read(from: &buf),@@ -31993,6 +32125,8 @@ public struct FfiConverterTypeAppWizardView: FfiConverterRustBuffer {FfiConverterOptionString.write(value.cloud, into: &buf)FfiConverterOptionString.write(value.host, into: &buf)FfiConverterOptionString.write(value.placementError, into: &buf)+ FfiConverterOptionString.write(value.placementHint, into: &buf)+ FfiConverterOptionTypeAppRuntimeSwitch.write(value.runtimeSwitch, into: &buf)FfiConverterBool.write(value.advanced, into: &buf)FfiConverterSequenceTypeAppTile.write(value.kindTiles, into: &buf)FfiConverterSequenceTypeAppMenuOption.write(value.runtimes, into: &buf)@@ -54208,6 +54342,30 @@ fileprivate struct FfiConverterOptionTypeAppReviewView: FfiConverterRustBuffer {}}+#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterOptionTypeAppRuntimeSwitch: FfiConverterRustBuffer {+ typealias SwiftType = AppRuntimeSwitch?++ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {+ guard let value = value else {+ writeInt(&buf, Int8(0))+ return+ }+ writeInt(&buf, Int8(1))+ FfiConverterTypeAppRuntimeSwitch.write(value, into: &buf)+ }++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {+ switch try readInt(&buf) as Int8 {+ case 0: return nil+ case 1: return try FfiConverterTypeAppRuntimeSwitch.read(from: &buf)+ default: throw UniffiInternalError.unexpectedOptionalTag+ }+ }+}+#if swift(>=5.8)@_documentation(visibility: private)#endifdiff --git a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lockindex 3084abd2a4..b30d0014a0 100644--- a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock+++ b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock@@ -1539,6 +1539,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit 0.25.13+spec-1.1.0","tracing","vnc-rs","windows-sys 0.61.2",diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lockindex 0c131f0490..2634a145c5 100644--- a/tests/e2e/cua-sdk/rust/Cargo.lock+++ b/tests/e2e/cua-sdk/rust/Cargo.lock@@ -1548,6 +1548,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit","tracing","vnc-rs","windows-sys 0.61.2",diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lockindex 038a90263c..63dc65dbc7 100644--- a/tests/e2e/local-runtimes/Cargo.lock+++ b/tests/e2e/local-runtimes/Cargo.lock@@ -694,6 +694,7 @@ dependencies = ["tempfile","thiserror 2.0.20","tokio",+ "toml_edit","tracing","vnc-rs","windows-sys 0.61.2",