Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces): dogfooding polish (welcome copy first) (#5893)
cua-agents[bot]928fe850d48b
diff --git a/apps/cua-spaces-desktop/src/bridge/cli.ts b/apps/cua-spaces-desktop/src/bridge/cli.tsnew file mode 100644index 0000000000..5c668718f9--- /dev/null+++ b/apps/cua-spaces-desktop/src/bridge/cli.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The bundled CLI on PATH (`cli.plan`, `cli.install`; the web bridge's+// ops/cli.ts): the first run's "Install the Cua CLI" screen and Settings'+// Command line row, as the SwiftUI host answers them+// (`WebUIBridge+Cli.swift`). Both run the app core's installer+// (`AppCliInstaller`): the plan writes+// nothing; Install writes the channel's CLI (`cua`, or `cua-local`) and adds+// its folder to PATH only when asked. `settings.get`'s `cli` names it from+// the last plan read.+import path from "node:path";++import type { AppCliInstallPlan } from "../native/generated/index";+import type { AppModel } from "../model/app-model";+import { recordCliInstall } from "../model/cli-record";+import { bool } from "./args";+import type { BridgeContext } from "./context";+import { Failure, type Handlers } from "./host";+import { encode } from "./value";++/** The installer for this app's bundled `cua` (it finds the CLI next to the "executable" it is given). */+export function cliInstaller({ model, supervisor }: Pick<BridgeContext, "model" | "supervisor">) {+ if (!supervisor) return null;+ return model.native.AppCliInstaller.forExecutable(path.join(path.dirname(supervisor.cua), "cua-spaces"));+}++/** `settings.get`'s `cli`: the plan's file name and whether it is on this computer; null until read. */+export function cliSetting(model: AppModel): { name: string; installed: boolean } | null {+ const plan = model.cliPlan;+ if (!plan) return null;+ const file = path.basename(plan.target.replaceAll("\\", "/"));+ return { name: file.replace(/\.exe$/i, ""), installed: plan.upToDate || Boolean(plan.found) };+}++/** Keeps `plan` as the last read and tells the page when `settings.get`'s `cli` changed. */+function notePlan(ctx: Pick<BridgeContext, "model" | "events">, plan: AppCliInstallPlan) {+ const before = JSON.stringify(cliSetting(ctx.model));+ ctx.model.cliPlan = plan;+ if (JSON.stringify(cliSetting(ctx.model)) !== before) ctx.events.emit("settings.changed");+ return encode(plan);+}++/** Reads the plan once (at launch), so the pages know whether the CLI is here. */+export async function readCliPlan(ctx: BridgeContext): Promise<void> {+ const installer = cliInstaller(ctx);+ if (installer) notePlan(ctx, await installer.plan());+}++export function cliMethods(ctx: BridgeContext): Handlers {+ const note = (plan: AppCliInstallPlan) => notePlan(ctx, plan);+ return {+ "cli.plan": async () => {+ const installer = cliInstaller(ctx);+ return installer ? note(await installer.plan()) : null;+ },+ "cli.install": async (args) => {+ const modifyPath = bool(args, "modifyPath");+ const installer = cliInstaller(ctx);+ if (!installer) throw Failure.unsupported("This build has no bundled cua to install.");+ const planned = await installer.plan();+ const installed = await installer.install({ modifyPath });+ // Windows: the uninstaller removes what this install added (the PATH entry only when it was added now).+ await recordCliInstall(installed.target, modifyPath && !planned.onPath, ctx.platform).catch((error) =>+ console.warn(`[cua-spaces] could not record the cua command for the uninstaller: ${String(error)}`),+ );+ return note(installed);+ },+ };+}diff --git a/apps/cua-spaces-desktop/src/bridge/host-start.ts b/apps/cua-spaces-desktop/src/bridge/host-start.tsindex 948e9c9513..b28fac9be0 100644--- a/apps/cua-spaces-desktop/src/bridge/host-start.ts+++ b/apps/cua-spaces-desktop/src/bridge/host-start.ts@@ -10,6 +10,7 @@// whether the keychain prompt is on screen. (The refresh after an update is// `refreshAfterUpdate`, started in main.ts.)// Also the menu bar item's and the tray's menu (`menuItems`).+import { readCliPlan } from "./cli";import type { AppMenuItem, AppSpace } from "../native/generated/index";import { LocalNetworkPermission } from "../model/local-network";import { SecurityAgentWatcher } from "../model/security-agent";@@ -92,6 +93,8 @@ export function startHost(ctx: BridgeContext, o: { onboarded: () => boolean }):whenReady(() => {if (stopped) return;stops.push(parts.notifications.startPolling());+ // Whether the bundled CLI is on PATH, for the pages' terminal hints (`settings.get`'s `cli`).+ void readCliPlan(ctx).catch(() => {});void (async () => {// What the rule reads: whether this machine provides Spaces.await model.host.refresh();diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.tsindex 7c7040a420..b590c41a12 100644--- a/apps/cua-spaces-desktop/src/bridge/index.ts+++ b/apps/cua-spaces-desktop/src/bridge/index.ts@@ -29,6 +29,7 @@ import { nudgesMethods } from "./nudges";import { onboardingMethods } from "./onboarding";import { presenceMethods } from "./presence";import { linksMethods } from "./links";+import { cliMethods } from "./cli";import { relayUsageMethods } from "./relay-usage";import { resourcesMethods } from "./resources";import { sessionMethods, sessionState } from "./session";@@ -76,6 +77,7 @@ export const AREAS = [resourcesMethods,checklistMethods,linksMethods,+ cliMethods,presenceMethods,];diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 8e10a103e2..114b87dea0 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -50,6 +50,7 @@ export const METHODS = ["machines.rename", "machines.remove", "machines.checkHealth","checklist.get", "checklist.send","links.list", "links.create", "links.stop",+ "cli.plan", "cli.install",] as const;/** A live desktop's media ticket for the page's WebCodecs player,diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.tsindex e070c3f81a..e87852644f 100644--- a/apps/cua-spaces-desktop/src/bridge/settings.ts+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts@@ -18,6 +18,7 @@ import type { BridgeContext } from "./context";import { Failure, type Handlers } from "./host";import { hostParts, type HostParts } from "./host-parts";import { encode } from "./value";+import { cliSetting } from "./cli";function telemetryInput(model: AppModel): AppTelemetryInput | undefined {try {@@ -91,6 +92,8 @@ export function settingsState(model: AppModel, parts: HostParts) {// The account app (CUA_ENV, CUA_ACCOUNT_APP_URL): the page's core has no// environment, so Upgrade's billing fallback names this one.accountUrl: model.native.appAccountAppUrl(),+ // The CLI this app installs and whether it is here (`cli.ts`).+ cli: cliSetting(model),};}diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.tsindex dc65975d98..3c716321c9 100644--- a/apps/cua-spaces-desktop/src/model/app-model.ts+++ b/apps/cua-spaces-desktop/src/model/app-model.ts@@ -10,6 +10,7 @@import { randomUUID } from "node:crypto";import type { Native } from "../native/load";import type {+ AppCliInstallPlan,AppCreateAction,AppCreatesState,AppCreateSpaceArgs,@@ -130,6 +131,8 @@ export class AppModel {roster: AppRosterState;/** The selected Space (the sidebar's selection). */selectedSpaceId: string | null = null;+ /** The bundled CLI's install plan as last read (`cli.plan`, `settings.get`'s `cli`). */+ cliPlan: AppCliInstallPlan | null = null;loaded = false;/** The last list read failed: the page says so above every page, and the* rows already listed stay (the SwiftUI app's `rosterError`). Never thediff --git a/apps/cua-spaces-desktop/src/model/cli-record.ts b/apps/cua-spaces-desktop/src/model/cli-record.tsnew file mode 100644index 0000000000..4ce74a85f3--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/cli-record.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { execFile } from "node:child_process";+import * as path from "node:path";++/**+ * Windows: the key the uninstaller reads (packaging/installer.nsh) to remove+ * the `cua` this app put on PATH with the app, and nothing it did not: the+ * file it copied, and its folder's PATH entry when this app added it.+ * Elsewhere the CLI stays, like the user's ~/.cua: the .deb's is a link into+ * the app that goes with it, as the SwiftUI app's into its bundle.+ */+export const WINDOWS_APP_KEY = "HKCU\\Software\\ai.cua.spaces.desktop";++/** The `reg add` calls that record an installed CLI. */+export function cliRecordArgs(target: string, addedToPath: boolean): string[][] {+ const value = (name: string, data: string) => ["add", WINDOWS_APP_KEY, "/v", name, "/t", "REG_SZ", "/d", data, "/f"];+ return [value("CliInstalled", target), ...(addedToPath ? [value("CliPathAdded", path.win32.dirname(target))] : [])];+}++const reg = (args: string[]) =>+ new Promise<void>((resolve, reject) => execFile("reg", args, { windowsHide: true }, (error) => (error ? reject(error) : resolve())));++/**+ * Windows: records a CLI the app put on PATH (after "Install" in the first+ * run's terminal step or in Settings), so the uninstaller removes it. Nothing+ * is written elsewhere, and nothing is installed unless someone asks.+ */+export async function recordCliInstall(target: string, addedToPath: boolean, platform: NodeJS.Platform = process.platform, record = reg): Promise<void> {+ if (platform !== "win32") return;+ for (const args of cliRecordArgs(target, addedToPath)) await record(args);+}diff --git a/apps/cua-spaces-desktop/src/model/environment.ts b/apps/cua-spaces-desktop/src/model/environment.tsindex 4ebdd6c695..721d04633d 100644--- a/apps/cua-spaces-desktop/src/model/environment.ts+++ b/apps/cua-spaces-desktop/src/model/environment.ts@@ -7,7 +7,6 @@// the window's critical path. Nothing here reads the keychain or waits on// the daemon before the window shows: the page shows the launch// (`startup.get`) on stand-ins that wait for the services.-import { execFile } from "node:child_process";import { existsSync, readFileSync } from "node:fs";import * as os from "node:os";import * as path from "node:path";@@ -154,8 +153,7 @@ export function makeModel(o: EnvironmentOptions): Environment {// Signed in now (access given after the start): read it again.if (gate.current) model.attachLive();};- // First launch: the bundled `cua` on PATH, silently (the SwiftUI app's first run does the same).- if (cua && firstRunDue) startup.onReady.push(() => void installCliSilently(native, cua));+ // The bundled `cua` goes on PATH only when someone chooses it (the first run's terminal step, or Settings): not at launch.startup.begin();return { model, supervisor, settingsPath, onboardingPath, cua };}@@ -276,38 +274,7 @@ export async function reconnect(model: AppModel, supervisor: DaemonSupervisor, rreturn true;}-/**- * Windows: the key the uninstaller reads (packaging/installer.nsh) to remove- * the `cua` this app put on PATH with the app, and nothing it did not: the- * file it copied, and its folder's PATH entry when this app added it.- * Elsewhere the CLI stays, like the user's ~/.cua: the .deb's is a link into- * the app that goes with it, as the SwiftUI app's into its bundle.- */-export const WINDOWS_APP_KEY = "HKCU\\Software\\ai.cua.spaces.desktop";--/** The `reg add` calls that record an installed CLI. */-export function cliRecordArgs(target: string, addedToPath: boolean): string[][] {- const value = (name: string, data: string) => ["add", WINDOWS_APP_KEY, "/v", name, "/t", "REG_SZ", "/d", data, "/f"];- return [value("CliInstalled", target), ...(addedToPath ? [value("CliPathAdded", path.win32.dirname(target))] : [])];-}--const reg = (args: string[]) =>- new Promise<void>((resolve, reject) => execFile("reg", args, { windowsHide: true }, (error) => (error ? reject(error) : resolve())));--/** Puts the bundled `cua` on PATH: a current install, or a build without the CLI, writes nothing. */-export async function installCliSilently(native: Native, cua: string, platform: NodeJS.Platform = process.platform, record = reg): Promise<void> {- try {- // The installer finds the CLI next to the "executable" it is given.- const installer = native.AppCliInstaller.forExecutable(path.join(path.dirname(cua), "cua-spaces"));- const plan = await installer.plan();- if (plan.upToDate || !plan.source) return;- const installed = await installer.install({ modifyPath: !plan.onPath });- console.log(`[cua-spaces] installed the cua command at ${installed.target}`);- if (platform === "win32") for (const args of cliRecordArgs(installed.target, !plan.onPath)) await record(args);- } catch (error) {- console.warn(`[cua-spaces] could not install the cua command: ${words(error)}`);- }-}+export { WINDOWS_APP_KEY, cliRecordArgs, recordCliInstall } from "./cli-record";/** This computer as the Machines page's Details names it: its name, the* app's version and its system ("macOS 26.5.2"), read once. */diff --git a/apps/cua-spaces-desktop/test/uninstall.test.ts b/apps/cua-spaces-desktop/test/uninstall.test.tsindex ebc9011100..9419a08d62 100644--- a/apps/cua-spaces-desktop/test/uninstall.test.ts+++ b/apps/cua-spaces-desktop/test/uninstall.test.ts@@ -14,7 +14,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";vi.mock("electron", () => ({ app: { isPackaged: true }, shell: {} }));const { appImageCua, appImageDaemonRoot } = await import("../src/model/appimage-cua");-const { WINDOWS_APP_KEY, cliRecordArgs, installCliSilently } = await import("../src/model/environment");+const { WINDOWS_APP_KEY, cliRecordArgs, recordCliInstall } = await import("../src/model/environment");const { WINDOWS_RUN_NAME } = await import("../src/login-item");const require = createRequire(import.meta.url);@@ -143,16 +143,10 @@ describe("the Windows installer and uninstaller", () => {});describe("the CLI the app puts on PATH", () => {- const plan = { upToDate: false, source: "C:\\app\\resources\\native\\cua.exe", onPath: false };- const fakeNative = (installed: { target: string }) =>- ({- AppCliInstaller: { forExecutable: () => ({ plan: async () => plan, install: async () => installed }) },- }) as never;-it("is recorded on Windows, with the PATH entry only when the app added it", async () => {const target = "C:\\Users\\me\\AppData\\Local\\Programs\\cua\\bin\\cua.exe";const calls: string[][] = [];- await installCliSilently(fakeNative({ target }), "C:\\app\\resources\\native\\cua.exe", "win32", async (args) => void calls.push(args));+ await recordCliInstall(target, true, "win32", async (args) => void calls.push(args));expect(calls).toEqual([["add", WINDOWS_APP_KEY, "/v", "CliInstalled", "/t", "REG_SZ", "/d", target, "/f"],["add", WINDOWS_APP_KEY, "/v", "CliPathAdded", "/t", "REG_SZ", "/d", "C:\\Users\\me\\AppData\\Local\\Programs\\cua\\bin", "/f"],@@ -162,7 +156,7 @@ describe("the CLI the app puts on PATH", () => {it("is not recorded elsewhere (the .deb's is a link into the app)", async () => {const calls: string[][] = [];- await installCliSilently(fakeNative({ target: "/home/me/.local/bin/cua" }), "/opt/Cua Spaces/resources/native/cua", "linux", async (args) => void calls.push(args));+ await recordCliInstall("/home/me/.local/bin/cua", true, "linux", async (args) => void calls.push(args));expect(calls).toEqual([]);});});diff --git a/apps/cua-spaces-macos/Package.resolved b/apps/cua-spaces-macos/Package.resolvedindex 7f2df47e16..479e7d7b3a 100644--- a/apps/cua-spaces-macos/Package.resolved+++ b/apps/cua-spaces-macos/Package.resolved@@ -1,6 +1,15 @@{- "originHash" : "c5511707dd25b9c6c310b371466e6064a8fa5397690a090025d44b3817c90ec2",+ "originHash" : "b52af08eb5059379c96073b62be34e36c80d7a32917ac65823e7870e63a761da","pins" : [+ {+ "identity" : "permissionflow",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/jaywcjlove/PermissionFlow",+ "state" : {+ "revision" : "65434c9ae04dba97cf52c1dffbe3e4e62b547c82",+ "version" : "2.11.4"+ }+ },{"identity" : "sparkle","kind" : "remoteSourceControl",diff --git a/apps/cua-spaces-macos/Package.swift b/apps/cua-spaces-macos/Package.swiftindex 897e3d796e..d01d420117 100644--- a/apps/cua-spaces-macos/Package.swift+++ b/apps/cua-spaces-macos/Package.swift@@ -23,6 +23,12 @@ import PackageDescription// framework that scripts/build-app.sh embeds in Contents/Frameworks and// scripts/build-release.sh signs from the inside out.//+// PermissionFlow (MIT, pinned to a release) is the guide to Screen+// Recording and Accessibility in System Settings: it opens the pane and+// floats this app beside it to drag into the list (PermissionGuide.swift).+// Its strings ship as a SwiftPM resource bundle, which build-app.sh copies+// into Contents/Resources like ours.+//// UI tests (XCUITest) live in UITests/ and build through project.yml// (XcodeGen) on a macOS runner with Xcode.let package = Package(@@ -39,6 +45,7 @@ let package = Package(.package(name: "CuaSpacesApp", path: "../../libs/spaces-app-swift"),.package(name: "CuaSpacesNotch", path: "../../libs/spaces-notch-swift"),.package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.10.0"),+ .package(url: "https://github.com/jaywcjlove/PermissionFlow", exact: "2.11.4"),],targets: [.target(@@ -51,6 +58,7 @@ let package = Package(.product(name: "CuaSpacesTeleport", package: "CuaSpacesApp"),.product(name: "CuaSpacesNotchUI", package: "CuaSpacesNotch"),.product(name: "Sparkle", package: "Sparkle"),+ .product(name: "PermissionFlow", package: "PermissionFlow"),],path: "Sources/CuaSpacesMacKit",resources: [.process("Resources")],@@ -68,7 +76,8 @@ let package = Package(.product(name: "CuaSpacesFFI", package: "CuaSpacesApp"),.product(name: "CuaSpacesStreaming", package: "CuaSpacesApp"),.product(name: "CuaSpacesNotchUI", package: "CuaSpacesNotch"),- .product(name: "CuaSpacesNotchHelper", package: "CuaSpacesNotch")],+ .product(name: "CuaSpacesNotchHelper", package: "CuaSpacesNotch"),+ .product(name: "PermissionFlow", package: "PermissionFlow")],path: "Tests/CuaSpacesMacTests",resources: [.copy("Snapshots")],swiftSettings: [.swiftLanguageMode(.v5)]diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swiftindex 2ffca8f1ba..ae385c4f18 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift@@ -171,11 +171,19 @@ enum ServiceLauncher {if serviceChild > 0 { kill(serviceChild, s) }}}- // Sharing the desktop needs Screen Recording and Accessibility. Ask- // now, as "Cua Spaces" (macOS shows each prompt once and lists the- // app in both panes); a background capture alone is refused without- // a prompt.- if !spec.args.contains("--no-desktop") {+ // Sharing the desktop needs Screen Recording and Accessibility. Once+ // the app has run with its window on this Mac, the app asks for+ // them itself, in its own words, with a guide to System Settings+ // (its first run's "Share this Mac's screen", and Settings):+ // macOS's bare prompts here would pop over that screen first.+ // Hosting set up without the app ever showing (the CLI, a headless+ // Mac) still asks here, as "Cua Spaces" (macOS shows each prompt+ // once and lists the app in both panes); a background capture alone+ // is refused without a prompt.+ let appAsks = PermissionGuide.appAsks(specPath: specFile)+ NSLog("cua-spaces service: Screen Recording and Accessibility are asked %@",+ appAsks ? "by the app (its permissions screen)" : "here (macOS's prompts)")+ if !spec.args.contains("--no-desktop") && !appAsks {if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }let prompt = "AXTrustedCheckOptionPrompt" // kAXTrustedCheckOptionPrompt_ = AXIsProcessTrustedWithOptions([prompt: true] as CFDictionary)diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swiftindex 9205c1df8e..fb3130c2a6 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift@@ -54,4 +54,10 @@ TargetEnvironment.pin()cuaSpacesRegister()// `CUA_SPACES_OFFSCREEN=1` (debug): an accessory app, for captures nobody sees.OffscreenRun.prepare()+// The app runs with its window here: it asks for Screen Recording and+// Accessibility itself (its first run and Settings, PermissionGuide), so the+// host service no longer shows macOS's own prompts (ServiceLauncher).+if let spec = HelperService.specPath(info: Bundle.main.infoDictionary, home: NSHomeDirectory()) {+ PermissionGuide.noteAppAsks(specPath: spec)+}CuaSpacesMacApp.main()diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swiftnew file mode 100644index 0000000000..b236cf3d8b--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift@@ -0,0 +1,68 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import AppKit+import PermissionFlow++/// The app's own guide to a privacy pane of System Settings, so nobody+/// meets macOS's bare "allow?" prompt first. PermissionFlow (MIT,+/// github.com/jaywcjlove/PermissionFlow, pinned in Package.swift) opens the+/// pane and floats a small panel beside System Settings with this app to+/// drag into the list. The app's name and icon are this bundle's, so Cua+/// Spaces Local shows as itself.+///+/// The first run's "Share this Mac's screen" and Settings' "Permissions"+/// reach it through `host.openSettings`: Screen Recording and Accessibility+/// are guided, every other pane just opens.+@MainActor+public enum PermissionGuide {+ /// A file beside the host service's spec (`<CuaHome>/helper/`), written+ /// once the app has run with its window on this Mac: from then on the+ /// app asks for both permissions itself, and the host service+ /// (ServiceLauncher) never shows macOS's own prompts. A Mac hosting from+ /// the CLI only, where the app never showed, keeps them. A file, not+ /// the app's defaults: the service reads it at launch without depending+ /// on how launchd's process resolves the preferences domain.+ public nonisolated static func markerPath(specPath: String) -> String {+ ((specPath as NSString).deletingLastPathComponent as NSString)+ .appendingPathComponent("permissions-asked-in-app")+ }++ public nonisolated static func appAsks(specPath: String) -> Bool {+ FileManager.default.fileExists(atPath: markerPath(specPath: specPath))+ }++ public nonisolated static func noteAppAsks(specPath: String) {+ let marker = markerPath(specPath: specPath)+ guard !FileManager.default.fileExists(atPath: marker) else { return }+ try? FileManager.default.createDirectory(+ atPath: (marker as NSString).deletingLastPathComponent, withIntermediateDirectories: true)+ FileManager.default.createFile(atPath: marker, contents: Data("1\n".utf8))+ }++ /// The pane a System Settings URL names, when the guide knows it.+ nonisolated static func pane(for url: String) -> PermissionFlowPane? {+ if url.contains("Privacy_ScreenCapture") { return .screenRecording }+ if url.contains("Privacy_Accessibility") { return .accessibility }+ return nil+ }++ private static var controller: PermissionFlowController?++ /// Guides `url`'s pane: false when the guide doesn't know it (open it+ /// plainly then).+ @discardableResult+ public static func guide(_ url: String) -> Bool {+ guard let pane = pane(for: url) else { return false }+ let app = Bundle.main.bundleURL+ let flow = controller ?? PermissionFlowController(configuration: .init(requiredAppURLs: [app]))+ controller = flow+ // Where the click came from, for the panel's flight to System Settings.+ let from = NSApp.keyWindow.map { w -> CGRect in+ let mouse = NSEvent.mouseLocation+ return w.frame.contains(mouse) ? CGRect(x: mouse.x - 20, y: mouse.y - 10, width: 40, height: 20) : w.frame+ }+ flow.authorize(pane: pane, suggestedAppURLs: [app], sourceFrameInScreen: from)+ return true+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Cli.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Cli.swiftnew file mode 100644index 0000000000..9e0d568ec9--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Cli.swift@@ -0,0 +1,58 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import CuaSpacesFFI+import Foundation++/// The app's bundled `cua` on PATH: the first run's "Install the Cua CLI"+/// screen and Settings' Command line row (`ops/cli.ts` in the web bridge).+/// Both run the app core's installer (`AppCliInstaller`): `cli.plan` reads+/// what installing would do and writes nothing; `cli.install` writes only+/// after the person pressed Install. What it installs is this build's+/// channel's (`cua`, or `cua-local` in Cua Spaces Local: the app sets+/// `CUA_CHANNEL` before anything starts), and it adds the bin folder to PATH+/// only when asked (when it is not on PATH).+extension WebUIBridge {+ func routeCli(_ method: String, _ args: [String: Any]) async throws -> Any? {+ switch method {+ case "cli.plan":+ let plan = await makeCliInstaller().plan()+ noteCliPlan(plan)+ return BridgeValue.encode(plan)+ case "cli.install":+ guard let modifyPath = args["modifyPath"] as? Bool else { throw Failure.badArgs("modifyPath: boolean") }+ let plan = try await makeCliInstaller().install(request: AppCliInstallRequest(modifyPath: modifyPath))+ noteCliPlan(plan)+ return BridgeValue.encode(plan)+ default:+ return nil+ }+ }++ /// `settings.get`'s `cli`: the CLI's name (the plan's file) and whether+ /// it is on this computer; null until the plan was read once (read now,+ /// and `settings.changed` follows).+ func cliSetting() -> Any {+ guard let plan = cliPlan else {+ if !cliPlanRequested {+ cliPlanRequested = true+ Task { @MainActor [weak self] in+ guard let self else { return }+ self.noteCliPlan(await self.makeCliInstaller().plan())+ }+ }+ return NSNull()+ }+ let file = URL(fileURLWithPath: plan.target).lastPathComponent+ return [+ "name": file.hasSuffix(".exe") ? String(file.dropLast(4)) : file,+ "installed": plan.upToDate || plan.found != nil,+ ] as [String: Any]+ }++ func noteCliPlan(_ plan: AppCliInstallPlan) {+ let changed = cliPlan != plan+ cliPlan = plan+ if changed { host?.emit("settings.changed") }+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 08a69c5258..a5d9ceb54a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -295,7 +295,9 @@ extension WebUIBridge {guard url.hasPrefix("x-apple.systempreferences:"), let u = URL(string: url) else {throw Failure.badArgs("Only System Settings panes open here")}- NSWorkspace.shared.open(u)+ // Screen Recording and Accessibility: the app's guide to the+ // pane (PermissionFlow), never macOS's bare prompt.+ if !PermissionGuide.guide(url) { NSWorkspace.shared.open(u) }return NSNull()default:diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 1f5f1936ca..7d40beb5ee 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -123,10 +123,19 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"checklist.get", "checklist.send",// Links to things you run (WebUIBridge+Pages.swift)."links.list", "links.create", "links.stop",+ // The bundled CLI on PATH (WebUIBridge+Cli.swift).+ "cli.plan", "cli.install",]let model: AppModelvar actions: WebUIActions?+ /// The app core's CLI installer for this app (tests give their own paths).+ var makeCliInstaller: () -> AppCliInstaller = {+ AppCliInstaller.forExecutable(executable: Bundle.main.executablePath ?? "")+ }+ /// The CLI's install plan as last read (`settings.get`'s `cli`).+ var cliPlan: AppCliInstallPlan?+ var cliPlanRequested = falseweak var host: WebUIWindowController?/// What each `followChanges` event last saw.private var signatures: [String: String] = [:]@@ -402,6 +411,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {if let result = try await routeFiles(method, args) { return result }if let result = try await routePage(method, args) { return result }if let result = try routeNudges(method, args) { return result }+ if let result = try await routeCli(method, args) { return result }throw Failure.unimplemented(method)}}@@ -516,6 +526,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {// The account app (CUA_ENV, CUA_ACCOUNT_APP_URL): the page's core// has no environment, so Upgrade's billing fallback names this one."accountUrl": appAccountAppUrl(),+ // The CLI this app installs and whether it is here (WebUIBridge+Cli.swift).+ "cli": cliSetting(),]}@@ -826,6 +838,10 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {guard let state = model.host.state, var out = BridgeValue.encode(state) as? [String: Any] else { return NSNull() }out["machineId"] = model.host.machineId ?? NSNull()out["progress"] = model.host.progress ?? NSNull()+ // The name System Settings lists this app under ("Cua Spaces Local"),+ // for the permissions screen's words.+ out["appName"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String+ ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? NSNull()// Before setup the host has no name yet: the web UI's setup form// starts with what the system calls this Mac, as the native one does.if !state.configured, (out["name"] as? String)?.isEmpty ?? true, let name = model.host.computerName() {diff --git a/apps/cua-spaces-macos/THIRD_PARTY_NOTICES.md b/apps/cua-spaces-macos/THIRD_PARTY_NOTICES.mdindex 454a529ae3..fac1389a19 100644--- a/apps/cua-spaces-macos/THIRD_PARTY_NOTICES.md+++ b/apps/cua-spaces-macos/THIRD_PARTY_NOTICES.md@@ -30,6 +30,15 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.+## PermissionFlow++The app links [PermissionFlow](https://github.com/jaywcjlove/PermissionFlow)+2.11.4 (pinned in `Package.resolved`), unmodified, with its+`PermissionFlow_PermissionFlow.bundle` strings in `Contents/Resources`: the+guide to Screen Recording and Accessibility in System Settings+(`Sources/CuaSpacesMacKit/Models/PermissionGuide.swift`). Copyright (c) 2026+小弟调调 (jaywcjlove), under the MIT License above.+## SparkleThe app bundles [Sparkle](https://github.com/sparkle-project/Sparkle) 2.10.0,diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex e0f92acfe2..6db2a3acca 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -44,6 +44,11 @@ struct BridgeContractTests {telemetry: FixtureTelemetry())let bridge = WebUIBridge(model: model, allowedOrigins: [])bridge.actions = WebUIActions(openSpace: { _ in }, openMain: {})+ // The CLI's plan on temp folders, not this Mac's ~/.local/bin.+ let cliDir = dir.appendingPathComponent("cli").path+ bridge.makeCliInstaller = {+ AppCliInstaller.withPaths(bundled: nil, binDir: cliDir, pathEnv: "", profile: cliDir + "/.zshrc")+ }// "Send file…" picks this instead of showing the native panel.bridge.pickFiles = { [URL(fileURLWithPath: "/tmp/cua-contract-notes.txt")] }return bridge@@ -194,6 +199,11 @@ struct BridgeContractTests {await model.keyvault.refresh()let bridge = WebUIBridge(model: model, allowedOrigins: [])bridge.actions = WebUIActions(openSpace: { _ in }, openMain: {})+ // The CLI's plan on temp folders, not this Mac's ~/.local/bin.+ let cliDir = dir.appendingPathComponent("cli").path+ bridge.makeCliInstaller = {+ AppCliInstaller.withPaths(bundled: nil, binDir: cliDir, pathEnv: "", profile: cliDir + "/.zshrc")+ }// "Send file…" picks this instead of showing the native panel.bridge.pickFiles = { [URL(fileURLWithPath: "/tmp/cua-contract-notes.txt")] }let space = try #require(model.spaces.first?.id)@@ -209,6 +219,7 @@ struct BridgeContractTests {("nudges.pending", [:]), ("nudges.answer", ["id": "risky-1-1", "choice": "here"]),("app.info", [:]), ("session.get", [:]), ("relay.usage", [:]), ("resources.get", ["visible": true]), ("session.signOut", [:]),("links.list", [:]), ("links.create", ["target": "space:dev:3000"]), ("links.stop", ["id": "all"]),+ ("cli.plan", [:]),("checklist.get", [:]), ("checklist.send", ["action": ["type": "done", "step": "teleport"]]),("spaces.list", [:]),("spaces.createOptions", [:]), ("spaces.cancelCreate", ["pendingId": "pending:none"]),@@ -298,6 +309,7 @@ struct BridgeContractTests {"keyvault.unlock": "asks for Touch ID", "keyvault.unlockVault": "asks for Touch ID or a passphrase in a sheet","keyvault.setup": "asks for Touch ID or a passphrase in a sheet; keyvaultSetupRefusesASetUpVault covers the fixture","startup.act": "brings the app to the front; startupStatesHaveTheirShape covers the states",+ "cli.install": "writes the CLI into a bin folder and a shell profile; CliBridgeTests covers it on temp folders",]static func shapes() throws -> [String: Any] {diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CliBridgeTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CliBridgeTests.swiftnew file mode 100644index 0000000000..9f9a0bd03f--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CliBridgeTests.swift@@ -0,0 +1,70 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++@testable import CuaSpacesMacKit+import CuaSpacesFFI+import Foundation+import Testing++/// The bundled CLI on PATH (`cli.plan`, `cli.install`, `settings.get`'s+/// `cli`): the app core's installer, on temp folders and a fake `cua`.+@MainActor+struct CliBridgeTests {+ private func bridge(_ dir: URL, bundled: String?) -> WebUIBridge {+ let m = AppModel(backend: FixtureSpacesBackend(), keyvault: KeyvaultModel(client: nil),+ onboarding: OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path),+ settingsPath: dir.appendingPathComponent("settings.json").path,+ telemetry: FixtureTelemetry(), devices: FixtureDevices())+ let b = WebUIBridge(model: m, allowedOrigins: [])+ let bin = dir.appendingPathComponent("bin").path+ let profile = dir.appendingPathComponent(".zshrc").path+ b.makeCliInstaller = { AppCliInstaller.withPaths(bundled: bundled, binDir: bin, pathEnv: "/usr/bin", profile: profile) }+ return b+ }++ /// A fake bundled `cua` that answers `--version` as the real one does.+ private func fakeCua(_ dir: URL) throws -> String {+ let app = dir.appendingPathComponent("App/cua")+ try FileManager.default.createDirectory(at: app.deletingLastPathComponent(), withIntermediateDirectories: true)+ try "#!/bin/sh\necho 'cua 0.9.0'\n".write(to: app, atomically: true, encoding: .utf8)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: app.path)+ return app.path+ }++ private func tempDir() throws -> URL {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-cli-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ return dir+ }++ @Test func aDiskImageInstallPlansThenInstallsOnlyWhenAsked() async throws {+ let dir = try tempDir()+ defer { try? FileManager.default.removeItem(at: dir) }+ let b = bridge(dir, bundled: try fakeCua(dir))+ let plan = try #require(try await b.handle("cli.plan", [:]) as? [String: Any])+ #expect(plan["target"] as? String == dir.appendingPathComponent("bin/cua").path)+ #expect(plan["onPath"] as? Bool == false)+ #expect(plan["found"] is NSNull)+ // Nothing written by the plan.+ #expect(!FileManager.default.fileExists(atPath: dir.appendingPathComponent("bin/cua").path))+ let settings = b.settings()["cli"] as? [String: Any]+ #expect(settings?["name"] as? String == "cua")+ #expect(settings?["installed"] as? Bool == false)++ let done = try #require(try await b.handle("cli.install", ["modifyPath": true]) as? [String: Any])+ #expect(done["upToDate"] as? Bool == true)+ #expect(FileManager.default.fileExists(atPath: dir.appendingPathComponent("bin/cua").path))+ #expect(try String(contentsOf: dir.appendingPathComponent(".zshrc"), encoding: .utf8).contains(dir.appendingPathComponent("bin").path))+ #expect((b.settings()["cli"] as? [String: Any])?["installed"] as? Bool == true)+ }++ @Test func aBuildWithoutABundledCliHasNothingToInstall() async throws {+ let dir = try tempDir()+ defer { try? FileManager.default.removeItem(at: dir) }+ let b = bridge(dir, bundled: nil)+ let plan = try #require(try await b.handle("cli.plan", [:]) as? [String: Any])+ #expect(plan["source"] is NSNull)+ await #expect(throws: (any Error).self) { _ = try await b.handle("cli.install", ["modifyPath": false]) }+ await #expect(throws: (any Error).self) { _ = try await b.handle("cli.install", [:]) }+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swiftnew file mode 100644index 0000000000..cb093c07e7--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift@@ -0,0 +1,19 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++@testable import CuaSpacesMacKit+import Foundation+import PermissionFlow+import Testing++/// `host.openSettings` guides Screen Recording and Accessibility (the panes+/// the host's permission hints and the first run's rows name); any other+/// pane just opens.+struct PermissionGuideTests {+ @Test func guidesTheTwoPanesASharedScreenNeeds() {+ #expect(PermissionGuide.pane(for: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") == .screenRecording)+ #expect(PermissionGuide.pane(for: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") == .accessibility)+ #expect(PermissionGuide.pane(for: "x-apple.systempreferences:com.apple.LoginItems-Settings.extension") == nil)+ #expect(PermissionGuide.pane(for: "x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork") == nil)+ }+}diff --git a/apps/cua-spaces-macos/scripts/install-local.sh b/apps/cua-spaces-macos/scripts/install-local.shindex 08aa7c0b44..8b58bdaf79 100755--- a/apps/cua-spaces-macos/scripts/install-local.sh+++ b/apps/cua-spaces-macos/scripts/install-local.sh@@ -812,6 +812,12 @@ if ditto "$STAGE_APP" "$APP_DEST" && verify_local_bundle "$APP_DEST"; thenfifiif [ "$install_valid" = true ]; then+ # The helper keeps running from the moved-aside copy until it restarts,+ # so LaunchServices learns that path and System Settings then lists+ # "Cua Spaces Local.app.install-backup.<pid>". Forget it before deleting.+ if [ -d "$APP_BACKUP" ] && [ -x "$LSREGISTER" ]; then+ "$LSREGISTER" -u "$APP_BACKUP" >/dev/null 2>&1 || true+ firm -rf "$APP_BACKUP"elserm -rf "$APP_DEST"diff --git a/apps/cua-spaces-web/public/onboarding/agent-other.webp b/apps/cua-spaces-web/public/onboarding/agent-other.webpindex 3bf0d9540e..903468f95d 100644Binary files a/apps/cua-spaces-web/public/onboarding/agent-other.webp and b/apps/cua-spaces-web/public/onboarding/agent-other.webp differdiff --git a/apps/cua-spaces-web/src/__tests__/cli-hints-summary.test.tsx b/apps/cua-spaces-web/src/__tests__/cli-hints-summary.test.tsxnew file mode 100644index 0000000000..24d424e08b--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/cli-hints-summary.test.tsx@@ -0,0 +1,81 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// New Space's Summary: "Or run this in Terminal" with the create the core+// would make (`wizard.createArgs`) under the host's CLI name, and nothing+// while the CLI is not installed.++import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { DemoOptions } from "@/bridge/adapters/demo";+import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { resetNewSpaceSession } from "@/bridge/new-space";+import { mountApp, stubBrowserApis } from "./app-harness";++beforeEach(resetNewSpaceSession);+afterEach(cleanup);+stubBrowserApis();++/** Through the wizard to its Summary, with "Open when ready" as given. */+async function toSummary(openWhenReady: boolean): Promise<HTMLElement> {+ fireEvent.click(await screen.findByRole("button", { name: /New Space/ }));+ const dialog = await waitFor(+ () => {+ const d = document.querySelector<HTMLElement>("[data-new-space]");+ expect(d).not.toBeNull();+ return d!;+ },+ { timeout: 4000 },+ );+ for (let step = 0; step < 3; step++) {+ const next = await waitFor(() => {+ const b = dialog.querySelector<HTMLButtonElement>("[data-wizard-primary]")!;+ expect(b.disabled).toBe(false);+ return b;+ });+ if (step === 2) {+ const box = dialog.querySelector<HTMLElement>("[data-open-when-ready]")!;+ if ((box.getAttribute("aria-checked") === "true") !== openWhenReady) fireEvent.click(box);+ await waitFor(() => expect(box.getAttribute("aria-checked")).toBe(String(openWhenReady)));+ }+ fireEvent.click(next);+ }+ await waitFor(() => expect(dialog.querySelector("[data-summary]")).not.toBeNull());+ return dialog;+}++const mount = (cli?: DemoOptions["cli"]) => mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { cli } });++describe.skipIf(!wasmBuilt)("New Space's Summary, in Terminal", () => {+ it("shows the create the wizard would make, under the released app's CLI", { timeout: 20_000 }, async () => {+ await mount();+ const dialog = await toSummary(false);+ const block = await waitFor(() => {+ const b = dialog.querySelector<HTMLElement>("[data-cli-hint=block]");+ expect(b).not.toBeNull();+ return b!;+ });+ expect(block.textContent).toContain("Or run this in Terminal");+ const command = block.querySelector("[data-cli-command]")!.textContent!;+ expect(command).toMatch(/^cua spaces create \S+ --on local --kind (container|vm)( |$)/);+ });++ it("names a Local build's CLI, and adds opening the Space when it opens when ready", { timeout: 20_000 }, async () => {+ await mount("local");+ const dialog = await toSummary(true);+ const lines = await waitFor(() => {+ const text = dialog.querySelector("[data-cli-hint=block] [data-cli-command]")?.textContent ?? "";+ expect(text).toMatch(/^cua-local spaces create /);+ return text.split("\n");+ });+ // The open line needs the Space's name; the wizard names every Space.+ if (lines.length > 1) expect(lines[1]).toMatch(/^cua-local sb view \S+/);+ });++ it("stays hidden while the CLI is not installed", { timeout: 20_000 }, async () => {+ await mount("missing");+ const dialog = await toSummary(false);+ await new Promise((r) => setTimeout(r, 50));+ expect(dialog.querySelector("[data-cli-hint]")).toBeNull();+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/cli-settings.test.tsx b/apps/cua-spaces-web/src/__tests__/cli-settings.test.tsxnew file mode 100644index 0000000000..ca1f780730--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/cli-settings.test.tsx@@ -0,0 +1,42 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Settings → Terminal: the first run's CLI install, reachable later.++import { cleanup, fireEvent, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { mountApp, stubBrowserApis } from "./app-harness";++afterEach(cleanup);+stubBrowserApis();++describe.skipIf(!wasmBuilt)("Settings, Terminal", () => {+ it("names the file, installs on Install, then says where it is", { timeout: 20_000 }, async () => {+ const calls: { op: string; args: unknown }[] = [];+ await mountApp("/settings", {+ failsCreates: false,+ listsGhost: false,+ demo: { cli: "missing" },+ intercept: (op, args) => {+ calls.push({ op, args });+ return undefined;+ },+ });+ const row = await waitFor(() => {+ const r = document.querySelector<HTMLElement>('[data-settings-cli="missing"]');+ expect(r).not.toBeNull();+ return r!;+ }, { timeout: 8000 });+ expect(row.textContent).toMatch(/Not installed\. Install puts it at ~\/\.local\/bin\/cua\./);+ expect(calls.some((c) => c.op === "cli.install")).toBe(false);+ fireEvent.click(row.querySelector("[data-settings-cli-install]")!);+ await waitFor(() => expect(document.querySelector('[data-settings-cli="installed"]')?.textContent).toMatch(/Installed at ~\/\.local\/bin\/cua\..*cua spaces ls/));+ expect(calls.find((c) => c.op === "cli.install")?.args).toEqual({ modifyPath: true });+ });++ it("shows where a Local build's CLI is", { timeout: 20_000 }, async () => {+ await mountApp("/settings", { failsCreates: false, listsGhost: false, demo: { cli: "local" } });+ await waitFor(() => expect(document.querySelector('[data-settings-cli="installed"]')?.textContent).toMatch(/~\/\.local\/bin\/cua-local.*cua-local spaces ls/), { timeout: 8000 });+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx b/apps/cua-spaces-web/src/__tests__/first-run.test.tsxindex cc02532ef5..791fc01540 100644--- a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/first-run.test.tsx@@ -32,14 +32,14 @@ afterEach(cleanup);type Calls = { op: string; args: unknown }[];-async function mount(opts: { host?: (h: HostStatus) => HostStatus; local?: (l: NonNullable<NewSpaceOptions["local"]>) => NewSpaceOptions["local"]; agents?: (rows: AgentSetupRow[]) => AgentSetupRow[] } = {}) {+async function mount(opts: { signedIn?: boolean; host?: (h: HostStatus) => HostStatus; local?: (l: NonNullable<NewSpaceOptions["local"]>) => NewSpaceOptions["local"]; agents?: (rows: AgentSetupRow[]) => AgentSetupRow[]; cli?: "missing" | "local" } = {}) {await testCore();const calls: Calls = [];await mountApp("/onboarding", {failsCreates: false,listsGhost: false,// A first run: signed out, and Cua in no agent's settings yet.- demo: { signedIn: false, onboarded: false },+ demo: { signedIn: opts.signedIn ?? false, onboarded: false, cli: opts.cli },intercept: (op, args) => {calls.push({ op, args });return undefined;@@ -105,7 +105,7 @@ const noAgents = (rows: AgentSetupRow[]) => rows.map((r) => ({ ...r, installed:describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {it("walks Welcome, Pick your agent, Connect your devices and Try it, connecting only what is clicked", async () => {const calls = await mount();- await waitFor(() => expect(heading()).toBe("Your agents get their own computer."));+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));click("[data-onboarding-primary]");await waitFor(() => expect(heading()).toBe("Pick your agent."));// The agents found here, most preferred first; nothing connected by itself.@@ -141,7 +141,7 @@ describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {it("Back works from every step after Welcome, all the way to Welcome, keeping what was picked", async () => {const calls = await mount();- await waitFor(() => expect(heading()).toBe("Your agents get their own computer."));+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));expect(document.querySelector("[data-first-run-back]")).toBeNull();click("[data-onboarding-primary]");await waitFor(() => expect(heading()).toBe("Pick your agent."));@@ -158,12 +158,35 @@ describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {await waitFor(() => expect(heading()).toBe("Pick your agent."));expect(document.querySelector<HTMLElement>('[data-first-run-agent="codex"]')!.dataset.connected).toBe("true");click("[data-first-run-back]");- await waitFor(() => expect(heading()).toBe("Your agents get their own computer."));+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));// Going back only navigates: nothing was connected again or undone.expect(readFirstRun().picked).toEqual(["codex"]);expect(calls.filter((c) => c.op === "agents.configure")).toHaveLength(1);});+ it("Back sits above the heading, apart from the choices; Tab goes primary, secondary, Back; Esc goes back", async () => {+ writeFirstRun({ step: "devices" });+ await mount();+ await waitFor(() => expect(heading()).toBe("Connect your other devices."));+ const step = document.querySelector<HTMLElement>('[data-first-run="devices"]')!;+ const back = step.querySelector<HTMLElement>("[data-first-run-back]")!;+ // Drawn first (above the heading), but last in the page's order.+ expect(back.className).toContain("order-first");+ const order = Array.from(step.querySelectorAll<HTMLElement>("[data-onboarding-primary], [data-first-run-secondary], [data-first-run-back]"));+ expect(order.map((el) => (el.matches("[data-onboarding-primary]") ? "primary" : el.matches("[data-first-run-back]") ? "back" : "secondary"))).toEqual(["primary", "secondary", "back"]);+ // "Not now" is a button of its own, described by the note under it.+ const secondary = step.querySelector<HTMLElement>("[data-first-run-secondary]")!;+ expect(screen.getByRole("button", { name: "Not now" })).toBe(secondary);+ expect(document.getElementById(secondary.getAttribute("aria-describedby")!)?.textContent).toBe("This Mac works without it.");+ fireEvent.keyDown(window, { key: "Escape" });+ await waitFor(() => expect(heading()).toBe("Pick your agent."));+ fireEvent.keyDown(window, { key: "Escape" });+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ // Welcome has no Back, so Esc stays.+ fireEvent.keyDown(window, { key: "Escape" });+ expect(heading()).toBe("Your computers, shared by your team and its agents.");+ });+it("Codex: its ChatGPT sign-in and OpenAI key follow it, and the sign-in starts on this computer", async () => {writeFirstRun({ step: "connect" });const calls = await mount({ agents: (rows) => rows.map((r) => ({ ...r, installed: r.agent === "codex" })) });@@ -192,15 +215,116 @@ describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {await waitFor(() => expect(calls.some((c) => c.op === "session.signIn")).toBe(true));});+ it("a disk-image install offers the Cua CLI after Pick your agent: the exact file, then Install only when pressed", async () => {+ const calls = await mount({ cli: "missing" });+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Pick your agent."));+ // The install plan is read: the run has the CLI's screen.+ await waitFor(() => expect(document.querySelector("ol[aria-label]")!.getAttribute("aria-label")).toBe("Step 2 of 5"));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Use Cua from the Terminal."));+ const facts = [...document.querySelectorAll<HTMLElement>("[data-first-run-cli-fact]")].map((e) => e.textContent);+ expect(facts).toEqual(["Installs~/.local/bin/cua", "Adds to PATH~/.local/bin, in ~/.zshrc"]);+ expect(document.querySelector("[data-step]")!.getAttribute("data-step")).toBe("cli");+ expect(document.querySelector("ol[aria-label]")!.getAttribute("aria-label")).toBe("Step 3 of 5");+ // Nothing is written before Install.+ expect(calls.some((c) => c.op === "cli.install")).toBe(false);+ click('[data-first-run-cli-primary="install"]');+ await waitFor(() => expect(heading()).toBe("Cua is ready in Terminal."));+ expect(calls.find((c) => c.op === "cli.install")?.args).toEqual({ modifyPath: true });+ expect(document.querySelector("[data-first-run-cli-done]")!.textContent).toMatch(/cua spaces ls/);+ await waitFor(() => expect(document.querySelector('[data-first-run-cli-primary="continue"]')!.textContent).toBe("Continue"));+ click('[data-first-run-cli-primary="continue"]');+ await waitFor(() => expect(heading()).toBe("Connect your other devices."));+ // Back shows the result again.+ click("[data-first-run-back]");+ await waitFor(() => expect(heading()).toBe("Cua is ready in Terminal."));+ });++ it("Not now leaves the CLI as it is; with the CLI already installed there is no such screen", async () => {+ const calls = await mount({ cli: "missing" });+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Pick your agent."));+ // The install plan is read: the run has the CLI's screen.+ await waitFor(() => expect(document.querySelector("ol[aria-label]")!.getAttribute("aria-label")).toBe("Step 2 of 5"));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Use Cua from the Terminal."));+ click("[data-first-run-secondary]");+ await waitFor(() => expect(heading()).toBe("Connect your other devices."));+ expect(calls.some((c) => c.op === "cli.install")).toBe(false);+ cleanup();+ localStorage.clear();+ resetSavedOnboardingCache();+ resetFirstRunCache();+ await mount();+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Pick your agent."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Connect your other devices."));+ });++ it("a signed-in Mac that shares its screen asks for two permissions in its own words, and Allow opens the guide", async () => {+ const SR = "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture";+ const AX = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";+ let missing = [+ { id: "screen-recording", label: "Screen Recording", settingsUrl: SR },+ { id: "accessibility", label: "Accessibility", settingsUrl: AX },+ ];+ writeFirstRun({ step: "devices", picked: ["codex"] });+ const calls = await mount({+ signedIn: true,+ host: (h) => ({ ...h, configured: true, shareDesktop: true, appName: "Cua Spaces Local", permissions: missing }),+ });+ await waitFor(() => expect(heading()).toBe("This Mac is in your account."));+ click('[data-first-run-devices-primary="continue"]');+ await waitFor(() => expect(heading()).toBe("Share this Mac's screen."));+ expect(document.body.textContent).toMatch(/To let your team and agents see and use this Mac, allow two permissions\./);+ expect(document.body.textContent).toMatch(/turn on Cua Spaces Local\./);+ // Nothing is asked before a click.+ expect(calls.some((c) => c.op === "host.openSettings")).toBe(false);+ const rows = () => [...document.querySelectorAll<HTMLElement>("[data-first-run-permissions] [data-first-run-status]")].map((e) => `${e.dataset.firstRunStatus}:${e.dataset.state}`);+ await waitFor(() => expect(rows()).toEqual(["screen-recording:fix", "accessibility:fix"]));+ click('[data-first-run-status="screen-recording"] [data-first-run-action="allow"]');+ await waitFor(() => expect(calls.find((c) => c.op === "host.openSettings")?.args).toEqual({ url: SR }));+ // Granted in System Settings: a check, live; Continue once both are.+ missing = [];+ fireEvent.focus(window);+ await waitFor(() => expect(rows()).toEqual(["screen-recording:ok", "accessibility:ok"]));+ click('[data-first-run-permissions-primary="continue"]');+ await waitFor(() => expect(heading()).toBe("Try it in OpenAI Codex."));+ click("[data-first-run-back]");+ await waitFor(() => expect(heading()).toBe("Share this Mac's screen."));+ });++ it("Not now on the permissions screen goes on; a Mac kept for Spaces only never sees it", async () => {+ writeFirstRun({ step: "permissions", picked: ["codex"] });+ let share = true;+ const calls = await mount({+ signedIn: true,+ host: (h) => ({ ...h, configured: true, shareDesktop: share, permissions: [{ id: "accessibility", label: "Accessibility" }] }),+ });+ await waitFor(() => expect(heading()).toBe("Share this Mac's screen."));+ click('[data-first-run-permissions-secondary="not-now"]');+ await waitFor(() => expect(heading()).toBe("Try it in OpenAI Codex."));+ expect(calls.some((c) => c.op === "host.openSettings")).toBe(false);+ share = false;+ writeFirstRun({ step: "permissions" });+ fireEvent.focus(window);+ await waitFor(() => expect(heading()).toBe("Try it in OpenAI Codex."));+ });+it("with no agent: install one or use the CLI, then a one-click first Space", async () => {const calls = await mount({ agents: noAgents, local: (l) => ({ ...l, backends: ["docker"], macosImage: null, hostArch: "amd64" }) });- await waitFor(() => expect(heading()).toBe("Your agents get their own computer."));+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));click("[data-onboarding-primary]");await waitFor(() => expect(heading()).toBe("Connect an agent."));expect(agents()).toEqual([]);const alts = [...document.querySelectorAll<HTMLElement>("[data-first-run-alternative]")].map((e) => e.dataset.firstRunAlternative);expect(alts).toEqual(["install", "cli"]);- expect(document.querySelector('[data-first-run-alternative="cli"]')!.textContent).toMatch(/cua spaces create linux/);+ expect(document.querySelector('[data-first-run-alternative="cli"]')!.textContent).toMatch(/cua spaces create linux --on local/);click("[data-onboarding-primary]");await waitFor(() => expect(heading()).toBe("Connect your other devices."));click("[data-first-run-secondary]");diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex 6971af9f18..94fa105378 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -109,6 +109,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"links.list": {},"links.create": { target: "space:dev:3000" },"links.stop": { id: "all" },+ "cli.plan": {},+ "cli.install": { modifyPath: true },"presence.join": { spaceId: SPACE },"presence.publish": { handle: "p1", x: 0.5, y: 0.5, visible: true },"presence.leave": { handle: "p1" },diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex eb6ce1fad3..e64b3ce83b 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -20,6 +20,7 @@ import { RESOURCES_ARGS } from "../ops/resources";import { MACHINES_ARGS } from "../ops/machines";import { CHECKLIST_ARGS } from "../ops/checklist";import { LINKS_ARGS } from "../ops/links";+import { CLI_ARGS } from "../ops/cli";import { PRESENCE_ARGS } from "../ops/presence";import { RUNTIME_FIX_ARGS } from "../ops/runtime-fix";import type { HostWindow } from "../detect";@@ -141,6 +142,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {...MACHINES_ARGS,...CHECKLIST_ARGS,...LINKS_ARGS,+ ...CLI_ARGS,...PRESENCE_ARGS,...RUNTIME_FIX_ARGS,};diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex bc557e9259..ae710cf0fd 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -43,6 +43,7 @@ import { demoKeyvaultSetupHandlers, demoKeyvaultSetupState, demoNoVaultOverview,import { unsupportedStreamOps } from "../ops/stream";import { unsupportedPresenceOps } from "../ops/presence";import { unsupportedRuntimeFixOps } from "../ops/runtime-fix";+import type { CliInstallPlan } from "../contracts/first-run";import { unsupportedChecklistOps } from "../ops/checklist";import { demoTeleportHandlers } from "./demo/teleport";import { createDemoSettings } from "./demo/settings";@@ -96,6 +97,10 @@ export interface DemoOptions {* `?demo=create-fail-runtime`) or `disk` (every create is short of disk* space, `?demo=create-fail-disk`). */failCreates?: "runtime-once" | "disk";+ /** The CLI the demo host reports: the released app's `cua` on PATH unless+ * set; `local` is a Local build's (`?demo=cli-local`), `missing` one+ * not installed (`?demo=cli-missing`). */+ cli?: "local" | "missing";}/** The SDK's words for the failures `failCreates` plays. */@@ -129,6 +134,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {agents: (["none", "codex"] as const).find((a) => flags.has(`agents-${a}`)),nudge: (["second-agent", "risky"] as const).find((n) => flags.has(`nudge-${n}`)),disk: flags.has("disk-full") ? "full" : flags.has("low-disk") ? "low" : undefined,+ cli: flags.has("cli-local") ? "local" : flags.has("cli-missing") ? "missing" : undefined,failCreates: flags.has("create-fail-runtime") ? "runtime-once" : flags.has("create-fail-disk") ? "disk" : undefined,...(flags.has("update-ready")? { update: { status: "downloaded" as const, version: "0.9.3", percent: 100, notesUrl: DEMO_NOTES } }@@ -237,6 +243,24 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reconst replaceRow = (id: string, patch: Partial<SpaceRow>) => {state.rows = state.rows.map((r) => (r.id === id ? { ...r, ...patch } : r));};+ // The bundled CLI (`?demo=cli-missing`: a disk-image install, none on PATH yet).+ const cliName = options.cli === "local" ? "cua-local" : "cua";+ let cliInstalled = options.cli !== "missing";+ const cliPlan = (): CliInstallPlan => {+ const target = `/Users/me/.local/bin/${cliName}`;+ return {+ source: `/Applications/Cua Spaces.app/Contents/MacOS/cua`,+ target,+ binDir: "/Users/me/.local/bin",+ method: "symlink",+ installed: cliInstalled,+ upToDate: cliInstalled,+ onPath: cliInstalled,+ pathProfile: cliInstalled ? null : "/Users/me/.zshrc",+ pathLine: cliInstalled ? null : 'export PATH="/Users/me/.local/bin:$PATH"',+ found: cliInstalled ? target : null,+ };+ };const settingsSnapshot = (): SettingsSnapshot => ({values: { ...state.settings },defaultLocation: { value: state.settings.defaultLocation, source: "config", path: "~/.cua/config.toml" },@@ -244,6 +268,8 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...(state.hostSettings ? { hostSettings: { ...state.hostSettings } } : {}),// The macOS hosts register ⌘⇧Space; the Windows and Linux shells have none.globalShortcut: state.platform.os === "macos" ? { label: state.settings.hotkey, registered: true } : null,+ // What a host's CLI install plan names (`CuaChannel::cli_name`): Local's is `cua-local`.+ cli: { name: cliName, installed: cliInstalled },});const overview = () => {if (!state.keyvaultSetUp) return demoNoVaultOverview(now());@@ -599,6 +625,12 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...unsupportedChecklistOps("demo"),...unsupportedPresenceOps("demo"),...unsupportedRuntimeFixOps("demo"),+ "cli.plan": () => cliPlan(),+ "cli.install": async () => {+ await wait(step);+ cliInstalled = true;+ return cliPlan();+ },};return {diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex 068e295f83..4de47103ec 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -62,6 +62,7 @@ import { RESOURCES_OPERATIONS } from "../ops/resources";import { MACHINES_OPERATIONS } from "../ops/machines";import { CHECKLIST_OPERATIONS } from "../ops/checklist";import { LINKS_OPERATIONS } from "../ops/links";+import { CLI_OPERATIONS } from "../ops/cli";import { PRESENCE_OPERATIONS } from "../ops/presence";import { RUNTIME_FIX_OPERATIONS } from "../ops/runtime-fix";import { tauriTelemetryOps } from "../ops/telemetry";@@ -102,6 +103,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [...MACHINES_OPERATIONS,...CHECKLIST_OPERATIONS,...LINKS_OPERATIONS,+ ...CLI_OPERATIONS,...PRESENCE_OPERATIONS,...RUNTIME_FIX_OPERATIONS,];diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex 4d781eb321..85e16bcd07 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -65,6 +65,7 @@ import type { HostChecklistState } from "../ops/checklist";import type { LinkCreate, ShareLink } from "../ops/links";import { unsupportedPresenceOps, type PresenceJoinInfo } from "../ops/presence";import { unsupportedRuntimeFixOps } from "../ops/runtime-fix";+import type { CliInstallPlan } from "../contracts/first-run";import type { SpaceRow } from "../contracts/spaces";import {isWebkitResponse,@@ -316,6 +317,7 @@ export function toSettingsSnapshot(s: WkSettings, page: Pick<SettingsValues, "th},globalShortcut: s.globalShortcut ? { label: s.globalShortcut.label, registered: s.globalShortcut.registered } : null,accountUrl: s.accountUrl ?? null,+ cli: s.cli && s.cli.name ? { name: s.cli.name, installed: Boolean(s.cli.installed) } : null,};}@@ -418,6 +420,7 @@ export function toHostStatus(h: WkHostState): HostStatus {ownerEmail: h.ownerEmail ?? null,account: h.account ?? null,progress: h.progress ?? null,+ appName: h.appName ?? null,};}@@ -698,6 +701,9 @@ export function createWebkitAdapter("links.list": () => request<{ links: ShareLink[] }>("links.list"),"links.create": (a: LinkCreate) => request<ShareLink>("links.create", a as unknown as Record<string, unknown>),"links.stop": ({ id }) => request<{ stopped: string[] }>("links.stop", { id }),+ // The bundled CLI on PATH (the app core's installer in the host).+ "cli.plan": () => request<CliInstallPlan | null>("cli.plan"),+ "cli.install": ({ modifyPath }) => request<CliInstallPlan>("cli.install", { modifyPath }),// Presence over the page's own video: the Mac app draws it natively....(electron? {diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex b1bd1282d9..51faf3c6f5 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -472,6 +472,82 @@"json"]},+ "CliInstallPlan": {+ "type": "object",+ "properties": {+ "source": {+ "type": [+ "string",+ "null"+ ]+ },+ "target": {+ "type": "string"+ },+ "binDir": {+ "type": "string"+ },+ "method": {+ "enum": [+ "symlink",+ "copy",+ null+ ]+ },+ "installed": {+ "type": "boolean"+ },+ "upToDate": {+ "type": "boolean"+ },+ "installedVersion": {+ "type": [+ "string",+ "null"+ ]+ },+ "bundledVersion": {+ "type": [+ "string",+ "null"+ ]+ },+ "shadowedBy": {+ "type": [+ "string",+ "null"+ ]+ },+ "onPath": {+ "type": "boolean"+ },+ "pathProfile": {+ "type": [+ "string",+ "null"+ ]+ },+ "pathLine": {+ "type": [+ "string",+ "null"+ ]+ },+ "found": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "target",+ "binDir",+ "installed",+ "upToDate",+ "onPath"+ ]+ },"CloudPricing": {"type": "object","properties": {@@ -1233,6 +1309,12 @@"string","null"]+ },+ "appName": {+ "type": [+ "string",+ "null"+ ]}},"required": [@@ -3025,6 +3107,24 @@"string","null"]+ },+ "cli": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "name": {+ "type": "string"+ },+ "installed": {+ "type": "boolean"+ }+ },+ "required": [+ "name",+ "installed"+ ]}},"required": [@@ -4279,6 +4379,12 @@"string","null"]+ },+ "appName": {+ "type": [+ "string",+ "null"+ ]}},"required": [@@ -4710,6 +4816,24 @@"string","null"]+ },+ "cli": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "name": {+ "type": "string"+ },+ "installed": {+ "type": "boolean"+ }+ },+ "required": [+ "name",+ "installed"+ ]}},"required": [@@ -5308,6 +5432,19 @@"state"]},+ "cli.install": {+ "$ref": "#/$defs/CliInstallPlan"+ },+ "cli.plan": {+ "anyOf": [+ {+ "$ref": "#/$defs/CliInstallPlan"+ },+ {+ "type": "null"+ }+ ]+ },"clouds.connect": {"$ref": "#/$defs/CloudProviderWire"},@@ -7077,6 +7214,19 @@"state"]},+ "cli.install": {+ "$ref": "#/$defs/CliInstallPlan"+ },+ "cli.plan": {+ "anyOf": [+ {+ "$ref": "#/$defs/CliInstallPlan"+ },+ {+ "type": "null"+ }+ ]+ },"clouds.connect": {"$ref": "#/$defs/CloudProviderWire"},diff --git a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts b/apps/cua-spaces-web/src/bridge/contracts/first-run.tsindex c17735cad4..3bde3af156 100644--- a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/first-run.ts@@ -7,8 +7,60 @@* Rust is the source of truth.*/-/** Welcome, Pick your agent (`connect`), Connect your other devices, Try it (`setup`). */-export type FirstRunStep = "welcome" | "connect" | "devices" | "setup";+/** Welcome, Pick your agent (`connect`), Install the Cua CLI (`cli`, only+ * while it is missing), Connect your other devices, Share this Mac's screen+ * (`permissions`, only on a signed-in Mac that shares it), Try it (`setup`). */+export type FirstRunStep = "welcome" | "connect" | "cli" | "devices" | "permissions" | "setup";++/** What installing the app's bundled CLI would do (`installer::CliInstallPlan`). */+export interface CliInstallPlan {+ /** The bundled CLI, when this build carries one. */+ source?: string | null;+ /** The exact file Install writes (`~/.local/bin/cua`, or `cua-local`). */+ target: string;+ binDir: string;+ method?: "symlink" | "copy" | null;+ installed: boolean;+ upToDate: boolean;+ installedVersion?: string | null;+ bundledVersion?: string | null;+ shadowedBy?: string | null;+ onPath: boolean;+ pathProfile?: string | null;+ pathLine?: string | null;+ /** A working CLI of this channel already on this computer. */+ found?: string | null;+}++/** The app's bundled CLI on the Command line screen (`first_run::FirstRunCli`). */+export interface FirstRunCli {+ plan: CliInstallPlan | null;+ installing: boolean;+ /** Installed from this screen: the file written. */+ installed: string | null;+ error: string | null;+}++/** "Installs", "~/.local/bin/cua". */+export interface FirstRunCliFact {+ label: string;+ value: string;+}++/** Install the Cua CLI (`first_run::CliView`): the first run's screen and Settings' row. */+export interface FirstRunCliView {+ title: string;+ lede: string;+ name: string;+ facts: FirstRunCliFact[];+ status: string;+ installed: boolean;+ busy: boolean;+ tryCommand: string | null;+ error: string | null;+ primary: FirstRunButton | null;+ secondary: FirstRunButton | null;+}export interface FirstRunAgent {agent: string;@@ -34,6 +86,10 @@ export interface FirstRunHost {online?: boolean | null;permissions: FirstRunPermission[];error?: string | null;+ /** People it is shared with see and use its screen (null: not known). */+ shareDesktop?: boolean | null;+ /** The name System Settings lists the app under ("Cua Spaces Local"). */+ appName?: string | null;}export interface FirstRunOffer {@@ -89,6 +145,10 @@ export interface FirstRunInput {offers: FirstRunOffer[];extra: FirstRunExtra;plan: FirstRunPlan | null;+ /** The app's bundled CLI (absent: not read). */+ cli?: FirstRunCli;+ /** The CLI's name (`SettingsSnapshot.cli`); null: the plan's file name, else `cua`. */+ cliName?: string | null;}export interface FirstRunButton {@@ -168,10 +228,25 @@ export interface FirstRunDevicesView {note: string | null;}+/** Share this Mac's screen: Screen Recording and Accessibility, each with+ * Allow (the app's guide to its System Settings pane) and a check once+ * granted (`first_run::PermissionsView`). */+export interface FirstRunPermissionsView {+ title: string;+ lede: string;+ /** `screen-recording`, `accessibility`: `ok`, `fix` (Allow), `checking`. */+ rows: FirstRunRow[];+ note: string;+ /** "Continue" once both are granted. */+ primary: FirstRunButton | null;+ /** "Not now" while one is missing. */+ secondary: FirstRunButton | null;+}+export type FirstRunRowState = "checking" | "ok" | "fix";export interface FirstRunRow {- id: "agent" | "computer" | "account";+ id: "agent" | "computer" | "account" | "screen-recording" | "accessibility";state: FirstRunRowState;title: string;note: string;@@ -249,8 +324,13 @@ export interface FirstRunView {welcome: FirstRunWelcomeView | null;connect: FirstRunConnectView | null;devices: FirstRunDevicesView | null;+ /** Only on a signed-in Mac that shares its screen. */+ permissions?: FirstRunPermissionsView | null;setup: FirstRunSetupView | null;+ cli: FirstRunCliView | null;art: FirstRunArt;+ /** The screens this run shows, in order (Back and Continue follow them). */+ steps: FirstRunStep[];dots: number;current: number;}diff --git a/apps/cua-spaces-web/src/bridge/contracts/host.ts b/apps/cua-spaces-web/src/bridge/contracts/host.tsindex 79a3bd2dac..ebab801c9e 100644--- a/apps/cua-spaces-web/src/bridge/contracts/host.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/host.ts@@ -431,7 +431,9 @@ export interface HostStatus {account?: HostAccount | null;/** What a running setup (or Sign In) waits for, such as finishing the* sign-in in the browser (the SwiftUI app's `HostModel.progress`). */- progress?: string | null;+ progress?: string | null; /** The name System Settings lists the app under ("Cua Spaces", "Cua+ * Spaces Local"): the Mac app's own name, for the permissions screen. */+ appName?: string | null;}/** The account signed in to Cua in the app (`host::HostAccount`). */diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 7d99750779..6e377493ad 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -65,10 +65,11 @@ import type { RiskyRequest } from "../ops/nudges";import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SpaceResources } from "../ops/resources";import type { HostChecklistState } from "../ops/checklist";import type { ShareLink } from "../ops/links";+import type { CliInstallPlan } from "./first-run";import type { PresenceCursorWire, PresenceJoinInfo, PresenceParticipantWire } from "../ops/presence";import type { StartupState } from "../ops/startup";import type { StreamTicket } from "../ops/stream";-import type { GlobalShortcut, HostSettings, HostSignIn, HostSignInFailure, OpName, SessionSnapshot, SettingsSnapshot, SettingsValues } from "../protocol";+import type { CliInfo, GlobalShortcut, HostSettings, HostSignIn, HostSignInFailure, OpName, SessionSnapshot, SettingsSnapshot, SettingsValues } from "../protocol";import type { WebkitMethod, WkHostState, WkMachines, WkOnboarding, WkSession, WkSettings, WkSettingsRow, WkSpace, WkSpaces } from "../webkit-protocol";import { Defs, any, bool, dict, list, nul, nullable, num, obj, object, oneOf, opt, optNull, str, union, type Schema } from "./schema";@@ -80,6 +81,25 @@ const os = oneOf("macos", "windows", "linux", "unknown");/* ---- Spaces and machines --------------------------------------------------- */+const CliInstallPlanShape = ref(+ "CliInstallPlan",+ obj<CliInstallPlan>()({+ source: optNull(str),+ target: str,+ binDir: str,+ method: optNull(oneOf("symlink", "copy")),+ installed: bool,+ upToDate: bool,+ installedVersion: optNull(str),+ bundledVersion: optNull(str),+ shadowedBy: optNull(str),+ onPath: bool,+ pathProfile: optNull(str),+ pathLine: optNull(str),+ found: optNull(str),+ }),+);+const DiskWarningShape = ref("DiskWarning", obj<DiskWarning>()({ level: oneOf("ok", "low", "critical"), free: num, total: num, threshold: num }));/** `resources.get`'s computers (CUA-1880). */@@ -187,6 +207,7 @@ const HostStatusShape = ref(ownerEmail: optNull(str),account: optNull(object({ id: optNull(str), email: optNull(str), display: optNull(str) })),progress: optNull(str),+ appName: optNull(str),}),);@@ -284,6 +305,7 @@ const SettingsShape = ref(),globalShortcut: optNull(obj<GlobalShortcut>()({ label: str, registered: bool })),accountUrl: optNull(str),+ cli: optNull(obj<CliInfo>()({ name: str, installed: bool })),}),);@@ -1051,6 +1073,8 @@ export const OP_SHAPES: Record<OpName, Schema> = {"links.list": object({ links: list(ShareLinkShape) }),"links.create": ShareLinkShape,"links.stop": object({ stopped: strings }),+ "cli.plan": nullable(CliInstallPlanShape),+ "cli.install": CliInstallPlanShape,"presence.join": obj<PresenceJoinInfo>()({handle: str,me: PresenceParticipantShape,@@ -1142,6 +1166,7 @@ const WkHostShape = ref(ownerEmail: optNull(str),account: optNull(object({ id: optNull(str), email: optNull(str), display: optNull(str) })),progress: optNull(str),+ appName: optNull(str),}),);@@ -1217,6 +1242,7 @@ const WkSettingsShape = ref(updateChannel: optNull(oneOf("stable", "beta")),globalShortcut: optNull(object({ label: str, registered: bool })),accountUrl: optNull(str),+ cli: optNull(object({ name: str, installed: bool })),}),);@@ -1456,6 +1482,8 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"links.list": OP_SHAPES["links.list"],"links.create": OP_SHAPES["links.create"],"links.stop": OP_SHAPES["links.stop"],+ "cli.plan": OP_SHAPES["cli.plan"],+ "cli.install": OP_SHAPES["cli.install"],};/** Methods whose answer has no shape here, and why (none today: keep thediff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 7dbd1e18e0..635a4956c1 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -45,6 +45,7 @@ import { RESOURCES_COVERAGE } from "./ops/resources";import { MACHINES_COVERAGE } from "./ops/machines";import { CHECKLIST_COVERAGE } from "./ops/checklist";import { LINKS_COVERAGE } from "./ops/links";+import { CLI_COVERAGE } from "./ops/cli";import { PRESENCE_COVERAGE } from "./ops/presence";import { RUNTIME_FIX_COVERAGE } from "./ops/runtime-fix";import { TELEMETRY_COVERAGE } from "./ops/telemetry";@@ -174,6 +175,7 @@ export const HOST_COVERAGE = {...MACHINES_COVERAGE,...CHECKLIST_COVERAGE,...LINKS_COVERAGE,+ ...CLI_COVERAGE,...PRESENCE_COVERAGE,...RUNTIME_FIX_COVERAGE,} as const satisfies Record<OpName, OpCoverage>;diff --git a/apps/cua-spaces-web/src/bridge/first-run.ts b/apps/cua-spaces-web/src/bridge/first-run.tsindex fa41e98dc0..2b1892d333 100644--- a/apps/cua-spaces-web/src/bridge/first-run.ts+++ b/apps/cua-spaces-web/src/bridge/first-run.ts@@ -3,7 +3,10 @@/*** The first run every host shows: Welcome, Pick your agent, Connect your- * other devices (an optional sign-in), then Try it in your agent. The words,+ * other devices (an optional sign-in), Share this Mac's screen (a signed-in+ * Mac that shares its screen: Screen Recording and Accessibility, each with+ * Allow, which `host.openSettings` turns into the app's guide to the pane),+ * then Try it in your agent. The words,* the agents' order, which button does what and the to-do list on Home are* the app core's (`firstRun.view`, `firstRun.todos`,* `cua-spaces-app-core/src/first_run.rs`); this module gathers what the core@@ -35,10 +38,14 @@ import type { CoreClient } from "./core";import type { AgentSetupRow } from "./contracts/agents";import type { HostStatus } from "./contracts/host";import type {+ CliInstallPlan,FirstRunAgent,+ FirstRunCli,+ FirstRunCliView,FirstRunExtra,FirstRunInput,FirstRunOffer,+ FirstRunPermissionsView,FirstRunPlan,FirstRunStep,FirstRunTodos,@@ -86,6 +93,39 @@ export function firstRunView(core: CoreClient, input: FirstRunInput): FirstRunVireturn core.tryCall<FirstRunView>("firstRun.view", { input }) ?? fallbackView(input);}+/** Install the Cua CLI, as the first run and Settings show it (`firstRun.cli`). */+export function firstRunCliView(core: CoreClient, input: Pick<FirstRunInput, "cli" | "cliName">): FirstRunCliView | null {+ return core.tryCall<FirstRunCliView>("firstRun.cli", { input: { ...input } }) ?? null;+}++/** The CLI is on this computer (`FirstRunCli::present`). */+export function cliPresent(cli: FirstRunCli | undefined): boolean {+ return Boolean(cli?.installed || cli?.plan?.upToDate || cli?.plan?.found);+}++/** The app carries a CLI and none is on this computer (`FirstRunCli::missing`). */+export function cliMissing(cli: FirstRunCli | undefined): boolean {+ return !cliPresent(cli) && Boolean(cli?.plan?.source);+}++/** The screens a run shows (`first_run::steps`): the CLI's only while it+ * is missing; Share this Mac's screen only on a signed-in Mac that shares+ * its screen (`first_run::asks_permissions`). */+export function firstRunSteps(input: FirstRunInput): FirstRunStep[] {+ const cli = input.step === "cli" || Boolean(input.cli?.installed) || cliMissing(input.cli);+ const asks = input.hostOs === "macos" && input.signedIn && input.host?.shareDesktop !== false;+ return ["welcome", "connect", ...(cli ? ["cli" as const] : []), "devices", ...(asks ? ["permissions" as const] : []), "setup"];+}++/** The two permissions a shared screen needs (`firstRun.permissions`): the+ * first run's screen and Settings' group say the same. */+export function firstRunPermissions(core: CoreClient, input: FirstRunInput): FirstRunPermissionsView {+ return (+ core.tryCall<FirstRunPermissionsView>("firstRun.permissions", { input }) ??+ fallbackView({ ...input, step: "permissions", hostOs: "macos", signedIn: true }).permissions!+ );+}+export function firstRunTodos(core: CoreClient, input: FirstRunInput): FirstRunTodos | null {return core.tryCall<FirstRunTodos>("firstRun.todos", { input }) ?? null;}@@ -112,7 +152,7 @@ const rank = (id: string) => {return i < 0 ? PREFERENCE.length : i;};-/** Without the core: the four screens in their plainest state. Not the+/** Without the core: the screens in their plainest state. Not the* product's behaviour; the demo and tests without wasm use it. */function fallbackView(input: FirstRunInput): FirstRunView {const place = input.hostOs === "macos" ? "this Mac" : input.hostOs === "windows" ? "this PC" : "this computer";@@ -120,21 +160,48 @@ function fallbackView(input: FirstRunInput): FirstRunView {const found = (input.agents ?? []).filter((a) => a.installed || a.configured).sort((a, b) => rank(a.agent) - rank(b.agent));const connected = found.filter((a) => a.configured || (input.picked ?? []).includes(a.agent));const lead = connected[0] ?? null;- const steps = ["welcome", "connect", "devices", "setup"] as const;+ const steps = firstRunSteps(input);+ // The permissions screen of a Mac that no longer asks shows Try it instead.+ const step: FirstRunStep = steps.includes(input.step) ? input.step : "setup";+ const at = Math.max(steps.indexOf(step), 0);const base: FirstRunView = {- step: input.step,+ step,later: "Skip for now",welcome: null,connect: null,devices: null,+ permissions: null,setup: null,- art: { agent: lead?.agent ?? found[0]?.agent ?? "other", computer: "on", extra: input.step === "welcome" ? "none" : "outline" },- dots: 4,- current: steps.indexOf(input.step),+ cli: null,+ art: { agent: lead?.agent ?? found[0]?.agent ?? "other", computer: "on", extra: step === "welcome" ? "none" : "outline" },+ steps,+ dots: steps.length,+ current: at,};- switch (input.step) {+ switch (step) {+ case "cli": {+ const name = input.cliName ?? "cua";+ const present = cliPresent(input.cli);+ const plan = input.cli?.plan ?? null;+ return {+ ...base,+ cli: {+ title: present ? "Cua is ready in Terminal." : "Use Cua from the Terminal.",+ lede: `Type ${name} in Terminal to make and use Spaces, for you and your agents.`,+ name,+ facts: plan ? [{ label: present ? "Installed at" : "Installs", value: input.cli?.installed ?? plan.target }] : [],+ status: present ? "Installed." : "Not installed.",+ installed: present,+ busy: Boolean(input.cli?.installing),+ tryCommand: present ? `${name} spaces ls` : null,+ error: input.cli?.error ? `Couldn't install it: ${input.cli.error}` : null,+ primary: present || !plan?.source ? { id: "continue", label: "Continue" } : { id: "install", label: "Install" },+ secondary: present || !plan?.source ? null : { id: "not-now", label: "Not now" },+ },+ };+ }case "welcome":- return { ...base, welcome: { title: "Your agents get their own computer.", lede: `Spaces on ${place}, away from your files and your mouse.`, primary: { id: "start", label: "Get started" } } };+ return { ...base, welcome: { title: "Your computers, shared by your team and its agents.", lede: `Run agents in Spaces on ${place}, or on any computer your team connects.`, primary: { id: "start", label: "Get started" } } };case "connect":return {...base,@@ -169,6 +236,33 @@ function fallbackView(input: FirstRunInput): FirstRunView {note: input.signedIn ? null : `${Place} works without it.`,},};+ case "permissions": {+ const host = input.host;+ const known = host?.configured && !input.hostSettingUp ? host : null;+ const rows = (+ [+ ["screen-recording", `See ${place}'s screen`, "So your team and agents can see what's on it.", "Privacy_ScreenCapture"],+ ["accessibility", "Use the mouse and keyboard", `So they can click and type on ${place}.`, "Privacy_Accessibility"],+ ] as const+ ).map(([id, title, note, pane]) => {+ const missing = known?.permissions.find((p) => p.id === id && !p.granted);+ if (!known) return { id, state: "checking" as const, title, note: `Adding ${place} to your account first…`, action: null, settingsUrl: null };+ if (!missing) return { id, state: "ok" as const, title, note: "Allowed", action: null, settingsUrl: null };+ return { id, state: "fix" as const, title, note, action: { id: "allow", label: "Allow" }, settingsUrl: missing.settingsUrl ?? `x-apple.systempreferences:com.apple.preference.security?${pane}` };+ });+ const all = rows.every((r) => r.state === "ok");+ return {+ ...base,+ permissions: {+ title: `Share ${place}'s screen.`,+ lede: `To let your team and agents see and use ${place}, allow two permissions.`,+ rows,+ note: `Allow opens System Settings and shows you where to turn on ${host?.appName || "Cua Spaces"}.`,+ primary: all ? { id: "continue", label: "Continue" } : null,+ secondary: all ? null : { id: "not-now", label: "Not now" },+ },+ };+ }case "setup":return {...base,@@ -331,7 +425,7 @@ export interface FirstRunUsage {help: string | null;}-const STEPS: FirstRunStep[] = ["welcome", "connect", "devices", "setup"];+const STEPS: FirstRunStep[] = ["welcome", "connect", "cli", "devices", "permissions", "setup"];export interface FirstRunHook {view: FirstRunView;@@ -348,7 +442,7 @@ export interface FirstRunHook {connect(agent: string): Promise<void>;/** Starts an agent's own sign-in on this computer (`codex login`). */signIn(agent: string): Promise<void>;- /** A screen's button: `start`, `continue`, `skip`, `not-now` (next screen), `sign-in`, `set-up`, `open-settings`, `copy`, `add`. */+ /** A screen's button: `start`, `continue`, `skip`, `not-now` (next screen), `install` (the CLI), `sign-in`, `set-up`, `open-settings`, `allow` (the app's guide to that System Settings pane), `copy`, `add`. */act(id: string, settingsUrl?: string | null): Promise<void>;/** Copies `text` (the tab shown), else the selected request. */copyPrompt(text?: string): Promise<void>;@@ -364,6 +458,82 @@ export interface FirstRunHook {back(): void;}+/** The first run's input with nothing read yet. */+const NO_INPUT: FirstRunInput = {+ step: "welcome",+ hostOs: "macos",+ agents: null,+ agent: null,+ picked: null,+ keys: null,+ agentSigningIn: null,+ agentSignInError: null,+ connecting: false,+ connectError: null,+ agentOpenBeforeSetup: null,+ agentUsedAt: null,+ signedIn: false,+ signingIn: false,+ host: null,+ hostSettingUp: false,+ offers: [],+ extra: { phase: "none" },+ plan: null,+};++export interface ScreenPermissions {+ view: FirstRunPermissionsView;+ /** A row's Allow: the app's guide to that System Settings pane. */+ allow(settingsUrl: string): Promise<void>;+}++/** Settings' "Permissions": the first run's two rows, live, on a Mac that+ * is set up and shares its screen (null anywhere else). */+export function useScreenPermissions(active = true, pollMs = FIRST_RUN_POLL_MS): ScreenPermissions | null {+ const ctx = useContext(BridgeContext);+ if (!ctx) throw new Error("bridge hooks need a <BridgeProvider> above them");+ const { core, adapter } = ctx;+ const [host, setHost] = useState<HostStatus | null>(null);+ useEffect(() => {+ if (!active || !adapter || hostOs() !== "macos") return;+ let live = true;+ const read = () =>+ void adapter+ .call("host.status", {})+ .then((h) => live && setHost(h))+ .catch(() => {});+ read();+ const timer = setInterval(read, pollMs);+ window.addEventListener("focus", read);+ return () => {+ live = false;+ clearInterval(timer);+ window.removeEventListener("focus", read);+ };+ }, [active, adapter, pollMs]);+ if (hostOs() !== "macos" || !adapter || !host?.configured || host.shareDesktop === false) return null;+ const input: FirstRunInput = {+ ...NO_INPUT,+ step: "permissions",+ signedIn: true,+ host: {+ configured: true,+ running: Boolean(host.service?.running),+ online: host.online ?? null,+ permissions: host.permissions.map((p) => ({ id: p.id, granted: Boolean(p.granted), settingsUrl: p.settingsUrl ?? null })),+ error: host.error ?? null,+ shareDesktop: host.shareDesktop ?? null,+ appName: host.appName ?? null,+ },+ };+ return {+ view: firstRunPermissions(core, input),+ allow: async (settingsUrl) => {+ await adapter.call("host.openSettings", { url: settingsUrl });+ },+ };+}+/** Live readings while `active` (the first run, or what reads its state). */export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunHook {const ctx = useContext(BridgeContext);@@ -391,6 +561,8 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunconst keysInput = agentKeys.unsupported || agentKeys.isLoading ? null : agentKeys.input;const [tick, setTick] = useState(0);const shownRef = useRef(false);+ // The app's bundled CLI: its install plan (read once a run shows), and Install's progress.+ const cli = useCliInstall(active);const signedIn = Boolean(session.data?.signedIn);const signingIn = session.data?.signIn.kind === "starting" || session.data?.signIn.kind === "waiting";@@ -411,7 +583,7 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRun.then((rows) => live && setAgents(rows)).catch(() => live && setAgents((a) => a ?? []));}- if (step === "devices" || step === "setup" || s.finishedLater) {+ if (step === "devices" || step === "permissions" || step === "setup" || s.finishedLater) {void adapter.call("host.status", {}).then((h) => live && setHost(h))@@ -496,12 +668,16 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunonline: host.online ?? null,permissions: host.permissions.map((p) => ({ id: p.id, granted: Boolean(p.granted), settingsUrl: p.settingsUrl ?? null })),error: setupError ?? host.error ?? null,+ shareDesktop: host.shareDesktop ?? null,+ appName: host.appName ?? null,}: null,hostSettingUp: settingUp,offers,extra: withoutFix(extra),plan,+ cli: cli.state,+ cliName: settings.data?.cli?.name ?? null,};// The lead connected agent (the core's order), for the try screen's access log.@@ -560,7 +736,10 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunconst go = (next: FirstRunStep) => {writeFirstRun(next === "setup" ? { step: next, setupStartedMs: readFirstRun().setupStartedMs ?? Date.now() } : { step: next });};- const forward = () => go(STEPS[Math.min(STEPS.indexOf(step) + 1, STEPS.length - 1)]!);+ // The screens this run shows (the core's): the CLI's only while it is missing.+ const shown = view.steps?.length ? view.steps : firstRunSteps(input);+ const at = Math.max(shown.indexOf(view.step), 0);+ const forward = () => go(shown[Math.min(at + 1, shown.length - 1)]!);const setUpThisComputer = async () => {if (!store || settingUp) return;@@ -578,7 +757,7 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRun// Signed in on a computer that isn't in the account yet: add it, once.const autoSetUp = useRef(false);useEffect(() => {- if (!active || (step !== "devices" && step !== "setup") || !signedIn || !host || host.configured || autoSetUp.current) return;+ if (!active || (step !== "devices" && step !== "permissions" && step !== "setup") || !signedIn || !host || host.configured || autoSetUp.current) return;autoSetUp.current = true;void setUpThisComputer();// eslint-disable-next-line react-hooks/exhaustive-deps@@ -669,6 +848,9 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRuncase "not-now":forward();break;+ case "install":+ await cli.install();+ break;case "sign-in":await session.signIn().catch(() => {});break;@@ -677,6 +859,8 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunawait setUpThisComputer();break;case "open-settings":+ case "allow":+ // A privacy pane: the Mac app guides it (PermissionFlow).if (settingsUrl && adapter) {await (settingsUrl.startsWith("x-apple.systempreferences:")? adapter.call("host.openSettings", { url: settingsUrl })@@ -706,7 +890,57 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunwriteFirstRun({ finishedLater: true });},back() {- go(STEPS[Math.max(STEPS.indexOf(step) - 1, 0)]!);+ go(shown[Math.max(at - 1, 0)]!);+ },+ };+}++/** The app's bundled CLI and its install (the Command line screen, Settings' row). */+export interface CliInstallHook {+ state: FirstRunCli;+ /** Installs it (adding its folder to PATH only when it is not there), then reads the plan and the settings again. */+ install(): Promise<void>;+}++/** Reads the install plan while `active` (a host without one leaves `plan` null). */+export function useCliInstall(active = true): CliInstallHook {+ const ctx = useContext(BridgeContext);+ if (!ctx) throw new Error("bridge hooks need a <BridgeProvider> above them");+ const { adapter, store } = ctx;+ const [plan, setPlan] = useState<CliInstallPlan | null>(null);+ const [installing, setInstalling] = useState(false);+ const [installed, setInstalled] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ if (!active || !adapter) return;+ let live = true;+ adapter+ .call("cli.plan", {})+ .then((p) => live && setPlan(p))+ .catch(() => live && setPlan(null));+ return () => {+ live = false;+ };+ }, [active, adapter]);+ return {+ state: { plan, installing, installed, error },+ async install() {+ if (!adapter || installing || !plan?.source) return;+ setInstalling(true);+ setError(null);+ let done: CliInstallPlan;+ try {+ done = await adapter.call("cli.install", { modifyPath: !plan.onPath });+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ setInstalling(false);+ return;+ }+ setInstalled(done.target);+ setPlan(done);+ setInstalling(false);+ // The pages' terminal hints follow the host's `settings.cli`.+ await store?.refresh("settings").catch(() => {});},};}diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex d06e608f79..3652016ea0 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -74,6 +74,7 @@ export {type AppearanceTheme,type HostEvent,type HostOperations,+ type CliInfo,type GlobalShortcut,type HostSettings,type OpName,@@ -180,15 +181,24 @@ export {FIRST_RUN_POLL_MS,TEAMMATES_KEY,UPSELL_DISMISSED_KEY,+ firstRunPermissions,firstRunTodos,firstRunView,+ firstRunCliView,+ firstRunSteps,+ cliMissing,+ cliPresent,+ useCliInstall,+ type CliInstallHook,noteTeammates,readFirstRun,resetFirstRunCache,useFirstRun,useFirstRunSaved,+ useScreenPermissions,writeFirstRun,type FirstRunHook,+ type ScreenPermissions,type FirstRunUsage,type FirstRunSaved,} from "./first-run";diff --git a/apps/cua-spaces-web/src/bridge/ops/cli.ts b/apps/cua-spaces-web/src/bridge/ops/cli.tsnew file mode 100644index 0000000000..67cde9bff5--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/ops/cli.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The app's bundled CLI on PATH: the first run's "Install the Cua CLI"+ * screen and Settings' Command line row. Both hosts run the app core's+ * installer (`cua-spaces-app-core/src/installer.rs`, through the FFI's+ * `AppCliInstaller`): `plan` reads what installing would do and writes+ * nothing; `install` writes only when the person pressed Install. What it+ * installs is the build channel's (`cua`, or `cua-local` for Cua Spaces+ * Local), and it adds the bin folder to PATH only when it is not there.+ *+ * | Operation | Electron | SwiftUI | Tauri |+ * |---|---|---|---|+ * | `cli.plan` | `AppCliInstaller.plan` (`src/bridge/cli.ts`) | `AppCliInstaller.plan` (`WebUIBridge+Cli.swift`) | unsupported |+ * | `cli.install {modifyPath}` | `AppCliInstaller.install` | `AppCliInstaller.install` | unsupported |+ *+ * After an install the host's `settings.get` names the CLI as installed+ * (`SettingsSnapshot.cli`), so the pages' terminal hints show.+ */++import { UnsupportedOperationError, type BridgeMode } from "../adapter";+import type { OpCoverage } from "../coverage";+import type { CliInstallPlan } from "../contracts/first-run";++export interface CliOps {+ /** What installing would do; null where this app carries no CLI to install. */+ "cli.plan": { args: Record<string, never>; result: CliInstallPlan | null };+ /** Installs it (after Install was pressed); `modifyPath` adds the bin folder to PATH. */+ "cli.install": { args: { modifyPath: boolean }; result: CliInstallPlan };+}++export const CLI_OPERATIONS = ["cli.plan", "cli.install"] as const satisfies readonly (keyof CliOps)[];++const TAURI = "the Tauri app installs the CLI on its own installer page (`installer_cli_plan`, `installer_install_cli`)";++export const CLI_COVERAGE = {+ "cli.plan": { webkit: { methods: ["cli.plan"] }, tauri: [], unsupported: { tauri: TAURI } },+ "cli.install": { webkit: { methods: ["cli.install"] }, tauri: [], unsupported: { tauri: TAURI } },+} as const satisfies Record<keyof CliOps, OpCoverage>;++/** A host that can't install the CLI. */+export function unsupportedCliOps(mode: BridgeMode) {+ const no = (op: keyof CliOps) => (): Promise<never> => Promise.reject(new UnsupportedOperationError(mode, op));+ return { "cli.plan": no("cli.plan"), "cli.install": no("cli.install") };+}++/** Arguments that take each down its usual path (coverage tests). */+export const CLI_ARGS = {+ "cli.plan": {},+ "cli.install": { modifyPath: true },+};diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex 279f659c4c..27b58d3327 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -50,6 +50,7 @@ import { RESOURCES_OPERATIONS, type ResourcesOps } from "./ops/resources";import { MACHINES_OPERATIONS, type MachinesOps } from "./ops/machines";import { CHECKLIST_OPERATIONS, type ChecklistOps } from "./ops/checklist";import { LINKS_OPERATIONS, type LinksOps } from "./ops/links";+import { CLI_OPERATIONS, type CliOps } from "./ops/cli";import { PRESENCE_OPERATIONS, type PresenceOps } from "./ops/presence";import { RUNTIME_FIX_OPERATIONS, type RuntimeFixOps } from "./ops/runtime-fix";import { TELEMETRY_OPERATIONS, type TelemetryOps } from "./ops/telemetry";@@ -110,6 +111,19 @@ export interface SettingsSnapshot {/** The host's account app (`https://app.cua.ai`, or staging's), which the* page's core cannot resolve itself. Absent or null: the production one. */accountUrl?: string | null;+ /** The CLI this app puts on PATH, for the pages' "run this in Terminal"+ * hints: its name (`CuaChannel::cli_name`, from the host's CLI install+ * plan) and whether it is on this computer. Absent or null: the host+ * can't say, and the hints stay hidden. */+ cli?: CliInfo | null;+}++/** `SettingsSnapshot.cli`. */+export interface CliInfo {+ /** The command to type (`cua` for the released app). */+ name: string;+ /** It is installed on this computer. */+ installed: boolean;}/** A system-wide shortcut the host registered (macOS: ⌘⇧Space). */@@ -208,6 +222,7 @@ export interface HostOperationsMachinesOps,ChecklistOps,LinksOps,+ CliOps,PresenceOps,RuntimeFixOps {"spaces.list": { args: Record<string, never>; result: SpaceRow[] };@@ -319,6 +334,7 @@ export const OPERATIONS = [...MACHINES_OPERATIONS,...CHECKLIST_OPERATIONS,...LINKS_OPERATIONS,+ ...CLI_OPERATIONS,...PRESENCE_OPERATIONS,...RUNTIME_FIX_OPERATIONS,...SETTINGS_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 8705d5504a..aa6296495c 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -170,6 +170,8 @@ export const WEBKIT_METHODS = ["links.list","links.create","links.stop",+ "cli.plan",+ "cli.install",] as const;export type WebkitMethod = (typeof WEBKIT_METHODS)[number];@@ -337,6 +339,9 @@ export interface WkSettings {globalShortcut?: { label: string; registered: boolean } | null;/** The host's account app (`app_account_app_url`); absent or null: none named. */accountUrl?: string | null;+ /** The CLI the app installs (its install plan's file name) and whether it+ * is on this computer; absent or null: not known. */+ cli?: { name: string; installed: boolean } | null;}/** `keyvault.*`: the core's page views, plus the overview (camelCase records). */@@ -382,4 +387,6 @@ export interface WkHostState {account?: { id?: string | null; email?: string | null; display?: string | null } | null;/** `HostModel.progress`: what a running setup or Sign In waits for. */progress?: string | null;+ /** The app's name as System Settings lists it ("Cua Spaces Local"). */+ appName?: string | null;}diff --git a/apps/cua-spaces-web/src/components/__tests__/empty-home.test.tsx b/apps/cua-spaces-web/src/components/__tests__/empty-home.test.tsxindex 592b15a020..9909af5ab5 100644--- a/apps/cua-spaces-web/src/components/__tests__/empty-home.test.tsx+++ b/apps/cua-spaces-web/src/components/__tests__/empty-home.test.tsx@@ -1,12 +1,12 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { BridgeProvider, emptyHome, type EmptyHome as EmptyHomeView } from "@/bridge";import type { DataAdapter } from "@/bridge/adapter";-import { createDemoAdapter } from "@/bridge/adapters/demo";+import { createDemoAdapter, type DemoOptions } from "@/bridge/adapters/demo";import type { CoreClient } from "@/bridge/core";import { readNewSpaceSession, resetNewSpaceSession, wizardView } from "@/bridge/new-space";import { noCore, testCore, wasmBuilt } from "@/bridge/__tests__/testCore";@@ -37,8 +37,8 @@ function stubCore(asked: unknown[] = []): CoreClient {} as unknown as CoreClient;}-function mount(core: CoreClient, home: EmptyHomeView) {- const base = createDemoAdapter({ latencyMs: 1, stepMs: 4, noSpaces: true });+function mount(core: CoreClient, home: EmptyHomeView, cli?: DemoOptions["cli"]) {+ const base = createDemoAdapter({ latencyMs: 1, stepMs: 4, noSpaces: true, cli });const created: unknown[] = [];// Records any create: a tile never starts one.const adapter = Object.assign(Object.create(base) as DataAdapter, {@@ -84,8 +84,31 @@ describe("the empty home's words", () => {expect(document.activeElement).toBe(linux);expect(linux.className).toContain("focus-visible:ring-2");expect(macos.className).toContain("hover:");- // The page header's New Space is the one.- expect(screen.getAllByRole("button")).toHaveLength(2);+ // The page header's New Space is the one (the rest copy terminal commands).+ expect(screen.getAllByRole("button").filter((b) => !b.hasAttribute("data-cli-copy"))).toHaveLength(2);+ });+});++describe("the empty home's terminal line", () => {+ const commands = () => [...document.querySelectorAll("[data-cli-command]")].map((c) => c.textContent);++ it("offers each system's create, copyable, under the released app's CLI", async () => {+ mount(stubCore(), emptyHome(stubCore(), "arm64", "macos")!);+ await waitFor(() => expect(commands()).toEqual(["cua spaces create linux --on local", "cua spaces create macos --on local"]));+ expect(screen.getByText("Prefer the terminal?")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Copy cua spaces create linux --on local" })).toBeTruthy();+ });++ it("names a Local build's CLI, as its host reports it", async () => {+ mount(stubCore(), emptyHome(stubCore(), "amd64", "linux")!, "local");+ await waitFor(() => expect(commands()).toEqual(["cua-local spaces create linux --on local"]));+ });++ it("stays hidden while the CLI is not installed", async () => {+ mount(stubCore(), emptyHome(stubCore(), "arm64", "macos")!, "missing");+ await new Promise((r) => setTimeout(r, 30));+ expect(screen.queryByText("Prefer the terminal?")).toBeNull();+ expect(commands()).toEqual([]);});});diff --git a/apps/cua-spaces-web/src/components/cli-hint.tsx b/apps/cua-spaces-web/src/components/cli-hint.tsxnew file mode 100644index 0000000000..b8cf23f38d--- /dev/null+++ b/apps/cua-spaces-web/src/components/cli-hint.tsx@@ -0,0 +1,89 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The terminal command next to a GUI action, for people who would rather+ * type it: quiet, copyable, and only where the app's CLI is on this+ * computer (`SettingsSnapshot.cli`). The commands are `lib/cli-commands.ts`'s.+ */++import { CheckIcon, CopyIcon } from "lucide-react";+import { useState } from "react";++import { useSettings } from "@/bridge";+import { Button } from "@/components/ui/button";+import { shownCli } from "@/lib/cli-commands";+import { cn } from "@/lib/utils";++/** The CLI to name in hints, or null when they stay hidden. */+export function useCliName(): string | null {+ return shownCli(useSettings().data?.cli);+}++function useCopy(text: string): [boolean, () => void] {+ const [copied, setCopied] = useState(false);+ const copy = () => {+ void navigator.clipboard?.writeText(text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1200);+ });+ };+ return [copied, copy];+}++function CopyButton({ text, className }: { text: string; className?: string }) {+ const [copied, copy] = useCopy(text);+ return (+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ data-cli-copy=""+ aria-label={copied ? "Copied" : `Copy ${text}`}+ title={copied ? "Copied" : "Copy"}+ onClick={copy}+ className={cn("size-6 shrink-0 text-muted-foreground hover:text-foreground", className)}+ >+ {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}+ </Button>+ );+}++/** The empty state's line: "Prefer the terminal?" and each command, copyable. */+export function CliHintLine({ commands, className }: { commands: string[]; className?: string }) {+ if (!commands.length) return null;+ return (+ <div data-cli-hint="line" className={cn("flex flex-wrap items-center justify-center gap-x-2 gap-y-1.5 text-xs text-muted-foreground", className)}>+ <span>Prefer the terminal?</span>+ {commands.map((command) => (+ <span key={command} className="inline-flex items-center rounded-md bg-foreground/[0.05] py-0.5 pr-0.5 pl-2">+ <code data-cli-command="" className="font-mono text-[11px] text-foreground/80 select-all">+ {command}+ </code>+ <CopyButton text={command} />+ </span>+ ))}+ </div>+ );+}++/** New Space's Summary block: "Or run this in Terminal", the commands, one copy. */+export function CliHintBlock({ commands }: { commands: string[] }) {+ const text = commands.join("\n");+ const [copied, copy] = useCopy(text);+ if (!commands.length) return null;+ return (+ <div data-cli-hint="block" className="mt-4">+ <div className="flex items-center justify-between px-1 pb-1.5">+ <span className="text-xs text-muted-foreground">Or run this in Terminal</span>+ <Button type="button" size="sm" variant="ghost" data-cli-copy="" onClick={copy} className="h-6 gap-1 px-1.5 text-xs text-muted-foreground hover:text-foreground">+ {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}+ {copied ? "Copied" : "Copy"}+ </Button>+ </div>+ <pre data-cli-command="" className="overflow-x-auto rounded-lg bg-foreground/[0.04] px-3 py-2.5 font-mono text-[11.5px] leading-[1.6] whitespace-pre-wrap [overflow-wrap:anywhere] text-foreground/85 select-all dark:bg-black/25">+ {text}+ </pre>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/components/empty-home.tsx b/apps/cua-spaces-web/src/components/empty-home.tsxindex b0a4395c50..852f847284 100644--- a/apps/cua-spaces-web/src/components/empty-home.tsx+++ b/apps/cua-spaces-web/src/components/empty-home.tsx@@ -8,14 +8,17 @@* and macOS on Apple silicon Macs) with its time and size from the core,* under the Spaces header (its New Space opens the wizard with nothing* chosen). A tile opens New Space with that system chosen, on this machine- * (the wizard says when it can't run here).+ * (the wizard says when it can't run here). Below them, the same creates+ * as terminal commands, when the app's CLI is installed.*/import { useNewSpaceWizard, type EmptyHome as EmptyHomeView, type EmptyTile } from "@/bridge";import { useEffect } from "react";+import { CliHintLine, useCliName } from "@/components/cli-hint";import { useFirstRunStep } from "@/components/first-run-guide";import { OsIcon } from "@/components/os-icon";+import { createAliasCommand } from "@/lib/cli-commands";/** `unread`: the host could not read the Spaces list (`listNotice`): the* title says so and no system is offered, as the SwiftUI app's does. */@@ -23,6 +26,9 @@ export function EmptyHome({ home, unread = false }: { home: EmptyHomeView; unreaconst wizard = useNewSpaceWizard();const start = (tile: EmptyTile) => wizard.show(null, tile.os);const step = useFirstRunStep();+ // The same creates in a terminal, when the app's CLI is on this computer.+ const cli = useCliName();+ const commands = cli ? home.tiles.map((tile) => createAliasCommand(cli, tile.os)) : [];useEffect(() => {if (!unread) step("guide_shown");// eslint-disable-next-line react-hooks/exhaustive-deps@@ -48,6 +54,7 @@ export function EmptyHome({ home, unread = false }: { home: EmptyHomeView; unrea<Tile key={tile.os} tile={tile} onStart={start} />))}</div>+ <CliHintLine commands={commands} className="mt-4" /></>)}</section>diff --git a/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsx b/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsxindex 6ddd6bc9b2..f194241358 100644--- a/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsx+++ b/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsx@@ -4,12 +4,14 @@import { CheckIcon, ChevronRightIcon, LoaderCircleIcon, TriangleAlertIcon } from "lucide-react";import { useEffect, useState, type ReactNode } from "react";-import { useBridge, useConnectCloud, useNewSpaceWizard, useSpaces, type RuntimeSwitch, type WizardAction, type WizardField, type WizardTile, type WizardView } from "@/bridge";+import { useBridge, useConnectCloud, useNewSpaceWizard, useSpaces, type CreateSpaceArgs, type RuntimeSwitch, type WizardAction, type WizardField, type WizardTile, type WizardView } from "@/bridge";+import { CliHintBlock, useCliName } from "@/components/cli-hint";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { toastError } from "@/components/ui/toast";+import { createCommand, openCommand } from "@/lib/cli-commands";import { macosLimitText } from "@/lib/spaces";import { cn } from "@/lib/utils";import { useCreateFromWizard } from "@/hooks/use-new-space";@@ -678,17 +680,39 @@ function OptionsStep({ v }: { v: WizardView }) {function SummaryStep({ v }: { v: WizardView }) {return (- <Group data-summary="">- {v.summary.map((fact) => (- <div key={fact.label} data-summary-row="" className="flex items-baseline justify-between gap-6 px-4 py-2 text-[13px]">- <span className="shrink-0 text-muted-foreground">{fact.label}</span>- <span className={cn("min-w-0 text-right break-all", fact.label === "Image" && "font-mono text-xs")}>{fact.value}</span>- </div>- ))}- </Group>+ <>+ <Group data-summary="">+ {v.summary.map((fact) => (+ <div key={fact.label} data-summary-row="" className="flex items-baseline justify-between gap-6 px-4 py-2 text-[13px]">+ <span className="shrink-0 text-muted-foreground">{fact.label}</span>+ <span className={cn("min-w-0 text-right break-all", fact.label === "Image" && "font-mono text-xs")}>{fact.value}</span>+ </div>+ ))}+ </Group>+ <SummaryCommands v={v} />+ </>);}+/** What Create does, as terminal commands (the create the core would make,+ * then opening it when "Open when it's ready" is on); only with the CLI+ * installed. */+function SummaryCommands({ v }: { v: WizardView }) {+ const { core } = useBridge();+ const cli = useCliName();+ if (!cli) return null;+ let args: CreateSpaceArgs | undefined;+ try {+ args = core.tryCall<CreateSpaceArgs>("wizard.createArgs", { plan: v.plan });+ } catch {+ args = undefined;+ }+ const create = args ? createCommand(cli, args) : null;+ if (!args || !create) return null;+ const open = v.plan.openWhenReady ? openCommand(cli, args) : null;+ return <CliHintBlock commands={open ? [create, open] : [create]} />;+}+/* ---- Connect by address ---------------------------------------------------- */function AddressStep({ v }: { v: WizardView }) {diff --git a/apps/cua-spaces-web/src/components/settings/cli-section.tsx b/apps/cua-spaces-web/src/components/settings/cli-section.tsxnew file mode 100644index 0000000000..f29bf0f840--- /dev/null+++ b/apps/cua-spaces-web/src/components/settings/cli-section.tsx@@ -0,0 +1,55 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Settings → Terminal: the app's bundled `cua`, as the first run's+ * "Use Cua from the Terminal" screen words it (`firstRun.cli`): where it is, or+ * the exact file Install writes, and Install. Shown where the host can read+ * the install plan (`cli.plan`).+ */++import { firstRunCliView, useBridge, useCliInstall, useSettings } from "@/bridge";+import { SettingsGroup, SettingsRow } from "@/components/settings-group";+import { Button } from "@/components/ui/button";++/** "~/.local/bin, in ~/.zshrc" as a sentence. */+function pathLine(value: string): string {+ const [dir, profile] = value.split(", in ");+ return profile ? `Install also adds ${dir} to your PATH in ${profile}.` : `Install also adds ${dir} to your PATH.`;+}++export function CliSettingsSection() {+ const { core } = useBridge();+ const cli = useCliInstall();+ const name = useSettings().data?.cli?.name ?? null;+ if (!cli.state.plan) return null;+ const view = firstRunCliView(core, { cli: cli.state, cliName: name });+ if (!view) return null;+ const install = view.primary?.id === "install" ? view.primary : null;+ const pathFact = view.facts.find((f) => f.label === "Adds to PATH");+ return (+ <SettingsGroup title="Terminal">+ <div data-settings-cli={view.installed ? "installed" : "missing"}>+ <SettingsRow+ label="Cua in Terminal"+ description={+ <>+ {view.status}+ {view.error ? <span className="mt-0.5 block text-destructive">{view.error}</span> : null}+ {!view.installed && pathFact ? <span className="mt-0.5 block">{pathLine(pathFact.value)}</span> : null}+ </>+ }+ control={+ install ? (+ <Button size="sm" variant="outline" disabled={view.busy} data-settings-cli-install="" onClick={() => void cli.install()}>+ {view.busy ? "Installing…" : install.label}+ </Button>+ ) : view.tryCommand ? (+ <code className="font-mono text-xs text-muted-foreground">{view.tryCommand}</code>+ ) : null+ }+ />+ </div>+ </SettingsGroup>+ );+}diff --git a/apps/cua-spaces-web/src/components/settings/screen-permissions-section.tsx b/apps/cua-spaces-web/src/components/settings/screen-permissions-section.tsxnew file mode 100644index 0000000000..43fdc669c3--- /dev/null+++ b/apps/cua-spaces-web/src/components/settings/screen-permissions-section.tsx@@ -0,0 +1,49 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { CheckIcon } from "lucide-react";++import { useScreenPermissions } from "@/bridge";+import { SettingsGroup, SettingsRow } from "@/components/settings-group";+import { Button } from "@/components/ui/button";+import { toastError } from "@/components/ui/toast";++/**+ * Settings, Permissions: the first run's "Share this Mac's screen" rows+ * (Screen Recording, Accessibility), for whoever chose "Not now" there.+ * Only on a Mac that is set up and shares its screen. Allow opens the app's+ * guide to the System Settings pane; a check shows once it is granted.+ */+export function ScreenPermissionsSection() {+ const perms = useScreenPermissions();+ if (!perms) return null;+ const { view } = perms;+ return (+ <SettingsGroup title="Permissions">+ {view.rows.map((r) => (+ <SettingsRow+ key={r.id}+ label={r.title}+ description={r.note}+ control={+ r.state === "ok" ? (+ <span className="flex size-5 items-center justify-center rounded-full bg-[#1f9d55] text-white" aria-label="Allowed" data-settings-permission={r.id} data-state="ok">+ <CheckIcon className="size-3" strokeWidth={3} />+ </span>+ ) : r.action && r.settingsUrl ? (+ <Button+ size="sm"+ variant="outline"+ data-settings-permission={r.id}+ data-state={r.state}+ onClick={() => void perms.allow(r.settingsUrl!).catch(toastError("Couldn't open System Settings"))}+ >+ {r.action.label}+ </Button>+ ) : null+ }+ />+ ))}+ </SettingsGroup>+ );+}diff --git a/apps/cua-spaces-web/src/lib/cli-commands.test.ts b/apps/cua-spaces-web/src/lib/cli-commands.test.tsnew file mode 100644index 0000000000..16a8a97ff1--- /dev/null+++ b/apps/cua-spaces-web/src/lib/cli-commands.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";++import type { CreateSpaceArgs } from "@/bridge";++import { createAliasCommand, createCommand, openCommand, shellWord, shownCli } from "./cli-commands";++// The names a host reports: the released app's, and a Local build's+// (`CuaChannel::cli_name`). The builder takes either as given.+const STABLE = "cua";+const LOCAL = "cua-local";++const linux: CreateSpaceArgs = { image: "ghcr.io/trycua/linux:24.04", on: "local", kind: "container", runtime: "auto", spacesd: true };+const macos: CreateSpaceArgs = { image: "ghcr.io/trycua/macos:26", on: "local", kind: "vm", runtime: "lume", spacesd: true };++describe("shownCli", () => {+ it("names the host's CLI only when it is installed", () => {+ expect(shownCli({ name: STABLE, installed: true })).toBe("cua");+ expect(shownCli({ name: LOCAL, installed: true })).toBe("cua-local");+ expect(shownCli({ name: STABLE, installed: false })).toBeNull();+ expect(shownCli({ name: " ", installed: true })).toBeNull();+ expect(shownCli(null)).toBeNull();+ expect(shownCli(undefined)).toBeNull();+ });+});++describe("the empty state's creates", () => {+ it("use the CLI's image aliases, under the channel's name", () => {+ expect(createAliasCommand(STABLE, "linux")).toBe("cua spaces create linux --on local");+ expect(createAliasCommand(STABLE, "macos")).toBe("cua spaces create macos --on local");+ expect(createAliasCommand(LOCAL, "linux")).toBe("cua-local spaces create linux --on local");+ expect(createAliasCommand(LOCAL, "macos")).toBe("cua-local spaces create macos --on local");+ });+});++describe("New Space's create", () => {+ it("names the image, the place and the kind; an automatic runtime is the CLI's default", () => {+ expect(createCommand(STABLE, linux)).toBe("cua spaces create ghcr.io/trycua/linux:24.04 --on local --kind container");+ expect(createCommand(LOCAL, linux)).toBe("cua-local spaces create ghcr.io/trycua/linux:24.04 --on local --kind container");+ });++ it("passes a chosen runtime, name, resources and GPU", () => {+ expect(createCommand(STABLE, { ...macos, name: "studio", cpus: 4, memoryMb: 8192, diskGb: 80, gpu: "paravirtual" })).toBe(+ "cua spaces create ghcr.io/trycua/macos:26 --on local --kind vm --runtime lume --name studio --cpus 4 --memory-mb 8192 --disk-gb 80 --gpu paravirtual",+ );+ expect(createCommand(LOCAL, { ...linux, kind: "vm", runtime: "qemu" })).toBe("cua-local spaces create ghcr.io/trycua/linux:24.04 --on local --kind vm --runtime qemu");+ });++ it("runs on another of your machines, or in your cloud", () => {+ expect(createCommand(STABLE, { ...linux, on: "host:0123abcd4567ef89" })).toBe("cua spaces create ghcr.io/trycua/linux:24.04 --on host:0123abcd4567ef89 --kind container");+ expect(createCommand(STABLE, { ...linux, on: "aws" })).toBe("cua spaces create ghcr.io/trycua/linux:24.04 --on aws --kind container");+ expect(createCommand(STABLE, { ...linux, on: "auto" })).toBe("cua spaces create ghcr.io/trycua/linux:24.04 --on auto --kind container");+ });++ it("quotes what the shell would split", () => {+ expect(createCommand(STABLE, { ...linux, name: "Dan's box" })).toBe(`cua spaces create ghcr.io/trycua/linux:24.04 --on local --kind container --name 'Dan'\\''s box'`);+ expect(shellWord("plain-name_1")).toBe("plain-name_1");+ expect(shellWord("two words")).toBe("'two words'");+ expect(shellWord("")).toBe("''");+ });++ it("shows nothing where the CLI can't create (Cua Cloud has ended, no machine picked)", () => {+ expect(createCommand(STABLE, { ...linux, on: "cloud" })).toBeNull();+ expect(createCommand(STABLE, { ...linux, on: "host:" })).toBeNull();+ expect(createCommand(STABLE, { ...linux, on: "" })).toBeNull();+ });+});++describe("opening the Space", () => {+ it("is `sb view NAME` for a named Space on this computer", () => {+ expect(openCommand(STABLE, { ...linux, name: "dev" })).toBe("cua sb view dev");+ expect(openCommand(LOCAL, { ...linux, name: "my space" })).toBe("cua-local sb view 'my space'");+ });++ it("is not offered without a name, or for another computer's Space", () => {+ expect(openCommand(STABLE, linux)).toBeNull();+ expect(openCommand(STABLE, { ...linux, name: "dev", on: "host:abc" })).toBeNull();+ });+});diff --git a/apps/cua-spaces-web/src/lib/cli-commands.ts b/apps/cua-spaces-web/src/lib/cli-commands.tsnew file mode 100644index 0000000000..7dea6a9669--- /dev/null+++ b/apps/cua-spaces-web/src/lib/cli-commands.ts@@ -0,0 +1,65 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The terminal commands that do what a New Space choice does, for people who+ * would rather type them. Every command and flag here is the `cua` CLI's own+ * (`cua spaces create --help`, `cua sb view --help`); nothing is shown that+ * the CLI does not take.+ *+ * The program's name is the host's (`SettingsSnapshot.cli`): `cua` for the+ * released app and the CLI name of the app's channel for another build+ * (`CuaChannel::cli_name` in cua-home), so a Local build's hints run Local's+ * CLI. The page never names a channel's CLI itself.+ */++import type { CliInfo, CreateSpaceArgs } from "@/bridge";++/** The CLI to show hints for: none when the host did not say, or the CLI is not installed. */+export function shownCli(cli: CliInfo | null | undefined): string | null {+ const name = cli?.name.trim();+ return cli?.installed && name ? name : null;+}++const PLAIN = /^[A-Za-z0-9_@%+=:,./-]+$/;++/** One shell word: as is when it needs no quoting, else in single quotes. */+export function shellWord(word: string): string {+ if (word && PLAIN.test(word)) return word;+ return `'${word.replaceAll("'", `'\\''`)}'`;+}++/** The empty state's create for one system: `cua spaces create linux --on local` (the CLI's image alias). */+export function createAliasCommand(cli: string, os: "linux" | "macos"): string {+ return `${cli} spaces create ${os} --on local`;+}++/**+ * `cua spaces create` with the image, place, kind, runtime, name, resources+ * and GPU New Space chose (`wizard.createArgs`). Null when the place is one+ * the CLI no longer creates on (`cloud`: Cua Cloud has ended) or is not+ * named yet.+ */+export function createCommand(cli: string, args: CreateSpaceArgs): string | null {+ const on = args.on.trim();+ if (!on || on === "cloud" || on === "host:") return null;+ const words = [cli, "spaces", "create", args.image, "--on", on, "--kind", args.kind];+ if (args.runtime && args.runtime !== "auto") words.push("--runtime", args.runtime);+ if (args.name?.trim()) words.push("--name", args.name.trim());+ if (args.cpus) words.push("--cpus", String(args.cpus));+ if (args.memoryMb) words.push("--memory-mb", String(args.memoryMb));+ if (args.diskGb) words.push("--disk-gb", String(args.diskGb));+ if (args.gpu) words.push("--gpu", args.gpu);+ return words.map((w, i) => (i < 3 ? w : shellWord(w))).join(" ");+}++/**+ * `cua sb view NAME`: opens a Space's desktop, as "Open when it's ready"+ * does. Only for a Space on this computer with a name (another computer's+ * Space is not a sandbox here).+ */+export function openCommand(cli: string, args: CreateSpaceArgs): string | null {+ const name = args.name?.trim();+ if (args.on !== "local" || !name) return null;+ return `${cli} sb view ${shellWord(name)}`;+}diff --git a/apps/cua-spaces-web/src/routes/onboarding/index.tsx b/apps/cua-spaces-web/src/routes/onboarding/index.tsxindex 4e49bfffe0..4f7f25fc58 100644--- a/apps/cua-spaces-web/src/routes/onboarding/index.tsx+++ b/apps/cua-spaces-web/src/routes/onboarding/index.tsx@@ -2,7 +2,7 @@// Copyright (c) 2026 Cua AI, Inc.import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";-import { CheckIcon, CopyIcon } from "lucide-react";+import { ArrowLeftIcon, CheckIcon, CopyIcon } from "lucide-react";import { useEffect, useState, type ReactNode } from "react";import { useAgentKeys, useFirstRun, type FirstRunArt, type FirstRunCredential, type FirstRunExtraView, type FirstRunHook, type FirstRunRow, type FirstRunView } from "@/bridge";@@ -33,7 +33,9 @@ export const Route = createFileRoute("/onboarding/")({/*** The first run, the same on macOS, Windows and Linux: Welcome, Pick your- * agent, Connect your other devices (optional), Try it in your agent. Every+ * agent, Install the Cua CLI (only while the app's CLI is not on this+ * computer), Connect your other devices (optional), Share this Mac's screen+ * (a signed-in Mac that shares it), Try it in your agent. Every* word, the agents' order and which button does what are the app core's* (`firstRun.view`, through `useFirstRun`); this file places them beside the* keycap art, as plain rows.@@ -61,13 +63,28 @@ function OnboardingPage() {document.querySelector<HTMLElement>("[data-onboarding-heading]")?.focus();}, [view.step]);+ // Esc goes back a step, like the "Back" link, on every step that has one.+ // An open sheet or menu keeps its own Esc.+ const canGoBack = view.step !== "welcome";+ useEffect(() => {+ if (!canGoBack) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== "Escape" || e.defaultPrevented || e.isComposing) return;+ if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')) return;+ e.preventDefault();+ fr.back();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [canGoBack, fr.back]);+return (<div className="relative flex h-full flex-col overflow-hidden bg-[#F4F5F7] dark:bg-[#07080a]" data-step={view.step}><Backdrop /><Art art={view.art} step={view.step} /><header className="relative z-30 flex shrink-0 items-center justify-between px-10 pt-[calc(var(--titlebar-height)+12px)] pb-2"><CuaWordmark />- <button type="button" onClick={leave} className="text-[13px] text-muted-foreground hover:text-foreground" data-onboarding-later="">+ <button type="button" onClick={leave} className={cn(QUIET_LINK, "text-[13px]")} data-onboarding-later="">{view.later}</button></header>@@ -75,7 +92,9 @@ function OnboardingPage() {<div className="my-auto flex max-w-[600px] flex-col py-6">{view.welcome ? <Welcome fr={fr} view={view} /> : null}{view.connect ? <Connect fr={fr} view={view} /> : null}+ {view.cli ? <CommandLine fr={fr} view={view} /> : null}{view.devices ? <Devices fr={fr} view={view} /> : null}+ {view.permissions ? <Permissions fr={fr} view={view} /> : null}{view.setup ? <Setup fr={fr} view={view} onFinish={() => void finish()} /> : null}</div></div>@@ -124,11 +143,39 @@ function Primary({ label, onClick, ...rest }: { label: string; onClick: () => vo);}-function Quiet({ label, onClick, ...rest }: { label: string; onClick: () => void } & Record<`data-${string}`, string | undefined>) {+/** The quieter choice beside the primary: the same pill, outlined, lower contrast. */+function Secondary({ label, onClick, describedBy, ...rest }: { label: string; onClick: () => void; describedBy?: string } & Record<`data-${string}`, string | undefined>) {return (- <button type="button" className="text-[13px] text-muted-foreground hover:text-foreground" onClick={onClick} {...rest}>+ <Button+ size="lg"+ variant="ghost"+ className="h-11 rounded-full border-foreground/20 px-6 text-[15px] font-normal text-foreground/75 hover:bg-foreground/[0.06] hover:text-foreground"+ aria-describedby={describedBy}+ data-first-run-secondary=""+ onClick={onClick}+ {...rest}+ >{label}- </button>+ </Button>+ );+}++const QUIET_LINK = "-mx-1.5 rounded-md px-1.5 py-0.5 text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60";++/**+ * A step after Welcome: "Back" sits above the heading, apart from the+ * step's own choices. It comes last in the page's order, so Tab goes+ * primary, then secondary, then Back; Esc does the same as Back.+ */+function Step({ id, onBack, children }: { id: string; onBack: () => void; children: ReactNode }) {+ return (+ <div data-first-run={id} className="flex flex-col">+ {children}+ <button type="button" onClick={onBack} aria-keyshortcuts="Escape" className={cn(QUIET_LINK, "order-first mb-5 inline-flex items-center gap-1.5 self-start text-[13px]")} data-first-run-back="">+ <ArrowLeftIcon aria-hidden className="size-3.5" />+ Back+ </button>+ </div>);}@@ -190,7 +237,7 @@ function Connect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {const keys = useAgentKeys();const [copied, setCopied] = useState(false);return (- <div data-first-run="connect">+ <Step id="connect" onBack={fr.back}><Heading>{c.title}</Heading><Lede>{c.lede}</Lede>{c.agents.length ? (@@ -270,10 +317,9 @@ function Connect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {{c.error}</p>) : null}- <div className="mt-6 flex items-center gap-4">+ <div className="mt-6 flex flex-wrap items-center gap-3"><Primary label={c.primary.label} onClick={() => void fr.act(c.primary.id)} />- {c.secondary ? <Quiet label={c.secondary.label} onClick={() => void fr.act(c.secondary!.id)} data-first-run-secondary="" /> : null}- <Quiet label="Back" onClick={fr.back} data-first-run-back="" />+ {c.secondary ? <Secondary label={c.secondary.label} onClick={() => void fr.act(c.secondary!.id)} /> : null}</div>{fr.usage ? (<label className="mt-5 flex items-center gap-2.5 text-[13px] text-muted-foreground" data-first-run-usage="">@@ -287,7 +333,7 @@ function Connect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {</label>) : null}{keys.sheet ? <KeySheet key={keys.sheet.provider} keys={keys} provider={keys.sheet.provider} env={keys.sheet.env} /> : null}- </div>+ </Step>);}@@ -322,7 +368,7 @@ function CredentialRowView({ row: r, onAct }: { row: FirstRunCredential; onAct:function Devices({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {const d = view.devices!;return (- <div data-first-run="devices">+ <Step id="devices" onBack={fr.back}><Heading>{d.title}</Heading><Lede>{d.lede}</Lede><Rows className="mt-6" data-first-run-devices="">@@ -334,17 +380,85 @@ function Devices({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {))}{d.status ? <StatusLine row={d.status} onAct={() => void fr.act(d.status!.action?.id ?? "")} /> : null}</Rows>- <div className="mt-7 flex items-center gap-4">+ <div className="mt-7 flex flex-wrap items-center gap-3"><Primary label={d.primary.label} onClick={() => void fr.act(d.primary.id)} data-first-run-devices-primary={d.primary.id} />- {d.secondary ? <Quiet label={d.secondary.label} onClick={() => void fr.act(d.secondary!.id)} data-first-run-secondary="" /> : null}- <Quiet label="Back" onClick={fr.back} data-first-run-back="" />+ {d.secondary ? <Secondary label={d.secondary.label} onClick={() => void fr.act(d.secondary!.id)} describedBy={d.note ? "first-run-devices-note" : undefined} /> : null}</div>- {d.note ? <p className="mt-4 text-[13px] text-muted-foreground">{d.note}</p> : null}- </div>+ {d.note ? (+ <p id="first-run-devices-note" className="mt-3 text-[13px] text-muted-foreground" data-first-run-devices-note="">+ {d.note}+ </p>+ ) : null}+ </Step>+ );+}++/* ---- Install the Cua CLI (only while it is missing) ----------------------------------- */++/** What Install writes (the exact file, and the PATH line when one is+ * needed), Install or Not now, and the result with a command to try. */+function CommandLine({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {+ const c = view.cli!;+ return (+ <Step id="cli" onBack={fr.back}>+ <Heading>{c.title}</Heading>+ <Lede>{c.lede}</Lede>+ <Rows className="mt-6" data-first-run-cli="">+ {c.facts.map((f) => (+ <div key={f.label} className="flex items-baseline gap-3 py-2.5 text-[14px]" data-first-run-cli-fact={f.label}>+ <span className="w-48 shrink-0">{f.label}</span>+ <code className="min-w-0 font-mono text-[13px] break-all text-muted-foreground">{f.value}</code>+ </div>+ ))}+ {c.installed && c.tryCommand ? (+ <div className="flex items-center gap-3 py-2.5" data-first-run-cli-done="">+ <StateIcon state="ok" />+ <div className="min-w-0 flex-1 text-[14px]">+ Open a new terminal window and try <code className="font-mono text-[13px]">{c.tryCommand}</code>+ </div>+ </div>+ ) : null}+ </Rows>+ {c.error ? (+ <p role="alert" className="mt-3 text-[13px] text-destructive" data-first-run-cli-error="">+ {c.error}+ </p>+ ) : null}+ <div className="mt-7 flex flex-wrap items-center gap-3">+ {c.primary ? (+ <Primary label={c.busy ? "Installing…" : c.primary.label} onClick={() => !c.busy && void fr.act(c.primary!.id)} data-first-run-cli-primary={c.primary.id} />+ ) : null}+ {c.secondary && !c.busy ? <Secondary label={c.secondary.label} onClick={() => void fr.act(c.secondary!.id)} /> : null}+ </div>+ </Step>);}-/* ---- 4 · Try it ---------------------------------------------------------------------- */+/* ---- 4 · Share this Mac's screen (a signed-in Mac that shares it) ------------------- */++function Permissions({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {+ const p = view.permissions!;+ return (+ <Step id="permissions" onBack={fr.back}>+ <Heading>{p.title}</Heading>+ <Lede>{p.lede}</Lede>+ <Rows className="mt-6" data-first-run-permissions="">+ {p.rows.map((r) => (+ <StatusLine key={r.id} row={r} onAct={r.action ? () => void fr.act(r.action!.id, r.settingsUrl) : undefined} />+ ))}+ </Rows>+ <p className="mt-3 text-[13px] text-muted-foreground" data-first-run-permissions-note="">+ {p.note}+ </p>+ <div className="mt-7 flex flex-wrap items-center gap-3">+ {p.primary ? <Primary label={p.primary.label} onClick={() => void fr.act(p.primary!.id)} data-first-run-permissions-primary={p.primary.id} /> : null}+ {p.secondary ? <Secondary label={p.secondary.label} onClick={() => void fr.act(p.secondary!.id)} data-first-run-permissions-secondary={p.secondary.id} /> : null}+ </div>+ </Step>+ );+}++/* ---- 5 · Try it ---------------------------------------------------------------------- */function Setup({ fr, view, onFinish }: { fr: FirstRunHook; view: FirstRunView; onFinish: () => void }) {const s = view.setup!;@@ -359,7 +473,7 @@ function Setup({ fr, view, onFinish }: { fr: FirstRunHook; view: FirstRunView; osetTimeout(() => setCopied(false), 1500);};return (- <div data-first-run="setup">+ <Step id="setup" onBack={fr.back}><Heading>{s.title}</Heading><Lede>{s.lede}</Lede>{s.prompt && tabs.length > 1 ? (@@ -400,13 +514,12 @@ function Setup({ fr, view, onFinish }: { fr: FirstRunHook; view: FirstRunView; o</div>) : null}{s.extra ? <ExtraCard extra={s.extra} fr={fr} /> : null}- <div className="mt-8 flex items-center gap-4">+ <div className="mt-8 flex items-center gap-3"><Button size="lg" className="h-11 min-w-28 rounded-full px-6 text-[15px]" disabled={!s.primary.enabled} data-onboarding-primary="" data-first-run-primary={s.primary.id} onClick={onFinish}>{s.primary.label}</Button>- <Quiet label="Back" onClick={fr.back} data-first-run-back="" /></div>- </div>+ </Step>);}@@ -451,7 +564,7 @@ function ExtraCard({ extra, fr }: { extra: FirstRunExtraView; fr: FirstRunHook }</button>))}{extra.action ? (- <button type="button" className="px-2 text-[14px] font-medium underline decoration-foreground/25 underline-offset-4" onClick={() => act(extra.action!.id)}>+ <button type="button" className="rounded-md px-2 text-[14px] font-medium underline decoration-foreground/25 underline-offset-4 outline-none focus-visible:ring-2 focus-visible:ring-ring/60" onClick={() => act(extra.action!.id)}>{extra.action.label}</button>) : null}diff --git a/apps/cua-spaces-web/src/routes/settings/index.tsx b/apps/cua-spaces-web/src/routes/settings/index.tsxindex c5a540d994..71b7da91d8 100644--- a/apps/cua-spaces-web/src/routes/settings/index.tsx+++ b/apps/cua-spaces-web/src/routes/settings/index.tsx@@ -24,6 +24,8 @@ import { writeSavedOnboarding } from "@/bridge/onboarding";import { SettingsGroup, SettingsRow } from "@/components/settings-group";import { AdvancedSection } from "@/components/settings/advanced-section";import { AgentsSettingsSection } from "@/components/settings/agents-section";+import { CliSettingsSection } from "@/components/settings/cli-section";+import { ScreenPermissionsSection } from "@/components/settings/screen-permissions-section";import { SharedLinks } from "@/components/links/shared-links";import { CoreSettingsRow, CoreSettingsSection } from "@/components/settings/core-section";import { Button } from "@/components/ui/button";@@ -153,6 +155,8 @@ function CoreGeneralPage({ page }: { page: CorePage }) {<GlobalShortcutRow shortcut={settings?.globalShortcut} /></SettingsGroup>+ <ScreenPermissionsSection />+<StorageSection />{runtimes?.rows.length ? <CoreSettingsSection section={runtimes} foldNotes onChoose={choose} /> : null}@@ -161,6 +165,8 @@ function CoreGeneralPage({ page }: { page: CorePage }) {{agents ? <AgentsSettingsSection section={agents} /> : null}+ <CliSettingsSection />+{/* The cua-driver skill for every agent (the SwiftUI app offers it in its first run). */}<SettingsGroup title="Background computer use"><Suspense fallback={<div className="h-48" />}>@@ -297,6 +303,8 @@ function FallbackSettingsPage() {<GlobalShortcutRow shortcut={settings?.globalShortcut} /></SettingsGroup>+ <ScreenPermissionsSection />+<StorageSection /><SettingsGroup title="Spaces">diff --git a/docs/content/docs/spaces/guides/install.mdx b/docs/content/docs/spaces/guides/install.mdxindex e584677594..6b0724d571 100644--- a/docs/content/docs/spaces/guides/install.mdx+++ b/docs/content/docs/spaces/guides/install.mdx@@ -62,7 +62,7 @@ The first time you open the app, it walks you through a short setup. The| Step | What it does ||---|---|-| Your agents get their own computer | The welcome. |+| Your computers, shared by your team and its agents | The welcome. || Pick your agent | The agents found on this computer, most used first (Hermes, Claude Code, Codex, Cursor, then the rest). Press **Connect** on each one you want; nothing is connected until you do. See [Connect your agent](/spaces/guides/connect-your-agent). || Connect your other devices | Optional. Signing in lets your other computers and your cloud reach this computer's Spaces. **Not now** skips it; this computer works without an account. || Try it in your agent | A request to paste into the agent you connected, which makes a Space on this computer. With no agent, a first Space in one click: Linux, or macOS on a Mac with Apple silicon. |diff --git a/docs/content/docs/spaces/quickstart.mdx b/docs/content/docs/spaces/quickstart.mdxindex fd5fdfd655..cf73aca246 100644--- a/docs/content/docs/spaces/quickstart.mdx+++ b/docs/content/docs/spaces/quickstart.mdx@@ -60,7 +60,7 @@ has the details for each system.## 2. Pick your agent-Open Cua Spaces. The first screen says "Your agents get their own computer."+Open Cua Spaces. The first screen says "Your computers, shared by your team and its agents."Press **Get started**.**Pick your agent** lists the agents found on this computer, such as Hermes,diff --git a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/codec_audio.rs b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/codec_audio.rsindex f441271654..c0d0916bcc 100644--- a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/codec_audio.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/codec_audio.rs@@ -61,7 +61,16 @@ impl CodecAudioProvider {/// server in the container, for example).pub fn new() -> Option<Self> {let capture = platform_capture().ok()?;- capture.sources().ok()?;+ // On macOS, listing the sources lists ScreenCaptureKit's shareable+ // content, which needs Screen Recording: without it macOS shows its+ // own prompt, at every service start, over whatever the person is+ // doing (Cua Spaces' first run among them). The app asks for the+ // permission in its own words, so probe only once it is granted;+ // until then the provider still exists and a stream lists the+ // sources when it opens.+ if screen_capture_allowed() {+ capture.sources().ok()?;+ }let opus = open_audio_encoder(&AudioEncodingConfig::downlink()).is_ok();Some(Self { capture, opus })}@@ -299,3 +308,21 @@ impl AudioProvider for CodecAudioProvider {}}}++/// Screen Recording is granted to this process (macOS; elsewhere always),+/// read without asking (`CGPreflightScreenCaptureAccess` never prompts).+fn screen_capture_allowed() -> bool {+ #[cfg(target_os = "macos")]+ {+ #[link(name = "CoreGraphics", kind = "framework")]+ unsafe extern "C" {+ fn CGPreflightScreenCaptureAccess() -> bool;+ }+ // SAFETY: no arguments; reads this process's TCC state.+ unsafe { CGPreflightScreenCaptureAccess() }+ }+ #[cfg(not(target_os = "macos"))]+ {+ true+ }+}diff --git a/libs/cua/crates/cua-spaces-app-core/parity/first-run.json b/libs/cua/crates/cua-spaces-app-core/parity/first-run.jsonindex 605363cac0..7264843d3f 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/first-run.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/first-run.json@@ -1,6 +1,6 @@{"name": "first-run",- "about": "The agent-first first run, one screen state per storyboard frame: Welcome; Pick your agent (only the agents found here, most preferred first: Hermes, Claude Code, Codex, Cursor, then the rest; one Connect each, none connected by itself, each naming the file it changes; the connected agents' own sign-ins and keys in the same order; nothing found: install an agent or use the CLI); Connect your other devices (optional sign-in: your other computers and your cloud, Not now); and Try it in the lead agent (a request to paste, waiting until the agent used Cua; no agent: a one-click first Space, Linux first, then Omarchy and macOS only where they run and fit). No plan is shown. Home's to-do list after Skip for now treats signing in as optional. Each case patches the base input; every app draws firstRun.view's words and must say the same.",+ "about": "The agent-first first run, one screen state per storyboard frame: Welcome; Pick your agent (only the agents found here, most preferred first: Hermes, Claude Code, Codex, Cursor, then the rest; one Connect each, none connected by itself, each naming the file it changes; the connected agents' own sign-ins and keys in the same order; nothing found: install an agent or use the CLI); Connect your other devices (optional sign-in: your other computers and your cloud, Not now); on a signed-in Mac that shares its screen, Share this Mac's screen (Screen Recording and Accessibility, Allow each, a check once granted, Not now); and Try it in the lead agent (a request to paste, waiting until the agent used Cua; no agent: a one-click first Space, Linux first, then Omarchy and macOS only where they run and fit). No plan is shown. Home's to-do list after Skip for now treats signing in as optional. Each case patches the base input; every app draws firstRun.view's words and must say the same. Install the Cua CLI shows between Pick your agent and Connect your other devices only while the app's bundled CLI is not on this computer (a disk-image install): the exact file, the PATH line when one is needed, Install or Not now, and the result; Local builds name cua-local.","base": {"step": "welcome","hostOs": "macos",@@ -38,6 +38,23 @@{ "name": "15 no agent: a first Space", "patch": { "step": "setup", "agents": [{ "agent": "claude-code", "name": "Claude Code", "installed": false, "configured": false }, { "agent": "codex", "name": "OpenAI Codex", "installed": false, "configured": false }] }, "todos": true },{ "name": "16 no agent: making macOS", "patch": { "step": "setup", "agents": [{ "agent": "claude-code", "name": "Claude Code", "installed": false, "configured": false }, { "agent": "codex", "name": "OpenAI Codex", "installed": false, "configured": false }], "extra": { "phase": "creating", "name": "macOS 1", "os": "macos", "detail": "Downloading macOS · 4.2 of 22.3 GB · 85 MB/s · about 4 min", "fraction": 0.19 } } },{ "name": "17 no agent: an Intel Mac, Linux only", "patch": { "step": "setup", "agents": [{ "agent": "claude-code", "name": "Claude Code", "installed": false, "configured": false }, { "agent": "codex", "name": "OpenAI Codex", "installed": false, "configured": false }], "offers": [{ "os": "linux", "time": "about 2 min" }, { "os": "macos", "time": "10 to 30 min the first time", "blocked": "This Mac can't run macOS Spaces: they need Apple silicon." }] } },- { "name": "18 to-do list, signed in, a permission missing", "patch": { "step": "setup", "picked": ["claude-code"], "signedIn": true, "host": { "configured": true, "running": true, "online": true, "permissions": [{ "id": "accessibility", "granted": false, "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" }] } }, "todos": true }+ { "name": "18 to-do list, signed in, a permission missing", "patch": { "step": "setup", "picked": ["claude-code"], "signedIn": true, "host": { "configured": true, "running": true, "online": true, "permissions": [{ "id": "accessibility", "granted": false, "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" }] } }, "todos": true },+ {"name": "cli 01 a disk-image install offers the CLI screen", "steps": true, "patch": {"step": "connect", "cli": {"plan": {"source": "/Applications/Cua Spaces.app/Contents/MacOS/cua", "target": "/Users/ada/.local/bin/cua", "binDir": "/Users/ada/.local/bin", "method": "symlink", "installed": false, "upToDate": false, "onPath": false, "pathProfile": "/Users/ada/.zshrc", "pathLine": "export PATH=\"/Users/ada/.local/bin:$PATH\"", "found": null}}}},+ {"name": "cli 02 install the Cua CLI", "steps": true, "patch": {"step": "cli", "cli": {"plan": {"source": "/Applications/Cua Spaces.app/Contents/MacOS/cua", "target": "/Users/ada/.local/bin/cua", "binDir": "/Users/ada/.local/bin", "method": "symlink", "installed": false, "upToDate": false, "onPath": false, "pathProfile": "/Users/ada/.zshrc", "pathLine": "export PATH=\"/Users/ada/.local/bin:$PATH\"", "found": null}}}},+ {"name": "cli 03 installing", "patch": {"step": "cli", "cli": {"plan": {"source": "/Applications/Cua Spaces.app/Contents/MacOS/cua", "target": "/Users/ada/.local/bin/cua", "binDir": "/Users/ada/.local/bin", "method": "symlink", "installed": false, "upToDate": false, "onPath": false, "pathProfile": "/Users/ada/.zshrc", "pathLine": "export PATH=\"/Users/ada/.local/bin:$PATH\"", "found": null}, "installing": true}}},+ {"name": "cli 04 install failed", "patch": {"step": "cli", "cli": {"plan": {"source": "/Applications/Cua Spaces.app/Contents/MacOS/cua", "target": "/Users/ada/.local/bin/cua", "binDir": "/Users/ada/.local/bin", "method": "symlink", "installed": false, "upToDate": false, "onPath": false, "pathProfile": "/Users/ada/.zshrc", "pathLine": "export PATH=\"/Users/ada/.local/bin:$PATH\"", "found": null}, "error": "permission denied"}}},+ {"name": "cli 05 installed", "steps": true, "patch": {"step": "cli", "cli": {"plan": {"source": "/Applications/Cua Spaces.app/Contents/MacOS/cua", "target": "/Users/ada/.local/bin/cua", "binDir": "/Users/ada/.local/bin", "method": "symlink", "installed": false, "upToDate": false, "onPath": false, "pathProfile": "/Users/ada/.zshrc", "pathLine": "export PATH=\"/Users/ada/.local/bin:$PATH\"", "found": null}, "installed": "/Users/ada/.local/bin/cua"}}},+ {"name": "cli 06 already installed: no CLI screen", "steps": true, "patch": {"step": "connect", "cli": {"plan": {"source": "/Applications/Cua Spaces.app/Contents/MacOS/cua", "target": "/Users/ada/.local/bin/cua", "binDir": "/Users/ada/.local/bin", "method": "symlink", "installed": true, "upToDate": true, "onPath": true, "pathProfile": null, "pathLine": null, "found": "/Users/ada/.local/bin/cua"}}}},+ {"name": "cli 07 Cua Spaces Local installs cua-local", "patch": {"step": "cli", "cli": {"plan": {"source": "/Users/ada/Applications/Cua Spaces Local.app/Contents/MacOS/cua", "target": "/Users/ada/.local/bin/cua-local", "binDir": "/Users/ada/.local/bin", "method": "symlink", "installed": false, "upToDate": false, "onPath": true, "pathProfile": null, "pathLine": null, "found": null}}}},+ {"name": "cli 08 Local's no-agent CLI line names cua-local", "patch": {"step": "connect", "agents": [], "cliName": "cua-local"}},+ { "name": "19 this Mac in the account, Continue goes to permissions", "patch": { "step": "devices", "signedIn": true, "host": { "configured": true, "running": true, "online": true, "permissions": [{ "id": "screen-recording", "granted": false, "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" }, { "id": "accessibility", "granted": false, "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" }] } }, "steps": true },+ { "name": "20 permissions, this Mac still being added", "patch": { "step": "permissions", "signedIn": true, "hostSettingUp": true, "host": { "configured": false, "running": false, "permissions": [] } }, "steps": true },+ { "name": "21 permissions, both missing (Cua Spaces Local)", "patch": { "step": "permissions", "signedIn": true, "host": { "configured": true, "running": true, "online": true, "appName": "Cua Spaces Local", "permissions": [{ "id": "screen-recording", "granted": false, "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" }, { "id": "accessibility", "granted": false, "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" }] } }, "steps": true },+ { "name": "22 permissions, Screen Recording allowed", "patch": { "step": "permissions", "signedIn": true, "host": { "configured": true, "running": true, "online": true, "appName": "Cua Spaces", "permissions": [{ "id": "accessibility", "granted": false, "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" }] } }, "steps": true },+ { "name": "23 permissions, both allowed", "patch": { "step": "permissions", "signedIn": true, "host": { "configured": true, "running": true, "online": true, "appName": "Cua Spaces", "permissions": [] } }, "steps": true },+ { "name": "24 try it after permissions, Back goes to permissions", "patch": { "step": "setup", "picked": ["hermes"], "signedIn": true, "host": { "configured": true, "running": true, "online": true, "permissions": [] } }, "steps": true },+ { "name": "25 not signed in: Not now skips permissions", "patch": { "step": "devices" }, "steps": true },+ { "name": "26 a Mac kept for Spaces only: no permissions screen", "patch": { "step": "permissions", "picked": ["hermes"], "signedIn": true, "host": { "configured": true, "running": true, "online": true, "shareDesktop": false, "permissions": [] } }, "steps": true },+ { "name": "27 a Windows PC: no permissions screen", "patch": { "step": "devices", "hostOs": "windows", "signedIn": true, "host": { "configured": true, "running": true, "online": true, "permissions": [] } }, "steps": true }]}diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.jsonindex fcc4dad853..e65d83644c 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json@@ -6,9 +6,9 @@"case": "01 welcome","step": "welcome","welcome": {- "lede": "Spaces on this Mac, away from your files and your mouse.",+ "lede": "Run agents in Spaces on this Mac, or on any computer your team connects.","primary": "start:Get started",- "title": "Your agents get their own computer."+ "title": "Your computers, shared by your team and its agents."}},{@@ -92,7 +92,7 @@"agents": [],"alternatives": ["install: Install an agent — Hermes, Claude Code, OpenAI Codex or Cursor, then come back here. <https://cua.ai/docs/spaces/guides/connect-your-agent>",- "cli: Use the CLI — Make a Space on this Mac from a terminal. `cua spaces create linux`"+ "cli: Use the CLI — Make a Space on this Mac from a terminal. `cua spaces create linux --on local`"],"credentials": null,"error": null,@@ -336,6 +336,378 @@"lede": "A couple of things are left.","progress": "1 of 5 done"}+ },+ {+ "art": "hermes on outline",+ "case": "cli 01 a disk-image install offers the CLI screen",+ "connect": {+ "agents": [+ "Hermes (~/.hermes/config.yaml) connect:Connect",+ "Claude Code (~/.claude.json) connect:Connect",+ "OpenAI Codex (~/.codex/config.toml) connect:Connect"+ ],+ "alternatives": [],+ "credentials": null,+ "error": null,+ "lede": "Found on this Mac. You can add more later.",+ "primary": "continue:Continue",+ "secondary": "skip:Skip",+ "title": "Pick your agent."+ },+ "step": "connect",+ "steps": [+ "welcome",+ "connect",+ "cli",+ "devices",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "cli 02 install the Cua CLI",+ "cli": {+ "error": null,+ "facts": [+ "Installs: ~/.local/bin/cua",+ "Adds to PATH: ~/.local/bin, in ~/.zshrc"+ ],+ "lede": "Type cua in Terminal to make and use Spaces, for you and your agents.",+ "primary": "install:Install",+ "secondary": "not-now:Not now",+ "status": "Not installed. Install puts it at ~/.local/bin/cua.",+ "title": "Use Cua from the Terminal.",+ "try": null+ },+ "step": "cli",+ "steps": [+ "welcome",+ "connect",+ "cli",+ "devices",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "cli 03 installing",+ "cli": {+ "error": null,+ "facts": [+ "Installs: ~/.local/bin/cua",+ "Adds to PATH: ~/.local/bin, in ~/.zshrc"+ ],+ "lede": "Type cua in Terminal to make and use Spaces, for you and your agents.",+ "primary": "install:Installing…",+ "secondary": "not-now:Not now",+ "status": "Installing…",+ "title": "Use Cua from the Terminal.",+ "try": null+ },+ "step": "cli"+ },+ {+ "art": "hermes on outline",+ "case": "cli 04 install failed",+ "cli": {+ "error": "Couldn't install it: permission denied",+ "facts": [+ "Installs: ~/.local/bin/cua",+ "Adds to PATH: ~/.local/bin, in ~/.zshrc"+ ],+ "lede": "Type cua in Terminal to make and use Spaces, for you and your agents.",+ "primary": "install:Try again",+ "secondary": "not-now:Not now",+ "status": "Not installed. Install puts it at ~/.local/bin/cua.",+ "title": "Use Cua from the Terminal.",+ "try": null+ },+ "step": "cli"+ },+ {+ "art": "hermes on outline",+ "case": "cli 05 installed",+ "cli": {+ "error": null,+ "facts": [+ "Installed at: ~/.local/bin/cua"+ ],+ "lede": "Type cua in Terminal to make and use Spaces, for you and your agents.",+ "primary": "continue:Continue",+ "secondary": "",+ "status": "Installed at ~/.local/bin/cua.",+ "title": "Cua is ready in Terminal.",+ "try": "cua spaces ls"+ },+ "step": "cli",+ "steps": [+ "welcome",+ "connect",+ "cli",+ "devices",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "cli 06 already installed: no CLI screen",+ "connect": {+ "agents": [+ "Hermes (~/.hermes/config.yaml) connect:Connect",+ "Claude Code (~/.claude.json) connect:Connect",+ "OpenAI Codex (~/.codex/config.toml) connect:Connect"+ ],+ "alternatives": [],+ "credentials": null,+ "error": null,+ "lede": "Found on this Mac. You can add more later.",+ "primary": "continue:Continue",+ "secondary": "skip:Skip",+ "title": "Pick your agent."+ },+ "step": "connect",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "cli 07 Cua Spaces Local installs cua-local",+ "cli": {+ "error": null,+ "facts": [+ "Installs: ~/.local/bin/cua-local"+ ],+ "lede": "Type cua-local in Terminal to make and use Spaces, for you and your agents.",+ "primary": "install:Install",+ "secondary": "not-now:Not now",+ "status": "Not installed. Install puts it at ~/.local/bin/cua-local.",+ "title": "Use Cua from the Terminal.",+ "try": null+ },+ "step": "cli"+ },+ {+ "art": "other on outline",+ "case": "cli 08 Local's no-agent CLI line names cua-local",+ "connect": {+ "agents": [],+ "alternatives": [+ "install: Install an agent — Hermes, Claude Code, Codex or Cursor, then come back here. <https://cua.ai/docs/spaces/guides/connect-your-agent>",+ "cli: Use the CLI — Make a Space on this Mac from a terminal. `cua-local spaces create linux --on local`"+ ],+ "credentials": null,+ "error": null,+ "lede": "No agents found on this Mac.",+ "primary": "continue:Continue",+ "secondary": "skip:Skip",+ "title": "Connect an agent."+ },+ "step": "connect"+ },+ {+ "art": "hermes on outline",+ "case": "19 this Mac in the account, Continue goes to permissions",+ "devices": {+ "lede": "Sign in on your other computers, and they reach its Spaces.",+ "note": null,+ "primary": "continue:Continue",+ "rows": [+ "Your other computers — They join this Mac's pool",+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"+ ],+ "secondary": "",+ "status": "[ok] This Mac is in your account — Your other computers can reach its Spaces.",+ "title": "This Mac is in your account."+ },+ "step": "devices",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "permissions",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "20 permissions, this Mac still being added",+ "permissions": {+ "lede": "To let your team and agents see and use this Mac, allow two permissions.",+ "note": "Allow opens System Settings and shows you where to turn on Cua Spaces.",+ "primary": "",+ "rows": [+ "[checking] See this Mac's screen — Adding this Mac to your account first…",+ "[checking] Use the mouse and keyboard — Adding this Mac to your account first…"+ ],+ "secondary": "not-now:Not now",+ "title": "Share this Mac's screen."+ },+ "step": "permissions",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "permissions",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "21 permissions, both missing (Cua Spaces Local)",+ "permissions": {+ "lede": "To let your team and agents see and use this Mac, allow two permissions.",+ "note": "Allow opens System Settings and shows you where to turn on Cua Spaces Local.",+ "primary": "",+ "rows": [+ "[fix] See this Mac's screen — So your team and agents can see what's on it. (allow:Allow) <x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture>",+ "[fix] Use the mouse and keyboard — So they can click and type on this Mac. (allow:Allow) <x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility>"+ ],+ "secondary": "not-now:Not now",+ "title": "Share this Mac's screen."+ },+ "step": "permissions",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "permissions",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "22 permissions, Screen Recording allowed",+ "permissions": {+ "lede": "To let your team and agents see and use this Mac, allow two permissions.",+ "note": "Allow opens System Settings and shows you where to turn on Cua Spaces.",+ "primary": "",+ "rows": [+ "[ok] See this Mac's screen — Allowed",+ "[fix] Use the mouse and keyboard — So they can click and type on this Mac. (allow:Allow) <x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility>"+ ],+ "secondary": "not-now:Not now",+ "title": "Share this Mac's screen."+ },+ "step": "permissions",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "permissions",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "23 permissions, both allowed",+ "permissions": {+ "lede": "To let your team and agents see and use this Mac, allow two permissions.",+ "note": "Allow opens System Settings and shows you where to turn on Cua Spaces.",+ "primary": "continue:Continue",+ "rows": [+ "[ok] See this Mac's screen — Allowed",+ "[ok] Use the mouse and keyboard — Allowed"+ ],+ "secondary": "",+ "title": "Share this Mac's screen."+ },+ "step": "permissions",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "permissions",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "24 try it after permissions, Back goes to permissions",+ "setup": {+ "extra": null,+ "lede": "Paste this. Hermes makes the Space itself.",+ "primary": "done:Done",+ "prompt": "Paste this in Hermes: Make a Linux Space on this Mac and stream the desktop in a new window. / It runs on this Mac.",+ "status": "[checking] Waiting for Hermes… — If Hermes was already open, restart it.",+ "title": "Try it in Hermes."+ },+ "step": "setup",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "permissions",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "25 not signed in: Not now skips permissions",+ "devices": {+ "lede": "Sign in once, and your other computers reach this Mac's Spaces.",+ "note": "This Mac works without it.",+ "primary": "sign-in:Sign in to connect",+ "rows": [+ "Your other computers — They join this Mac's pool",+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"+ ],+ "secondary": "not-now:Not now",+ "status": null,+ "title": "Connect your other devices."+ },+ "step": "devices",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "26 a Mac kept for Spaces only: no permissions screen",+ "setup": {+ "extra": null,+ "lede": "Paste this. Hermes makes the Space itself.",+ "primary": "done:Done",+ "prompt": "Paste this in Hermes: Make a Linux Space on this Mac and stream the desktop in a new window. / It runs on this Mac.",+ "status": "[checking] Waiting for Hermes… — If Hermes was already open, restart it.",+ "title": "Try it in Hermes."+ },+ "step": "setup",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "setup"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "27 a Windows PC: no permissions screen",+ "devices": {+ "lede": "Sign in on your other computers, and they reach its Spaces.",+ "note": null,+ "primary": "continue:Continue",+ "rows": [+ "Your other computers — They join this PC's pool",+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"+ ],+ "secondary": "",+ "status": "[ok] This PC is in your account — Your other computers can reach its Spaces.",+ "title": "This PC is in your account."+ },+ "step": "devices",+ "steps": [+ "welcome",+ "connect",+ "devices",+ "setup"+ ]}]}diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex f424a153d2..979e9b0817 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -315,8 +315,10 @@ pub const METHODS: &[&str] = &["upsell.allows","firstRun.view","firstRun.todos",+ "firstRun.permissions","firstRun.agentUsed","firstRun.leadAgent",+ "firstRun.cli","telemetry.upsell","nudge.secondAgent","nudge.riskyAction",@@ -550,7 +552,9 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {}"upsell.allows" => out(upsell::allows(&a.get("state")?)),"firstRun.view" => out(crate::first_run::view(&a.get("input")?)),+ "firstRun.cli" => out(crate::first_run::cli_view(&a.get("input")?)),"firstRun.todos" => out(crate::first_run::todos(&a.get("input")?)),+ "firstRun.permissions" => out(crate::first_run::permissions_view(&a.get("input")?)),"firstRun.agentUsed" => out(crate::first_run::agent_used(&a.get::<Vec<crate::first_run::AccessLine>>("lines")?,a.get::<u64>("sinceMs")?,diff --git a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs b/libs/cua/crates/cua-spaces-app-core/src/first_run.rsindex f71015eb9f..9989233ce0 100644--- a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs@@ -1,27 +1,39 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-//! The first run every app shows: four short screens, agent first.+//! The first run every app shows: a few short screens, agent first.//!-//! 1. **Welcome.** "Your agents get their own computer." One button.+//! 1. **Welcome.** "Your computers, shared by your team and its agents." One button.//! 2. **Pick your agent.** The agents found on this computer, in the order//! [`PREFERENCE`] gives (Hermes, Claude Code, Codex, Cursor, then the//! rest), one Connect each. Nothing is connected until its button is//! pressed, and each row names the file Cua changes. The connected//! agents' own sign-ins and keys follow, in the same order. Nothing//! found: install an agent, or use the CLI.+//! Then **Install the Cua CLI**, only while the app's bundled CLI is not+//! on this computer (an app installed from the disk image has none on+//! PATH): what it installs and the exact file, Install or Not now, and+//! the result. It is the app's install plan ([`crate::installer`]):+//! nothing is written before Install, and the file is the channel's+//! (`cua`, or `cua-local` for Cua Spaces Local).//! 3. **Connect your other devices** (optional). Signing in lets your other//! computers and your cloud reach this computer's Spaces. "Not now" skips//! it: this computer works without an account.-//! 4. **Try it in your agent.** A first request for the lead connected agent+//! 4. **Share this Mac's screen** (only a signed-in Mac that shares its+//! screen). Screen Recording and Accessibility, one row each, with Allow+//! (the app's guide to the System Settings pane) and a check once+//! granted; "Not now" leaves them for Settings. macOS's own prompts never+//! show first: the app asks here, in its own words.+//! 5. **Try it in your agent.** A first request for the lead connected agent//! (read-only, with Copy) that makes a Space on this computer, and a line//! that turns green when the agent used Cua. No agent: a one-click first//! Space instead.//!-//! Nothing starts or connects by itself, permissions are asked where a task-//! needs them (not here), and no plan is shown. The words, the order and-//! which button does what are decided here, so every app says the same-//! thing; the page gathers the readings and draws what [`view`] returns.+//! Nothing starts or connects by itself, permissions are asked only on a Mac+//! that shares its screen (screen 4), and no plan is shown. The words, the+//! order and which button does what are decided here, so every app says the+//! same thing; the page gathers the readings and draws what [`view`]+//! returns.//!//! What each reading is, and how real it is://!@@ -61,13 +73,23 @@ const TRY_PROMPT_OTHER: &str ="Make a Linux Space on this computer and stream the desktop in a new window.";const TRY_PROMPT_PC: &str = "Make a Linux Space on this PC and stream the desktop in a new window.";-/// The same first Space from a terminal (no agent found).-pub const CLI_FIRST_SPACE: &str = "cua spaces create linux";+/// The CLI's name when the host did not say (the released app's,+/// `CuaChannel::cli_name`). A Local build's host passes its own.+fn default_cli_name() -> &'static str {+ cua_home::channel::CuaChannel::Stable.cli_name()+}++/// The same first Space from a terminal (no agent found), under the CLI+/// name of the app's channel: `cua spaces create linux --on local`, or+/// `cua-local spaces create linux --on local` in Cua Spaces Local.+pub fn cli_first_space(cli: &str) -> String {+ format!("{cli} spaces create linux --on local")+}/// Where to get an agent (none found).pub const AGENTS_GUIDE_URL: &str = "https://cua.ai/docs/spaces/guides/connect-your-agent";-/// The four screens. `connect` and `setup` keep their old names, so a run+/// The screens. `connect` and `setup` keep their old names, so a run/// saved by an older app resumes on the matching screen.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "kebab-case")]@@ -76,21 +98,79 @@ pub enum FirstRunStep {Welcome,/// Pick your agent.Connect,+ /// Install the Cua CLI (only while it is not installed).+ Cli,/// Connect your other devices.Devices,+ /// Share this Mac's screen: Screen Recording and Accessibility. Only on+ /// a signed-in Mac that shares its screen ([`asks_permissions`]).+ Permissions,/// Try it in your agent.Setup,}-impl FirstRunStep {- fn index(self) -> u8 {- match self {- FirstRunStep::Welcome => 0,- FirstRunStep::Connect => 1,- FirstRunStep::Devices => 2,- FirstRunStep::Setup => 3,- }+/// The app's bundled CLI, as its install plan reads it (the Command line+/// screen, and Settings' row).+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct FirstRunCli {+ /// What installing would do (`cli.plan`; none: not read yet, or this+ /// app can't install it).+ pub plan: Option<crate::installer::CliInstallPlan>,+ /// Install is running.+ pub installing: bool,+ /// Installed from this screen: the file written.+ pub installed: Option<String>,+ /// Installing failed with this.+ pub error: Option<String>,+}++impl FirstRunCli {+ /// The CLI is on this computer: installed here, the target is current,+ /// or a working one of this channel was found.+ pub fn present(&self) -> bool {+ self.installed.is_some()+ || self+ .plan+ .as_ref()+ .is_some_and(|p| p.up_to_date || p.found.is_some())+ }++ /// The app carries a CLI it can install, and none is on this computer.+ pub fn missing(&self) -> bool {+ !self.present() && self.plan.as_ref().is_some_and(|p| p.source.is_some())}++ /// Where it is (installed here, current at the target, or found).+ fn location(&self) -> Option<String> {+ self.installed.clone().or_else(|| {+ let p = self.plan.as_ref()?;+ if p.up_to_date {+ Some(p.target.clone())+ } else {+ p.found.clone()+ }+ })+ }+}++/// The screens this run shows, in order: Install the Cua CLI only while+/// the app's CLI is missing (and while it is the screen shown, so its+/// result stays until Continue); Share this Mac's screen only where+/// [`asks_permissions`].+pub fn steps(input: &FirstRunInput) -> Vec<FirstRunStep> {+ let cli =+ input.step == FirstRunStep::Cli || input.cli.installed.is_some() || input.cli.missing();+ let mut out = vec![FirstRunStep::Welcome, FirstRunStep::Connect];+ if cli {+ out.push(FirstRunStep::Cli);+ }+ out.push(FirstRunStep::Devices);+ if asks_permissions(input) {+ out.push(FirstRunStep::Permissions);+ }+ out.push(FirstRunStep::Setup);+ out}/// An agent the setup knows (`agents.setup`'s row, trimmed).@@ -112,7 +192,8 @@ pub struct FirstRunAgent {pub mcp_config: Option<String>,}-/// A permission this computer still needs (`host.status`'s hint).+/// A permission this computer still needs (`host.status`'s hint: the host+/// lists only the missing ones).#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct FirstRunPermission {@@ -135,6 +216,12 @@ pub struct FirstRunHost {pub permissions: Vec<FirstRunPermission>,/// The host setup failed with this.pub error: Option<String>,+ /// People it is shared with see and use its screen (none: not known,+ /// the default for a new host: yes).+ pub share_desktop: Option<bool>,+ /// The name System Settings lists the app under ("Cua Spaces", "Cua+ /// Spaces Local"; none: not known).+ pub app_name: Option<String>,}/// A first Space this computer can make in one click (the Spaces page's@@ -237,6 +324,27 @@ pub struct FirstRunInput {pub offers: Vec<FirstRunOffer>,pub extra: FirstRunExtra,pub plan: Option<FirstRunPlan>,+ /// The app's bundled CLI (the Command line screen).+ pub cli: FirstRunCli,+ /// The CLI's name (`SettingsSnapshot.cli`: `CuaChannel::cli_name`);+ /// none: the install plan's file name, else `cua`.+ pub cli_name: Option<String>,+}++/// The CLI's name for `input`: the host's, else the install plan's file+/// name, else the released app's.+pub fn cli_name(input: &FirstRunInput) -> String {+ let given = input+ .cli_name+ .as_deref()+ .map(str::trim)+ .filter(|n| !n.is_empty());+ let planned = input.cli.plan.as_ref().and_then(|p| {+ let file = p.target.rsplit(['/', '\\']).next()?;+ let file = file.strip_suffix(".exe").unwrap_or(file);+ (!file.is_empty()).then_some(file)+ });+ given.or(planned).unwrap_or(default_cli_name()).to_string()}/// A button: what it says and what it does (`id`).@@ -258,7 +366,7 @@ fn button(id: &str, label: &str) -> FirstRunButton {#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct WelcomeView {- /// "Your agents get their own computer."+ /// "Your computers, shared by your team and its agents."pub title: String,pub lede: String,/// "Get started" (`start`).@@ -497,6 +605,27 @@ pub struct ArtView {pub extra: String,}+/// Screen 3b: the two permissions a shared screen needs.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PermissionsView {+ /// "Share this Mac's screen."+ pub title: String,+ /// "To let your team and agents see and use this Mac, allow two+ /// permissions."+ pub lede: String,+ /// Screen Recording, then Accessibility (`id` the host's permission+ /// id): `ok` once granted, `fix` with Allow (`allow`; `settings_url`+ /// the pane), `checking` while this computer is still being added.+ pub rows: Vec<CheckRow>,+ /// What Allow does, naming the app as System Settings lists it.+ pub note: String,+ /// "Continue" once both are granted.+ pub primary: Option<FirstRunButton>,+ /// "Not now" (`not-now`) while one is missing: Settings has them later.+ pub secondary: Option<FirstRunButton>,+}+/// Screen 4.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -523,13 +652,51 @@ pub struct FirstRunView {pub welcome: Option<WelcomeView>,pub connect: Option<ConnectView>,pub devices: Option<DevicesView>,+ pub permissions: Option<PermissionsView>,pub setup: Option<SetupView>,+ /// Install the Cua CLI.+ pub cli: Option<CliView>,pub art: ArtView,- /// Four page marks.+ /// The screens this run shows ([`steps`]), for Back and Continue.+ pub steps: Vec<FirstRunStep>,+ /// One page mark per screen.pub dots: u8,pub current: u8,}+/// A fact on the Command line screen ("Installs", "~/.local/bin/cua").+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CliFact {+ pub label: String,+ pub value: String,+}++/// Install the Cua CLI: the first run's screen, and Settings' row.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CliView {+ pub title: String,+ pub lede: String,+ /// The CLI's name (`cua`, `cua-local`).+ pub name: String,+ /// What Install writes: the file, and the PATH line when one is needed.+ pub facts: Vec<CliFact>,+ /// One plain line on where it stands (Settings' description).+ pub status: String,+ /// It is on this computer.+ pub installed: bool,+ /// Install is running.+ pub busy: bool,+ /// A command to try once it is installed.+ pub try_command: Option<String>,+ pub error: Option<String>,+ /// `install` ("Install", "Try again"), or `continue` once installed.+ pub primary: Option<FirstRunButton>,+ /// `not-now` until it is installed.+ pub secondary: Option<FirstRunButton>,+}+/// A line of Home's "Finish setting up" list.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -846,8 +1013,8 @@ fn default_or(name: &str, id: &str) -> String {fn welcome_view(input: &FirstRunInput) -> WelcomeView {let place = this_computer(&input.host_os);WelcomeView {- title: "Your agents get their own computer.".into(),- lede: format!("Spaces on {place}, away from your files and your mouse."),+ title: "Your computers, shared by your team and its agents.".into(),+ lede: format!("Run agents in Spaces on {place}, or on any computer your team connects."),primary: button("start", "Get started"),}}@@ -899,7 +1066,7 @@ fn connect_view(input: &FirstRunInput) -> ConnectView {title: "Use the CLI".into(),note: format!("Make a Space on {place} from a terminal."),url: None,- command: Some(CLI_FIRST_SPACE.into()),+ command: Some(cli_first_space(&cli_name(input))),},]} else {@@ -1020,6 +1187,91 @@ fn devices_view(input: &FirstRunInput) -> DevicesView {}}+/// The first run asks for Screen Recording and Accessibility: on a Mac,+/// signed in (so it is added to the account and shared), when it shares+/// its screen. A Mac kept for Spaces only, or one not signed in, never+/// sees the screen.+pub fn asks_permissions(input: &FirstRunInput) -> bool {+ input.host_os == "macos"+ && input.signed_in+ && input+ .host+ .as_ref()+ .is_none_or(|h| h.share_desktop != Some(false))+}++/// The two permissions a shared screen needs, as rows: also what Settings+/// shows later (the same words and buttons).+pub fn permissions_view(input: &FirstRunInput) -> PermissionsView {+ let place = this_computer(&input.host_os);+ let app = input+ .host+ .as_ref()+ .and_then(|h| h.app_name.clone())+ .filter(|n| !n.trim().is_empty())+ .unwrap_or_else(|| "Cua Spaces".into());+ // The host lists only what is missing, and only once it is set up.+ let known = input+ .host+ .as_ref()+ .filter(|h| h.configured && !input.host_setting_up);+ let rows: Vec<CheckRow> = [+ // Plain words, not the panes' names: macOS renames them (Accessibility+ // is "Device Control and Data Access" from macOS 27), and Allow opens+ // the right one anyway.+ (+ "screen-recording",+ format!("See {place}'s screen"),+ "So your team and agents can see what's on it.".to_string(),+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",+ ),+ (+ "accessibility",+ "Use the mouse and keyboard".to_string(),+ format!("So they can click and type on {place}."),+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",+ ),+ ]+ .into_iter()+ .map(|(id, title, note, pane)| {+ let (state, note, action, settings_url) = match known {+ None => (+ RowState::Checking,+ format!("Adding {place} to your account first…"),+ None,+ None,+ ),+ Some(host) => match missing_permission(host, id) {+ Some(p) => (+ RowState::Fix,+ note,+ Some(button("allow", "Allow")),+ Some(p.settings_url.unwrap_or_else(|| pane.into())),+ ),+ None => (RowState::Ok, "Allowed".into(), None, None),+ },+ };+ CheckRow {+ id: id.into(),+ state,+ title,+ note,+ action,+ settings_url,+ }+ })+ .collect();+ let all = rows.iter().all(|r| r.state == RowState::Ok);+ PermissionsView {+ title: format!("Share {place}'s screen."),+ lede: format!("To let your team and agents see and use {place}, allow two permissions."),+ rows,+ note: format!("Allow opens System Settings and shows you where to turn on {app}."),+ primary: all.then(|| button("continue", "Continue")),+ secondary: (!all).then(|| button("not-now", "Not now")),+ }+}+fn missing_permission(host: &FirstRunHost, id: &str) -> Option<FirstRunPermission> {host.permissions.iter()@@ -1374,17 +1626,101 @@ fn art(input: &FirstRunInput) -> ArtView {/// The first run as drawn.pub fn view(input: &FirstRunInput) -> FirstRunView {- let step = input.step;+ let all = steps(input);+ // The permissions screen of a Mac that no longer asks (signed out, or+ // its screen is not shared) shows the try screen instead.+ let step = if all.contains(&input.step) {+ input.step+ } else {+ FirstRunStep::Setup+ };+ let steps = all;+ let current = steps.iter().position(|s| *s == step).unwrap_or(0);FirstRunView {step,later: "Skip for now".into(),welcome: (step == FirstRunStep::Welcome).then(|| welcome_view(input)),connect: (step == FirstRunStep::Connect).then(|| connect_view(input)),devices: (step == FirstRunStep::Devices).then(|| devices_view(input)),+ permissions: (step == FirstRunStep::Permissions).then(|| permissions_view(input)),setup: (step == FirstRunStep::Setup).then(|| setup_view(input)),+ cli: (step == FirstRunStep::Cli).then(|| cli_view(input)),art: art(input),- dots: 4,- current: step.index(),+ dots: steps.len() as u8,+ current: current as u8,+ steps,+ }+}++/// Install the Cua CLI, as the first run and Settings show it.+pub fn cli_view(input: &FirstRunInput) -> CliView {+ let name = cli_name(input);+ let cli = &input.cli;+ let installed = cli.present();+ let mut facts = Vec::new();+ if let Some(at) = cli.location().filter(|_| installed) {+ facts.push(CliFact {+ label: "Installed at".into(),+ value: tilde(&at),+ });+ } else if let Some(plan) = &cli.plan {+ facts.push(CliFact {+ label: "Installs".into(),+ value: tilde(&plan.target),+ });+ if !plan.on_path+ && let Some(profile) = &plan.path_profile+ {+ facts.push(CliFact {+ label: "Adds to PATH".into(),+ value: format!("{}, in {}", tilde(&plan.bin_dir), tilde(profile)),+ });+ }+ }+ let status = if cli.installing {+ "Installing…".to_string()+ } else if let Some(at) = cli.location().filter(|_| installed) {+ format!("Installed at {}.", tilde(&at))+ } else if let Some(plan) = cli.plan.as_ref().filter(|p| p.source.is_some()) {+ format!("Not installed. Install puts it at {}.", tilde(&plan.target))+ } else {+ "This app can't install it here.".to_string()+ };+ let can_install = !installed && cli.plan.as_ref().is_some_and(|p| p.source.is_some());+ CliView {+ title: if installed {+ "Cua is ready in Terminal.".into()+ } else {+ "Use Cua from the Terminal.".into()+ },+ lede: format!("Type {name} in Terminal to make and use Spaces, for you and your agents."),+ facts,+ status,+ installed,+ busy: cli.installing,+ try_command: installed.then(|| format!("{name} spaces ls")),+ error: cli+ .error+ .as_ref()+ .map(|e| format!("Couldn't install it: {e}")),+ primary: if installed {+ Some(button("continue", "Continue"))+ } else if can_install {+ Some(button(+ "install",+ if cli.installing {+ "Installing…"+ } else if cli.error.is_some() {+ "Try again"+ } else {+ "Install"+ },+ ))+ } else {+ Some(button("continue", "Continue"))+ },+ secondary: (!installed && can_install).then(|| button("not-now", "Not now")),+ name,}}@@ -1639,7 +1975,10 @@ mod tests {assert!(drawn[n as usize]);}let w = view(&input(FirstRunStep::Welcome, vec![])).welcome.unwrap();- assert_eq!(w.title, "Your agents get their own computer.");+ assert_eq!(+ w.title,+ "Your computers, shared by your team and its agents."+ );assert_eq!(w.primary.id, "start");}@@ -1793,7 +2132,10 @@ mod tests {c.alternatives[0].note,"Hermes, Claude Code, Codex or Cursor, then come back here.");- assert_eq!(c.alternatives[1].command.as_deref(), Some(CLI_FIRST_SPACE));+ assert_eq!(+ c.alternatives[1].command.as_deref(),+ Some("cua spaces create linux --on local")+ );// Still looking: no alternatives yet.let looking = connect(&FirstRunInput {agents: None,@@ -1894,6 +2236,120 @@ mod tests {);}+ /// Where Back and Continue go from `v`.+ fn nav(v: &FirstRunView) -> (FirstRunStep, FirstRunStep) {+ let at = v.current as usize;+ (+ v.steps[at.saturating_sub(1)],+ v.steps[(at + 1).min(v.steps.len() - 1)],+ )+ }++ fn missing(id: &str) -> FirstRunPermission {+ FirstRunPermission {+ id: id.into(),+ granted: false,+ settings_url: None,+ }+ }++ #[test]+ fn a_shared_mac_asks_for_two_permissions_after_the_account_and_never_before() {+ let mut i = FirstRunInput {+ step: FirstRunStep::Devices,+ host_os: "macos".into(),+ ..Default::default()+ };+ // Not signed in: Not now goes straight to the try screen.+ let v = view(&i);+ assert_eq!((nav(&v).1, v.dots), (FirstRunStep::Setup, 4));++ i.signed_in = true;+ i.host = Some(FirstRunHost {+ configured: true,+ running: true,+ permissions: vec![missing("screen-recording"), missing("accessibility")],+ ..Default::default()+ });+ let v = view(&i);+ assert_eq!((nav(&v).1, v.dots), (FirstRunStep::Permissions, 5));++ i.step = FirstRunStep::Permissions;+ let v = view(&i);+ assert_eq!(+ (nav(&v).0, nav(&v).1, v.current),+ (FirstRunStep::Devices, FirstRunStep::Setup, 3)+ );+ let p = v.permissions.unwrap();+ assert_eq!(p.title, "Share this Mac's screen.");+ assert_eq!(+ p.lede,+ "To let your team and agents see and use this Mac, allow two permissions."+ );+ assert_eq!(+ p.rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),+ ["screen-recording", "accessibility"]+ );+ assert!(p.rows.iter().all(|r| r.state == RowState::Fix+ && r.action.as_ref().is_some_and(|a| a.id == "allow")+ && r.settings_url.is_some()));+ assert!(p.primary.is_none());+ assert_eq!(p.secondary.unwrap().id, "not-now");+ assert!(p.note.contains("turn on Cua Spaces."));++ // Granted one by one: a check each, then Continue.+ let host = i.host.as_mut().unwrap();+ host.permissions = vec![missing("accessibility")];+ host.app_name = Some("Cua Spaces Local".into());+ let p = view(&i).permissions.unwrap();+ assert_eq!(p.rows[0].state, RowState::Ok);+ assert_eq!(p.rows[1].state, RowState::Fix);+ assert!(p.note.contains("turn on Cua Spaces Local."));+ i.host.as_mut().unwrap().permissions.clear();+ let p = view(&i).permissions.unwrap();+ assert!(+ p.rows+ .iter()+ .all(|r| r.state == RowState::Ok && r.action.is_none())+ );+ assert_eq!(p.primary.unwrap().id, "continue");+ assert!(p.secondary.is_none());++ // Still being added: nothing is known yet, nothing is granted.+ i.host_setting_up = true;+ let p = view(&i).permissions.unwrap();+ assert!(p.rows.iter().all(|r| r.state == RowState::Checking));+ assert!(p.primary.is_none());+ }++ #[test]+ fn no_permissions_screen_without_a_shared_mac_screen() {+ let mut i = FirstRunInput {+ step: FirstRunStep::Permissions,+ host_os: "macos".into(),+ signed_in: true,+ host: Some(FirstRunHost {+ configured: true,+ share_desktop: Some(false),+ ..Default::default()+ }),+ ..Default::default()+ };+ // Spaces only: the saved step falls through to the try screen.+ let v = view(&i);+ assert_eq!(v.step, FirstRunStep::Setup);+ assert!(v.permissions.is_none());+ assert_eq!((nav(&v).0, v.dots), (FirstRunStep::Devices, 4));+ // Not a Mac.+ i.host_os = "windows".into();+ i.host.as_mut().unwrap().share_desktop = None;+ assert!(!asks_permissions(&i));+ // Signed out.+ i.host_os = "macos".into();+ i.signed_in = false;+ assert!(!asks_permissions(&i));+ }+#[test]fn the_try_screen_waits_for_the_lead_agent_and_done_is_never_blocked() {let mut i = FirstRunInput {@@ -2104,4 +2560,175 @@ mod tests {}}}++ fn plan(found: Option<&str>, on_path: bool, target: &str) -> crate::installer::CliInstallPlan {+ crate::installer::CliInstallPlan {+ source: Some("/Applications/Cua Spaces.app/Contents/MacOS/cua".into()),+ target: target.into(),+ bin_dir: "/Users/ada/.local/bin".into(),+ on_path,+ path_profile: (!on_path).then(|| "/Users/ada/.zshrc".into()),+ path_line: (!on_path).then(|| "export PATH=\"/Users/ada/.local/bin:$PATH\"".into()),+ found: found.map(Into::into),+ ..Default::default()+ }+ }++ const STABLE_TARGET: &str = "/Users/ada/.local/bin/cua";+ const LOCAL_TARGET: &str = "/Users/ada/.local/bin/cua-local";++ #[test]+ fn the_cli_screen_shows_only_while_the_bundled_cli_is_missing() {+ let base = input(FirstRunStep::Connect, vec![claude(true)]);+ // Not read yet, or no plan here: no screen.+ assert_eq!(steps(&base).len(), 4);+ // A disk-image install: the bundled CLI, nothing on PATH.+ let dmg = FirstRunInput {+ cli: FirstRunCli {+ plan: Some(plan(None, false, STABLE_TARGET)),+ ..Default::default()+ },+ ..base.clone()+ };+ assert_eq!(+ steps(&dmg),+ [+ FirstRunStep::Welcome,+ FirstRunStep::Connect,+ FirstRunStep::Cli,+ FirstRunStep::Devices,+ FirstRunStep::Setup+ ]+ );+ let v = view(&FirstRunInput {+ step: FirstRunStep::Cli,+ ..dmg.clone()+ });+ assert_eq!((v.dots, v.current), (5, 2));+ // Already installed (or a working one found): no screen.+ let found = FirstRunInput {+ cli: FirstRunCli {+ plan: Some(plan(Some(STABLE_TARGET), true, STABLE_TARGET)),+ ..Default::default()+ },+ ..base.clone()+ };+ assert_eq!(steps(&found).len(), 4);+ // A build without a bundled CLI can't install one: no screen.+ let unbundled = FirstRunInput {+ cli: FirstRunCli {+ plan: Some(crate::installer::CliInstallPlan {+ source: None,+ ..plan(None, true, STABLE_TARGET)+ }),+ ..Default::default()+ },+ ..base+ };+ assert_eq!(steps(&unbundled).len(), 4);+ }++ #[test]+ fn the_cli_screen_names_the_file_asks_first_and_shows_the_result() {+ let mut i = FirstRunInput {+ step: FirstRunStep::Cli,+ cli: FirstRunCli {+ plan: Some(plan(None, false, STABLE_TARGET)),+ ..Default::default()+ },+ ..input(FirstRunStep::Cli, vec![claude(true)])+ };+ let c = view(&i).cli.unwrap();+ assert_eq!(c.title, "Use Cua from the Terminal.");+ assert_eq!(c.name, "cua");+ assert_eq!(+ c.facts,+ [+ CliFact {+ label: "Installs".into(),+ value: "~/.local/bin/cua".into()+ },+ CliFact {+ label: "Adds to PATH".into(),+ value: "~/.local/bin, in ~/.zshrc".into()+ },+ ]+ );+ assert_eq!(c.primary, Some(button("install", "Install")));+ assert_eq!(c.secondary, Some(button("not-now", "Not now")));+ assert!(!c.installed && c.try_command.is_none());+ assert_eq!(+ c.status,+ "Not installed. Install puts it at ~/.local/bin/cua."+ );++ i.cli.installing = true;+ let c = cli_view(&i);+ assert!(c.busy);+ assert_eq!(c.status, "Installing…");++ i.cli.installing = false;+ i.cli.error = Some("permission denied".into());+ let c = cli_view(&i);+ assert_eq!(+ c.error.as_deref(),+ Some("Couldn't install it: permission denied")+ );+ assert_eq!(c.primary, Some(button("install", "Try again")));++ i.cli.error = None;+ i.cli.installed = Some(STABLE_TARGET.into());+ let v = view(&i);+ // The result stays on its screen until Continue.+ assert!(v.steps.contains(&FirstRunStep::Cli));+ let c = v.cli.unwrap();+ assert!(c.installed);+ assert_eq!(c.title, "Cua is ready in Terminal.");+ assert_eq!(c.status, "Installed at ~/.local/bin/cua.");+ assert_eq!(c.try_command.as_deref(), Some("cua spaces ls"));+ assert_eq!(c.primary, Some(button("continue", "Continue")));+ assert_eq!(c.secondary, None);+ }++ #[test]+ fn local_builds_name_their_own_cli() {+ // The host names it (`SettingsSnapshot.cli`)...+ let named = FirstRunInput {+ cli_name: Some("cua-local".into()),+ ..input(FirstRunStep::Connect, vec![])+ };+ let c = connect(&named);+ assert_eq!(+ c.alternatives[1].command.as_deref(),+ Some("cua-local spaces create linux --on local")+ );+ // ...or its install plan's file does.+ let planned = FirstRunInput {+ step: FirstRunStep::Cli,+ cli: FirstRunCli {+ plan: Some(plan(None, true, LOCAL_TARGET)),+ ..Default::default()+ },+ ..input(FirstRunStep::Cli, vec![])+ };+ assert_eq!(cli_name(&planned), "cua-local");+ let c = cli_view(&planned);+ assert_eq!(c.facts[0].value, "~/.local/bin/cua-local");+ assert_eq!(c.facts.len(), 1, "on PATH already: no PATH line");+ assert_eq!(+ cli_name(&FirstRunInput {+ cli: FirstRunCli {+ plan: Some(plan(None, true, "C:\\Users\\ada\\bin\\cua-local.exe")),+ ..Default::default()+ },+ ..Default::default()+ }),+ "cua-local"+ );+ assert_eq!(cli_name(&FirstRunInput::default()), "cua");+ assert_eq!(+ cli_first_space("cua-local"),+ "cua-local spaces create linux --on local"+ );+ }}diff --git a/libs/cua/crates/cua-spaces-app-core/src/parity.rs b/libs/cua/crates/cua-spaces-app-core/src/parity.rsindex 6d72139c28..2bc4f024fa 100644--- a/libs/cua/crates/cua-spaces-app-core/src/parity.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/parity.rs@@ -3469,6 +3469,33 @@ fn run_first_run(f: &Value, h: &dyn Host) -> Result<Value, String> {"note": k["note"],});}+ if v["permissions"].is_object() {+ let k = &v["permissions"];+ let rows: Vec<String> = k["rows"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|r| {+ format!(+ "{}{}",+ row(r),+ if r["settingsUrl"].is_string() {+ format!(" <{}>", s(&r["settingsUrl"]))+ } else {+ String::new()+ }+ )+ })+ .collect();+ frame["permissions"] = json!({+ "title": k["title"],+ "lede": k["lede"],+ "rows": rows,+ "note": k["note"],+ "primary": btn(&k["primary"]),+ "secondary": btn(&k["secondary"]),+ });+ }if v["setup"].is_object() {let k = &v["setup"];let extra = if k["extra"].is_object() {@@ -3513,6 +3540,28 @@ fn run_first_run(f: &Value, h: &dyn Host) -> Result<Value, String> {"primary": format!("{}{}", btn(&k["primary"]), if k["primary"]["enabled"].as_bool() == Some(true) { "" } else { " (off)" }),});}+ if v["cli"].is_object() {+ let k = &v["cli"];+ let facts: Vec<String> = k["facts"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|f| format!("{}: {}", s(&f["label"]), s(&f["value"])))+ .collect();+ frame["cli"] = json!({+ "title": k["title"],+ "lede": k["lede"],+ "facts": facts,+ "status": k["status"],+ "try": k["tryCommand"],+ "error": k["error"],+ "primary": btn(&k["primary"]),+ "secondary": btn(&k["secondary"]),+ });+ }+ if case["steps"].as_bool() == Some(true) {+ frame["steps"] = v["steps"].clone();+ }if case["todos"].as_bool() == Some(true) {let t = c(h, "firstRun.todos", json!({ "input": input }))?;let items: Vec<String> = t["items"]