Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

103 KB
Raw Blame
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.

import AppKit
import CuaSDK
import CuaSpacesFFI
import Foundation
import Observation

/// A teleport handed from the notch to a Space's detail.
public struct PendingTeleport: Equatable {
    public var spaceId: String
    public var entry: TeleportCatalogEntry?
    public var files: [String]
}

/// What the main window shows.
public enum MainSelection: Hashable {
    case space(String)
    case keyvault(KvSelection)
    /// Persistent agents.
    case agents
    /// The Cua Volume.
    case drive
    /// The notifications feed.
    case notifications
    /// Your machines: this one and the others that run your Spaces.
    case machines
    /// The getting-started checklist.
    case gettingStarted
}

/// A detail action to run once that Space's detail shows (the checklist's
/// Teleport and Share).
public struct DetailRequest: Equatable {
    public let spaceId: String
    public let action: AppDetailActionId
}

/// The app's root model. It holds the core's Space list state and forwards
/// every decision to the app core (`appRosterReduce`, `appSidebar`,
/// `appSpaceDetail`); views render what it exposes.
@MainActor
@Observable
public final class AppModel {
    public let backend: SpacesBackend
    /// The launch until the live services are in (ready at once for
    /// fixtures and tests): the window shows it instead of its content.
    public let startup: StartupModel
    /// The SDK backend, once the launch made it (nil in fixtures, and when
    /// it could not start).
    public private(set) var live: LiveSpacesBackend?
    private var whenLive: [(LiveSpacesBackend) -> Void] = []
    public private(set) var roster: AppRosterState
    public var query = ""
    public var selection: MainSelection?
    /// Several Spaces picked in the sidebar (⌘- or ⇧-click, ⌘A): the
    /// detail says how many and offers what they can do together. Empty
    /// while one item (`selection`) is selected.
    public var pickedSpaceIds: Set<String> = []
    /// The delete-and-leave confirm on screen (the core's
    /// `spaces.bulkConfirm`), with the Spaces it asks about.
    public var bulkAsk: BulkAsk?
    /// The Spaces a confirmed bulk delete or leave is working through.
    public internal(set) var bulkRunItems: [AppBulkItem]?
    /// The ids of that run with their result in, so far.
    public internal(set) var bulkFinished: [String] = []
    /// The bulk delete or leave's done toast ("Deleted 3 Spaces.").
    public var bulkToast: AppBulkDone?
    public var rosterError: String?
    /// Another app keeps its own daemon running and this app uses it (the
    /// supervisor yields to it after replacing it once): one line above
    /// every page while it lasts. Nil otherwise.
    public var daemonNotice: String?
    public var banner: String?
    public var bannerIsError = false
    public var showingNewSpace = false
    /// The command palette (⌘K).
    public var showingPalette = false
    public var confirmDeleteId: String?
    /// A Space menu's action, run by that Space's detail when it shows.
    public var detailRequest: DetailRequest?
    /// A teleport the notch started: the Space and the dropped app.
    public var pendingTeleport: PendingTeleport?
    public private(set) var loaded = false
    /// Some of your computers have not answered the last list read yet
    /// (`Spaces.list_known`): the list is not "no Spaces" meanwhile.
    public private(set) var listIncomplete = false
    /// How many computers are still being reached (0 when unknown).
    public private(set) var listReaching: UInt32 = 0
    /// Your other computers' rows are the last known ones (kept across a
    /// daemon restart), not yet confirmed.
    public private(set) var listStale = false
    /// What your other computers are creating now (CUA-2349), as the last list read said.
    public private(set) var listCreating: [SpaceCreatingElsewhere] = []
    /// `listCreating` less what the list already has a row for (the same
    /// name on that computer), like the Electron host.
    public var creatingElsewhere: [SpaceCreatingElsewhere] {
        listCreating.filter { c in
            !spaces.contains { $0.name == c.name && $0.id.hasPrefix("relay:\(c.machineId)") }
        }
    }
    /// The Spaces page's empty state and "Reaching N computers…" line, as
    /// the core decides them: the first-run page only for a complete list.
    public var listView: AppListView {
        appSpacesListView(input: AppListViewInput(loaded: loaded, incomplete: listIncomplete,
                                                  reaching: listReaching, count: UInt32(spaces.count)))
    }

    public let wizard: WizardModel
    public let keyvault: KeyvaultModel
    public let onboarding: OnboardingModel
    public let notch: NotchModel
    /// This machine: its state, page and the host setup form.
    public let host: HostModel
    /// This Mac's enrollment on the relay, the account's devices, approvals.
    public let devices: DevicesModel
    /// Persistent agents, the Cua Volume and the notifications feed.
    public let persistent: PersistentModel
    /// The getting-started checklist.
    public let checklist: ChecklistModel
    /// Settings, Storage: the Cua Volume's store, Finder volume and cache.
    public internal(set) var storage: StorageModel
    /// Settings, Connections: the provider keys agents get (kept by the daemon).
    public let agentKeys: AgentKeysModel
    /// The user's own clouds: the "Your cloud" tile and "Connect a cloud".
    public let cloud: CloudModel
    /// The cloud hosts the elastic pool added (Machines), read-only.
    public let elastic: ElasticModel
    /// The Cua account, the telemetry switch and the coding agents.
    let account: AccountRunning?
    let telemetry: TelemetryRunning?
    let agentSetup: AgentSetupRunning?
    /// The signed-in account.
    public private(set) var identity: String?
    /// The session's `cloudConfigured` field: nothing probes it any more
    /// (Cua Cloud has ended), so it stays false.
    public private(set) var cloudConfigured = false
    /// The Settings sign-in in progress.
    public private(set) var signIn: AppSignInPhase = .idle
    /// The page a waiting sign-in finishes on ("Open the browser again").
    public private(set) var signInURL: URL?
    /// A failed sign-in's toast (the classic window shows it for a while).
    public var signInToast: AppSignInToast?
    /// A sign-in still waiting after this fails (a device code lives
    /// about this long).
    public var signInTimeout: Duration = .seconds(600)
    /// Tells one sign-in from the next (a timeout of an old one is ignored).
    private var signInAttempt = 0
    /// The attempt in progress asked for a code instead of the browser's way back.
    private var signInByCode = false
    public private(set) var telemetryInput: AppTelemetryInput?
    /// Reads the account's Teams from the Spaces API (nil: Settings shows
    /// the account app's links only). Set by `AppEnvironment`.
    public var teamsReader: TeamsReading?
    /// Where Settings' Teams stand: not read yet, read, or failed.
    public private(set) var teamsState: AppTeamsState = .signedOut
    /// The owner's one-line note that sharing is for teams now and some
    /// people can no longer open a shared computer; shown once.
    public private(set) var shareRemovalNote: AppShareRemovalNote?
    /// This app as a login item (nil: no Launch at login row).
    let loginItem: LoginItemControlling?
    /// What the system reports for it (nil until read).
    public private(set) var loginItemStatus: AppLoginItemStatus?
    public private(set) var loginItemBusy = false
    public private(set) var loginItemError: String?
    public private(set) var agentRows: [AppAgentSettingsRow]?
    public private(set) var agentsBusy = false
    public private(set) var agentsPending: [String] = []
    /// Why the last agent action failed, per agent.
    var agentFailures: [String: String] = [:]
    /// The registry's Spaces (before This machine is added).
    var registrySpaces: [AppSpace] = []
    /// Memory and storage use of the Spaces whose detail is showing.
    public private(set) var usage: [String: AppSpaceUsage] = [:]
    /// Spaces being created: each shows in the list the moment its create
    /// starts and follows the SDK's progress (`spaces::creating`). Spaces
    /// being deleted, which show Deleting until the delete returns.
    public private(set) var creates = AppCreatesState(pending: [], deleting: [], powering: [], streaks: [])
    /// Sidebar rows as targets for a dragged real window.
    public let dropTargets = SidebarDropTargets()
    /// The New UI window's Space tiles, the same kind of target.
    public let pageDropTargets = SidebarDropTargets()
    public var settings: AppSettings
    let settingsPath: String
    /// Settings → About and the updater (none until `AppEnvironment`
    /// starts one).
    public var updates = UpdatesModel(updater: nil)

    public init(backend: SpacesBackend, keyvault: KeyvaultModel,
                onboarding: OnboardingModel, settingsPath: String,
                host: HostRunning? = nil, account: AccountRunning? = nil,
                telemetry: TelemetryRunning? = nil, agentSetup: AgentSetupRunning? = nil,
                devices: DevicesRunning? = nil,
                presence: PresenceChecking = LivePresence(), loginItem: LoginItemControlling? = nil,
                startup: StartupModel? = nil) {
        self.backend = backend
        self.startup = startup ?? StartupModel()
        self.devices = DevicesModel(devices: devices, presence: presence)
        self.persistent = PersistentModel(tools: backend as? AgentsToolRunning)
        self.checklist = ChecklistModel(path: URL(fileURLWithPath: settingsPath)
            .deletingLastPathComponent().appendingPathComponent("checklist.json").path)
        self.storage = StorageModel(tools: backend as? AgentsToolRunning)
        self.agentKeys = AgentKeysModel(tools: backend as? AgentsToolRunning)
        self.cloud = CloudModel(tools: backend as? CloudToolRunning)
        // Fixtures never read the real cua home's ledger.
        let fixtures = backend as? FixtureSpacesBackend
        self.elastic = ElasticModel(tools: backend as? CloudToolRunning,
                                    ledger: fixtures.map { fx in { fx.fixtureElastic ? FixtureSpacesBackend.fixtureLedger() : nil } })
        self.loginItem = loginItem
        self.host = HostModel(host: host)
        self.account = account
        self.telemetry = telemetry
        self.agentSetup = agentSetup
        self.roster = appRosterInitial(spaces: [])
        self.keyvault = keyvault
        self.onboarding = onboarding
        self.settingsPath = settingsPath
        let settings = appSettingsLoad(path: settingsPath)
        self.settings = settings
        self.wizard = WizardModel(env: AppWizardEnv(
            defaultLocation: settings.defaultLocation,
            localAvailable: true, localReason: nil, localBackends: nil, localDetails: nil,
            maxCpus: UInt32(max(2, min(16, ProcessInfo.processInfo.activeProcessorCount))),
            hostArch: Self.hostArch, lumeSource: nil, linuxSource: nil, storage: nil, clouds: [], hosts: [],
            experiments: settings.experiments, gpus: nil, nameSeed: nil))
        self.notch = NotchModel()
        // Pinned Spaces and desktops come first in the notch, across restarts.
        notch.setPinned(settings.notchPinned)
        // The notch tiles and the preview cover read one thumbnail store,
        // filled from the SDK's shared cache.
        notch.thumbnails.fetch = { [backend] id, maxAgeMs in await backend.thumbnail(id: id, maxAgeMs: maxAgeMs) }
        // The app core's usage events for each step (the Tauri app sends
        // the same ones): Settings, Storage, enrollment. The first run's
        // are the web page's (`telemetry.track`).
        self.checklist.telemetry = telemetry
        self.storage.telemetry = telemetry
        self.devices.telemetry = telemetry
        // Live Keyvault sign-ins show left of the notch (and in the menu).
        // Dismissed ones stay hidden across launches (Settings file).
        keyvault.dismissed = settings.dismissedAccess
        keyvault.siteIconsFromGoogle = { [weak self] in self?.settings.keyvaultSiteIcons ?? true }
        keyvault.onSharing = { [weak self] _ in self?.syncNotchKeyvault() }
        keyvault.onDismissed = { [weak self] ids in
            guard let self else { return }
            self.settings.dismissedAccess = ids
            self.saveSettings()
        }
        self.host.onChange = { [weak self] in self?.recompose() }
        // Providing Spaces turned on: ask for Local Network access now, on
        // this Mac's screen (the same steps as before a macOS Space is
        // created here), so a macOS Space another device creates here
        // connects instead of failing with "No route to host".
        self.host.onStartedProvidingSpaces = { [weak self] in self?.askLocalNetworkForHosting() }
        followChecklist()
        // No notification prompt before the first run is done.
        PermissionRequester.firstRunDone = { [weak onboarding] in onboarding?.completed ?? false }
        // Done's "Launch at login" checkbox is the user's choice.
        onboarding.onLaunchAtLogin = { [weak self] on in self?.setLaunchAtLogin(on) }
        // Which experiments are on: the day's `cua_app_active` carries them.
        telemetry?.record(appTelemetryExperimentsOn(experiments: settings.experiments))
        // The notifications marker lives in the settings file, so a restart
        // never posts the same entry again.
        persistent.seenMs = { [weak self] in self?.settings.notificationsSeenMs ?? 0 }
        persistent.saveSeenMs = { [weak self] seen in
            guard let self else { return }
            self.settings.notificationsSeenMs = seen
            self.saveSettings()
        }
        self.identity = account?.identity()
        self.host.identity = identity
        self.devices.signedIn = identity != nil
        // "Sign in again" in the enroll sheet is the account's sign-in.
        self.devices.signIn = { [weak self] in
            guard let self else { return false }
            await self.beginSignIn()
            if case .failed = self.signIn { return false }
            return self.identity != nil
        }
        // "Set up for access" signs in inline when relay setup has no
        // account, then carries on.
        self.host.signIn = { [weak self] in
            guard let self else { return false }
            await self.beginSignIn()
            if case .failed = self.signIn { return false }
            return self.identity != nil
        }
        // Relay sharing follows the sign-in: whose account this Mac is
        // shared with, read from the local session (no network).
        self.host.currentAccount = { [weak self] in
            guard let self, let account = self.account, let who = account.identity() else { return nil }
            let profile = account.profile()
            let name = profile?.name.flatMap { $0.trimmingCharacters(in: .whitespaces).isEmpty ? nil : $0 }
            return AppHostAccount(id: profile?.subject, email: profile?.email, display: name ?? who)
        }
        // A row takes a window drop by the core's rule (the notch tiles' too).
        dropTargets.isDropTarget = { [weak self] id in
            self?.spaces.first { $0.id == id }.map { appSpaceAcceptsDrop(space: $0) } ?? false
        }
        pageDropTargets.isDropTarget = dropTargets.isDropTarget
    }

    // MARK: - Launch

    /// Runs `f` with the SDK backend once the launch has it (now, when it
    /// already does). Never runs without one.
    public func onLive(_ f: @escaping (LiveSpacesBackend) -> Void) {
        if let live { f(live) } else { whenLive.append(f) }
    }

    /// The live services are in: read the account again (it was unknown
    /// until now) and show what the backend has.
    func attachLive(_ live: LiveSpacesBackend?) {
        identity = account?.identity()
        host.identity = identity
        devices.signedIn = identity != nil
        if let live {
            self.live = live
            let queued = whenLive
            whenLive = []
            for f in queued { f(live) }
        }
        watchListFromNow()
        Task {
            await refresh()
            await keyvault.refresh()
            await devices.refresh()
        }
    }

    // MARK: - Space list

    public var spaces: [AppSpace] { roster.spaces }

    /// The sidebar, from the core.
    public var sidebar: AppSidebarView {
        appSidebar(spaces: spaces, query: query, selectedId: selectedSpaceId ?? "")
    }

    public var selectedSpaceId: String? {
        if case .space(let id) = selection { return id }
        return nil
    }

    /// The selected Space and its detail, from the core.
    public var selectedSpace: AppSpace? {
        guard case .space = selection else { return nil }
        let id = sidebar.selectedId
        return spaces.first { $0.id == id }
    }

    /// Every Space's latest thumbnail: the notch tiles' and the preview
    /// cover's one store.
    public var thumbnails: SpaceThumbnails { notch.thumbnails }

    /// The Spaces that can stream now (running and reachable).
    public var streamableSpaceIds: [String] {
        spaces.filter { detail($0).canStream }.map(\.id)
    }

    /// What the Space's preview card shows over (or instead of) its live
    /// desktop, from the core.
    public func cover(_ detail: AppSpaceDetail, requested: Bool, stream: AppStreamPhase) -> AppDesktopCover {
        appDesktopCover(input: AppDesktopCoverInput(
            canStream: detail.canStream, previewText: detail.previewText,
            autoConnect: settings.autoConnect, connectRequested: requested, stream: stream,
            access: detail.access))
    }

    /// The detail as this Mac sees it: a machine reached through the
    /// relay has its Connect greyed out while this Mac is not enrolled, and
    /// one that does not share its desktop shows why in its place.
    public func detail(_ space: AppSpace) -> AppSpaceDetail {
        appSpaceDetailFor(space: space, usage: usage[space.id], hostArch: Self.hostArch,
                          access: devices.accessNotice)
    }

    /// The Spaces one of your machines provides (its detail lists them).
    public func hostedRows(_ machineId: String) -> [AppSidebarRow] {
        appHostedRows(spaces: spaces, machineSpaceId: machineId, selectedId: sidebar.selectedId ?? "")
    }

    // MARK: - Machines and getting started

    /// The Machines page's rows (the core's `machines::page_rows`, which
    /// the web UI lists too): This machine, the machines the Spaces list
    /// shows (one sharing its desktop, one that provides Spaces), then
    /// the account's devices that are none of them; each computer once.
    public var machinePageRows: [AppMachinePageRow] { appMachinesPageRows(input: machinesPageInput) }

    /// What the Machines page is listed from: the Spaces list, the
    /// account's devices, the hostnames and who the relay sees connected.
    var machinesPageInput: AppMachinesPageInput {
        let devices = self.devices.snapshot == nil ? [] : self.devices.input.devices.map {
            AppDeviceIn(id: $0.id, name: $0.name, platform: $0.platform ?? "", lastSeen: $0.lastSeen,
                        current: $0.current, state: $0.state)
        }
        return AppMachinesPageInput(
            hostOs: .macos, spaces: spaces, devices: devices, hostnames: relayHostnames,
            presence: self.devices.relayOnline, now: self.devices.nowSecs)
    }

    /// The Machines page as every UI draws it (the core's
    /// `machines_view::view`, which the New UI draws too): the list in
    /// groups with one line each, and each machine's page.
    public var machinesView: AppMachinesView {
        let relay = (devices.snapshot?.machines ?? []).map {
            AppMachinesViewRelay(id: $0.id, role: $0.role, team: $0.team, ownerEmail: $0.ownerEmail,
                                 providesSpaces: $0.providesSpaces)
        }
        // The Cua Spaces update this app found: a peer on a newer Cua is
        // fixed by it (this app bundles its Cua), and by nothing else.
        let update = updates.updateState
        let found = [.available, .downloading, .downloaded].contains(update.status) ? update.version ?? "" : ""
        return appMachinesView(input: AppMachinesViewInput(
            page: machinesPageInput, relay: relay, host: host.state, about: Self.machinesAbout, rows: nil,
            health: machineHealth.keys.sorted().compactMap { machineHealth[$0] },
            appUpdate: found, appUpdateReady: !found.isEmpty && update.status == .downloaded,
            clouds: cloud.cloudsInput))
    }

    /// What each machine's own daemon last reported of its health, by
    /// Machines page row id (`checkMachineHealth`): the view's issues.
    public var machineHealth: [String: AppMachinesViewHealth] = [:]
    @ObservationIgnored private var healthCheck: Task<Void, Never>?

    /// At most this many machines are checked at once.
    static let healthConcurrency = 3
    /// One machine's check may take this long.
    static let healthTimeout: Double = 35

    /// Checks the health of every machine the Machines page can check
    /// (`healthTarget`: This Mac through its daemon, another of your
    /// machines that is online through its own daemon over the relay or
    /// mesh), a few at once, and keeps what each said. A machine that is
    /// no longer checkable (offline, removed) loses its old result, so no
    /// stale issue shows. One check at a time; a call during one waits for
    /// it.
    public func checkMachineHealth() async {
        if let running = healthCheck {
            await running.value
            return
        }
        let task = Task { await self.runHealthChecks() }
        healthCheck = task
        await task.value
        healthCheck = nil
    }

    private func runHealthChecks() async {
        let targets = machinesView.machines.compactMap { m in m.healthTarget.map { (id: m.id, target: $0) } }
        let wanted = Set(targets.map(\.id))
        machineHealth = machineHealth.filter { wanted.contains($0.key) }
        let backend = self.backend
        var pending = targets[...]
        while !pending.isEmpty {
            let batch = pending.prefix(Self.healthConcurrency)
            pending = pending.dropFirst(batch.count)
            let results = await withTaskGroup(of: (String, AppMachinesViewHealth).self) { group in
                for t in batch {
                    group.addTask {
                        let machine = t.target.isEmpty ? nil : t.target
                        let r = await withTimeout(seconds: Self.healthTimeout) {
                            try await backend.machineHealth(machine: machine)
                        }
                        switch r {
                        case .success(var h):
                            h.id = t.id
                            return (t.id, h)
                        case .failure(let error):
                            let why = (error as? TimeoutError) != nil
                                ? "it didn\u{2019}t answer within \(Int(Self.healthTimeout)) s"
                                : LiveSpacesBackend.words(error)
                            return (t.id, AppMachinesViewHealth(id: t.id, checks: [], cuaVersion: "", error: why))
                        }
                    }
                }
                var out: [(String, AppMachinesViewHealth)] = []
                for await r in group { out.append(r) }
                return out
            }
            for (id, h) in results where wanted.contains(id) { machineHealth[id] = h }
        }
    }

    /// This Mac as the Machines page names it: its name, the app's
    /// version and macOS's.
    static let machinesAbout: AppMachinesViewAbout = {
        let info = Bundle.main.infoDictionary ?? [:]
        let v = ProcessInfo.processInfo.operatingSystemVersion
        let os = v.patchVersion == 0 ? "macOS \(v.majorVersion).\(v.minorVersion)"
            : "macOS \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"
        return AppMachinesViewAbout(
            computerName: Foundation.Host.current().localizedName ?? "",
            appVersion: info["CuaVersion"] as? String ?? info["CFBundleShortVersionString"] as? String ?? "",
            osVersion: os)
    }()

    /// Renames a machine from the Machines page: `this-mac` is this Mac's
    /// own relay registration (its host setup takes the name too).
    public func renameMachine(id: String, name: String) async throws {
        guard let clean = appDevicesCleanName(name: name) else {
            throw CuaError.InvalidArgument(message: "A machine needs a name")
        }
        let machine = id == "this-mac" ? host.machineId : id
        guard let machine, let relay = devices.devices else {
            throw CuaError.InvalidArgument(message: "Renaming a machine needs a signed-in, enrolled Mac")
        }
        try await relay.renameMachine(id: machine, name: clean)
        await host.refresh()
        await devices.refresh()
        await refresh(fresh: true)
    }

    /// Remove from account: `machine` leaves the relay directory, then
    /// `device` is revoked. This Mac's own host setup is the host's
    /// `remove` instead. The Spaces made on the machine are detached (they
    /// come back when it is added again), or with `deleteSpaces` deleted too.
    public func removeMachine(machine: String?, device: String?, deleteSpaces: Bool = false) async throws {
        if let machine {
            if deleteSpaces {
                try await backend.relayUnregisterComputer(id: "relay:\(machine)", deleteSpaces: true)
            } else {
                try await backend.relayUnregister(id: "relay:\(machine)")
            }
        }
        if let device {
            guard let relay = devices.devices else {
                throw CuaError.InvalidArgument(message: "Revoking a machine needs a signed-in Cua account")
            }
            try await relay.revoke(id: device)
        }
        await devices.refresh()
        await refresh(fresh: true)
    }

    /// Forgets a cloud (`cloud_disconnect`); with `deleteResources`, deletes what Cua created there first.
    public func disconnectCloud(_ provider: String, deleteResources: Bool) async throws {
        try await cloud.disconnect(provider, deleteResources: deleteResources)
    }

    /// Approves or denies what an agent set up in a cloud (`cloud_approve`).
    public func approveCloud(_ provider: String, approve: Bool) async throws {
        try await cloud.approve(provider, approve: approve)
    }

    /// What each machine sharing its desktop (`relay:<machine>`) reported
    /// as its hostname, by machine id: the page lists it and the device on
    /// it once.
    var relayHostnames: [String: String] {
        var out: [String: String] = [:]
        for space in spaces where space.id.hasPrefix("relay:") && space.host == nil {
            if let name = backend.reportedHostname(id: space.id) { out[String(space.id.dropFirst(6))] = name }
        }
        return out
    }

    /// Your Spaces: neither This machine nor one of your machines.
    var realSpaces: [AppSpace] {
        spaces.filter { !$0.id.hasPrefix("relay:") && !detail($0).isHost && !$0.hidden }
    }

    /// Where "Add a computer" opens: the New UI's sheet (one row per way to
    /// add a computer, and Have a code? Enter it).
    public static let addComputerRoute = MainUIRoute.path("/machines?add=1")
    /// Agent runs seen in any Space (a Space's detail, the web UI's
    /// Agents page): the checklist's "Run an agent".
    public private(set) var agentRunsSeen = 0

    /// A Space's agent runs were read: `count` of them.
    public func sawAgentRuns(_ count: Int) {
        if count > agentRunsSeen { agentRunsSeen = count }
    }

    /// "Add a computer": the New UI's sheet, whichever UI is up.
    /// Whether the persistent agents were read for the checklist.
    private var checklistReadAgents = false

    /// What the checklist ticks off from what the app shows: the core's
    /// one reading (`checklist::observe_from`), whichever UI is open.
    var checklistSeen: AppChecklistAction {
        appChecklistObserveFrom(seen: AppChecklistSeen(
            machines: machinePageRows, spaces: spaces,
            agents: UInt32(persistent.agentCount), runs: UInt32(agentRunsSeen)))
    }

    /// Ticks the checklist off from what the app shows now, and again each
    /// time that changes, whichever UI is open (or none).
    func followChecklist() {
        let seen = withObservationTracking { checklistSeen } onChange: { [weak self] in
            DispatchQueue.main.async { self?.followChecklist() }
        }
        checklist.send(seen)
    }

    /// "Add a machine": New Space's "Connect by address".
    public func openAddMachine() async {
        openWebRoute?(Self.addComputerRoute)
    }

    /// Getting started (the palette, Help): opens the checklist again.
    public func openGettingStarted() {
        checklist.send(.reopen)
        selection = .gettingStarted
    }

    /// A checklist step's button.
    public func runChecklistStep(_ step: AppChecklistStep) async {
        switch step {
        case .addMachine:
            selection = .machines
            await openAddMachine()
        case .createSpace: await openNewSpace()
        case .teleport: await openOnSpace(.teleport)
        case .share: await openOnSpace(.share)
        case .runAgent: selection = .agents
        }
    }

    /// Opens `action` on the first Space that offers it now; without one,
    /// New Space (no Space yet) or the first Space (to start it).
    private func openOnSpace(_ action: AppDetailActionId) async {
        let real = realSpaces
        if real.isEmpty { return await openNewSpace() }
        let ready = real.first { space in
            detail(space).actions.contains { $0.id == action && $0.enabled }
        }
        let space = ready ?? real[0]
        selection = .space(space.id)
        if ready != nil { detailRequest = DetailRequest(spaceId: space.id, action: action) }
    }


    /// Reads a Space's memory and storage use now.
    public func refreshUsage(_ id: String) async {
        if let u = await backend.usage(id: id) { usage[id] = u }
    }

    /// Refreshes a Space's memory and storage use at the core's low rate
    /// while its detail shows (the caller's task is cancelled when it hides),
    /// until a delete starts.
    public func pollUsage(_ id: String) async {
        while !Task.isCancelled, !isDeleting(id) {
            await refreshUsage(id)
            try? await Task.sleep(for: .milliseconds(Int(appUsageRefreshMs())))
        }
    }

    public func send(_ action: AppRosterAction) {
        roster = appRosterReduce(state: roster, action: action)
        notch.spaces = roster.spaces
        syncNotchKeyvault()
    }

    // MARK: - Keyvault sign-ins in Spaces

    /// The Spaces a Keyvault sign-in is live in ("Signed in" in the list;
    /// dismissing hides only the notch's indicator).
    public var signedInSpaceIds: Set<String> { Set(keyvault.signedIn(spaces)) }

    /// The notch's key indicator, its line and the tiles' key, without the
    /// dismissed copies.
    func syncNotchKeyvault() {
        notch.setKeyvault(label: keyvault.notchLabel, signedIn: keyvault.signedIn(spaces, notch: true))
    }

    /// A Space's "Signed in" badge: the Keyvault's Access page, with that
    /// Space's row brought forward.
    public func showAccess(spaceId: String) {
        keyvault.focusKey = spaces.first { $0.id == spaceId }.flatMap { keyvault.accessKey(for: $0) }
        keyvault.selection = .category(category: .access)
        selection = .keyvault(.category(category: .access))
    }

    /// The roster: This machine first (when this app manages a host), then
    /// the registry's Spaces.
    func recompose() {
        let now = Int64(Date().timeIntervalSince1970 * 1000)
        // This Mac's own relay entry is "This machine", not one of "My machines".
        let listed = appWithoutThisRelayMachine(spaces: registrySpaces, thisMachineId: host.machineId)
        let spaces = host.host == nil ? listed
            : appWithThisMachine(spaces: listed, status: host.summaryInput, nowMs: now)
        send(.syncSpaces(spaces: appCreatesCompose(spaces: spaces, state: creates)))
    }

    /// Advances the Spaces being created and redraws the list.
    func sendCreate(_ action: AppCreateAction) {
        // A create started, reached ready or failed (how long it took).
        telemetry?.record(appTelemetryCreates(state: creates, action: action, nowMs: Self.nowMs()))
        creates = appCreatesReduce(state: creates, action: action)
        recompose()
        tickWhileCreating()
    }

    /// While a create runs, time moves its bar within a phase that reports
    /// no fraction: the core computes it from `now` (4 Hz, as the Tauri app
    /// does).
    private var createTicker: Task<Void, Never>?

    private func tickWhileCreating() {
        let running = creates.pending.contains { $0.error == nil && $0.spaceId == nil }
        if !running {
            createTicker?.cancel()
            createTicker = nil
            return
        }
        guard createTicker == nil else { return }
        createTicker = Task { @MainActor [weak self] in
            while !Task.isCancelled {
                try? await Task.sleep(for: .milliseconds(Self.createTickMs))
                guard let self, !Task.isCancelled else { return }
                self.sendTick()
                self.recompose()
            }
        }
    }

    /// A tick moves the bars (and may stall a row) without redrawing twice.
    private func sendTick() {
        let now = Self.nowMs()
        telemetry?.record(appTelemetryCreates(state: creates, action: .tick(now: now), nowMs: now))
        creates = appCreatesReduce(state: creates, action: .tick(now: now))
    }

    static let createTickMs = 250
    /// How often the app's refresh checks relay sharing against the sign-in.
    static let accountCheckInterval: TimeInterval = 120

    static func nowMs() -> Int64 { Int64(Date().timeIntervalSince1970 * 1000) }

    // MARK: - List health

    /// How long one read of the registry may take before this refresh gives
    /// up on it (the read keeps going; the next refresh waits on it rather
    /// than asking again).
    public var listTimeout: Double = 20
    /// How long the host's own reads in a refresh may take.
    public var hostTimeout: Double = 15
    /// With no successful list read for this long, the daemon connection
    /// is made again (`reconnect`).
    public var listStaleAfter: TimeInterval = 45
    /// The last time the registry was read.
    public private(set) var lastListOk: Date?
    /// The last time the daemon answered a list read, with the rows or with
    /// an error of its own (the relay refused the sign-in, say): the
    /// connection works, so a new one would not help.
    public private(set) var lastListAnswer: Date?
    /// The list health's clock (tests step it instead of waiting).
    @ObservationIgnored var listClock: @MainActor () -> Date = { Date() }
    /// Since when the list has been watched (the live services came in, or
    /// the last reconnect).
    private var listWatchedSince = Date()
    /// Makes a new SDK client of the daemon (starting the daemon again when
    /// it is gone) and hands it to the backend; false when it could not.
    /// Set once the live services are in (`AppEnvironment.attach`).
    public var reconnect: (@MainActor () async -> Bool)?
    public private(set) var reconnecting = false
    /// Reconnects so far (tests and logs).
    public private(set) var reconnects = 0
    /// The registry read in flight: refreshes share it, so a read that
    /// never returns is asked once, not once a poll.
    private var rowsInFlight: Task<AppListRead, Error>?
    /// Registry reads started so far, the one in flight and the newest
    /// one shown: an older read that answers late is not shown over it.
    private var rowsReads = 0
    private var rowsInFlightRead = 0
    private var rowsShownRead = 0
    private var hostInFlight: Task<Void, Never>?

    /// The list poll: a refresh every `interval`, each one bounded, and a
    /// reconnect when the list went stale. The window, the notch and New UI
    /// all show what this keeps fresh.
    public func startListPoll(every interval: Duration = .seconds(10)) -> Task<Void, Never> {
        Task { @MainActor [weak self] in
            while !Task.isCancelled {
                guard let self else { return }
                await self.refresh()
                await self.checkListHealth()
                try? await Task.sleep(for: interval)
            }
        }
    }

    /// Keeps the notch's hotspot indicator on while a Space exits through
    /// this computer ("Exit through: This computer"), as the hotspot's own
    /// indicator is. Read every 15 seconds, as the Electron notch does.
    /// Only while Secure Spaces (Labs) is on: off, nothing is read.
    public func startExitsPoll(every interval: Duration = .seconds(15)) -> Task<Void, Never> {
        Task { @MainActor [weak self] in
            while !Task.isCancelled {
                guard let self else { return }
                await self.syncNotchExits()
                try? await Task.sleep(for: interval)
            }
        }
    }

    /// Reads the exits once and shows them on the notch.
    func syncNotchExits() async {
        refreshDaemonExperiments()
        guard settings.experiments.secureSpaces else {
            notch.setExits([])
            return
        }
        notch.setExits(await backend.exitsThroughThisMachine())
    }

    /// The daemon's push of list changes (`watchList`), while it is kept.
    private var listWatch: AnyObject?
    /// The read a push started, and whether another push came meanwhile.
    private var listPushRead: Task<Void, Never>?
    private var listPushedAgain = false
    /// How long a push waits for the next one before the list is read (a
    /// computer coming up moves several of its Spaces at once).
    static let listPushSettleMs = 100

    /// Push: the daemon says when the list changed (a Space started or
    /// stopped on another computer, one came up or went away), and the list
    /// is read again then, within a second or two, instead of at the next
    /// poll. The poll stays as the fallback. Started again after a
    /// reconnect.
    public func startListWatch() async {
        listWatch = await backend.watchList { [weak self] in
            Task { @MainActor in self?.listPushed() }
        }
    }

    /// One read per burst of pushes; a push during a read reads once more.
    func listPushed() {
        guard listPushRead == nil else {
            listPushedAgain = true
            return
        }
        listPushRead = Task { @MainActor [weak self] in
            try? await Task.sleep(for: .milliseconds(Self.listPushSettleMs))
            while let self {
                self.listPushedAgain = false
                await self.refresh(fresh: true)
                if !self.listPushedAgain { break }
            }
            self?.listPushRead = nil
        }
    }

    /// Reconnects when the list has not been read for `listStaleAfter`
    /// (nothing before the live services are in).
    func checkListHealth(now: Date? = nil) async {
        guard startup.isReady, reconnect != nil, !reconnecting else { return }
        let now = now ?? listClock()
        let since = max(lastListAnswer ?? listWatchedSince, listWatchedSince)
        guard now.timeIntervalSince(since) >= listStaleAfter else { return }
        await reconnectNow(reason: "the Space list was not read for \(Int(now.timeIntervalSince(since))) s")
    }

    /// A new connection to the daemon, then the list again. One at a time.
    func reconnectNow(reason: String) async {
        guard let reconnect, !reconnecting else { return }
        reconnecting = true
        reconnects += 1
        NSLog("Cua Spaces: reconnecting to the cua daemon (%@)", reason)
        // What hung on the old connection is left behind.
        rowsInFlight = nil
        hostInFlight = nil
        let ok = await reconnect()
        listWatchedSince = listClock()
        reconnecting = false
        // The push came over the old connection: watch on the new one.
        if ok, listWatch != nil { await startListWatch() }
        if !ok { NSLog("Cua Spaces: the reconnect did not make a new connection; trying again later") }
        await refresh()
    }

    /// Whether a failed read is the daemon's own answer, not a connection
    /// that broke (only that one is made again).
    static func daemonAnswered(_ error: Error) -> Bool {
        switch error {
        case CuaError.DaemonNotRunning, CuaError.Transport, CuaError.Closed: false
        case is CuaError: true
        default: false
        }
    }

    /// The live services just came in: watch the list from now.
    func watchListFromNow() {
        listWatchedSince = listClock()
    }

    /// The host's reads, shared and bounded.
    private func refreshHost() async {
        let task = hostInFlight ?? Task { @MainActor [weak self] in
            guard let self else { return }
            await self.host.refresh()
            // At launch, then every few minutes: a session that expired for
            // good (or a `cua auth logout`) pauses relay sharing too.
            await self.host.reconcileAccount(ifOlderThan: Self.accountCheckInterval)
        }
        hostInFlight = task
        let finished = await withDeadline(seconds: hostTimeout) { await task.value }
        if finished, hostInFlight == task { hostInFlight = nil }
    }

    /// The registry, shared and bounded (`TimeoutError` past `listTimeout`),
    /// with the number of the read that answered. `fresh`: a new read, not
    /// one already in flight, which started before the change just made
    /// and may answer without it.
    private func readRows(fresh: Bool = false) async throws -> (list: AppListRead, read: Int) {
        if fresh || rowsInFlight == nil {
            rowsReads += 1
            rowsInFlightRead = rowsReads
            rowsInFlight = Task { [backend] in try await backend.listRead() }
        }
        guard let task = rowsInFlight else { throw CancellationError() }
        let read = rowsInFlightRead
        let result = await withTimeout(seconds: listTimeout) { try await task.value }
        if case .failure(TimeoutError.timedOut) = result {
            // Still running: the next refresh waits on the same read.
        } else if rowsInFlight == task {
            rowsInFlight = nil
        }
        return (try result.get(), read)
    }

    /// Re-reads the registry (and the host). Bounded: a daemon that stopped
    /// answering leaves the list as it was, and the poll reconnects.
    /// `fresh` after a change this app made (a create, a delete): the list
    /// is read again from now, so it shows the change.
    public func refresh(fresh: Bool = false) async {
        // The host's reads run beside the list, never ahead of it: this
        // Mac's Spaces show as soon as the daemon lists them, and "This
        // machine" joins them once the host answered (it recomposes then).
        async let hostRead: Void = refreshHostThenRecompose()
        defer { followIncompleteList() }
        do {
            let (list, read) = try await readRows(fresh: fresh)
            lastListOk = listClock()
            lastListAnswer = lastListOk
            // A read from before a newer one already shown is out of date.
            guard read >= rowsShownRead else {
                await hostRead
                return
            }
            rowsShownRead = read
            let now = Int64(Date().timeIntervalSince1970 * 1000)
            registrySpaces = appRowsToSpaces(rows: list.rows, nowMs: now)
            creates = appCreatesSettle(state: creates, spaces: registrySpaces)
            recompose()
            loaded = true
            listIncomplete = list.incomplete
            listReaching = list.reaching
            listStale = list.stale
            listCreating = list.creating
            // Your other computers could not be read: their rows are the
            // last known ones (this Mac's are current).
            rosterError = list.notice.isEmpty ? nil
                : "Could not reach your other machines. Their Spaces may be out of date."
            await hostRead
            // Your machines' load for their sidebar lines, every so often
            // (each machine is asked; never holds up the list).
            if registrySpaces.contains(where: { $0.id.hasPrefix("relay:") }),
               hostsReadAt.map({ Date().timeIntervalSince($0) >= Self.hostsRefreshInterval }) ?? true {
                hostsReadAt = Date()
                Task { await refreshHosts() }
            }
            // The pool's cloud hosts, spend and events (it reads no more
            // than every few seconds, and never holds up the list).
            Task { await elastic.refresh() }
            // The checklist's "Run an agent": read the persistent agents
            // once (the Agents page reads them again when it opens).
            if !checklistReadAgents, servicesIn, !checklist.state.done.contains(.runAgent) {
                checklistReadAgents = true
                Task { await persistent.loadAgents() }
            }
            if selection == nil, let first = sidebar.selectedId { selection = .space(first) }
            // A preview for every running Space from the daemon's cache
            // (it survives restarts), before one is opened.
            let running = streamableSpaceIds
            Task { await thumbnails.warm(running) }
        } catch TimeoutError.timedOut {
            // The daemon is slow or gone: the list stays as it was, and the
            // poll reconnects when it stays stale (`checkListHealth`).
            await hostRead
        } catch {
            if Self.daemonAnswered(error) { lastListAnswer = listClock() }
            // Errors may contain server bodies or credential-bearing URLs.
            rosterError = loaded
                ? "Could not refresh Spaces. Previously loaded rows may be out of date."
                : "Could not load Spaces. Try refreshing again."
            await hostRead
        }
    }

    /// The host's reads, then the list composed again with what they said
    /// ("This machine").
    private func refreshHostThenRecompose() async {
        await refreshHost()
        if loaded { recompose() }
    }

    /// While some of your computers have not answered, the list is read
    /// again soon (each read waits a moment for them in the daemon), not at
    /// the next poll.
    private var incompleteFollow: Task<Void, Never>?

    private func followIncompleteList() {
        guard listIncomplete, incompleteFollow == nil else { return }
        incompleteFollow = Task { @MainActor [weak self] in
            try? await Task.sleep(for: .milliseconds(Self.incompleteFollowMs))
            guard let self, !Task.isCancelled else { return }
            self.incompleteFollow = nil
            await self.refresh()
        }
    }

    static let incompleteFollowMs = 500

    public func select(_ id: String) {
        pickedSpaceIds = []
        selection = .space(id)
        send(.select(id: id, now: Int64(Date().timeIntervalSince1970 * 1000)))
    }

    // MARK: - New Space

    /// Opens the web UI's New Space wizard (`on`: "Run on" preset, or nil);
    /// false when there is no window to show it in. Set at launch.
    public var openWebNewSpace: ((_ on: String?) -> Bool)?
    /// The first run is due again (Settings, Welcome, Show again): opens its
    /// window (the web onboarding), which nothing else would while only
    /// Settings is up.
    public var openOnboarding: (() -> Void)?
    /// Opens the New UI window at a route (set at launch). "Add a computer"
    /// uses it: the sheet lives in the New UI, whichever UI is up.
    public var openWebRoute: ((MainUIRoute) -> Void)?

    /// New Space with "Run on" set to `on` (`host:<machine>`): a machine's
    /// "New Space on <name>…".
    public func openNewSpace(on: String) async {
        if openInWebUI(on: on) { return }
        await openNativeNewSpace()
        wizard.send(.choosePlacement(on: on))
    }

    /// New Space: the web UI's wizard (the native sheet only without one,
    /// in tests).
    /// `quick`: the empty home's one click: that OS's default Space, created at once
    /// when the core says it can be; else New Space opens on it and says why.
    public func openNewSpace(quick os: AppSpaceOs? = nil) async {
        if os == nil, openInWebUI(on: nil) { return }
        await openNativeNewSpace(quick: os)
    }

    private func openInWebUI(on: String?) -> Bool {
        guard let open = openWebNewSpace else { return false }
        return open(on)
    }

    /// The native New Space sheet (the web UI is off), or `quick`'s one click.
    public func openNativeNewSpace(quick os: AppSpaceOs? = nil) async {
        wizard.reset(env: await newSpaceEnv())
        if let os {
            wizard.send(.chooseOs(os: os))
            if wizard.view.canContinue { create(wizard.view.plan); return }
        }
        showingNewSpace = true
        telemetry?.record([.spaceWizard(action: "opened")])
        self.cloud.onConnected = { [weak self] in self?.cloudsChanged() }
    }

    /// What New Space knows, freshly probed (this Mac's runtimes, storage,
    /// GPUs, your machines that provide Spaces, your clouds, pricing): the
    /// native sheet's env, and New UI's (`spaces.createOptions`).
    /// Every probe runs at once and each is bounded, so the env comes in
    /// seconds even when one of them hangs (New UI's `spaces.createOptions`
    /// must answer before the page stops waiting).
    public func newSpaceEnv() async -> AppWizardEnv {
        async let runtimesProbe = backend.localRuntimes()
        async let storageProbe = backend.localStorage()
        async let gpusProbe = backend.gpuChoices()
        async let hostsProbe = backend.hosts()
        async let lumeProbe = backend.lumeSource()
        async let linuxProbe = backend.linuxSource()
        async let macosVmsProbe = backend.runningMacosVms()
        await self.cloud.refresh()
        let (runtimes, storage, gpus) = await (runtimesProbe, storageProbe, gpusProbe)
        (lumeSource, linuxSource) = await (lumeProbe, linuxProbe)
        hosts = await hostsProbe
        // Lume did not answer this time: keep what it said last (a VM that
        // stopped since shows on the next read that answers).
        runningMacosVms = await macosVmsProbe ?? runningMacosVms
        return wizardEnv(runtimes: runtimes, storage: storage, gpus: gpus)
    }

    /// What New Space knows without asking anything (no probe, no wait):
    /// the env New UI gets while the live services are still starting.
    public func knownNewSpaceEnv() -> AppWizardEnv {
        wizardEnv(runtimes: nil, storage: nil, gpus: nil)
    }

    /// The live services are in (the launch's stand-ins have them): until
    /// then every probe would wait for them.
    public var servicesIn: Bool {
        guard let pending = backend as? PendingSpacesBackend else { return true }
        return pending.gate.current != nil
    }

    /// macOS VMs running on this Mac (Lume's, Spaces or not), as New Space
    /// last read them; nil when Lume did not say. Apple's license allows two.
    public private(set) var runningMacosVms: Int?

    /// The connected clouds changed ("Connect a cloud"): the open wizard
    /// reads them again, where it is.
    func cloudsChanged() {
        wizard.update(env: wizardEnv(from: wizard.env))
    }

    /// Your machines that provide Spaces, as New Space or the sidebar last
    /// read them.
    var hosts: [AppSpaceHost] = []
    /// When the sidebar last asked for `hosts`.
    @ObservationIgnored private var hostsReadAt: Date?
    /// How often the sidebar asks your machines how busy they are.
    static let hostsRefreshInterval: TimeInterval = 30

    /// Reads your machines that provide Spaces again (how busy each is).
    func refreshHosts() async {
        hostsReadAt = Date()
        hosts = await backend.hosts()
    }

    /// The one short line under one of your machines in the sidebar ("3
    /// running · 40% CPU", "Paused"); `nil` for any other row, or while the
    /// machine is offline or reports no load.
    func hostLoadLine(_ rowId: String) -> String? {
        guard rowId.hasPrefix("relay:") else { return nil }
        let id = String(rowId.dropFirst("relay:".count))
        return hosts.first { $0.id == id }.flatMap { appHostLoadText(host: $0) }
    }

    /// Which Lume macOS Spaces run on (`runtime.lume`), once read.
    public private(set) var lumeSource: String?
    /// Which engine local Linux Spaces run on (`runtime.linux`), once read.
    public private(set) var linuxSource: String?
    /// `placement.overflow` (Settings, General), once read.
    public private(set) var placementOverflow: Bool?

    /// New Space's "Use built-in Lume" / "Use built-in runtime": switches
    /// `runtime.lume` or `runtime.linux`, then the open wizard reads the
    /// runtimes again (This Mac can run it now).
    public func applyRuntimeSwitch(_ change: AppRuntimeSwitch) async {
        let linux = change.setting == "runtime.linux"
        do {
            if linux {
                try await backend.setLinuxSource(change.value)
            } else {
                try await backend.setLumeSource(change.value)
            }
        } catch {
            show(error: LiveSpacesBackend.words(error))
            return
        }
        if linux {
            linuxSource = await backend.linuxSource() ?? change.value
        } else {
            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
        e.linuxSource = linuxSource
        wizard.update(env: e)
    }

    private func wizardEnv(from e: AppWizardEnv) -> AppWizardEnv {
        var e = e
        e.clouds = cloud.clouds
        e.hosts = hosts
        e.experiments = settings.experiments
        if appIsCloudWord(on: cloud.defaultOn ?? "") { e.defaultLocation = .yours }
        return e
    }

    private func wizardEnv(runtimes: (ready: [String], details: [String: String])?,
                           storage: LocalStorage?,
                           gpus: [AppGpuChoice]?) -> AppWizardEnv {
        let backends = runtimes?.ready
        return wizardEnv(from: AppWizardEnv(
            defaultLocation: settings.defaultLocation,
            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, lumeSource: lumeSource, linuxSource: linuxSource,
            storage: storage.map(Self.wizardStorage),
            clouds: [], hosts: [],
            experiments: settings.experiments, gpus: gpus, nameSeed: nil))
    }

    /// The New Space panel's Cancel.
    public func cancelNewSpace() {
        showingNewSpace = false
        telemetry?.record([.spaceWizard(action: "cancelled")])
    }

    /// Records a Spaces app feature (a fixed name; the Tauri app uses the
    /// same words).
    public func recordFeature(_ name: String) {
        telemetry?.record(appTelemetryFeature(feature: name))
    }

    /// Where views send usage events.
    public var telemetrySink: TelemetryRunning? { telemetry }

    /// This Mac's CPU architecture, as the image catalog spells it (the
    /// app core's): the wizard's platform, a pending create's, and the
    /// emulation warning on a Space's Architecture.
    static let hostArch = appHostArch()

    /// The SDK's storage probe as the wizard env takes it.
    static func wizardStorage(_ s: LocalStorage) -> AppLocalStorage {
        func volume(_ v: StorageVolume?) -> AppStorageVolume? {
            v.map { AppStorageVolume(availableBytes: $0.availableBytes, totalBytes: $0.totalBytes, name: $0.name) }
        }
        return AppLocalStorage(reserveBytes: s.reserveBytes, lume: volume(s.lume), qemu: volume(s.qemu),
                               container: volume(s.container), pulled: s.pulled,
                               linuxRuntimeDownloadBytes: s.linuxRuntimeDownloadBytes)
    }

    /// "Create Space": the new Space shows in the list and the notch at
    /// once (the core's pending row), follows the SDK's create progress, and
    /// hands over to the registry's row when it is ready. A failure stays on
    /// its row; a cancelled create (Cancel, or `cua spaces cancel`
    /// elsewhere) only leaves the list.
    public func create(_ plan: AppCreatePlan) {
        showingNewSpace = false
        telemetry?.record([.spaceWizard(action: "submitted")])
        let args = appWizardCreateArgs(plan: plan)
        let pendingId = "pending:\(UUID().uuidString.lowercased())"
        startCreate(args, os: plan.image.os, pendingId: pendingId, select: plan.openDesktop)
        // A failure stays on its row.
        Task {
            guard let id = try? await followCreate(args, os: plan.image.os, pendingId: pendingId), plan.openDesktop else { return }
            WebUIWindowController.actions?.openSpace(id)
        }
    }

    /// Runs a create from the core's create arguments: the native sheet's
    /// (`create`) and New UI's (`spaces.create`, with the page's pending id).
    /// The new Space shows in the list and the notch at once (the core's
    /// pending row), follows the SDK's progress (also handed to `progress`)
    /// and hands over to the registry's row when it is ready; returns its
    /// id. A failure stays on its row; a cancelled create (Cancel, or `cua
    /// spaces cancel` elsewhere) only leaves the list. Either way it throws.
    ///
    /// A failure that usually passes (the core's `fail_decision`: a runtime
    /// that did not start this time, a network drop during the download, a
    /// VM that did not answer in time) runs the create once more by itself,
    /// the row saying "Retrying…"; `retrying` hears of it first (New UI's
    /// page applies the same failure). Only the final outcome throws.
    @discardableResult
    public func runCreate(_ args: AppCreateSpaceArgs, os: AppSpaceOs, pendingId: String,
                          progress: (@MainActor @Sendable (SpaceCreateProgress) -> Void)? = nil,
                          retrying: (@MainActor @Sendable (_ error: String, _ errorVariant: String) -> Void)? = nil)
        async throws -> String {
        startCreate(args, os: os, pendingId: pendingId, select: false)
        return try await followCreate(args, os: os, pendingId: pendingId, progress: progress, retrying: retrying)
    }

    /// The pending row (selected when `open`).
    private func startCreate(_ args: AppCreateSpaceArgs, os: AppSpaceOs, pendingId: String, select open: Bool) {
        // A create on one of your machines (`host:<machine>`) says which, so
        // that machine's own record of the Space it is creating is not a
        // second row next to this one, and a failure names the machine.
        let machine = args.on.hasPrefix("host:") ? String(args.on.dropFirst("host:".count)) : nil
        sendCreate(.start(id: pendingId, name: args.name ?? "", os: os,
                          provider: args.on == "local" ? .local : .relay,
                          now: Self.nowMs(),
                          image: args.image, kind: args.kind, hostArch: Self.hostArch, gpu: args.gpu != nil,
                          host: machine, hostName: machine.flatMap(machineName(of:))))
        // The detail shows the live desktop inline: selecting the new Space
        // opens it (`plan.openDesktop`), starting with its progress.
        if open { select(pendingId) }
    }

    /// The name of one of your machines, from the Spaces it provides (or its
    /// own entry on the relay).
    private func machineName(of id: String) -> String? {
        spaces.first { $0.id == "relay:\(id)" }?.name
            ?? spaces.first { $0.host == id && $0.hostName != nil }?.hostName
    }

    /// Asks for macOS Local Network access before a macOS Space is created
    /// on this Mac (the core's steps; nil in fixtures and tests that do not
    /// set one).
    public var localNetworkGate: LocalNetworkGate?

    /// The Local Network steps run when this Mac started providing Spaces
    /// (tests await it).
    @ObservationIgnored var hostingLocalNetworkCheck: Task<Void, Never>?

    /// Runs the Local Network steps for a Mac that just started providing
    /// Spaces: the explanation, then macOS's own prompt (the person answers
    /// it), or the fix when access was turned off. Setup already finished,
    /// so Cancel or a refusal changes nothing else; the next local macOS
    /// create asks again.
    func askLocalNetworkForHosting() {
        guard let gate = localNetworkGate,
              appLocalNetworkApplies(provider: .local, os: .macos, hostIsMac: true) else { return }
        hostingLocalNetworkCheck = Task { @MainActor in
            try? await gate.check()
        }
    }

    /// What the daemon found when it last tried this Mac's local network:
    /// true allowed, false blocked, nil not known yet. The daemon is the
    /// process that reaches the macOS VMs, and macOS decides Local Network
    /// per process, so the app's own connect (`localNetworkGate`) can pass
    /// while the daemon is still blocked. The daemon's connect is also what
    /// makes macOS ask, so this runs where the person expects it: the
    /// permissions page.
    public private(set) var daemonLocalNetworkAllowed: Bool?
    private var daemonLocalNetworkAt = Date.distantPast
    private var daemonLocalNetworkBusy = false

    /// Asks the daemon (its machine check, `machine.local_network`) and
    /// remembers the answer; at most once per `minimum` seconds.
    public func checkLocalNetworkFromDaemon(every minimum: TimeInterval = 4) async {
        guard !daemonLocalNetworkBusy, Date().timeIntervalSince(daemonLocalNetworkAt) >= minimum else { return }
        daemonLocalNetworkBusy = true
        defer {
            daemonLocalNetworkBusy = false
            daemonLocalNetworkAt = Date()
        }
        let backend = self.backend
        let answer = await withTimeout(seconds: 20) { try await backend.machineHealth(machine: nil) }
        guard case .success(let health) = answer,
              let check = health.checks.first(where: { $0.id == "machine.local_network" }) else { return }
        switch check.status {
        case "pass": daemonLocalNetworkAllowed = true
        case "fail": daemonLocalNetworkAllowed = false
        default: break
        }
    }

    /// How long the daemon may take to take a create (its first progress
    /// report, "Preparing", comes as it starts): past it the create fails
    /// at once, with Try again, instead of after the 4 min stall.
    public var createAcceptTimeout: Double = 30

    /// The create the daemon never took.
    struct CreateNotAccepted: LocalizedError {
        let seconds: Int
        var errorDescription: String? {
            "Cua's background service didn't start this create within \(seconds) s. "
                + "Cua Spaces reconnected to it. Try again."
        }
    }

    /// The SDK's create, through to the registry's row; once more when the
    /// core says the failure usually passes (`retryPending` on the row).
    private func followCreate(_ args: AppCreateSpaceArgs, os: AppSpaceOs, pendingId: String,
                              progress: (@MainActor @Sendable (SpaceCreateProgress) -> Void)? = nil,
                              retrying: (@MainActor @Sendable (_ error: String, _ errorVariant: String) -> Void)? = nil)
        async throws -> String {
        // A macOS Space here needs Local Network access: explained and asked
        // for now, or the create fails at once with the fix (never retried).
        if let gate = localNetworkGate,
           appLocalNetworkApplies(provider: args.on == "local" ? .local : .relay, os: os, hostIsMac: true) {
            do {
                try await gate.check()
            } catch where isCancelled(error) {
                sendCreate(.cancelDone(id: pendingId))
                throw error
            } catch {
                sendCreate(.fail(id: pendingId, error: LiveSpacesBackend.words(error),
                                 errorVariant: Self.errorVariant(error), now: Self.nowMs()))
                throw error
            }
        }
        while true {
            let reconnectsBefore = reconnects
            do {
                return try await attemptCreate(args, pendingId: pendingId, progress: progress)
            } catch where isCancelled(error) {
                throw error
            } catch {
                guard let row = creates.pending.first(where: { $0.id == pendingId }),
                      row.retryPending, !row.cancelling else { throw error }
                retrying?(LiveSpacesBackend.words(error), Self.errorVariant(error))
                // Cua's service did not take the create: it is being
                // connected again; the second try goes over the new connection.
                if row.retriedSubclass == "daemon_unresponsive", reconnect != nil {
                    var waited = 0
                    while (reconnects == reconnectsBefore || reconnecting) && waited < 120 {
                        try? await Task.sleep(for: .milliseconds(250))
                        waited += 1
                    }
                }
            }
        }
    }

    /// The error enum's case name telemetry and the core read (`Runtime`).
    static func errorVariant(_ error: Error) -> String {
        (error as? LocalNetworkRefusal)?.variant
            ?? (error as? CuaError).flatMap { Mirror(reflecting: $0).children.first?.label } ?? ""
    }

    /// One run of the SDK's create: the row follows it; a failure is put on
    /// the row (the core may turn it into a retry) and thrown.
    private func attemptCreate(_ args: AppCreateSpaceArgs, pendingId: String,
                               progress: (@MainActor @Sendable (SpaceCreateProgress) -> Void)?) async throws -> String {
        do {
            let accepted = CreateAcceptance()
            let backend = self.backend
            let create = Task {
                // The connection it goes over, so a cancel of this attempt
                // goes there too, never to the next connection's retry.
                let connection = await (backend as? PendingSpacesBackend)?.connection() ?? backend
                accepted.sent(on: connection)
                return try await connection.create(args, createId: pendingId) { p in
                    accepted.mark()
                    Task { @MainActor [weak self] in
                        self?.sendCreate(.progress(id: pendingId, phase: p.phase,
                                                   fraction: p.fraction, now: Self.nowMs(),
                                                   bytesDone: p.bytesDone, bytesTotal: p.bytesTotal,
                                                   bytesPerSecond: p.bytesPerSecond))
                        progress?(p)
                    }
                }
            }
            let id = try await awaitAccepted(create, accepted: accepted, pendingId: pendingId)
            sendCreate(.finish(id: pendingId, spaceId: id))
            await refresh(fresh: true)
            if selectedSpaceId == pendingId { select(id) }
            // Listed: the pending row is gone from the list already, so
            // drop it from the state too. Not listed yet (a slow read): the
            // finished row stays until a read lists the Space.
            if registrySpaces.contains(where: { $0.id == id }) {
                sendCreate(.dismiss(id: pendingId))
            }
            return id
        } catch where isCancelled(error) {
            // Cancelled, here or elsewhere: the row goes; it did not fail.
            sendCreate(.cancelDone(id: pendingId))
            throw error
        } catch {
            devices.noteRefusal(LiveSpacesBackend.words(error), surface: "app_create")
            sendCreate(.fail(id: pendingId, error: LiveSpacesBackend.words(error),
                             errorVariant: Self.errorVariant(error), now: Self.nowMs()))
            throw error
        }
    }

    /// The create's result, or `CreateNotAccepted` when the daemon reported
    /// nothing within `createAcceptTimeout` (then the create is cancelled
    /// where it may still arrive, and the connection is made again).
    private func awaitAccepted(_ create: Task<String, Error>, accepted: CreateAcceptance,
                               pendingId: String) async throws -> String {
        let limit = createAcceptTimeout
        let first = await withTimeout(seconds: limit) { try await create.value }
        switch first {
        case .success(let id): return id
        case .failure(TimeoutError.timedOut) where !accepted.done:
            NSLog("Cua Spaces: the cua daemon did not take create %@ within %d s", pendingId, Int(limit))
            // Best effort: it may still reach the daemon over the old
            // connection; never wait on it. Only that connection: the
            // retry goes over the new one under the same create id.
            if let connection = accepted.connection {
                Task.detached {
                    _ = await withTimeout(seconds: 30) { try await connection.cancelCreate(createId: pendingId) }
                }
            }
            Task { @MainActor [weak self] in await self?.reconnectNow(reason: "a create was not taken") }
            throw CreateNotAccepted(seconds: Int(limit.rounded(.up)))
        case .failure(TimeoutError.timedOut):
            // Taken: it runs as long as its phases do.
            return try await create.value
        case .failure(let error):
            throw error
        }
    }

    /// Cancel on a Space still being created: the row shows Cancelling
    /// until the SDK stopped the create and removed what it made, then goes;
    /// a cancel that fails says why on the row.
    public func cancelCreate(_ pendingId: String) {
        guard appCreatesIsPending(id: pendingId),
              creates.pending.contains(where: { $0.id == pendingId && !$0.cancelling }) else { return }
        sendCreate(.cancelStart(id: pendingId))
        Task {
            do {
                try await backend.cancelCreate(createId: pendingId)
                sendCreate(.cancelDone(id: pendingId))
            } catch {
                sendCreate(.cancelFail(id: pendingId, error: LiveSpacesBackend.words(error)))
            }
        }
    }

    public func addByAddress(url: String, token: String?, name: String?) async throws {
        try await backend.add(url: url, token: token, name: name)
        showingNewSpace = false
        await refresh(fresh: true)
    }

    /// Whether the Space is being deleted (its row shows Deleting).
    public func isDeleting(_ id: String) -> Bool {
        appCreatesIsDeleting(state: creates, id: id)
    }

    /// Delete (after the confirmation): the row shows Deleting at once and
    /// nothing streams from it any more; it goes when the SDK's delete
    /// returns. A failure restores it with the banner. A second Delete on a
    /// Space already deleting does nothing. `removeOnly` forgets any Space
    /// and keeps it running (Remove from List for a Space in your cloud).
    public func delete(_ space: AppSpace, removeOnly: Bool = false) {
        confirmDeleteId = nil
        // A failed create is only removed from the list.
        if appCreatesIsPending(id: space.id) {
            sendCreate(.dismiss(id: space.id))
            return
        }
        guard !isDeleting(space.id) else { return }
        recordFeature("space_delete")
        let detail = appSpaceDetail(space: space)
        sendCreate(.deleteStart(id: space.id, now: Int64(Date().timeIntervalSince1970 * 1000)))
        usage[space.id] = nil
        notch.thumbnails[space.id] = nil
        Task {
            do {
                try await backend.remove(id: space.id, removeOnly: removeOnly || detail.removeOnly)
                sendCreate(.deleteDone(id: space.id))
                await refresh(fresh: true)
            } catch {
                sendCreate(.deleteFail(id: space.id))
                show(error: appDeleteFailedText(name: space.name, error: LiveSpacesBackend.words(error)))
            }
        }
    }

    /// Bulk delete or leave (after the page's confirmation): every row says
    /// Deleting at once and goes when its own result comes back, at most
    /// three at a time; one failure never stops the rest. One result per
    /// id, in order; an id that is not listed answers not found.
    public func bulk(ids: [String], leave: Bool,
                     onResult: ((SpaceBulkResult) -> Void)? = nil) async -> [SpaceBulkResult] {
        confirmDeleteId = nil
        var results: [String: SpaceBulkResult] = [:]
        var todo: [AppSpace] = []
        for id in ids {
            guard let space = spaces.first(where: { $0.id == id }) else {
                results[id] = SpaceBulkResult(id: id, ok: false, error: "No Space \(id).")
                continue
            }
            if isDeleting(id) {
                results[id] = SpaceBulkResult(id: id, ok: false, error: "\(space.name) is already going.")
                continue
            }
            todo.append(space)
        }
        if !todo.isEmpty, !leave { recordFeature("space_delete") }
        for space in todo {
            sendCreate(.deleteStart(id: space.id, now: Self.nowMs()))
            usage[space.id] = nil
            notch.thumbnails[space.id] = nil
        }
        let backend = backend
        var queue = todo.map(\.id)
        await withTaskGroup(of: SpaceBulkResult.self) { group in
            func next() {
                guard !queue.isEmpty else { return }
                let id = queue.removeFirst()
                group.addTask {
                    let r = leave ? await backend.leave(ids: [id]) : await backend.deleteMany(ids: [id])
                    return r.first ?? SpaceBulkResult(id: id, ok: false, error: "No answer.")
                }
            }
            for _ in 0..<min(3, queue.count) { next() }
            for await r in group {
                results[r.id] = r
                sendCreate(r.ok ? .deleteDone(id: r.id) : .deleteFail(id: r.id))
                onResult?(r)
                next()
            }
        }
        if !todo.isEmpty { await refresh(fresh: true) }
        return ids.map { results[$0] ?? SpaceBulkResult(id: $0, ok: false, error: "No answer.") }
    }

    /// Gives a Space a new name (its id stays the same), then reads the list
    /// again so every view shows it. A refusal (a Space shared with you, a
    /// name taken or against the rule) throws in plain words; nothing
    /// changes.
    public func rename(_ space: AppSpace, to name: String) async throws {
        do {
            try await backend.rename(id: space.id, name: name)
        } catch {
            // The SDK's sentence without its kind ("permission denied: ...").
            throw FixtureError(message: KeyvaultModel.words(error))
        }
        await refresh(fresh: true)
    }

    /// The power button next to Delete: turns the Space off (`on` false:
    /// suspended or stopped, as its provider can) or back on. The row and
    /// the detail say Suspending (and the like) at once and the button
    /// waits; they keep saying so until the registry shows the Space off (or
    /// on). A failure shows inline on the row and the detail. A second
    /// press while one runs does nothing.
    public func setPower(_ space: AppSpace, on: Bool) {
        guard !appCreatesIsPowering(state: creates, id: space.id) else { return }
        sendCreate(.powerStart(id: space.id, on: on, now: Self.nowMs()))
        if !on {
            usage[space.id] = nil
            notch.thumbnails[space.id] = nil
        }
        Task {
            do {
                try await backend.setPower(id: space.id, on: on)
                sendCreate(.powerDone(id: space.id))
                await refresh(fresh: true)
            } catch {
                devices.noteRefusal(LiveSpacesBackend.words(error))
                sendCreate(.powerFail(id: space.id, error: LiveSpacesBackend.words(error)))
            }
        }
    }

    // MARK: - Settings and banners

    /// Pin to notch / Unpin from notch: the Spaces and machine desktops the
    /// notch lists first (`AppSettings.notchPinned`, in pin order). Saved
    /// with the settings, so a pin survives a restart; it grants nothing.
    public func setNotchPinned(_ ids: [String]) {
        guard ids != settings.notchPinned else { return }
        settings.notchPinned = ids
        saveSettings()
        notch.setPinned(ids)
    }

    /// Pins `id` to the notch, or unpins it when it is pinned.
    public func togglePin(_ id: String) {
        setNotchPinned(appNotchTogglePin(pinned: settings.notchPinned, id: id))
    }

    public func saveSettings() {
        try? appSettingsSave(path: settingsPath, settings: settings)
    }

    // MARK: - Tips

    /// Applies a tips event (the core's `tips::reduce`) and saves the tips.
    public func sendTips(_ event: AppTipsEvent) {
        let next = appTipsReduce(state: settings.tips, event: event)
        guard next != settings.tips else { return }
        settings.tips = next
        saveSettings()
    }

    /// The tip at the sidebar's foot (the core's `tips::view`, place
    /// sidebar): it belongs to no page of this UI, so nothing suppresses it.
    public var sidebarTip: AppTip? {
        Self.sidebarTip(machinesOnline: machinePageRows.filter(\.online).count, tips: settings.tips)
    }

    /// The sidebar's tip for `machinesOnline` of your computers online.
    public static func sidebarTip(machinesOnline: Int, tips: AppTipsState) -> AppTip? {
        appTipsView(place: .sidebar, facts: AppTipFacts(
            newestRunning: nil, spacePage: nil, agentsConnected: [], agentsInstalled: [],
            hasStopped: false, deletableStopped: 0, diskNearlyFull: false,
            secondComputerOnline: machinesOnline >= 2, sharedAny: false, pageTipShown: false), state: tips)
    }

    public func show(error: String) {
        devices.noteRefusal(error)
        banner = error
        bannerIsError = true
    }

    public func show(info: String) {
        banner = info
        bannerIsError = false
    }

    /// The menu bar item's status line.
    /// Counts the Spaces on or starting, the notch's count (never a stopped
    /// Space, This machine or another of your machines).
    public var statusLine: String { appOnStatusLine(count: appOnCount(spaces: spaces)) }

    /// The menu bar item's menu: the count, Cua Volume's sync state next to
    /// it and its conflicts, then the actions.
    public var menuBar: [AppMenuItem] {
        let items = appMenu(input: AppMenuInput(spaces: spaces, keyvault: keyvault.sharingLabel, sync: persistent.driveSync,
                                   nowMs: UInt64(Date().timeIntervalSince1970 * 1000),
                                   backend: persistent.driveBackend, experiments: settings.experiments))
        // Still launching (opened at login, waiting for Keychain access):
        // say so first, so the menu explains why nothing shows yet.
        let title = startup.copy.title
        guard !startup.isReady, !title.isEmpty else { return items }
        return [AppMenuItem(id: .status, label: title, shortcut: nil, enabled: false),
                AppMenuItem(id: .separator, label: "", shortcut: nil, enabled: false)] + items
    }

    /// The window chrome (account line, New Space, empty state).
    public var chrome: AppMainChrome {
        appMainChrome(input: AppChromeInput(identity: identity, cloudConfigured: cloudConfigured,
                                            canSignIn: account != nil, experiments: settings.experiments))
    }

    // MARK: - Account

    /// "Sign in" / "Sign in to Cua": the browser flow, the code while it waits.
    public func beginSignIn() async {
        guard let current = startSignIn() else { return }
        await runSignIn(current)
    }

    /// "Get a code instead": a code to enter on any device, for when the
    /// browser never gets back to the app.
    public func beginSignIn(code: Bool) async {
        guard let current = startSignIn(code: code) else { return }
        await runSignIn(current)
    }

    /// Marks a sign-in as starting, now (the web page reads it at once), and
    /// returns its attempt; nil when one is already starting.
    @discardableResult
    public func startSignIn(code: Bool = false) -> Int? {
        guard account != nil, signIn != .starting else { return nil }
        signInByCode = code
        signIn = .starting
        signInURL = nil
        signInAttempt += 1
        return signInAttempt
    }

    /// Runs attempt `current`: every way it ends is shown (`signIn`), never
    /// a silent stop.
    func runSignIn(_ current: Int) async {
        guard let account else { return }
        do {
            let attempt = signInByCode ? try await account.beginSignIn(code: true) : try await account.beginSignIn()
            // Cancelled, retried or signed in while it started.
            guard signInAttempt == current, signIn == .starting else { return }
            signIn = .waiting(userCode: attempt.userCode, opened: attempt.opened)
            signInURL = attempt.url
            let timeout = signInTimeout
            Task { @MainActor [weak self] in
                try? await Task.sleep(for: timeout)
                guard let self, self.signInAttempt == current, case .waiting = self.signIn else { return }
                self.signInFailed(appSignInFailed(reason: .notConfirmed, detail: nil))
            }
            let who = try await attempt.wait()
            // Whichever attempt the browser finished stored the session:
            // take it, even when a retry or Cancel superseded this one (an
            // earlier tab confirmed after all). Only a sign-out since then
            // leaves it.
            guard signInAttempt == current || identity == nil else { return }
            signInAttempt += 1
            let previous = identity
            identity = who ?? account.identity()
            host.identity = identity
            devices.signedIn = identity != nil
            // Activation funnel: the first run's page records `signed_in` on
            // its own (the core's flow); a sign-in once it is done (from
            // Settings, the machines page) records it here, for a new account.
            if onboarding.completed, let who = identity, !who.isEmpty, who != previous {
                telemetry?.record([.step(step: "signed_in", ok: true)])
            }
            signIn = .idle
            signInURL = nil
            // Relay sharing paused while signed out comes back for its
            // owner (another account is asked to set it up again).
            await host.reconcileAccount()
            // Signing in adds this computer (a computer set up before keeps its settings).
            await host.addAfterSignIn()
            await reloadTeams()
            await reloadShareRemovals()
        } catch {
            // A superseded attempt (a retry, Cancel) ends quietly; the one
            // shown fails with its reason.
            guard signInAttempt == current, signIn != .idle else { return }
            let variant = (error as? CuaError).flatMap { Mirror(reflecting: $0).children.first?.label } ?? ""
            signInFailed(appSignInFailedFromError(variant: variant, message: LiveSpacesBackend.words(error)))
        }
    }

    /// Shown where the sign-in was started and in the sidebar's foot, with
    /// a toast; counted by its kind only (the core keeps the words).
    private func signInFailed(_ phase: AppSignInPhase) {
        signIn = phase
        signInURL = nil
        guard case let .failed(reason, _, _) = phase else { return }
        signInToast = signInFooter.toast
        telemetry?.record(appTelemetrySignInFailure(reason: reason))
    }

    /// Stops waiting for the browser (the page can start again).
    public func cancelSignIn() {
        switch signIn {
        case .starting, .waiting:
            signInAttempt += 1
            telemetry?.record(appTelemetrySignInFailure(reason: nil))
        default: break
        }
        signIn = .idle
        signInURL = nil
    }

    /// Opens the sign-in page again (the tab was closed).
    public func reopenSignIn() {
        guard let signInURL else { return }
        NSWorkspace.shared.open(signInURL)
    }

    /// The sidebar's foot: every sign-in state in one place.
    public var signInFooter: AppSignInFooter {
        appSignInFooter(input: AppSignInFooterInput(identity: identity, cloudConfigured: cloudConfigured,
                                                    canSignIn: account != nil, signIn: signIn,
                                                    hasUrl: signInURL != nil))
    }

    public func signOut() async {
        try? await account?.signOut()
        identity = nil
        host.identity = nil
        devices.signedIn = false
        teamsState = .signedOut
        // Signed out: relay sharing stops (the setup stays to resume).
        await host.reconcileAccount()
        await devices.refresh()
        signIn = .idle
    }

    // MARK: - Settings page

    public var settingsPage: AppSettingsPage {
        appSettingsPage(input: AppSettingsInput(
            identity: identity, apiKeyClient: nil, signIn: signIn, canSignOut: account != nil && identity != nil,
            menuBar: settings.menuBar,
            telemetry: telemetryInput, agents: agentRows, agentsBusy: agentsBusy, agentsPending: agentsPending,
            teams: teamsSettingsInput,
            loginItem: loginItemInput,
            experiments: settings.experiments, keyvaultAutoWipe: keyvault.autoWipe,
            keyvaultUnlockPrompt: keyvault.unlockPromptShows,
            keyvaultSiteIcons: settings.keyvaultSiteIcons, keyvaultProtection: keyvault.page.protection,
            autoConnect: settings.autoConnect,
            overflow: placementOverflow,
            runtimes: runtimesInput,
            showTips: !settings.tips.off))
    }

    // MARK: - Runtimes (Settings, Advanced)

    /// Each kind of Space's runtime setting and what is installed for it,
    /// once read (`runtime_kinds`).
    public private(set) var runtimeKinds: [AppRuntimeKindInput]?
    /// The runtime doctor's answer for Settings (ready backends, why not),
    /// once read.
    public private(set) var runtimeDoctor: (ready: [String], details: [String: String])?
    /// When the runtimes were last read.
    @ObservationIgnored private var runtimesReadAt: Date?
    @ObservationIgnored private var runtimesReading = false
    /// How long a read of the runtimes stands before the page's next
    /// `settings.get` reads them again.
    static let runtimesRefreshInterval: TimeInterval = 15

    /// What Settings, Advanced's runtime rows are laid out from
    /// (`runtimes::section`): every kind, "Checking…" until read.
    public var runtimesInput: AppRuntimesInput {
        AppRuntimesInput(os: .macos, hostArch: Self.hostArch,
                         localBackends: runtimeDoctor?.ready, localDetails: runtimeDoctor?.details,
                         kinds: runtimeKinds)
    }

    /// Reads the runtimes again when the last read is older than
    /// `runtimesRefreshInterval` (or `force`), in the background: the page
    /// hears `settings.changed` when they come in.
    public func refreshRuntimesIfStale(force: Bool = false) {
        guard servicesIn, !runtimesReading else { return }
        if !force, let at = runtimesReadAt, Date().timeIntervalSince(at) < Self.runtimesRefreshInterval { return }
        runtimesReading = true
        Task { @MainActor in
            await readRuntimes()
            runtimesReading = false
        }
    }

    /// Reads each kind's setting, what is installed and the doctor.
    public func readRuntimes() async {
        async let doctor = backend.localRuntimes()
        async let kinds = backend.runtimeKinds()
        let (d, k) = await (doctor, kinds)
        runtimesReadAt = Date()
        if let d, runtimeDoctor.map({ $0.ready != d.ready || $0.details != d.details }) ?? true { runtimeDoctor = d }
        if let k, k != runtimeKinds { runtimeKinds = k }
    }

    /// A runtime row's choice (`runtime:<kind>`, `runtime-detected:<kind>`,
    /// `runtime-path:<kind>`): the setting the core names, written; the
    /// runtimes read again. Whether `row` was one.
    func chooseRuntime(row: String, option: String) async -> Bool {
        guard let change = appRuntimesChoose(input: runtimesInput, row: row, option: option) else { return false }
        do {
            try await backend.setRuntimeSetting(key: change.key, value: change.value)
        } catch {
            show(error: LiveSpacesBackend.words(error))
        }
        await readRuntimes()
        // New Space's "Use built-in" switches read the same settings.
        await loadRuntimeSettings()
        return true
    }

    /// Teams for Settings: the account's organizations with their people
    /// (the Spaces API), and the account app's address for this environment.
    var teamsSettingsInput: AppTeamsInput {
        AppTeamsInput(accountAppUrl: appAccountAppUrl(), state: identity == nil ? .signedOut : teamsState,
                      currentTeamId: settings.currentTeamId)
    }

    /// The account is in a team on the Teams plan, which sharing needs: nil
    /// until Teams are read, so the server decides.
    public var hasSharingTeam: Bool? {
        if case .ready(let list) = teamsState { return list.contains { $0.plan == "teams" } }
        return nil
    }

    /// Reads who lost access to a shared computer (sharing is for teams) and
    /// words the one-line note. Nothing when signed out or when there is no one.
    public func reloadShareRemovals() async {
        guard identity != nil, let teamsReader else {
            shareRemovalNote = nil
            return
        }
        let removals = (try? await teamsReader.shareRemovals()) ?? []
        shareRemovalNote = appShareRemovalNote(removals: removals)
    }

    /// Closes the note and tells the account it was seen, so it shows once.
    public func dismissShareRemovalNote() {
        shareRemovalNote = nil
        guard let teamsReader else { return }
        Task { try? await teamsReader.ackShareRemovals() }
    }

    /// Reads the account's Teams (Settings, Teams). A failure says so in the
    /// row; the account app's links stay.
    func reloadTeams() async {
        guard identity != nil, let teamsReader else {
            teamsState = .signedOut
            return
        }
        if case .ready = teamsState {} else { teamsState = .loading }
        do {
            let input = try await teamsReader.teams()
            guard identity != nil else { return }
            teamsState = input.state
        } catch {
            teamsState = .failed(message: LiveSpacesBackend.words(error))
        }
    }

    /// Settings, General with Settings, Storage after General while the Cua
    /// Volume experiment is on (the core's rule).
    public var settingsPageWithStorage: AppSettingsPage {
        appSettingsWithStorage(page: settingsPage, storage: storage.section, experiments: settings.experiments)
    }

    // MARK: - Experiments

    /// The experiments the daemon enforces (Secure Spaces, Child Spaces, CI runners, Public TCP shares, Phone app, Warm start) as
    /// the cua home keeps them: what `cua experiments enable` set shows here
    /// the next time Settings is read.
    public func refreshDaemonExperiments() {
        let kept = appSettingsLoad(path: settingsPath).experiments
        guard kept.secureSpaces != settings.experiments.secureSpaces
            || kept.childSpaces != settings.experiments.childSpaces
            || kept.askFirst != settings.experiments.askFirst
            || kept.ciRunners != settings.experiments.ciRunners
            || kept.tcpShares != settings.experiments.tcpShares
            || kept.mobile != settings.experiments.mobile
            || kept.warmPools != settings.experiments.warmPools else { return }
        settings.experiments.secureSpaces = kept.secureSpaces
        settings.experiments.childSpaces = kept.childSpaces
        settings.experiments.askFirst = kept.askFirst
        settings.experiments.ciRunners = kept.ciRunners
        settings.experiments.tcpShares = kept.tcpShares
        settings.experiments.mobile = kept.mobile
        settings.experiments.warmPools = kept.warmPools
    }

    /// Settings, Experiments: a switch and one line per experiment.
    public var experimentsPage: AppSettingsPage { appExperimentsPage(experiments: settings.experiments) }

    /// A switch in Settings, Experiments: saved, recorded, and followed by
    /// the first run and an open New Space. Off hides; nothing is undone.
    /// The New UI's switch ("Use classic UI") also saves the user's choice,
    /// which later launches keep whatever the default becomes.
    public func chooseExperiment(row: String, option: String) {
        let before = settings.experiments
        let next = appSettingsChooseExperiment(settings: settings, row: row, option: option)
        guard next != settings else { return }
        settings = next
        let after = next.experiments
        saveSettings()
        telemetry?.record(appTelemetryExperimentsChanged(before: before, after: after))
        applyExperiments(before: before, after: after)
    }

    /// Settings → About's channel, saved.
    public func setUpdateChannel(_ channel: AppUpdateChannel) {
        settings.updateChannel = channel
        saveSettings()
    }

    /// What follows a change of the switches: an open New Space.
    private func applyExperiments(before: AppExperiments, after: AppExperiments) {
        guard before != after else { return }
        wizard.update(env: wizardEnv(from: wizard.env))
        // The Volume page went with Cua Volume: back to the Spaces.
        if selection == .drive, chrome.volumeLabel == nil { selection = nil }
    }

    // MARK: - Launch at login

    /// The Settings toggle's state: the system's, never the one asked for.
    var loginItemInput: AppLoginItemInput? {
        loginItemStatus.map {
            AppLoginItemInput(status: $0, busy: loginItemBusy, error: loginItemError,
                              providesSpaces: providesSpaces, runsAgents: persistent.agentCount > 0)
        }
    }

    /// This Mac provides Spaces to your other devices.
    var providesSpaces: Bool { host.state.map { $0.configured && $0.provideSpaces } ?? false }

    /// Reads what the system reports.
    public func readLoginItem() {
        loginItemStatus = loginItem?.status()
    }

    /// The user turned it on or off (Settings, or the first run's Done):
    /// saved as their choice, applied, and read back.
    public func setLaunchAtLogin(_ on: Bool) {
        guard let loginItem, !loginItemBusy else { return }
        settings.launchAtLogin = on
        saveSettings()
        loginItemBusy = true
        loginItemError = nil
        do {
            if on { try loginItem.register() } else { try loginItem.unregister() }
            telemetry?.record([.feature(feature: on ? "launch_at_login_on" : "launch_at_login_off")])
        } catch {
            loginItemError = error.localizedDescription
        }
        loginItemStatus = loginItem.status()
        loginItemBusy = false
    }

    /// At launch, once the first run is done: an install that never chose
    /// (its first run predates the setting) is turned on when this Mac
    /// provides Spaces or runs persistent agents (the core's rule); a choice
    /// stands.
    public func applyLaunchAtLogin() async {
        guard let loginItem, onboarding.completed, settings.launchAtLogin == nil else {
            readLoginItem()
            return
        }
        await host.refresh()
        await persistent.loadAgents()
        let status = loginItem.status()
        let plan = appLoginItemLaunchPlan(choice: settings.launchAtLogin, onboarded: true,
                                          serves: providesSpaces || persistent.agentCount > 0, status: status)
        if plan.register {
            do { try loginItem.register() } catch { NSLog("Cua Spaces: launch at login: %@", "\(error)") }
        }
        if let record = plan.record {
            settings.launchAtLogin = record
            saveSettings()
        }
        readLoginItem()
    }

    /// Reads the usage-data switch alone. The web page gets it with its
    /// Settings snapshot (`settings.get`) and drops every usage signal while
    /// that has none, so it cannot wait for `loadSettings` (the page runs
    /// signed out, before Settings opens).
    public func refreshTelemetry() {
        telemetryInput = telemetry?.status()
    }

    /// Reads what Settings shows (telemetry, the coding agents).
    public func loadSettings() async {
        await loadRuntimeSettings()
        telemetryInput = telemetry?.status()
        readLoginItem()
        await storage.load()
        await reloadTeams()
        await reloadAgents()
        await keyvault.refresh()
    }

    /// Reads the settings Settings, Advanced shows from the config file
    /// (`runtime.lume`, `runtime.linux`, `placement.overflow`). The page's
    /// `settings.get` asks for them each time: without this read the
    /// runtime choices were missing from the page (only New Space's probe
    /// read them). Each one changes only when its value does, so the
    /// `settings.changed` it causes never loops.
    public func loadRuntimeSettings() async {
        let lume = await backend.lumeSource()
        let linux = await backend.linuxSource()
        let overflow = await backend.placementOverflow()
        if lume != lumeSource { lumeSource = lume }
        if linux != linuxSource { linuxSource = linux }
        if overflow != placementOverflow { placementOverflow = overflow }
    }

    /// Opens a website page (the account app's Teams page and billing).
    public func openBillingPage(_ raw: String) {
        guard let url = URL(string: raw), url.scheme == "https" || url.scheme == "http" else { return }
        BillingBrowser.open(url)
    }

    func reloadAgents() async {
        guard let agentSetup else {
            agentRows = []
            return
        }
        let rows = appAgentSettingsRows(statuses: await agentSetup.statuses(), total: agentSetup.skillsTotal())
        agentRows = rows.map { r in
            guard let why = agentFailures[r.agent] else { return r }
            var r = r
            r.configured = false
            r.detail = why
            return r
        }
    }

    /// A choice row changed.
    public func choose(row: String, option: String) async {
        switch row {
        case "team-current":
            // Settings, Teams: the team to work in (saved; the option is its id).
            settings.currentTeamId = option
            saveSettings()
        case "notch":
            settings.menuBar = option == "hide"
            saveSettings()
        case _ where row.hasPrefix("runtime"):
            _ = await chooseRuntime(row: row, option: option)
        case "placement-overflow":
            do {
                try await backend.setPlacementOverflow(option == "on")
                placementOverflow = await backend.placementOverflow() ?? (option == "on")
            } catch {
                show(error: LiveSpacesBackend.words(error))
            }
        case "auto-connect":
            settings.autoConnect = option == "on"
            saveSettings()
        case "launch-at-login":
            setLaunchAtLogin(option == "on")
        case "keyvault-auto-wipe":
            await keyvault.setAutoWipe(option == "on")
            if let error = keyvault.error { show(error: error) }
        case "keyvault-site-icons":
            settings.keyvaultSiteIcons = option == "on"
            saveSettings()
            // Turning it on asks for the rows' icons again.
            if settings.keyvaultSiteIcons { await keyvault.loadIcons() }
        case "keyvault-unlock-prompt":
            // On shows the prompt (Never ask again off); off is the stored
            // "Never ask again".
            await keyvault.setSkipUnlockPrompt(option != "on")
            if let error = keyvault.error { show(error: error) }
        case "tips", "reset-tips":
            // General's Show tips and Reset tips: the core's rule (`settings::choose`).
            settings = appSettingsChoose(settings: settings, row: row, option: option)
            saveSettings()
        case "telemetry":
            do {
                telemetryInput = try telemetry?.setEnabled(option == "on")
                // The switch sits beside the usage note (the first run's
                // Welcome, Settings): the notice was seen.
                telemetry?.acknowledgeNotice()
                // Crash reports follow the switch: off closes the reporter now.
                if let input = telemetryInput {
                    CrashReporting.switchChanged(enabled: input.enabled, noticeShown: true)
                }
            } catch {
                show(error: LiveSpacesBackend.words(error))
            }
        default: break
        }
    }

    /// A row's button.
    public func press(row: String) async {
        switch row {
        case "account": await signOut()
        case "sign-in": await beginSignIn()
        case "sign-in-code": cancelSignIn()
        case "reset-tips":
            await choose(row: row, option: "press")
        case "welcome":
            onboarding.restart()
            openOnboarding?()
        case "launch-at-login-approve":
            loginItem?.openSystemSettings()
        case "teams-manage", "teams-billing":
            // The account app (app.cua.ai): invites, roles and plans for
            // teams, billing.
            if let url = settingsPage.sections.flatMap(\.rows).first(where: { $0.id == row })?.linkUrl {
                openBillingPage(url)
            }
        default:
            guard row.hasPrefix("agent:"), let r = agentRows?.first(where: { "agent:\($0.agent)" == row }) else { return }
            await agentAction([r.agent], remove: r.configured)
        }
    }

    /// "Configure all detected agents".
    public func configureAllAgents() async {
        guard !agentsBusy else { return }
        let ids = (agentRows ?? []).filter(\.installed).map(\.agent)
        agentsBusy = true
        await agentAction(ids, remove: false)
        agentsBusy = false
    }

    /// Starts the agent's own sign-in on this Mac (`codex login`); the rows
    /// show `signedIn` once the agent wrote it.
    func agentSignIn(_ agent: String) async throws {
        guard let agentSetup else { return }
        try await agentSetup.signIn(agent: agent)
        await reloadAgents()
    }

    func agentAction(_ ids: [String], remove: Bool) async {
        guard let agentSetup, !ids.isEmpty else { return }
        agentsPending += ids
        defer { agentsPending.removeAll { ids.contains($0) } }
        do {
            let outcomes = remove ? try await agentSetup.remove(agents: ids)
                : try await agentSetup.setUp(agents: ids, skills: true, mcp: true)
            for id in ids {
                let s = appAgentSetupSummary(outcomes: outcomes, agent: id, name: id)
                agentFailures[id] = s.failed.isEmpty ? nil : s.failed.joined(separator: "; ")
            }
        } catch {
            for id in ids { agentFailures[id] = LiveSpacesBackend.words(error) }
        }
        await reloadAgents()
    }
}

/// Whether the daemon reported anything about a create yet.
final class CreateAcceptance: @unchecked Sendable {
    private let lock = NSLock()
    private var reported = false
    private var sentOn: SpacesBackend?
    func mark() { lock.withLock { reported = true } }
    var done: Bool { lock.withLock { reported } }
    /// The daemon connection the create was sent over (nil until it was).
    func sent(on connection: SpacesBackend) { lock.withLock { sentOn = connection } }
    var connection: SpacesBackend? { lock.withLock { sentOn } }
}