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.

37.1 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 LocalAuthentication
import Observation
import UserNotifications

/// This Mac as a client of the account on the relay: the cua SDK's
/// `Devices` (live) or `FixtureDevices` (fixtures, tests).
public protocol DevicesRunning: AnyObject, Sendable {
    func snapshot() async throws -> DevicesSnapshot
    func enroll() async throws -> DeviceEnrollment
    func checkEnrolled() async -> Bool
    func approve(code: String?, deviceId: String?) async throws
    func rename(id: String, name: String) async throws
    func revoke(id: String) async throws
    /// Vouches for a machine that registered without an enrolled device's
    /// proof (S5), from this enrolled device.
    func confirmMachine(id: String) async throws
    /// Renames a relay machine the account owns, from this enrolled device;
    /// this Mac's host setup takes the name when it is this Mac.
    func renameMachine(id: String, name: String) async throws
    /// A one-time link, QR code and install commands that add another
    /// computer to the account (or to `team`), from this enrolled device.
    func createPairingCode(team: String?) async throws -> PairingCode
    /// The account's pairing codes, newest first (without the codes).
    func pairingCodes() async throws -> [PairingCode]
    /// Revokes an unused pairing code (`pc_…`).
    func revokePairingCode(id: String) async throws
    /// The account's relay allowance this month; nil from a relay that
    /// meters nothing.
    func relayUsage() async throws -> AppRelayUsage?
    /// The account's default Space and the order to try when it is offline
    /// (`Devices.spaces_settings`).
    func spacesSettings() async throws -> SpacesSettings
    /// Replaces them (the whole setting); what the relay saved.
    func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings
    /// Where the default Space resolves now, with this Mac as the last
    /// resort (`Devices.resolve_default_space`). Creates nothing.
    func resolveDefaultSpace() async throws -> DefaultSpace
}

/// The SDK's `Devices` for the signed-in session (key in the session's vault,
/// shared with the `cua` CLI and daemon).
public final class LiveDevices: DevicesRunning, @unchecked Sendable {
    let inner: CuaSDK.Devices
    /// The account's token for the calls that take one (the allowance).
    let auth: CuaSDK.Auth?

    public init(inner: CuaSDK.Devices, auth: CuaSDK.Auth? = nil) {
        self.inner = inner
        self.auth = auth
    }

    /// This Mac on the default relay (`CUA_RELAY_URL`, else relay.cua.ai),
    /// named as Sharing names it ("Dana's MacBook Pro").
    public static func make(auth: CuaSDK.Auth) -> LiveDevices? {
        (try? auth.devices(relayUrl: nil, name: Foundation.Host.current().localizedName))
            .map { LiveDevices(inner: $0, auth: auth) }
    }

    public func snapshot() async throws -> DevicesSnapshot { try await inner.snapshot(auditLimit: 50) }
    public func enroll() async throws -> DeviceEnrollment { try await inner.enroll() }
    public func checkEnrolled() async -> Bool { await inner.checkEnrolled() }
    public func approve(code: String?, deviceId: String?) async throws {
        try Self.requireEnrolled(try await inner.approve(code: code, deviceId: deviceId))
    }

    /// Only say "approved" when the relay says the device is enrolled:
    /// anything else would leave the other device waiting while this one
    /// reads success.
    static func requireEnrolled(_ device: RelayDevice) throws {
        guard device.state == "enrolled" else {
            throw CuaError.Runtime(
                message: "The relay did not enroll \(device.name) (\(device.id)): it is \(device.state). "
                    + "Ask that machine for a new code and try again.")
        }
    }
    public func rename(id: String, name: String) async throws { _ = try await inner.rename(id: id, name: name) }
    public func revoke(id: String) async throws { _ = try await inner.revoke(id: id) }
    public func confirmMachine(id: String) async throws { _ = try await inner.confirmMachine(machineId: id) }
    public func renameMachine(id: String, name: String) async throws {
        _ = try await inner.renameMachine(machineId: id, name: name)
    }
    public func createPairingCode(team: String?) async throws -> PairingCode {
        try await inner.createPairingCode(team: team, ttlSecs: nil)
    }
    public func pairingCodes() async throws -> [PairingCode] { try await inner.pairingCodes() }
    public func revokePairingCode(id: String) async throws { try await inner.revokePairingCode(id: id) }
    /// The same read as Electron's and `cua usage`'s (`app_relay_usage`).
    public func relayUsage() async throws -> AppRelayUsage? {
        guard let auth else { return nil }
        return try await appRelayUsage(devices: inner, accountToken: try await auth.accessToken(force: false))
    }
    public func spacesSettings() async throws -> SpacesSettings { try await inner.spacesSettings() }
    public func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings {
        try await inner.setSpacesSettings(settings: settings)
    }
    public func resolveDefaultSpace() async throws -> DefaultSpace { try await inner.resolveDefaultSpace() }
}

/// An in-memory account on a relay (fixtures, tests): this Mac enrolled,
/// a new device and an expired one asking, and some access. It never
/// touches the network or the device key.
public final class FixtureDevices: DevicesRunning, @unchecked Sendable {
    public var current: DevicesSnapshot
    public private(set) var calls: [String] = []
    /// What `enroll` answers (a code unless set).
    public var enrollEnrolled = false
    /// What `checkEnrolled` answers.
    public var enrolledNow = false
    public var failApprove: String?
    /// `snapshot` fails with this (a device the relay has not enrolled).
    public var failSnapshot: String?
    /// What `relayUsage` answers (the free plan partway through the month
    /// unless set; `CUA_SPACES_RELAY_USAGE` picks one in a fixtures run).
    public var usage: AppRelayUsage? = FixtureDevices.usage(nil)

    public init(snapshot: DevicesSnapshot? = nil) {
        current = snapshot ?? FixtureDevices.sample(now: UInt64(Date().timeIntervalSince1970))
    }

    public static func sample(now: UInt64) -> DevicesSnapshot {
        let day: UInt64 = 86_400
        func device(_ id: String, _ name: String, _ state: String, _ platform: String,
                    until: UInt64?, seen: UInt64?, current: Bool = false) -> RelayDevice {
            RelayDevice(id: id, name: name, state: state, platform: platform, createdAt: now - 40 * day,
                        enrolledUntil: until, lastSeen: seen, current: current)
        }
        return DevicesSnapshot(
            localDeviceId: "dev_mac",
            devices: [
                device("dev_mac", "MacBook Pro", "enrolled", "macos", until: now + 24 * day, seen: now - 60,
                       current: true),
                device("dev_studio", "Studio", "enrolled", "linux", until: now + 12 * day, seen: now - 3 * 3600),
                device("dev_work", "Work laptop", "pending", "windows", until: nil, seen: nil),
                device("dev_old", "Old laptop", "expired", "linux", until: now - 2 * day, seen: now - 33 * day),
            ],
            enforceAfter: now - day,
            audit: [
                RelayAuditEvent(ts: now - 5 * 3600, kind: "machine_access", device: "dev_studio", machine: "m1",
                                subject: nil, detail: "owner"),
                RelayAuditEvent(ts: now - 2 * 3600, kind: "shared_access", device: nil, machine: "m1",
                                subject: "[email protected]", detail: nil),
                RelayAuditEvent(ts: now - 1800, kind: "device_registered", device: "dev_work", machine: nil,
                                subject: nil, detail: nil),
                RelayAuditEvent(ts: now - 600, kind: "machine_access", device: "dev_mac", machine: "m2",
                                subject: nil, detail: "owner"),
            ],
            machineNames: ["m1": "studio-mac", "m2": "build-box"],
            machines: [
                RelayMachine(id: "m1", spaceId: "relay:m1", name: "studio-mac", ownerId: "me",
                             ownerEmail: nil, role: "owner", online: true, sharing: true, version: "0.5.0",
                             url: "", allow: [], clients: [], confirmed: true, team: nil, providesSpaces: true),
                RelayMachine(id: "m2", spaceId: "relay:m2", name: "build-box", ownerId: "me",
                             ownerEmail: nil, role: "owner", online: false, sharing: true, version: "0.5.0",
                             url: "", allow: [], clients: [], confirmed: false, team: nil, providesSpaces: nil),
            ])
    }

    public func snapshot() async throws -> DevicesSnapshot {
        if let failSnapshot { throw CuaError.PermissionDenied(message: failSnapshot) }
        return current
    }

    public func enroll() async throws -> DeviceEnrollment {
        calls.append("enroll")
        let me = current.devices.first { $0.current } ?? RelayDevice(
            id: "dev_mac", name: "MacBook Pro", state: "pending", platform: "macos", createdAt: 0,
            enrolledUntil: nil, lastSeen: nil, current: true)
        return DeviceEnrollment(device: me, enrolled: enrollEnrolled, code: enrollEnrolled ? nil : "K7QX-M2RP")
    }

    public func checkEnrolled() async -> Bool {
        calls.append("check")
        return enrolledNow
    }

    public func approve(code: String?, deviceId: String?) async throws {
        calls.append("approve:\(code ?? deviceId ?? "")")
        if let failApprove { throw CuaError.PermissionDenied(message: failApprove) }
        for i in current.devices.indices where current.devices[i].id == deviceId
            || (code != nil && current.devices[i].state == "pending") {
            current.devices[i].state = "enrolled"
            break
        }
    }

    public func rename(id: String, name: String) async throws {
        calls.append("rename:\(id):\(name)")
        for i in current.devices.indices where current.devices[i].id == id { current.devices[i].name = name }
    }

    public func revoke(id: String) async throws {
        calls.append("revoke:\(id)")
        for i in current.devices.indices where current.devices[i].id == id { current.devices[i].state = "revoked" }
    }

    public func renameMachine(id: String, name: String) async throws {
        calls.append("rename-machine:\(id):\(name)")
        for i in current.machines.indices where current.machines[i].id == id { current.machines[i].name = name }
    }

    public func confirmMachine(id: String) async throws {
        calls.append("confirm-machine:\(id)")
        for i in current.machines.indices where current.machines[i].id == id { current.machines[i].confirmed = true }
    }

    /// The account's pairing codes as the relay keeps them (with the codes).
    public var pairing: [PairingCode] = []

    public func createPairingCode(team: String?) async throws -> PairingCode {
        calls.append("create-pairing-code:\(team ?? "")")
        let now = UInt64(Date().timeIntervalSince1970)
        let code = "K7QM-4XPB-\(String(format: "%04d", pairing.count + 1))"
        let made = PairingCode(
            id: "pc_fixture\(pairing.count + 1)", code: code, url: "https://cua.ai/add/\(code)",
            installSh: "curl -fsSL https://cua.ai/install.sh | sh -s -- --pair \(code)",
            installPowershell: "& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair \(code)",
            state: "active", team: team, createdAt: now, expiresAt: now + 1800, usedAt: nil, machine: nil)
        pairing.insert(made, at: 0)
        return made
    }

    public func pairingCodes() async throws -> [PairingCode] {
        calls.append("pairing-codes")
        return pairing.map {
            var listed = $0
            listed.code = nil
            listed.url = nil
            listed.installSh = nil
            listed.installPowershell = nil
            return listed
        }
    }

    public func revokePairingCode(id: String) async throws {
        calls.append("revoke-pairing-code:\(id)")
        for i in pairing.indices where pairing[i].id == id { pairing[i].state = "revoked" }
    }

    public func relayUsage() async throws -> AppRelayUsage? {
        calls.append("relay-usage")
        return usage
    }

    /// The account's default Space as the relay keeps it (unset unless set).
    public var spaces = SpacesSettings(defaultSpace: nil, fallback: [], fallbackOn: true, updatedAt: 0)

    public func spacesSettings() async throws -> SpacesSettings {
        calls.append("spaces-settings")
        return spaces
    }

    public func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings {
        calls.append("set-spaces-settings:\(settings.defaultSpace ?? "")")
        spaces = SpacesSettings(defaultSpace: settings.defaultSpace, fallback: settings.fallback,
                                fallbackOn: settings.fallbackOn, updatedAt: UInt64(Date().timeIntervalSince1970))
        return spaces
    }

    /// The relay's resolution over the fixture account's machines: the
    /// default, the order to try (or every other machine), then this Mac.
    public func resolveDefaultSpace() async throws -> DefaultSpace {
        calls.append("resolve-default-space")
        let machines = current.machines.map { ("relay:\($0.id)", $0.name, $0.online) }
        var order: [DefaultSpaceStep] = []
        if let d = spaces.defaultSpace, let m = machines.first(where: { $0.0 == d }) {
            order.append(DefaultSpaceStep(space: m.0, name: m.1, online: m.2, role: "default"))
        }
        if spaces.fallbackOn {
            let listed = spaces.fallback.isEmpty ? machines.map(\.0) : spaces.fallback
            for id in listed where id != spaces.defaultSpace {
                if let m = machines.first(where: { $0.0 == id }) {
                    order.append(DefaultSpaceStep(space: m.0, name: m.1, online: m.2, role: "fallback"))
                }
            }
        }
        order.append(DefaultSpaceStep(space: "relay:this-mac", name: "This Mac", online: true, role: "here"))
        let first = order.first(where: { $0.online && $0.role != "here" })
        let online = spaces.defaultSpace.map { d in machines.first(where: { $0.0 == d })?.2 ?? false }
        let reason = first.map { $0.role == "default" ? "default" : (spaces.defaultSpace == nil ? "unset" : "fallback") } ?? "here"
        return DefaultSpace(space: first?.space, reason: reason, defaultSpace: spaces.defaultSpace,
                            defaultOnline: online, order: order)
    }

    /// A relay allowance by name: `reached` (past it: the notice shows),
    /// `team` (a pooled team allowance, within it), `none` (a relay that
    /// meters nothing), else the free plan partway through the month.
    public static func usage(_ name: String?) -> AppRelayUsage? {
        let free = AppRelayUsage(
            metered: true, period: "2026-10", plan: "free", team: nil, liveSessions: 1, liveSessionsLimit: 2,
            hoursUsed: 6.5, hoursLimit: 20, myHoursUsed: 6.5, softLimitReached: false, reasons: [],
            upgradeUrl: "https://cua.ai/pricing")
        var u = free
        switch name {
        case "none": return nil
        case "warn":
            u.hoursUsed = 16.5
            u.myHoursUsed = 16.5
        case "reached":
            u.liveSessions = 2
            u.hoursUsed = 20.4
            u.myHoursUsed = 20.4
            u.softLimitReached = true
            u.reasons = ["hours"]
        case "team":
            u.plan = "team"
            u.team = AppRelayUsageTeam(id: "acme", seats: 3)
            u.liveSessionsLimit = 6
            u.hoursUsed = 31.5
            u.hoursLimit = 60
        default: break
        }
        return u
    }
}

/// Presence before approving a device: Touch ID, an Apple Watch or the
/// login password.
public protocol PresenceChecking: Sendable {
    /// Returns when the user confirmed `reason`; throws otherwise.
    func confirm(reason: String) async throws
}

/// LocalAuthentication's owner check, the same policy the cua daemon asks
/// for before the Keyvault widens access.
public struct LivePresence: PresenceChecking {
    public init() {}

    public func confirm(reason: String) async throws {
        let context = LAContext()
        var error: NSError?
        guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
            throw CuaError.PermissionDenied(message: "Touch ID and the login password are not available")
        }
        do {
            try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)
        } catch let e as LAError where [.userCancel, .systemCancel, .appCancel].contains(e.code) {
            throw CuaError.PermissionDenied(message: "Approval was cancelled")
        } catch {
            throw CuaError.PermissionDenied(message: "Approval was not confirmed")
        }
    }
}

/// A presence answer for tests: yes or no, recording the reasons asked.
public final class FixturePresence: PresenceChecking, @unchecked Sendable {
    public var allow: Bool
    public private(set) var asked: [String] = []
    public init(allow: Bool = true) { self.allow = allow }
    public func confirm(reason: String) async throws {
        asked.append(reason)
        if !allow { throw CuaError.PermissionDenied(message: "Approval was cancelled") }
    }
}

/// Where a Devices sheet shows: the main window or Settings.
public enum DevicesSurface: Sendable {
    case main
    case settings
}

/// Settings → Devices, the enroll sheet, the approval sheet and the main
/// window's banner. Every word and decision is the core's
/// (`appDevicesView`, `appEnroll*`, `appApprove*`); this runs the SDK calls
/// they ask for. Nothing here prompts on its own except a new device's
/// approval (a notification and the sheet): unattended agents keep their
/// device session without the user.
@MainActor
@Observable
public final class DevicesModel {
    let devices: DevicesRunning?
    let presence: PresenceChecking
    /// The relay's answer, once read.
    public private(set) var snapshot: DevicesSnapshot?
    /// When `snapshot` was read.
    public private(set) var refreshedAt: Date?
    /// The code this Mac shows while it waits for approval.
    public internal(set) var pendingCode: String?
    public private(set) var error: String?
    public private(set) var busy = false
    /// The enroll sheet, while it shows, and where.
    public var enroll: AppEnrollState?
    public var enrollSurface: DevicesSurface = .main
    /// The approval sheet, while it shows, and where.
    public var approval: AppApproveSheetState?
    public var approvalSurface: DevicesSurface = .main
    /// A new machine's confirm alert, while it shows (S5).
    public var confirming: AppUnconfirmedMachine?
    /// Signed in to Cua (no account, no devices). A change forgets the
    /// last allowance (another account's, or none).
    public var signedIn = false {
        didSet {
            guard signedIn != oldValue else { return }
            relayUsageGeneration += 1
            relayUsage = nil
            relayUsageReadAt = nil
        }
    }
    /// Runs the interactive sign-in; true once signed in again.
    public var signIn: (() async -> Bool)?
    /// Shows a system notification for a device asking to join.
    public var notify: ((AppApprovalPrompt) -> Void)?
    /// Approvals already announced (a device asks once per launch).
    var announced: Set<String> = []
    /// Re-verifications put off with Not Now.
    var dismissed: Set<String> = []
    /// Now (tests pin it).
    public var clock: () -> Date = { Date() }
    /// How long to wait between enrollment checks while the code shows.
    var pollInterval: Duration = .seconds(3)
    /// At most this many checks (10 minutes, the code's lifetime).
    var pollLimit = 200
    var locale = Locale.current
    var timeZone = TimeZone.current

    /// The account's relay allowance this month (metered only).
    public private(set) var relayUsage: AppRelayUsage?
    var relayUsageReadAt: Date?
    /// Bumped on every account change: an older read's answer is dropped.
    var relayUsageGeneration = 0
    /// Where a dismissed notice is remembered (the core's `dismissKey`).
    let defaults: UserDefaults
    static let relayNoticeDismissedKey = "cua.relayAllowance.dismissed"
    public private(set) var relayNoticeDismissed: String?
    /// The relay just refused a new session over the plan's cap: the sentence
    /// with Upgrade, shown until dismissed or a session starts.
    public private(set) var refusal: AppRelayAllowanceNotice?
    /// Where the refusal came from, for usage data and the upgrade link's
    /// `?from=`: `app_create` (a Space create) or `app_connect` (opening or
    /// starting one).
    public private(set) var refusalSurface = "app_connect"

    public init(devices: DevicesRunning?, presence: PresenceChecking = LivePresence(),
                defaults: UserDefaults = .standard) {
        self.devices = devices
        self.presence = presence
        self.defaults = defaults
        relayNoticeDismissed = defaults.string(forKey: Self.relayNoticeDismissedKey)
    }

    var nowSecs: UInt64 { UInt64(max(0, clock().timeIntervalSince1970)) }

    public var input: AppDevicesInput {
        snapshot.map { appDevicesInput(snapshot: $0, pendingCode: pendingCode) }
            ?? AppDevicesInput(devices: [], audit: [], localDeviceId: nil, pendingCode: pendingCode,
                               enforceAfter: nil, machineNames: [:], machines: [])
    }

    /// The Devices page.
    public var view: AppDevicesView { appDevicesView(input: input, now: nowSecs) }

    /// The main window's banner: signed in, read, and something needs the user.
    public var banner: AppDeviceBanner? {
        guard signedIn, snapshot != nil else { return nil }
        return view.banner
    }

    /// Signed in, read, and this Mac cannot open the account's machines
    /// (never enrolled, waiting for approval, expired, revoked): why, for
    /// every machine's greyed-out Connect, and its one action.
    public var accessNotice: AppMachineAccessNotice? {
        guard signedIn, snapshot != nil else { return nil }
        return appMachineAccessNotice(kind: view.thisDevice.kind, pendingCode: pendingCode)
    }

    public var enrollView: AppEnrollView? { enroll.map { appEnrollView(state: $0) } }
    public var approvalView: AppApproveSheetView? { approval.map { appApproveView(state: $0, devices: input.devices) } }

    // MARK: - Words the shell formats

    /// "Enrolled until Oct 27, 2026".
    public func thisDeviceText(_ t: AppThisDevice) -> String {
        guard let at = t.at else { return t.title }
        return "\(t.title) \(dateText(at))"
    }

    func dateText(_ secs: UInt64) -> String {
        let f = DateFormatter()
        f.locale = locale
        f.timeZone = timeZone
        f.dateStyle = .medium
        f.timeStyle = .none
        return f.string(from: Date(timeIntervalSince1970: TimeInterval(secs)))
    }

    /// "5 min ago", relative to the model's clock.
    public func relativeText(_ secs: UInt64) -> String {
        let f = RelativeDateTimeFormatter()
        f.locale = locale
        f.unitsStyle = .full
        let date = Date(timeIntervalSince1970: TimeInterval(secs))
        let now = clock()
        return date > now.addingTimeInterval(-60) ? "just now" : f.localizedString(for: date, relativeTo: now)
    }

    /// A row's second line: platform and state, then when it was last seen.
    public func rowDetail(_ r: AppDeviceRow) -> String {
        guard let seen = r.lastSeen else { return r.detail }
        return "\(r.detail), \(view.labels.lastSeen.lowercased()) \(relativeText(seen))"
    }

    // MARK: - Refresh

    /// Reads the relay; announces devices newly asking for approval.
    /// Reads the relay again when the last answer is older than `maxAge`
    /// seconds: the Machines page shows who is connected now, not at
    /// sign-in.
    public func refreshIfStale(maxAge: TimeInterval = 30) async {
        if let at = refreshedAt, clock().timeIntervalSince(at) < maxAge { return }
        await refresh()
    }

    /// Whether the relay saw each of the account's machines connected, by
    /// machine id, at the last read.
    public var relayOnline: [String: Bool] {
        Dictionary((snapshot?.machines ?? []).map { ($0.id, $0.online) }, uniquingKeysWith: { a, _ in a })
    }

    /// Each device's state (`enrolled`, `pending`, `expired`, `revoked`), by id.
    public var deviceStates: [String: String] {
        Dictionary((snapshot?.devices ?? []).map { ($0.id, $0.state) }, uniquingKeysWith: { a, _ in a })
    }

    public func refresh() async {
        guard signedIn, let devices else {
            snapshot = nil
            return
        }
        do {
            snapshot = try await devices.snapshot()
            refreshedAt = clock()
            error = nil
        } catch {
            self.error = LiveSpacesBackend.words(error)
            return
        }
        if view.enrolled { pendingCode = nil }
        for prompt in view.approvals where !announced.contains(prompt.deviceId) {
            announced.insert(prompt.deviceId)
            guard !prompt.expired || !dismissed.contains(prompt.deviceId) else { continue }
            notify?(prompt)
            if approval == nil, enroll == nil { openApproval(prompt, in: .main) }
        }
    }

    // MARK: - Relay usage

    /// How often the main window reads the allowance again, and how old a
    /// read may be when the app comes to the front (as the web UI).
    public static let relayUsagePoll: Duration = .seconds(300)
    public static let relayUsageFocusAge: TimeInterval = 60

    /// Settings' Relay usage row and the notice, in the core's words.
    public var relayUsageView: AppRelayUsageView? { relayUsage.flatMap { appRelayUsageView(usage: $0) } }

    /// The notice above the main window, until dismissed for this month and
    /// these reasons.
    ///
    /// At 80% of the relay hours (`warn`) it is a prompt, so it waits while a
    /// live session is going; past the allowance (`limit`) it always shows.
    public var relayNotice: AppRelayAllowanceNotice? {
        if let refusal { return refusal }
        guard let notice = relayUsageView?.notice, notice.dismissKey != relayNoticeDismissed else { return nil }
        if notice.level == "warn", (relayUsage?.liveSessions ?? 0) > 0 { return nil }
        return notice
    }

    /// One usage event for a Pro or Teams surface (`upsell_<surface>_<action>`,
    /// fixed names in the app core's telemetry schema).
    public func recordUpsell(_ feature: String) {
        telemetry?.record(appTelemetryFeature(feature: feature))
    }

    /// Keeps an error's text when it is the relay refusing a session over
    /// the plan's cap (the core's `appPlanLimitNotice`); any other error is
    /// not a refusal and leaves the notice alone. `surface`: `app_create`
    /// for a Space create, `app_connect` for opening or starting one.
    public func noteRefusal(_ error: String, surface: String = "app_connect") {
        guard let notice = appPlanLimitNotice(error: error, accountApp: appAccountAppUrl()) else { return }
        refusal = notice
        refusalSurface = surface
    }

    /// The notice is on screen: a refusal is `cua_plan_limit_shown` at its
    /// surface; the meter is `upsell_meter_shown`, and past a limit also
    /// `cua_plan_limit_shown` at `app_meter` (CUA-1881).
    public func recordNoticeShown(_ notice: AppRelayAllowanceNotice) {
        if notice == refusal {
            telemetry?.record(appTelemetryPlanLimit(action: "shown", surface: refusalSurface, kind: notice.kind, plan: notice.plan))
        } else {
            telemetry?.record(appTelemetryUpsell(surface: "meter", action: "shown", kind: notice.kind, plan: notice.plan))
        }
    }

    /// Upgrade on the notice: records `cua_upgrade_link_opened` (and the
    /// meter's `upsell_meter_click`) and answers the link to open, saying
    /// where it was opened from (`?from=`).
    public func openUpgrade(_ notice: AppRelayAllowanceNotice) -> URL? {
        guard let link = notice.upgradeUrl else { return nil }
        let surface: String
        if notice == refusal {
            surface = refusalSurface
            telemetry?.record(appTelemetryPlanLimit(action: "opened", surface: surface, kind: notice.kind, plan: notice.plan))
        } else {
            surface = "app_meter"
            telemetry?.record(appTelemetryUpsell(surface: "meter", action: "click", kind: notice.kind, plan: notice.plan))
        }
        return URL(string: appUpgradeLink(url: link, surface: surface))
    }

    /// A plan card link in Settings: `upsell_plan_card_click` and
    /// `cua_upgrade_link_opened`; the link says it came from there.
    public func openPlanLink(_ link: String) -> URL? {
        telemetry?.record(appTelemetryUpsell(surface: "plan_card", action: "click", kind: nil, plan: relayUsage?.plan))
        return URL(string: appUpgradeLink(url: link, surface: "app_plan_card"))
    }

    public func dismissRelayNotice() {
        if refusal != nil {
            refusal = nil
            return
        }
        guard let key = relayUsageView?.notice?.dismissKey else { return }
        recordUpsell("upsell_meter_dismiss")
        relayNoticeDismissed = key
        defaults.set(key, forKey: Self.relayNoticeDismissedKey)
    }

    /// Reads the allowance unless the last read is newer than `maxAge`
    /// seconds. A failed read keeps the last answer.
    public func readRelayUsage(maxAge: TimeInterval = 0) async {
        guard signedIn, let devices else {
            relayUsage = nil
            return
        }
        if maxAge > 0, let at = relayUsageReadAt, clock().timeIntervalSince(at) < maxAge { return }
        relayUsageReadAt = clock()
        let generation = relayUsageGeneration
        do {
            let usage = try await devices.relayUsage()
            guard generation == relayUsageGeneration else { return }
            relayUsage = usage?.metered == true ? usage : nil
        } catch {
            return
        }
    }

    // MARK: - Enroll this device

    public func startEnroll(in surface: DevicesSurface) {
        enrollSurface = surface
        enroll = appEnrollInitial()
    }

    public func closeEnroll() { enroll = nil }

    /// Where usage events go (enrolled by a sign-in or an approval, or
    /// failed; the app core's, like the Tauri app).
    public var telemetry: TelemetryRunning?

    func sendEnroll(_ action: AppEnrollAction) {
        guard let s = enroll else { return }
        telemetry?.record(appTelemetryEnroll(state: s, action: action))
        enroll = appEnrollReduce(state: s, action: action)
    }

    public func backEnroll() { sendEnroll(.back) }

    /// "Sign in again" or "Approve from another device".
    public func chooseEnroll(_ method: AppEnrollMethod) async {
        sendEnroll(.choose(method: method))
        if enroll?.phase == .signingIn {
            let ok = await signIn?() ?? false
            guard enroll?.phase == .signingIn else { return }
            if !ok {
                sendEnroll(.failed(error: "Sign-in did not finish."))
                return
            }
            sendEnroll(.signedIn)
        }
        guard enroll?.phase == .registering, let devices else { return }
        do {
            let r = try await devices.enroll()
            sendEnroll(.registered(enrolled: r.enrolled, code: r.code))
            pendingCode = r.enrolled ? nil : r.code
        } catch {
            sendEnroll(.failed(error: LiveSpacesBackend.words(error)))
            return
        }
        await waitForApproval()
        await refresh()
    }

    /// Checks until an enrolled device approves, the sheet closes or the
    /// code runs out.
    func waitForApproval() async {
        guard let devices else { return }
        var checks = 0
        while enroll?.phase == .waiting, checks < pollLimit, !Task.isCancelled {
            checks += 1
            if await devices.checkEnrolled() {
                sendEnroll(.approved)
                pendingCode = nil
                return
            }
            try? await Task.sleep(for: pollInterval)
        }
    }

    // MARK: - Approve another device

    public func openApproval(_ prompt: AppApprovalPrompt, in surface: DevicesSurface) {
        approvalSurface = surface
        approval = appApproveOpen(prompt: prompt)
    }

    /// The row's Approve… (the prompt for that device).
    public func openApproval(deviceId: String, in surface: DevicesSurface) {
        guard let p = view.approvals.first(where: { $0.deviceId == deviceId }) else { return }
        openApproval(p, in: surface)
    }

    public func setCode(_ code: String) {
        guard let s = approval else { return }
        approval = appApproveReduce(state: s, action: .setCode(code: code), devices: input.devices)
    }

    /// Approve: presence first, then the relay. `devices` is the account's
    /// current devices: once a code expires, it is how the sheet finds the
    /// sole waiting device of that name to offer approving by id instead.
    public func approve() async {
        guard let s = approval, let devices else { return }
        let deviceList = input.devices
        let next = appApproveReduce(state: s, action: .submit, devices: deviceList)
        guard next.busy, let request = appApproveView(state: next, devices: deviceList).request else { return }
        approval = next
        do {
            try await presence.confirm(reason: appApproveView(state: next, devices: deviceList).presenceReason)
            try await devices.approve(code: request.code, deviceId: request.deviceId)
        } catch {
            if let cur = approval {
                approval = appApproveReduce(state: cur, action: .failed(error: LiveSpacesBackend.words(error)), devices: deviceList)
            }
            return
        }
        approval = nil
        await refresh()
    }

    /// Deny (revokes a new device, one click) or Not Now (re-verification).
    public func deny() async {
        guard let s = approval else { return }
        let v = appApproveView(state: s, devices: input.devices)
        approval = nil
        guard v.denyRevokes else {
            dismissed.insert(s.deviceId)
            return
        }
        await run { try await $0.revoke(id: s.deviceId) }
    }

    /// The row's Deny (no sheet): revokes a still-pending device in one
    /// click, like the sheet's Deny, or (a device due for re-verification)
    /// only dismisses it, like the sheet's Not Now.
    public func denyApproval(deviceId: String) async {
        guard let p = view.approvals.first(where: { $0.deviceId == deviceId }) else { return }
        guard !p.expired else {
            dismissed.insert(p.deviceId)
            return
        }
        await run { try await $0.revoke(id: p.deviceId) }
    }

    // MARK: - Rows

    public func rename(id: String, to name: String) async {
        guard let clean = appDevicesCleanName(name: name) else { return }
        await run { try await $0.rename(id: id, name: clean) }
    }

    /// After the row's confirmation.
    public func revoke(id: String) async {
        await run { try await $0.revoke(id: id) }
    }

    // MARK: - New machines (S5)

    /// After the row's confirmation.
    public func confirmMachine(id: String) async {
        await run { try await $0.confirmMachine(id: id) }
    }

    func run(_ call: (DevicesRunning) async throws -> Void) async {
        guard let devices, !busy else { return }
        busy = true
        defer { busy = false }
        do {
            try await call(devices)
            error = nil
        } catch {
            self.error = LiveSpacesBackend.words(error)
            return
        }
        await refresh()
    }
}

/// System notifications for devices asking to join. Only a bundled app
/// posts them (a test process has no notification identity).
@MainActor
final class DeviceNotifier: NSObject, UNUserNotificationCenterDelegate {
    static let shared = DeviceNotifier()
    /// A notification was clicked (its identifier): the app opens its main UI.
    var onOpen: ((String) -> Void)?

    static var available: Bool { Bundle.main.bundleURL.pathExtension == "app" }

    func post(_ prompt: AppApprovalPrompt) {
        guard Self.available else { return }
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        let content = UNMutableNotificationContent()
        content.title = prompt.notifyTitle
        content.body = prompt.notifyBody
        content.sound = .default
        let request = UNNotificationRequest(identifier: "device-\(prompt.deviceId)", content: content, trigger: nil)
        Task {
            guard await PermissionRequester.notificationsAuthorized(center) else { return }
            try? await center.add(request)
        }
    }

    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification)
        async -> UNNotificationPresentationOptions { [.banner, .sound] }

    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
                                            didReceive response: UNNotificationResponse) async {
        let id = response.notification.request.identifier
        await MainActor.run {
            NSApp.activate()
            onOpen?(id)
        }
    }
}