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.

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

import AppKit
import CuaSDK
import CuaSpacesFFI
import CuaSpacesNotchUI
import Foundation

/// Process-level wiring: which backend, where state lives, and the start
/// views captures and UI tests use.
@MainActor
public enum AppEnvironment {
    /// Whether this is a Local build ("Cua Spaces Local", Info.plist
    /// `CuaChannel` = `local`, stamped by `scripts/build-app.sh --channel
    /// local`). Tests and every other build are Stable.
    static let isLocalChannel =
        ((Bundle.main.object(forInfoDictionaryKey: "CuaChannel") as? String) ?? "")
        .trimmingCharacters(in: .whitespaces).lowercased() == "local"

    /// The bundle identity (the Keyvault's trusted-caller requirement names
    /// it; see README "Keyvault identity"). A Local build keeps its settings
    /// in its own folder, `com.trycua.spaces.macos.local`, never Stable's.
    public static let bundleIdentifier = isLocalChannel ? "com.trycua.spaces.macos.local" : "com.trycua.spaces.macos"

    /// `$HOME`, so a temp HOME (tests, captures) keeps every file away from
    /// the account's real Library (`FileManager` ignores `$HOME`).
    static var home: URL {
        URL(fileURLWithPath: ProcessInfo.processInfo.environment["HOME"] ?? NSHomeDirectory(), isDirectory: true)
    }

    static var supportDirectory: URL {
        home.appendingPathComponent("Library/Application Support", isDirectory: true)
            .appendingPathComponent(bundleIdentifier, isDirectory: true)
    }

    /// The live model, or fixtures with `CUA_SPACES_FIXTURES=1` (UI tests).
    public static func makeModel() -> AppModel {
        let env = DevHooks.environment
        let fixtures = env["CUA_SPACES_FIXTURES"] == "1"
        let settingsPath = supportDirectory.appendingPathComponent("settings.json").path
        let onboardingPath = supportDirectory.appendingPathComponent("onboarding.json").path
        // The first launch after an update (the version the settings file
        // recorded changed): refresh the agents' skills below. This app's
        // own daemon needs no restart of its own: `cua daemon start` below
        // replaces a daemon whose executable was updated since it started.
        // Fixtures skip it (`CUA_SPACES_REFRESH=1` runs it anyway, for
        // end-to-end runs with a throwaway HOME).
        let info = AboutBundleInfo(bundle: .main)
        // Before the first `Cua`: this process's usage events are the app's
        // (`spaces_app`), wait for the notice the first run shows (never a
        // terminal notice), and start with `app_launched` (saying whether
        // the first run is still to finish).
        if !fixtures {
            // No keychain prompt from this process or the daemon it starts
            // (they inherit it): a read that would need one fails fast as
            // "needs access", and the window asks (`StartupModel`). The one
            // interactive read is the clicked `cua auth keychain --prompt`.
            setenv(keychainNonInteractiveEnv, "1", 1)
            let due = !(OnboardingModel.readCompleted(onboardingPath) ?? false)
            _ = appTelemetryStart(version: info.version, onboardingEligible: due)
        }
        var refresh: UpdateRefresh?
        if !fixtures || env["CUA_SPACES_REFRESH"] == "1",
           UpdateRefresh.record(settingsPath: settingsPath, version: info.version, build: info.build,
                                onboarded: OnboardingModel.readCompleted(onboardingPath) ?? false),
           let cua = bundledCua {
            refresh = UpdateRefresh(cua: cua, bundle: Bundle.main.bundlePath)
        }
        let updateRefresh = refresh
        // This app's own daemon, started before the SDK connects (it
        // replaces another build's, or its own from before an update);
        // fixtures never touch the host.
        let supervisor = fixtures ? nil : bundledCua.flatMap { DaemonSupervisor(bundledCua: $0) }
        // The live services come later, off the main thread (`StartupModel`):
        // until then the window shows the launch, on stand-ins that wait
        // for them. Nothing here reads the keychain or waits on the daemon.
        let gate = LiveGate<LiveServices>()
        let backend: SpacesBackend
        if fixtures {
            let fixture = FixtureSpacesBackend(rows: FixtureSpacesBackend.rows(environment: env))
            fixture.fixtureRuns["local:aurora"] = FixtureSpacesBackend.sampleRuns
            fixture.fixtureEvents = FixtureSpacesBackend.sampleEvents
            fixture.fixtureHealth = FixtureSpacesBackend.peerHealth(environment: env)
            backend = fixture
        } else {
            backend = PendingSpacesBackend(gate: gate)
        }
        let keyvault = KeyvaultModel(client: fixtures ? nil : KeyvaultClient(cuaHome: nil))
        if !fixtures {
            // Icons: caches survive restarts; fixtures never resolve apps or
            // touch the network.
            let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
                .appendingPathComponent(isLocalChannel ? "com.trycua.cua-spaces.local/icons" : "com.trycua.cua-spaces/icons")
            keyvault.appIcons = AppIconCache(dir: caches?.appendingPathComponent("apps"))
            keyvault.siteIconStore = SiteIconStore(dir: caches?.appendingPathComponent("sites"))
            keyvault.iconScale = Int(NSScreen.main?.backingScaleFactor ?? 2)
        }
        // Fixtures never touch the host service, the account, the telemetry
        // config or the coding agents' configs.
        let host: HostRunning = fixtures ? FixtureHost() : PendingHost(gate: gate)
        let account: AccountRunning = fixtures ? FixtureAccount(identity: env["CUA_SPACES_FIXTURE_PEER_CUA"] != nil ? "[email protected]" : nil) : PendingAccount(gate: gate)
        let telemetry: TelemetryRunning = fixtures ? FixtureTelemetry() : LiveTelemetry()
        let agents: AgentSetupRunning = fixtures ? FixtureAgentSetup() : PendingAgentSetup(gate: gate)
        // The first run's pages are the web UI's; this is its state file.
        let onboarding = OnboardingModel(statePath: onboardingPath)
        // This Mac on the relay: the session's device key (fixtures: an
        // in-memory account; presence answers yes there).
        let devices: DevicesRunning = fixtures ? fixtureDevices(env["CUA_SPACES_RELAY_USAGE"]) : PendingDevices(gate: gate)
        let startup = fixtures ? fixtureStartup(env["CUA_SPACES_STARTUP"]) : StartupModel(phase: .starting)
        let model = AppModel(backend: backend, keyvault: keyvault, onboarding: onboarding,
                             settingsPath: settingsPath,
                             host: host, account: account, telemetry: telemetry, agentSetup: agents,
                             devices: devices,
                             presence: fixtures ? FixturePresence() : LivePresence(),
                             loginItem: fixtures ? fixtureLoginItem(env["CUA_SPACES_LOGIN_ITEM"]) : MainAppLoginItem(),
                             startup: startup)
        if fixtures { model.teamsReader = FixtureTeams() }
        if !fixtures {
            // Local Network access is asked for before the first macOS
            // Space on this Mac, and when this Mac starts providing Spaces
            // (macOS Spaces your other devices create here need it), after
            // the core's explanation (not at launch, where the prompt came
            // without a reason).
            model.localNetworkGate = LocalNetworkGate(probe: LiveLocalNetworkProbe())
            // Signed out is nil (setup signs in first); anything else (no
            // network, the credential vault) is the error itself, never a
            // silent nil that reads as "not signed in".
            let token: (Bool) async throws -> String? = { force in
                guard let auth = await gate.wait().live?.cua.auth() else { return nil }
                do {
                    return try await auth.accessToken(force: force)
                } catch CuaError.Unauthenticated {
                    return nil
                }
            }
            model.host.accountToken = token
            model.teamsReader = LiveTeams(token: token)
            // The keychain check first (the bundled `cua`, without a prompt),
            // then the daemon and the SDK, all off the main thread.
            startup.keychain = bundledCua.map { BundledCuaKeychain(cua: $0) }
            startup.promptShowing = { SecurityAgentWindow.isShowing() }
            startup.start = { [weak model] in
                let services = await Task.detached(priority: .userInitiated) {
                    makeLiveServices(supervisor: supervisor)
                }.value
                // A start run again after a failed one: the first to finish
                // is the one handed over.
                guard gate.resolve(services), let model else { return }
                attach(services, to: model, supervisor: supervisor, refresh: updateRefresh)
            }
            startup.restart = { [weak model] in
                await Task.detached(priority: .userInitiated) { _ = supervisor?.restart() }.value
                // Signed in now (access given after the start): read it again.
                if let model, gate.current != nil { model.attachLive(model.live) }
            }
            startup.begin()
        }
        // Settings → About: Sparkle in the shipped app (a debug build's
        // `CUA_SPACES_UPDATER=live` starts it in a fixtures run too), an
        // in-memory updater for fixtures.
        let channel = model.settings.updateChannel
        let updater: UpdaterDriving? = fixtures && env["CUA_SPACES_UPDATER"] != "live"
            ? FixtureUpdater(lastCheck: Date().addingTimeInterval(-2 * 3600))
            : SparkleUpdater.start(channels: appAboutAllowedChannels(channel: channel))
        // `CUA_SPACES_FIXTURE_UPDATE=<version>` (fixtures): that update is found and downloaded.
        if let fixture = updater as? FixtureUpdater, let version = env["CUA_SPACES_FIXTURE_UPDATE"] {
            fixture.simulateFound(version: version)
            fixture.simulateDownloaded()
        }
        model.updates = UpdatesModel(updater: updater, channel: channel)
        model.updates.telemetry = telemetry
        model.updates.saveChannel = { [weak model] channel in model?.setUpdateChannel(channel) }
        // End-to-end runs: check now, with no window unless one is found.
        if env["CUA_SPACES_UPDATE_CHECK"] == "background", let sparkle = updater as? SparkleUpdater {
            sparkle.checkInBackground()
        }
        if fixtures, let updateRefresh {
            runRefresh(updateRefresh, daemonError: nil, model: model)
        }
        return model
    }

    /// Makes the live services (off the main thread: the daemon start
    /// waits up to 30 s, the SDK reads the session from the keychain).
    nonisolated static func makeLiveServices(supervisor: DaemonSupervisor?) -> LiveServices {
        var daemonError: String?
        do {
            let live = try makeLiveBackend(supervisor: supervisor, daemonError: &daemonError)
            let auth = live.cua.auth()
            return LiveServices(
                backend: live, live: live, account: LiveAccount(auth: auth),
                agentSetup: LiveAgentSetup(inner: live.cua.agentSetup(), cuaBinary: bundledCuaPath),
                devices: LiveDevices.make(auth: auth),
                host: CuaSDK.Host(cuaHome: nil), daemonError: daemonError)
        } catch {
            // Say so: an empty list (and an empty notch) would look like
            // "no Spaces".
            let message = "Could not start the cua SDK: \(LiveSpacesBackend.words(error))"
            NSLog("Cua Spaces: %@", message)
            return LiveServices(backend: FixtureSpacesBackend(rows: []), startError: message, daemonError: daemonError)
        }
    }

    /// The live services are in: what needs them starts now (on the main
    /// thread, nothing here waits).
    static func attach(_ services: LiveServices, to model: AppModel, supervisor: DaemonSupervisor?,
                       refresh: UpdateRefresh?) {
        if let live = services.live {
            if let supervisor {
                if live.cua.mode() == .daemon {
                    supervise(live, supervisor: supervisor, model: model)
                    model.reconnect = { [weak model] in
                        guard let model else { return false }
                        return await reconnect(model, supervisor: supervisor)
                    }
                } else {
                    // Last resort: Spaces run in the app; say what is missing.
                    model.show(error: "Cua Spaces could not start its daemon (\(services.daemonError ?? "it does not answer")). "
                               + "Spaces run inside the app for now; the Keyvault, agents and Cua Volume need the daemon. "
                               + "Reopen Cua Spaces to try again.")
                }
            }
        }
        model.attachLive(services.live)
        if let startError = services.startError { model.show(error: startError) }
        if let refresh { runRefresh(refresh, daemonError: services.daemonError, model: model) }
    }

    /// Watches the daemon `live` talks to, the one this app started or one
    /// it found running (a daemon from an earlier launch of this app is its
    /// own too): when it stops answering it is started again (`cua daemon
    /// start`, with keychain prompts off) and the app connects again.
    static func supervise(_ live: LiveSpacesBackend, supervisor: DaemonSupervisor, model: AppModel) {
        daemonSupervision?.cancel()
        // The daemon this connection was made on. `Cua.auto` refuses another
        // app's daemon that is older than this app's cua, so one it accepted
        // (of the same or a newer version) is used as this app's own.
        let first = Task { [cua = live.cua] in
            try? await withTimeout(seconds: 5) { try await cua.info() }.get()
        }
        let accepted = Task { await first.value?.daemonPid }
        // Another app's daemon this app replaced once, back again: used, and
        // said once, for as long as this connection uses it.
        Task { [weak model] in
            let info = await first.value
            let notice = info?.daemonPid.flatMap { supervisor.yieldsTo(pid: $0) }
                .map { DaemonSupervisor.yieldNotice(executable: $0, version: info?.daemonVersion) }
            await MainActor.run {
                if model?.daemonNotice != notice { model?.daemonNotice = notice }
            }
        }
        daemonSupervision = supervisor.supervise(
            isUp: { [cua = live.cua] in
                // Bounded for real (`withTimeout`): a call that never
                // returns reads as down, not as a supervisor stuck for good.
                let probe = await withTimeout(seconds: 5) { try await cua.info() }
                guard let pid = (try? probe.get())?.daemonPid else { return false }
                return await pid == accepted.value || supervisor.isOwn(pid: pid)
            },
            report: { [weak model] error in
                guard let model else { return }
                if let error { model.show(error: error) } else if model.bannerIsError { model.banner = nil }
            },
            restarted: { [weak model] in
                await model?.reconnectNow(reason: "the cua daemon was started again")
            },
            accepted: { await accepted.value })
    }

    /// A new SDK client: `cua daemon start` (which starts the daemon when
    /// it is gone and does nothing when it runs), then `Cua.auto`, which
    /// reads the daemon's discovery file again (its socket, loopback URL
    /// and token, new after a restart). The backend, the model and the
    /// supervisor move to it.
    static func reconnect(_ model: AppModel, supervisor: DaemonSupervisor) async -> Bool {
        let made: LiveSpacesBackend? = await Task.detached(priority: .userInitiated) {
            var daemonError: String?
            let live = try? makeLiveBackend(supervisor: supervisor, daemonError: &daemonError)
            if let daemonError { NSLog("Cua Spaces: reconnect: %@", daemonError) }
            return live
        }.value
        guard let live = made, let pending = model.backend as? PendingSpacesBackend else { return false }
        pending.replace(live, live: live)
        model.attachLive(live)
        if live.cua.mode() == .daemon { supervise(live, supervisor: supervisor, model: model) }
        return true
    }

    /// After an update: the agents' skills, then a notice saying so.
    static func runRefresh(_ refresh: UpdateRefresh, daemonError: String?, model: AppModel) {
        Task.detached {
            let agents = refresh.updateAgents()
            let notice = appAboutRefreshNotice(report: AppRefreshReport(agentsError: agents, daemonError: daemonError))
            NSLog("Cua Spaces: refreshed after an update (agents: %@, daemon: %@)",
                  agents ?? "ok", daemonError ?? "ok")
            if let notice { await MainActor.run { model.show(info: notice) } }
        }
    }

    /// `CUA_KEYCHAIN_NONINTERACTIVE` (cua-auth's `KEYCHAIN_NONINTERACTIVE_ENV`).
    nonisolated static let keychainNonInteractiveEnv = "CUA_KEYCHAIN_NONINTERACTIVE"

    /// Fixtures' launch (`CUA_SPACES_STARTUP`, for captures and UI tests):
    /// `needs-keychain` (`-locked`), `waiting` (the prompt left open; slow
    /// after 3 s), `denied`, `starting` (never finishes); else ready. Every
    /// one finishes on the fixture backend once its button is pressed.
    static func fixtureStartup(_ state: String?) -> StartupModel {
        let startup = StartupModel()
        let keychain: FixtureKeychain
        switch state ?? "" {
        case "needs-keychain": keychain = FixtureKeychain(quiet: .needsAccess(locked: false))
        case "needs-keychain-locked": keychain = FixtureKeychain(quiet: .needsAccess(locked: true))
        case "waiting":
            keychain = FixtureKeychain(quiet: .needsAccess(locked: false), prompted: nil)
            startup.slowAfter = .seconds(3)
        case "denied": keychain = FixtureKeychain(quiet: .needsAccess(locked: false), prompted: .denied)
        case "starting":
            keychain = FixtureKeychain(quiet: .ready)
            startup.start = { try? await Task.sleep(for: .seconds(3600)) }
            startup.startingSlowAfter = .seconds(3)
        default: return startup
        }
        startup.keychain = keychain
        startup.begin()
        if state == "waiting" { startup.act(.allowAccess) }
        if state == "denied" {
            Task { @MainActor in
                try? await Task.sleep(for: .milliseconds(100))
                startup.act(.allowAccess)
            }
        }
        return startup
    }

    /// Fixtures' login item, never the Mac's: `CUA_SPACES_LOGIN_ITEM` sets
    /// what it reports (`enabled`, `notRegistered`, `requiresApproval`,
    /// `notFound`; default enabled), for captures of each state.
    static func fixtureLoginItem(_ status: String?) -> FixtureLoginItem {
        switch status ?? "" {
        case "notRegistered": return FixtureLoginItem(.notRegistered)
        case "requiresApproval": return FixtureLoginItem(.requiresApproval)
        case "notFound": return FixtureLoginItem(.notFound)
        default: return FixtureLoginItem(.enabled)
        }
    }

    /// Fixtures' relay account: `CUA_SPACES_RELAY_USAGE` sets its allowance
    /// (`reached`, `team`, `none`; default the free plan partway through
    /// the month), for captures of Settings' Relay usage row and the notice.
    static func fixtureDevices(_ usage: String?) -> FixtureDevices {
        let devices = FixtureDevices()
        devices.usage = FixtureDevices.usage(usage)
        return devices
    }

    /// The supervision of this app's daemon ([`DaemonSupervisor`]), for the
    /// app's lifetime.
    static var daemonSupervision: Task<Void, Never>?

    /// The live backend on this app's own daemon: `cua daemon start` first
    /// (bounded; `daemonError` says why it failed), then the SDK, which uses
    /// only this build's daemon. When another build's daemon came up in
    /// between, the SDK refuses it with `DaemonNotRunning`, and one more
    /// start replaces it. Without a daemon the SDK runs Spaces in the app.
    nonisolated static func makeLiveBackend(supervisor: DaemonSupervisor?,
                                            daemonError: inout String?) throws -> LiveSpacesBackend {
        daemonError = startDaemon(supervisor)
        do {
            return try LiveSpacesBackend.make()
        } catch CuaError.DaemonNotRunning(let message) where supervisor != nil {
            if let error = supervisor?.start() { throw CuaError.DaemonNotRunning(message: "\(message) (\(error))") }
            return try LiveSpacesBackend.make()
        }
    }

    /// `cua daemon start`, once more when it failed: a daemon of the build
    /// before an update that was slow to stop is gone by then, and the
    /// second start brings up this build's instead of leaving the app to
    /// run Spaces in-process.
    nonisolated static func startDaemon(_ supervisor: DaemonSupervisor?) -> String? {
        guard let supervisor else { return nil }
        guard let first = supervisor.start() else { return nil }
        NSLog("Cua Spaces: starting the cua daemon failed, trying again: %@", first)
        return supervisor.start()
    }

    /// The `cua` this app bundles, when it has one.
    static var bundledCua: String? { bundledCuaPath }

    nonisolated static var bundledCuaPath: String? {
        let executable = Bundle.main.executablePath ?? CommandLine.arguments[0]
        let cua = URL(fileURLWithPath: executable).deletingLastPathComponent().appendingPathComponent("cua").path
        return FileManager.default.isExecutableFile(atPath: cua) ? cua : nil
    }

    /// Opens this app's own menu bar item (captures): clicks its status
    /// bar button.
    static func openMenuBarMenu() {
        for window in NSApp.windows where String(describing: type(of: window)).contains("StatusBar") {
            if let button = find(NSStatusBarButton.self, in: window.contentView) {
                button.performClick(nil)
                return
            }
        }
    }

    /// The Settings page a `settings-*` start view names.
    static func settingsRoute(_ view: String) -> MainUIRoute {
        switch view {
        case "settings-devices": return .path("/machines")
        case "settings-about": return .path("/settings/about")
        case "settings-experiments": return .path("/settings/experiments")
        default: return .settings
        }
    }

    private static func find<T: NSView>(_ type: T.Type, in view: NSView?) -> T? {
        guard let view else { return nil }
        if let hit = view as? T { return hit }
        for sub in view.subviews { if let hit = find(type, in: sub) { return hit } }
        return nil
    }

    /// `CUA_SPACES_START_VIEW` opens the web UI window at a page: `new-space`
    /// (also `new-space-picker`, `new-space-resources`), `keyvault`,
    /// `keyvault-waiting`, `approval` (Access), `onboarding`, `drive`, `this-machine`
    /// (also `host-setup`, `host-configured`: Machines), `settings`,
    /// `settings-devices`, `settings-about`, `settings-experiments`,
    /// `settings-storage`, `device-approval`, `device-enroll`,
    /// `device-enroll-code` (Settings, Devices), `space`; or the notch states `notch-open`
    /// (`notch`; 1.5 s after launch), `notch-hover`, `notch-permission`,
    /// `notch-drag-target` (`notch-prompt`) and `notch-drop`; `notch-menu` (the notch
    /// open and the menu bar menu) and `menu` (the menu alone; `menu-popup`
    /// shows its items as a context menu over the main window);
    /// `CUA_SPACES_CREATE` (`<image>[,<name>]`) creates a Space on this Mac
    /// through the New Space wizard's plan and the real create path, as if
    /// Create were pressed (end-to-end runs and captures), and
    /// `CUA_SPACES_CANCEL_AFTER` (seconds) presses its Cancel then;
    /// `CUA_SPACES_SELECT` selects a Space; `CUA_SPACES_NOTCH_HIGHLIGHT`
    /// (`tile`, `list`, `settings`, `search` or `tab`, optionally
    /// `:pressed`) forces a notch control's hover or pressed look. Static
    /// start states only.
    static func applyStartView(_ model: AppModel, notch: NotchController) {
        let env = DevHooks.environment
        let web = { (route: MainUIRoute) in WebUIWindowController.show(model: model, at: route) }
        Task {
            await model.refresh()
            await model.keyvault.refresh()
            if let id = env["CUA_SPACES_SELECT"] { model.select(id) }
            if let spec = env["CUA_SPACES_CREATE"], !spec.isEmpty {
                let parts = spec.split(separator: ",", maxSplits: 1).map(String.init)
                await model.openNativeNewSpace()
                let w = model.wizard
                w.send(.setPlacement(placement: .local))
                w.send(.setImageText(text: parts[0]))
                w.send(.pickImageSuggestion)
                if parts.count > 1 { w.send(.setName(name: parts[1])) }
                model.create(w.view.plan)
                if let after = env["CUA_SPACES_CANCEL_AFTER"].flatMap(Double.init),
                   let id = model.creates.pending.last?.id {
                    Task {
                        try? await Task.sleep(for: .seconds(after))
                        model.cancelCreate(id)
                    }
                }
            }
            switch env["CUA_SPACES_START_VIEW"] ?? "" {
            case "webui":
                WebUIWindowController.show(model: model)
                WebUIWindowController.startVideoHarness(model: model)
            case "new-space", "new-space-picker", "new-space-resources":
                // The web wizard (`CUA_SPACES_WIZARD_ON=yours`: "Run on" there).
                WebUIWindowController.showNewSpace(model: model, on: env["CUA_SPACES_WIZARD_ON"])
            case "keyvault", "keyvault-waiting":
                web(.keyvault)
            case "approval":
                web(.access)
            case "onboarding":
                // The first run again, on its page.
                model.onboarding.restart()
                web(.onboarding)
            case "drive":
                // The Volume page shows with Cua Volume on (this run only).
                model.settings.experiments.cuaVolume = true
                web(.drive)
            case "settings", "settings-devices", "settings-storage", "settings-about", "settings-experiments":
                // Storage shows with the Cua Volume experiment on (this run
                // only; the settings file is not written).
                if env["CUA_SPACES_START_VIEW"] == "settings-storage" { model.settings.experiments.cuaVolume = true }
                MainUIRouter(model: model).openSettings(Self.settingsRoute(env["CUA_SPACES_START_VIEW"] ?? "settings"))
            case "device-approval", "device-enroll", "device-enroll-code":
                // The web Devices page has the enroll and approval sheets.
                await model.devices.refresh()
                web(.path("/machines"))
            case "space":
                model.select("local:aurora")
                web(.space("local:aurora"))
            case "this-machine", "host-setup", "host-configured":
                model.select("this-mac")
                web(.machines)
            case "notch", "notch-open":
                // Closed first, then open once after 1.5 s, so a capture
                // sees the spring.
                try? await Task.sleep(for: .seconds(1.5))
                model.notch.send(.click)
            case "notch-menu":
                // The notch open, then the menu bar item's menu (both ours).
                try? await Task.sleep(for: .seconds(1.5))
                model.notch.send(.click)
                try? await Task.sleep(for: .seconds(1.5))
                openMenuBarMenu()
            case "menu":
                try? await Task.sleep(for: .seconds(1.5))
                openMenuBarMenu()
            case "menu-popup":
                // The menu bar item's items as a context menu over the main
                // window (captures on a crowded menu bar, where the item
                // can be hidden), once the sync status has been read.
                try? await Task.sleep(for: .seconds(4))
                await model.persistent.refreshSync()
                NSApp.activate()
                guard let view = NSApp.windows.first(where: { $0.isVisible && $0.contentView != nil
                    && $0.frame.width > 400 })?.contentView else { break }
                let menu = NSMenu()
                for item in model.menuBar {
                    if item.id == .separator { menu.addItem(.separator()); continue }
                    let m = NSMenuItem(title: item.label, action: nil, keyEquivalent: "")
                    m.isEnabled = item.enabled
                    menu.addItem(m)
                }
                menu.autoenablesItems = false
                menu.popUp(positioning: nil, at: NSPoint(x: 300, y: view.isFlipped ? 120 : view.bounds.height - 120), in: view)
            case "notch-activity-hotspot":
                model.notch.setActivity(hotspot: true, transfer: nil)
            case "notch-activity-transfer":
                model.notch.setActivity(hotspot: false, transfer: AppNotchTransfer(sent: 600, total: 1000))
            case "notch-activity-provisioning":
                if var s = model.notch.spaces.first(where: { $0.id != "this-mac" }) {
                    s.id = "direct:starter"
                    s.name = "Starter"
                    s.status = .provisioning
                    s.startedAt = Int64(Date().timeIntervalSince1970 * 1000) - 40_000
                    model.notch.spaces.append(s)
                }
            case "notch-hover":
                model.notch.send(.hoverEnter)
                model.notch.send(.dragPermission(granted: true))
            case "notch-permission":
                model.notch.send(.dragPermission(granted: false))
                model.notch.send(.click)
            case "notch-prompt", "notch-drag-target":
                model.notch.send(.drag(event: .start(windowId: nil, appName: env["CUA_SPACES_DRAG_APP"])))
            case "notch-drop":
                // The drop panel with a tile under the dragged window.
                model.notch.send(.drag(event: .start(windowId: nil, appName: env["CUA_SPACES_DRAG_APP"])))
                model.notch.send(.drag(event: .enterNotch))
                if let first = model.notch.view.tiles.first(where: \.dropTarget) {
                    model.notch.send(.drag(event: .over(spaceId: first.id)))
                }
            default:
                break
            }
            // A forced hover or pressed look on one notch control (static;
            // no input is replayed).
            if let raw = env["CUA_SPACES_NOTCH_HIGHLIGHT"] {
                let first = model.notch.view.tiles.first(where: \.dropTarget)?.id
                model.notch.highlight = NotchHighlight.parse(raw, firstTile: first)
            }
        }
    }
}