Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces): the new setup prepares the first Space while you set up, behind Labs (CUA-2851) (#6360)
cua-agents[bot]2829e00b180d
diff --git a/apps/cua-spaces-web/e2e/flows.ts b/apps/cua-spaces-web/e2e/flows.tsindex af6a1a1913..6467a52d68 100644--- a/apps/cua-spaces-web/e2e/flows.ts+++ b/apps/cua-spaces-web/e2e/flows.ts@@ -87,6 +87,10 @@ export const FLOW_PLAN: Record<string, FlowPlan> = {experiments: { status: "run", screen: "settings/advanced" },"placement-picker": { status: "run", screen: "new-space" },machines: { status: "run", screen: "machines" },+ prepare: {+ status: "skip",+ reason: "The new setup (Settings, Advanced, Labs) draws prepare.view as is; bridge/prepare-core.ts drives the wasm core and src/__tests__/first-run-parity.test.ts replays the flow",+ },"first-run": {status: "skip",reason: "The page draws firstRun.view as is; src/__tests__/first-run-parity.test.ts replays this flow on the wasm core and src/__tests__/first-run.test.tsx drives the screen",diff --git a/apps/cua-spaces-web/e2e/onboarding-short-window.spec.ts b/apps/cua-spaces-web/e2e/onboarding-short-window.spec.tsnew file mode 100644index 0000000000..72038bc3fd--- /dev/null+++ b/apps/cua-spaces-web/e2e/onboarding-short-window.spec.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Every first-run page keeps its action row inside the window, however short the window is: the+ * row sticks to the bottom of the content area and the page scrolls above it. Back and Skip for now+ * stay where they are. The same page height is set the way the Electron shell sets it (the window's+ * own size is the host's, so the page's height is fixed here).+ */++import { expect, test } from "./host";++const PAGES: { name: string; need: string[]; go: (page: import("@playwright/test").Page) => Promise<void> }[] = [+ { name: "Welcome", need: ["Get started", "Skip for now"], go: async () => {} },+ {+ name: "Pick your agent",+ need: ["Set up", "Not now", "Skip for now"],+ go: async (page) => {+ await page.locator("[data-onboarding-primary]").click();+ await page.locator("[data-first-run-set-up]").waitFor({ timeout: 30_000 });+ await page.waitForTimeout(800);+ },+ },+ {+ name: "Command line",+ need: ["Install", "Not now", "Skip for now"],+ go: async (page) => {+ await page.locator("[data-onboarding-primary]").click();+ await page.getByRole("button", { name: "Set up" }).waitFor({ timeout: 30_000 });+ await page.getByRole("button", { name: "Not now" }).click();+ await page.locator("[data-first-run='cli']").waitFor({ timeout: 30_000 });+ },+ },+ {+ name: "Add your other computers",+ need: ["Sign in", "Not now", "Skip for now"],+ go: async (page) => {+ await page.locator("[data-onboarding-primary]").click();+ await page.getByRole("button", { name: "Set up" }).waitFor({ timeout: 30_000 });+ await page.getByRole("button", { name: "Not now" }).click();+ await page.locator("[data-first-run='cli']").waitFor({ timeout: 30_000 });+ await page.getByRole("button", { name: "Not now" }).click();+ await page.locator("[data-first-run='devices']").waitFor({ timeout: 30_000 });+ },+ },+];++for (const height of [600, 700]) {+ test.describe(`a ${height} px window`, () => {+ test.use({ viewport: { width: 1280, height } });+ for (const p of PAGES) {+ test(`${p.name}: every action is inside the window`, async ({ page }) => {+ await page.goto("/onboarding?bridge=demo&demo=fresh,child-spaces,cli-missing&parity");+ await page.addStyleTag({ content: `html, body, #root { height: ${height}px !important; max-height: ${height}px !important; overflow: hidden !important; }` });+ await page.locator("[data-onboarding-heading]").waitFor();+ await p.go(page);+ const inView = await page.evaluate((h) => {+ return [...document.querySelectorAll("button")]+ .filter((b) => {+ const r = b.getBoundingClientRect();+ return r.width > 0 && r.height > 0 && r.top >= 0 && r.bottom <= h;+ })+ .map((b) => (b.textContent ?? "").trim());+ }, height);+ for (const name of p.need) expect(inView, `${name} on ${p.name} at ${height} px (in view: ${inView.join(" | ")})`).toContain(name);+ });+ }+ });+}diff --git a/apps/cua-spaces-web/src/__tests__/first-run-parity.test.ts b/apps/cua-spaces-web/src/__tests__/first-run-parity.test.tsindex c18ee8ac37..9c67972466 100644--- a/apps/cua-spaces-web/src/__tests__/first-run-parity.test.ts+++ b/apps/cua-spaces-web/src/__tests__/first-run-parity.test.ts@@ -13,7 +13,7 @@ import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";import type { FirstRunInput } from "@/bridge/contracts/first-run";import { firstRunTodos, firstRunView } from "@/bridge/first-run";import type { HostOs } from "@/bridge/host-os";-import { firstSpaceOffers } from "@/bridge/new-space";+import { firstPrompts, firstSpaceOffers } from "@/bridge/new-space";import type { WizardEnv } from "@/bridge/contracts/new-space";const DIR = join(import.meta.dirname, "..", "..", "..", "..", "libs", "cua", "crates", "cua-spaces-app-core", "parity");@@ -29,6 +29,10 @@ describe.skipIf(!wasmBuilt)("first-run parity (wasm core)", () => {const a = args as { env: WizardEnv; hostOs: HostOs };return firstSpaceOffers(core, a.env, a.hostOs);}+ if (method === "firstPrompts.choose") {+ const a = args as { env: WizardEnv; hostOs: HostOs };+ return firstPrompts(core, a.env, a.hostOs);+ }const input = (args as { input: FirstRunInput }).input;if (method === "firstRun.view") return firstRunView(core, input);if (method === "firstRun.todos") return firstRunTodos(core, input);diff --git a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx b/apps/cua-spaces-web/src/__tests__/first-run.test.tsxindex 73f34987aa..951d3da9ae 100644--- a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/first-run.test.tsx@@ -10,7 +10,7 @@import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { BridgeProvider } from "@/bridge";+import { BridgeProvider, setFlagOverride } from "@/bridge";import { createDemoAdapter } from "@/bridge/adapters/demo";import { noCore, testCore, wasmBuilt } from "@/bridge/__tests__/testCore";import type { AgentSetupRow, ConnectionReport } from "@/bridge/contracts/agents";@@ -20,6 +20,7 @@ import { readFirstRun, resetFirstRunCache, useFirstRun, writeFirstRun } from "@/import { CLOSED_NEW_SPACE, updateNewSpaceSession } from "@/bridge/new-space";import { resetSavedOnboardingCache } from "@/bridge/onboarding";import { connectedAppsState, resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { getDriver, resetPrepare } from "@/lib/prepare/store";import { mountApp, stubBrowserApis } from "./app-harness";stubBrowserApis();@@ -30,7 +31,12 @@ beforeEach(() => {updateNewSpaceSession(() => CLOSED_NEW_SPACE);resetConnectedAppsState();});-afterEach(cleanup);+afterEach(() => {+ cleanup();+ setFlagOverride("spaces_ask_first_home", null);+ setFlagOverride("spaces_new_onboarding", null);+ resetPrepare();+});type Calls = { op: string; args: unknown }[];@@ -216,6 +222,85 @@ describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {await waitFor(() => expect(calls.find((c) => c.op === "session.completeOnboarding")).toBeTruthy());});+ it("with the new setup on there is no Try it screen: the last screen ends the run on Home while the Space is prepared", { timeout: 40_000 }, async () => {+ setFlagOverride("spaces_ask_first_home", true);+ setFlagOverride("spaces_new_onboarding", true);+ resetPrepare();+ const calls: Calls = [];+ const { router } = await mountApp("/onboarding", {+ failsCreates: false,+ listsGhost: false,+ demo: { signedIn: false, onboarded: false },+ intercept: (op, args) => (calls.push({ op, args }), undefined),+ answer: (op, out) => (op === "agents.setup" || op === "agents.signIn" || op === "agents.configure" ? onlyCodex(out as AgentSetupRow[]) : out),+ });+ // Preparing started with the app, before any screen was answered.+ await waitFor(() => expect(getDriver()?.state?.wanted).toBe(true), { timeout: 15_000 });+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Let OpenAI Codex use Cua?"));+ click("[data-first-run-set-up]");+ await waitFor(() => expect(heading()).toBe("OpenAI Codex can use Cua."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Add your other computers."));+ // The dots say three screens: Welcome, Pick your agent, Add your other computers.+ expect(document.querySelector("ol[aria-label]")!.getAttribute("aria-label")).toBe("Step 3 of 3");+ click("[data-first-run-secondary]");+ await waitFor(() => expect(calls.find((c) => c.op === "session.completeOnboarding")).toBeTruthy());+ // No "Try it" screen and no prompt to copy; the person lands on Home.+ expect(document.body.textContent).not.toMatch(/Try it in/);+ expect(document.querySelector("textarea[data-first-run-prompt]")).toBeNull();+ await waitFor(() => expect(router.state.location.pathname).toBe("/home"));+ // The clock for "onboarding finished to ready" started when the last button was pressed.+ expect(getDriver()?.state?.onboardingDoneMs).not.toBeNull();+ });++ it("every page of the run shows its buttons: Welcome, Pick your agent (Set up, Not now, Back), Add your other machines (Sign in, Not now, Back)", { timeout: 40_000 }, async () => {+ setFlagOverride("spaces_ask_first_home", true);+ setFlagOverride("spaces_new_onboarding", true);+ resetPrepare();+ await mountApp("/onboarding", {+ failsCreates: false,+ listsGhost: false,+ demo: { signedIn: false, onboarded: false },+ answer: (op, out) => (op === "agents.setup" || op === "agents.signIn" || op === "agents.configure" ? onlyCodex(out as AgentSetupRow[]) : out),+ });+ const buttons = () => [...document.querySelectorAll("button")].map((b) => (b.textContent ?? "").trim()).filter(Boolean);+ // Page 1.+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ expect(buttons()).toEqual(expect.arrayContaining(["Get started", "Skip for now"]));+ expect(document.querySelector("[data-first-run-back]")).toBeNull();+ click("[data-onboarding-primary]");+ // Page 2: the agent rows with the one Set up and Not now, Back, and the page flow still going to Continue.+ await waitFor(() => expect(heading()).toBe("Let OpenAI Codex use Cua?"));+ expect(document.querySelector("[data-first-run-agent=codex]")).not.toBeNull();+ expect(buttons()).toEqual(expect.arrayContaining(["Set up", "Not now", "Back", "Skip for now"]));+ click("[data-first-run-set-up]");+ await waitFor(() => expect(heading()).toBe("OpenAI Codex can use Cua."));+ expect(document.querySelector("[data-first-run-agent=codex]")!.textContent).toContain("Ready");+ expect(buttons()).toEqual(expect.arrayContaining(["Continue", "Back"]));+ click("[data-onboarding-primary]");+ // The last page.+ await waitFor(() => expect(heading()).toBe("Add your other computers."));+ expect(buttons()).toEqual(expect.arrayContaining(["Sign in", "Not now", "Back"]));+ });++ it("with the new setup off the Try it screen is still last", async () => {+ setFlagOverride("spaces_new_onboarding", false);+ resetPrepare();+ await mount({ agents: onlyCodex });+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Let OpenAI Codex use Cua?"));+ click("[data-first-run-set-up]");+ await waitFor(() => expect(heading()).toBe("OpenAI Codex can use Cua."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(heading()).toBe("Add your other computers."));+ expect(document.querySelector("ol[aria-label]")!.getAttribute("aria-label")).toBe("Step 3 of 4");+ click("[data-first-run-secondary]");+ await waitFor(() => expect(heading()).toBe("Try it in OpenAI Codex."));+ });+it("counts each screen viewed and finished, a skipped one, and Skip for now, as fixed words only", async () => {const calls = await mount();const funnel = () =>diff --git a/apps/cua-spaces-web/src/__tests__/onboarding-lands-on-home.test.tsx b/apps/cua-spaces-web/src/__tests__/onboarding-lands-on-home.test.tsxnew file mode 100644index 0000000000..6c9fea23f1--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/onboarding-lands-on-home.test.tsx@@ -0,0 +1,93 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The last onboarding page of an ask-first run ends on Home (the prompt box and the suggestions), not inside a+// Space: the first agent keeps getting ready in the background, with one quiet line on that page.++import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { setFlagOverride } from "@/bridge";+import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { resetFirstRunCache } from "@/bridge/first-run";+import { resetSavedOnboardingCache } from "@/bridge/onboarding";+import { resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { resetAskTasks } from "@/lib/ask-first";+import { getDriver, resetPrepare } from "@/lib/prepare/store";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetSavedOnboardingCache();+ resetFirstRunCache();+ resetConnectedAppsState();+ resetPrepare();+ resetAskTasks();+ setFlagOverride("spaces_ask_first_home", true);+ setFlagOverride("spaces_new_onboarding", true);+});+afterEach(() => {+ cleanup();+ setFlagOverride("spaces_ask_first_home", null);+ setFlagOverride("spaces_new_onboarding", null);+ resetPrepare();+});++const click = (sel: string) => fireEvent.click(document.querySelector<HTMLElement>(sel)!);+const heading = () => document.querySelector("[data-onboarding-heading]")?.textContent ?? "";++async function throughOnboarding(hold?: Promise<void>) {+ const { router } = await mountApp("/onboarding", { failsCreates: false, listsGhost: false, hold, demo: { signedIn: false, onboarded: false, noSpaces: true, keys: "several" } });+ await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));+ click("[data-onboarding-primary]");+ await waitFor(() => expect(document.querySelector("[data-first-run-set-up]")).not.toBeNull(), { timeout: 15_000 });+ fireEvent.click(screen.getAllByRole("button", { name: "Not now" })[0]!);+ await waitFor(() => expect(heading()).toBe("Add your other computers."));+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));+ return router;+}++// The welcome's example jobs are still there (Home's own suggestions).+const expectCards = () => {+ expect(document.querySelectorAll("[data-home-card]").length).toBeGreaterThanOrEqual(2);+};++describe.skipIf(!wasmBuilt)("where the first run ends", () => {+ it("lands on Home with the prompt box and the suggestions, and says nothing about the home warming", { timeout: 60_000 }, async () => {+ let release!: () => void;+ const router = await throughOnboarding(new Promise<void>((r) => (release = r)));+ await waitFor(() => expect(router.state.location.pathname).toBe("/home"));+ // The prompt box and the suggestions are there, not a Space's page.+ expect(await screen.findByLabelText("What do you want to do?")).not.toBeNull();+ expectCards();+ expect(document.querySelector("[data-ask-first-home]")).not.toBeNull();+ // Warming is silent: no line, no steps, and the home is not in "Your Spaces".+ await waitFor(() => expect(getDriver()?.state?.pendingId).toBeTruthy());+ await act(async () => {+ await new Promise((r) => setTimeout(r, 600));+ });+ expect(document.querySelector("[data-prepare-line]")).toBeNull();+ expect(document.querySelector("[data-prepare-steps]")).toBeNull();+ expect(document.body.textContent).not.toContain("Getting your agent ready");+ expect(document.querySelector("[data-home-spaces]")?.textContent ?? "").not.toContain("home-claude-code");+ expect(getDriver()?.state?.onboardingDoneMs).not.toBeNull();+ // A prompt sent now is kept and goes once the agent is ready (the Space's thread says so).+ fireEvent.change(screen.getByLabelText("What do you want to do?"), { target: { value: "fix the build" } });+ fireEvent.click(screen.getByRole("button", { name: "Start" }));+ await waitFor(() => expect(getDriver()?.state?.messages.map((m) => m.text)).toEqual(["fix the build"]));+ release();+ });++ it("when everything is ready nothing is shown and the home is not in Your Spaces", { timeout: 60_000 }, async () => {+ const router = await throughOnboarding();+ await waitFor(() => expect(router.state.location.pathname).toBe("/home"));+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 30_000 });+ await waitFor(() => expect(document.querySelector("[data-prepare-line]")).toBeNull());+ expect(screen.getByLabelText("What do you want to do?")).not.toBeNull();+ expect(document.querySelector("[data-home-spaces]")?.textContent ?? "").not.toContain("home-claude-code");+ expect(document.body.textContent).not.toContain("home-claude-code");+ // The home that was made meanwhile does not take the suggestions away: nothing was asked yet.+ expectCards();+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/prepare-launch.test.tsx b/apps/cua-spaces-web/src/__tests__/prepare-launch.test.tsxnew file mode 100644index 0000000000..a5571e1de0--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/prepare-launch.test.tsx@@ -0,0 +1,142 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The ask-first Space is prepared from launch: the home is made while the person is still on the+// first screens, a message sent while it is being made is kept and goes once when the agent is ready+// (also after the app was quit), and onboarding ends in that Space with no "Try it" screen.++import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { setFlagOverride } from "@/bridge";+import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { resetConnectState } from "@/hooks/use-connectors";+import { resetAskTasks } from "@/lib/ask-first";+import { getDriver } from "@/lib/prepare/store";+import { resetPrepare } from "@/lib/prepare/store";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetAskTasks();+ resetConnectState();+ resetPrepare();+ setFlagOverride("spaces_ask_first_home", true);+ setFlagOverride("spaces_new_onboarding", true);+});+afterEach(() => {+ cleanup();+ resetPrepare();+ vi.unstubAllEnvs();+});++const q = (s: string) => document.querySelector<HTMLElement>(s);+type Call = { op: string; args: Record<string, unknown> };++async function compose(text: string) {+ const box = await waitFor(() => {+ const el = q("[data-composer]") as HTMLTextAreaElement | null;+ expect(el?.disabled).toBe(false);+ return el!;+ });+ fireEvent.change(box, { target: { value: text, selectionStart: text.length } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ await new Promise((r) => setTimeout(r, 20));+ });+}++describe.skipIf(!wasmBuilt)("preparing the ask-first Space from launch", () => {+ it("makes the home at launch, adds the agent and says ready", { timeout: 40000 }, async () => {+ const calls: Call[] = [];+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { onboarded: true }, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 20000 });+ const create = calls.find((c) => c.op === "spaces.create");+ expect(create?.args.config).toMatchObject({ name: "home-claude-code" });+ expect(calls.filter((c) => c.op === "spaces.create")).toHaveLength(1);+ expect(calls.find((c) => c.op === "thread.agentAdd")?.args).toMatchObject({ harness: "claude-code" });+ // Nothing was asked of the person.+ expect(calls.some((c) => c.op === "thread.post")).toBe(false);+ });++ it("shows the live preparing state on the home's page, keeps a message typed meanwhile and sends it once", { timeout: 60000 }, async () => {+ const calls: Call[] = [];+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { router } = await mountApp("/spaces", { failsCreates: false, listsGhost: false, hold, demo: { onboarded: true }, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await waitFor(() => expect(getDriver()?.state?.pendingId).toBeTruthy());+ const pending = getDriver()!.state!.pendingId!;+ await act(async () => {+ await router.navigate({ to: "/spaces/$spaceId", params: { spaceId: pending } });+ });+ const panel = await waitFor(() => {+ const el = q("[data-prepare]");+ expect(el).not.toBeNull();+ return el!;+ });+ expect(panel.dataset.prepare).toBe("preparing");+ expect(panel.textContent).toContain("Linux runtime");+ expect(panel.textContent).toContain("Your message sends as soon as your agent is ready");+ expect(panel.textContent).not.toContain("·");+ // The box works at once: the message is kept, shown as waiting, and nothing is posted.+ await compose("fix the failing tests");+ await waitFor(() => expect(getDriver()?.state?.messages.map((m) => m.text)).toEqual(["fix the failing tests"]));+ expect(calls.some((c) => c.op === "thread.post")).toBe(false);+ await waitFor(() => expect(document.body.textContent).toContain("Sends when your agent is ready"));+ release();+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 30000 });+ await waitFor(() => expect(calls.filter((c) => c.op === "thread.post")).toHaveLength(1), { timeout: 15000 });+ expect(String(calls.find((c) => c.op === "thread.post")?.args.text)).toContain("fix the failing tests");+ await waitFor(() => expect(getDriver()?.state?.messages[0]?.state).toBe("delivered"));+ // Later ticks do not send it again.+ await act(async () => {+ await new Promise((r) => setTimeout(r, 1500));+ });+ expect(calls.filter((c) => c.op === "thread.post")).toHaveLength(1);+ });++ it("a message kept when the app was quit is sent once after it opens again", { timeout: 60000 }, async () => {+ const calls: Call[] = [];+ // Run 1: the create never ends; a message is typed; the page goes away (the record is in storage).+ const hold = new Promise<void>(() => {});+ const { router } = await mountApp("/spaces", { failsCreates: false, listsGhost: false, hold, demo: { onboarded: true }, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await waitFor(() => expect(getDriver()?.state?.pendingId).toBeTruthy());+ const pending = getDriver()!.state!.pendingId!;+ await act(async () => {+ await router.navigate({ to: "/spaces/$spaceId", params: { spaceId: pending } });+ });+ await compose("keep me");+ await waitFor(() => expect(JSON.parse(localStorage.getItem("cua.prepare.v1") ?? "{}").messages?.length).toBe(1));+ cleanup();+ resetPrepare();+ expect(calls.some((c) => c.op === "thread.post")).toBe(false);+ // Run 2: a new page load with the same storage; the create runs again and finishes.+ calls.length = 0;+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { onboarded: true }, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 30000 });+ await waitFor(() => expect(calls.filter((c) => c.op === "thread.post")).toHaveLength(1), { timeout: 15000 });+ expect(String(calls.find((c) => c.op === "thread.post")?.args.text)).toContain("keep me");+ expect(calls.filter((c) => c.op === "spaces.create")).toHaveLength(1);+ });++ it("does not start without the new setup, or without the new Home", { timeout: 30000 }, async () => {+ setFlagOverride("spaces_new_onboarding", false);+ const calls: Call[] = [];+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { onboarded: true }, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await act(async () => {+ await new Promise((r) => setTimeout(r, 800));+ });+ expect(calls.some((c) => c.op === "spaces.create")).toBe(false);+ expect(getDriver()?.state?.wanted ?? false).toBe(false);+ cleanup();+ resetPrepare();+ setFlagOverride("spaces_ask_first_home", false);+ setFlagOverride("spaces_new_onboarding", true);+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { onboarded: true }, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await act(async () => {+ await new Promise((r) => setTimeout(r, 800));+ });+ expect(calls.some((c) => c.op === "spaces.create")).toBe(false);+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/warming-home-hidden.test.tsx b/apps/cua-spaces-web/src/__tests__/warming-home-hidden.test.tsxnew file mode 100644index 0000000000..c83c0c0b8f--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/warming-home-hidden.test.tsx@@ -0,0 +1,102 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The home that warms in the background for Home's prompt box is invisible infrastructure until a person writes+// into it: not on the Spaces list, in the sidebar or the palette, and not among the agents. Its own page and+// Home's preparing line still show it. The rule is the core's (`prepare.hidden`).++import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { setFlagOverride } from "@/bridge";+import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { resetFirstRunCache } from "@/bridge/first-run";+import { resetSavedOnboardingCache } from "@/bridge/onboarding";+import { resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { resetAskTasks } from "@/lib/ask-first";+import { getDriver, resetPrepare } from "@/lib/prepare/store";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetSavedOnboardingCache();+ resetFirstRunCache();+ resetConnectedAppsState();+ resetPrepare();+ resetAskTasks();+ setFlagOverride("spaces_ask_first_home", true);+ setFlagOverride("spaces_new_onboarding", true);+});+afterEach(() => {+ cleanup();+ setFlagOverride("spaces_ask_first_home", null);+ setFlagOverride("spaces_new_onboarding", null);+ resetPrepare();+});++const demo = { onboarded: true, noSpaces: true, keys: "several" as const };+const listText = () => document.querySelector("main")?.textContent ?? "";++describe.skipIf(!wasmBuilt)("the warming home is not on any list until a person wrote into it", () => {+ it("is not on the Spaces list or in the sidebar count while warm and unasked, and its page is still reachable", { timeout: 60_000 }, async () => {+ const { router } = await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo });+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 30_000 });+ // The host has the Space (it still counts toward its budget and usage); no list shows it.+ expect(getDriver()?.state?.homeSpaceId).toBe("local:home-claude-code");+ expect(listText()).not.toContain("home-claude-code");+ // Nowhere on the page: not the list, the sidebar's "Making" item, nor a tip about it.+ expect(document.body.textContent).not.toContain("home-claude-code");+ // Its own page is there (Home's Details link opens it).+ await act(async () => {+ await router.navigate({ to: "/spaces/$spaceId", params: { spaceId: "local:home-claude-code" } });+ });+ await waitFor(() => expect(document.body.textContent).toContain("home-claude-code"));+ });++ it("stays hidden after the app quits and opens again with the warm home and no message", { timeout: 60_000 }, async () => {+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo });+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 30_000 });+ expect(JSON.parse(localStorage.getItem("cua.prepare.v1") ?? "{}").askedMs).toBeNull();+ cleanup();+ resetPrepare();+ // A new page load with the same storage; the host (the demo) still has the home.+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo });+ await waitFor(() => expect(getDriver()?.state?.wanted).toBe(true));+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 30_000 });+ expect(listText()).not.toContain("home-claude-code");+ });++ it("shows up once the first message is sent, even while that message is only queued", { timeout: 60_000 }, async () => {+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { router } = await mountApp("/home", { failsCreates: false, listsGhost: false, hold, demo });+ await screen.findByLabelText("What do you want to do?");+ await waitFor(() => expect(getDriver()?.state?.pendingId).toBeTruthy());+ expect(getDriver()?.state?.askedMs).toBeNull();+ fireEvent.change(screen.getByLabelText("What do you want to do?"), { target: { value: "fix the build" } });+ fireEvent.click(screen.getByRole("button", { name: "Start" }));+ await waitFor(() => expect(getDriver()?.state?.askedMs).not.toBeNull());+ await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\//));+ release();+ await act(async () => {+ await router.navigate({ to: "/spaces" });+ });+ await waitFor(() => expect(listText()).toContain("home-claude-code"), { timeout: 30_000 });+ });++ it("a home that cannot be made yet is not on a list and Home stays silent", { timeout: 60_000 }, async () => {+ await mountApp("/home", { failsCreates: true, listsGhost: false, demo });+ await screen.findByLabelText("What do you want to do?");+ // A dropped connection is retried by itself: Home stays silent and the home stays off every list.+ await waitFor(() => expect(getDriver()?.view()?.phase).toBe("waiting"), { timeout: 30_000 });+ expect(document.querySelector("[data-prepare-line]")).toBeNull();+ expect(document.querySelector("[data-home-spaces]")?.textContent ?? "").not.toContain("home-claude-code");+ expect(listText()).not.toContain("home-claude-code");+ });++ it("a Space that is not the warming home is listed as before", { timeout: 60_000 }, async () => {+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { onboarded: true, keys: "several" } });+ await waitFor(() => expect(listText()).toContain("ubuntu-build"), { timeout: 20_000 });+ });+});diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex c2bceccee7..b76591ee85 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -162,6 +162,8 @@ export interface DemoOptions {/** Another of your computers is creating a Space (`?demo=creating-elsewhere`):* the Mac mini, a macOS Space 40% of the way (CUA-2349). */creatingElsewhere?: boolean;+ /** The home's create takes its time (`?demo=slow-home`), the rest of the demo does not: the first run to look at while it is preparing. */+ slowHome?: boolean;}/** What the Mac mini is creating (`?demo=creating-elsewhere`). */@@ -292,6 +294,9 @@ export function demoOptionsFromSearch(search: string): DemoOptions {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,+ // Slow creates, to look at a state before it is gone (`?demo=slow-create`).+ ...(flags.has("slow-create") ? { stepMs: 5000 } : {}),+ ...(flags.has("slow-home") ? { slowHome: true } : {}),creatingElsewhere: flags.has("creating-elsewhere"),failCreates: flags.has("create-fail-runtime") ? "runtime-once" : flags.has("create-fail-disk") ? "disk" : undefined,...(flags.has("intel-mac") ? { platform: { os: "macos" as const, arch: "amd64" as const } } : {}),@@ -502,6 +507,26 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re}throw new HostError(failure, "runtime");}+ // The Space the new setup prepares, on a new Mac: the Linux runtime downloads, then the image, then the Space boots.+ if (config.name?.startsWith("home-")) {+ const MB = 1_048_576;+ const homeStep = options.slowHome ? 7000 : step;+ const legs: [string, string, number][] = [+ ["preparing", "Setting up the Linux runtime", 440 * MB],+ ["pulling", config.image ?? "image", 366 * MB],+ ];+ for (const [phase, detail, total] of legs) {+ for (const fraction of [0, 0.15, 0.4, 0.7, 0.9]) {+ if (job.cancelled) throw new HostError("cancelled: the create was stopped and what it made was removed", "cancelled");+ emit({ type: "spaces.createProgress", progress: { pendingId, phase, fraction, detail, space: id, bytesDone: Math.round(fraction * total), bytesTotal: total, bytesPerSecond: 5 * MB } });+ await wait(homeStep / 2);+ }+ }+ for (const phase of ["creating", "booting", "waiting_for_services", "connecting"]) {+ emit({ type: "spaces.createProgress", progress: { pendingId, phase, fraction: 0.5, detail: phase, space: id } });+ await wait(homeStep / 2);+ }+ } elsefor (const phase of CREATE_PHASES) {for (const fraction of [0, 0.5]) {if (job.cancelled) throw new HostError("cancelled: the create was stopped and what it made was removed", "cancelled");diff --git a/apps/cua-spaces-web/src/bridge/agents-dm.ts b/apps/cua-spaces-web/src/bridge/agents-dm.tsindex ac7a1dee49..de2b6a0d41 100644--- a/apps/cua-spaces-web/src/bridge/agents-dm.ts+++ b/apps/cua-spaces-web/src/bridge/agents-dm.ts@@ -16,6 +16,7 @@* answers approvals.*/+import { useHiddenSpaceIds } from "../lib/prepare/store";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { CoreClient } from "./core";@@ -238,7 +239,9 @@ export function useAgentChats(attempts: readonly ChatAttempt[] = []): AgentChatsconst [settled, setSettled] = useState(false);const [pending, setPending] = useState(0);const [round, setRound] = useState(0);- const list = (spaces ?? []).filter((s) => !s.id.startsWith("pending:"));+ // The home warming for Home's box is no agent's place until a person wrote into it.+ const warming = useHiddenSpaceIds(core);+ const list = (spaces ?? []).filter((s) => !s.id.startsWith("pending:") && !warming.has(s.id));const ids = list.map((s) => s.id).join("\n");// Not asked again for a minute: a Space with no thread (a stopped machine, an old daemon) stays that way.const misses = useRef(new MissCache(MISS_TTL_MS));diff --git a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts b/apps/cua-spaces-web/src/bridge/contracts/first-run.tsindex afc5cd67b9..f51b085dd0 100644--- a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/first-run.ts@@ -153,6 +153,8 @@ export interface FirstRunInput {cli?: FirstRunCli;/** The CLI's name (`SettingsSnapshot.cli`); null: the plan's file name, else `cua`. */cliName?: string | null;+ /** Ask first is on: no Try it screen, and the last screen's button opens the ask-first Space. */+ askFirst?: boolean;}export interface FirstRunButton {diff --git a/apps/cua-spaces-web/src/bridge/contracts/prepare.ts b/apps/cua-spaces-web/src/bridge/contracts/prepare.tsnew file mode 100644index 0000000000..31e432ba0f--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/contracts/prepare.ts@@ -0,0 +1,128 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Preparing the ask-first Space (the Linux runtime, the agent image, the home+ * Space, the coding agent): types mirroring+ * `cua-spaces-app-core/src/prepare.rs` (the state machine, its page and its+ * numbers).+ */++export type PrepareStepId = "runtime" | "image" | "home" | "agent";+export type PrepareStepState = "pending" | "running" | "waiting" | "failed" | "done" | "skipped";+export type PrepareMessageState = "queued" | "delivering" | "delivered";++export interface PrepareStepRecord {+ state: PrepareStepState;+ done: number;+ total: number;+ perSecond: number | null;+ startedMs: number | null;+ finishedMs: number | null;+}++export interface PrepareMessage {+ id: string;+ text: string;+ agent: string;+ model: string | null;+ repo: string | null;+ state: PrepareMessageState;+ attempts: number;+ sentMs: number;+ claimedMs: number | null;+ deliveredMs: number | null;+ firstTokenMs: number | null;+}++/** The record the host keeps between launches (`schema` 1). */+export interface PrepareState {+ schema: number;+ wanted: boolean;+ startedMs: number | null;+ onboardingDoneMs: number | null;+ runtime: PrepareStepRecord;+ image: PrepareStepRecord;+ home: PrepareStepRecord;+ agent: PrepareStepRecord;+ harness: string;+ homeSpaceId: string | null;+ pendingId: string | null;+ attempt: number;+ failures: number;+ retryAtMs: number | null;+ trouble: { network: boolean; message: string } | null;+ online: boolean;+ readyMs: number | null;+ /** When a person first wrote into the home; until then no list shows it. */+ askedMs: number | null;+ messages: PrepareMessage[];+}++export type PrepareAction =+ | { type: "start"; nowMs: number; harness?: string | null; pendingId?: string | null }+ | { type: "onboardingDone"; nowMs: number }+ | { type: "phase"; nowMs: number; phase: string; detail?: string; done?: number | null; total?: number | null; perSecond?: number | null }+ | { type: "runtimeNotNeeded"; nowMs: number }+ | { type: "homeReady"; nowMs: number; spaceId: string }+ | { type: "agentReady"; nowMs: number }+ | { type: "failed"; nowMs: number; message: string; network?: boolean }+ | { type: "online"; nowMs: number; online: boolean }+ | { type: "tick"; nowMs: number }+ | { type: "retry"; nowMs: number }+ | { type: "resume"; nowMs: number }+ | { type: "homeGone"; nowMs: number }+ | { type: "send"; nowMs: number; id: string; text: string; agent?: string; model?: string | null; repo?: string | null }+ | { type: "delivered"; nowMs: number; id: string }+ | { type: "deliveryFailed"; nowMs: number; id: string }+ | { type: "threadHas"; nowMs: number; id: string; found: boolean }+ | { type: "firstToken"; nowMs: number; id: string }+ | { type: "asked"; nowMs: number };++export type PrepareEffect =+ | { type: "create" }+ | { type: "attachAgent" }+ | { type: "deliver"; id: string }+ | { type: "verifyDelivery"; id: string }+ | { type: "wakeAt"; atMs: number };++export interface PrepareReduced {+ state: PrepareState;+ effects: PrepareEffect[];+}++export interface PrepareStepView {+ id: PrepareStepId;+ label: string;+ state: PrepareStepState;+ detail: string | null;+ /** 0 to 1: the one thin bar of the block, under the current step only. */+ fraction: number | null;+}++export interface PrepareQueuedView {+ id: string;+ text: string;+ note: string;+}++export interface PrepareView {+ phase: "idle" | "preparing" | "waiting" | "failed" | "ready";+ title: string;+ /** Only when the steps cannot say it (connection lost, stopped, ready); null while preparing. */+ line: string | null;+ steps: PrepareStepView[];+ queued: PrepareQueuedView[];+ composerHint: string | null;+ action: { id: string; label: string } | null;+}++export interface PrepareMetrics {+ runtimeMs: number | null;+ imageMs: number | null;+ homeMs: number | null;+ agentMs: number | null;+ prepareMs: number | null;+ onboardingToReadyMs: number | null;+ messages: { id: string; sendToDeliveredMs: number | null; sendToFirstTokenMs: number | null }[];+}diff --git a/apps/cua-spaces-web/src/bridge/first-run.ts b/apps/cua-spaces-web/src/bridge/first-run.tsindex 2d2ca3e9c8..71090ae5e7 100644--- a/apps/cua-spaces-web/src/bridge/first-run.ts+++ b/apps/cua-spaces-web/src/bridge/first-run.ts@@ -59,6 +59,7 @@ import { onboardingInitial, onboardingTelemetry, onboardingView, readSavedOnboarimport type { OnboardingFlowState } from "./contracts/onboarding";import { useRelayUsage } from "./relay-usage";import { useAgentKeys } from "./agent-keys";+import { useNewOnboarding } from "./flags";import { newPendingId } from "./store";import { extraName, spokenName } from "./space-names";import { runCreateFix } from "./create-retry";@@ -115,7 +116,8 @@ export function cliMissing(cli: FirstRunCli | undefined): boolean {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"];+ // Ask first has no Try it screen: the person asks in the ask-first Space.+ return ["welcome", "connect", ...(cli ? ["cli" as const] : []), "devices", ...(asks ? ["permissions" as const] : []), ...(input.askFirst ? [] : ["setup" as const])];}/** The two permissions a shared screen needs (`firstRun.permissions`): the@@ -163,8 +165,10 @@ function fallbackView(input: FirstRunInput): FirstRunView {const lead = connected[0] ?? null;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 step: FirstRunStep = steps.includes(input.step) ? input.step : input.askFirst ? steps[steps.length - 1]! : "setup";const at = Math.max(steps.indexOf(step), 0);+ /** The button that ends an ask-first run says where it goes. */+ const continueLabel = (of: FirstRunStep) => (input.askFirst && steps[steps.length - 1] === of ? "Open Cua" : "Continue");const base: FirstRunView = {step,later: "Skip for now",@@ -232,7 +236,7 @@ function fallbackView(input: FirstRunInput): FirstRunView {{ title: "Your cloud", note: "Hetzner, AWS, Google Cloud or Modal" },],status: null,- primary: input.signedIn ? { id: "continue", label: "Continue" } : { id: "sign-in", label: "Sign in" },+ primary: input.signedIn ? { id: "continue", label: continueLabel("devices") } : { id: "sign-in", label: "Sign in" },secondary: input.signedIn ? null : { id: "not-now", label: "Not now" },note: input.signedIn ? null : `Not now keeps Cua on ${place} only. You can sign in later.`,},@@ -264,7 +268,7 @@ function fallbackView(input: FirstRunInput): FirstRunView {: `Allow two permissions so your team and agents can see and use ${place}.`,rows,note: `Allow opens System Settings, where you turn on ${host?.appName || "Cua Spaces"}.`,- primary: all ? { id: "continue", label: "Continue" } : null,+ primary: all ? { id: "continue", label: continueLabel("permissions") } : null,secondary: all ? null : { id: "not-now", label: "Not now" },},};@@ -569,7 +573,7 @@ export function useScreenPermissions(active = true, pollMs = FIRST_RUN_POLL_MS):}/** Live readings while `active` (the first run, or what reads its state). */-export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunHook {+export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS, onFinished?: () => void): FirstRunHook {const ctx = useContext(BridgeContext);if (!ctx) throw new Error("bridge hooks need a <BridgeProvider> above them");const { core, adapter, store } = ctx;@@ -579,6 +583,9 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunconst spaces = useSpaces();const offersHook = useFirstSpaceOffers();const usage = useRelayUsage();+ // The new setup (Settings, Advanced, Labs; off by default): no Try it screen, and the run ends on the new+ // Home while the first Space gets ready. Off, the first run is the one every install has.+ const askFirst = useNewOnboarding();const flags = useSyncExternalStore(subscribe, () => `${flag(UPSELL_DISMISSED_KEY)}:${flag(TEAMMATES_KEY)}`, () => "false:false");const [agents, setAgents] = useState<AgentSetupRow[] | null>(null);// The one connection status (`agents.status`); none where the host can't tell.@@ -729,11 +736,12 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunplan,cli: cli.state,cliName: settings.data?.cli?.name ?? null,+ askFirst,};// The lead connected agent (the core's order), for the try screen's access log.const leadName = (() => {- const v = firstRunView(core, { ...baseInput, step: "setup" });+ const v = firstRunView(core, { ...baseInput, step: "setup", askFirst: false });const t = v.setup?.prompt ? v.setup.title.replace(/^Try it in /, "").replace(/\.$/, "") : null;return t;})();@@ -798,6 +806,19 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunelse funnel("step_skipped", "step");go(shown[Math.min(at + 1, shown.length - 1)]!);};+ async function finishRun() {+ // "Not now" on the first Space card already counted that screen as skipped.+ if (extra.phase !== "not-now") funnel("step_completed");+ if (store) track(() => store.trackOnboardingFinished(telemetryState()));+ await session.completeOnboarding(host?.configured ? "host" : "client");+ writeFirstRun({ finishedLater: false, todosClosed: false });+ }+ /** The last screen's button with the new setup on: the run is finished and the app opens Home. */+ const endRun = async (how: "completed" | "skipped" = "completed") => {+ if (how === "skipped") funnel("step_skipped", "step");+ await finishRun();+ onFinished?.();+ };// Each screen is counted when it shows (once per arrival).useEffect(() => {@@ -957,14 +978,18 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunopenUrl: (url) => session.openExternal(url).catch(() => {}),extra: extraAct,async act(id, settingsUrl) {+ // With the new setup, the last screen ends the run: the person asks on Home while the first Space is prepared.+ const last = askFirst && at === shown.length - 1 && view.step !== "welcome";switch (id) {case "start":case "continue":- forward();+ if (last) await endRun();+ else forward();break;case "skip":case "not-now":- forward("skipped");+ if (last) await endRun("skipped");+ else forward("skipped");break;case "advanced":case "simple":@@ -1002,13 +1027,7 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRun}refresh();},- async finish() {- // "Not now" on the first Space card already counted that screen as skipped.- if (extra.phase !== "not-now") funnel("step_completed");- if (store) track(() => store.trackOnboardingFinished(telemetryState()));- await session.completeOnboarding(host?.configured ? "host" : "client");- writeFirstRun({ finishedLater: false, todosClosed: false });- },+ finish: finishRun,later() {funnel("step_skipped", "later");leftAtMs = Date.now();diff --git a/apps/cua-spaces-web/src/bridge/flags.ts b/apps/cua-spaces-web/src/bridge/flags.tsindex a2b91d587e..943f4f6dec 100644--- a/apps/cua-spaces-web/src/bridge/flags.ts+++ b/apps/cua-spaces-web/src/bridge/flags.ts@@ -24,10 +24,15 @@ import { useSyncExternalStore } from "react";* Home page that asks what you want done, starts it on a fresh computer and* follows it as a conversation. Settings → Advanced → Labs turns it on for* this device.+ * - `spaces_new_onboarding`: the new setup (CUA-2851): the first Linux Space+ * and its coding agent get ready while the person goes through the first+ * run, which has no "Try it" screen and ends on the "Ask first" Home. It+ * needs that Home, so it counts only while `spaces_ask_first_home` is on+ * too (Labs turns both on). Off by default: the first run stays as it is.*/-export type FlagName = "upsell_cards" | "spaces_ask_first_home";+export type FlagName = "upsell_cards" | "spaces_ask_first_home" | "spaces_new_onboarding";-const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false };+const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false, spaces_new_onboarding: false };const key = (name: string) => `cua.flag.${name}`;@@ -100,3 +105,14 @@ const subscribe = (l: () => void) => {export function useFlag(name: FlagName): boolean {return useSyncExternalStore(subscribe, () => flagOn(name), () => DEFAULTS[name]);}++/** The new setup is on: its own switch and the "Ask first" Home it ends on. */+export function newOnboardingOn(): boolean {+ return flagOn("spaces_new_onboarding") && flagOn("spaces_ask_first_home");+}++export function useNewOnboarding(): boolean {+ const own = useFlag("spaces_new_onboarding");+ const home = useFlag("spaces_ask_first_home");+ return own && home;+}diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex f3853b6da5..2c890e3eb4 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -117,6 +117,7 @@ export { signInFailedFromError, signInFailedPhase, signInFooter, type FailedPhasexport {useCloudActions,useConnectCloud,+ useFirstPrompts,useFirstSpaceOffers,useNewSpaceRequests,useNewSpaceWizard,@@ -128,9 +129,11 @@ export {type RuntimeFixHook,} from "./new-space-hooks";export { runCreateFix, type CreateFixActions } from "./create-retry";-export { createFailedText, emptyHome, type EmptyHome, type EmptyTile, type FirstSpaceOffer } from "./new-space";+export { createFailedText, emptyHome, type EmptyHome, type EmptyTile, type FirstPrompts, type FirstSpaceOffer, type PromptCap, type PromptExample, type PromptSuggestion } from "./new-space";export type * from "./contracts/volume";export * from "./volume";+export type * from "./contracts/prepare";+export * from "./prepare-core";export { ThumbnailStore, THUMBNAIL_CAP, THUMBNAIL_REFRESH_MS, thumbnailStore, useSpaceThumbnail } from "./thumbnails";export { useWindowDropTarget } from "./window-drop";export { useSpaceFiles, parseDropped, dropSendingText, dropSentText, sendFiles, splitDrop, type DropStatus, type SpaceFilesHook } from "./space-files";@@ -237,7 +240,7 @@ export {type UpsellPrompt,type UpsellSurface,} from "./upsell";-export { flagOn, setFlagOverride, setRemoteFlags, useFlag, type FlagName } from "./flags";+export { flagOn, newOnboardingOn, setFlagOverride, setRemoteFlags, useFlag, useNewOnboarding, type FlagName } from "./flags";export type { CreateReport, ReportPart, ReportSend } from "./diagnostic-report";export {FIRST_RUN_POLL_MS,diff --git a/apps/cua-spaces-web/src/bridge/new-space-hooks.ts b/apps/cua-spaces-web/src/bridge/new-space-hooks.tsindex ddfe8286b1..0f6895b29f 100644--- a/apps/cua-spaces-web/src/bridge/new-space-hooks.ts+++ b/apps/cua-spaces-web/src/bridge/new-space-hooks.ts@@ -3,7 +3,7 @@/** New Space and "Connect a cloud" for components (see `new-space.ts`). */-import { useContext, useEffect, useRef, useState, useSyncExternalStore } from "react";+import { useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { isUnsupported } from "./adapter";import { BridgeContext } from "./BridgeProvider";import type { CoreClient } from "./core";@@ -17,6 +17,7 @@ import {cloudSheetInput,cloudSheetReduce,cloudSheetView,+ firstPrompts,firstSpaceOffers,localBlocked,loadNewSpaceHostData as loadHostData,@@ -30,6 +31,7 @@ import {wizardOffered,wizardReduce,wizardView,+ type FirstPrompts,type FirstSpaceOffer,type NewSpaceSession,} from "./new-space";@@ -207,6 +209,12 @@ export function useFirstSpaceOffers(): FirstSpaceHook {};}+/** The example jobs for this machine, the core's choice from what it can do now; null until the core is ready. */+export function useFirstPrompts(): FirstPrompts | null {+ const { core, env } = useNewSpaceEnv();+ return useMemo(() => firstPrompts(core, env), [core, env]);+}+/*** The host's requests for New Space (the SwiftUI app's menu items and* notch, `spaces.newRequested`): opens the wizard once the core is ready,diff --git a/apps/cua-spaces-web/src/bridge/new-space.ts b/apps/cua-spaces-web/src/bridge/new-space.tsindex f1169da45f..035a9b4e3f 100644--- a/apps/cua-spaces-web/src/bridge/new-space.ts+++ b/apps/cua-spaces-web/src/bridge/new-space.ts@@ -170,6 +170,50 @@ export interface FirstSpaceOffer {args: CreateSpaceArgs;}+/** What an example needs (`first_prompts::Cap`). */+export type PromptCap = "linux-space" | "macos-space" | "windows-space" | "kvm" | "fill-in" | "account";++/** One example job card on an empty Home (`first_prompts::Suggestion`). */+export interface PromptSuggestion {+ id: string;+ family: string;+ title: string;+ detail: string;+ os: "linux" | "macos" | "windows";+ prompt: string;+ why: string;+ needs: PromptCap[];+}++/** One example to copy (`first_prompts::Example`): a whole prompt that needs no repo and no account. */+export interface PromptExample {+ id: string;+ family: string;+ text: string;+ /** Why this is useful, one line. */+ why: string;+ needs: PromptCap[];+}++/** The example jobs for this machine (`first_prompts::FirstPrompts`): examples to copy, best fit first, and Home's cards. */+export interface FirstPrompts {+ caps: { macos: boolean; windows: boolean; kvm: boolean; macosCached: boolean; windowsCached: boolean };+ /** Onboarding's one example sentence, from the bug-on-platform entries: a system this machine can run. */+ lede: string;+ examples: PromptExample[];+ suggestions: PromptSuggestion[];+}++/**+ * The jobs the app suggests, chosen by the core from what this machine can do now (`firstPrompts.choose`):+ * always a job that works on every host, and a macOS job only where a macOS Space can be made. No shell+ * keeps a sentence of its own. Null without the core.+ */+export function firstPrompts(core: CoreClient, env: WizardEnv, os: HostOs = hostOs()): FirstPrompts | null {+ if (core.status !== "ready" || !core.methods.includes("firstPrompts.choose")) return null;+ return core.call<FirstPrompts>("firstPrompts.choose", { env, hostOs: os });+}+/** Bytes the way the wizard shows them (binary units labeled GB). */export function sizeText(bytes: number): string {const gb = bytes / 1024 ** 3;diff --git a/apps/cua-spaces-web/src/bridge/parity.ts b/apps/cua-spaces-web/src/bridge/parity.tsindex abc37a0de5..27e4ab0d60 100644--- a/apps/cua-spaces-web/src/bridge/parity.ts+++ b/apps/cua-spaces-web/src/bridge/parity.ts@@ -55,6 +55,7 @@ import {telemetryShare,telemetryStorage,} from "./telemetry";+import { prepareHidden, prepareListed, prepareMetrics, prepareReduce, prepareView } from "./prepare-core";import { hostFormInitial, hostFormReduce, hostFormView, type HostFormView } from "./this-machine";import type { AccountMenuInput, ProBannerInput } from "./contracts/spaces-page";import {@@ -224,6 +225,12 @@ function spacesPageMethods(core: CoreClient): Record<string, (a: Args) => unknow"settings.choose": (a) => chooseSettings(core, a.settings, a.row, a.option),"upsell.proBanner": (a) => proBanner(core, a as ProBannerInput),"account.menu": (a) => accountMenu(core, a as AccountMenuInput),+ // Preparing the ask-first Space (prepare-core.ts).+ "prepare.reduce": (a) => prepareReduce(core, a.state, a.action),+ "prepare.view": (a) => prepareView(core, a.state),+ "prepare.metrics": (a) => prepareMetrics(core, a.state),+ "prepare.hidden": (a) => prepareHidden(core, a.state),+ "prepare.listed": (a) => prepareListed(core, a.state, a.ids),};}diff --git a/apps/cua-spaces-web/src/bridge/prepare-core.ts b/apps/cua-spaces-web/src/bridge/prepare-core.tsnew file mode 100644index 0000000000..37f4b84b5c--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/prepare-core.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The app core's preparing state machine (`prepare.reduce`, `prepare.view`,+ * `prepare.metrics`; `cua-spaces-app-core/src/prepare.rs`). Without the core+ * there is nothing to prepare: every call answers `null`.+ */++import type { CoreClient } from "./core";+import type { PrepareAction, PrepareMetrics, PrepareReduced, PrepareState, PrepareView } from "./contracts/prepare";++export function prepareReduce(core: CoreClient, state: PrepareState | null, action: PrepareAction): PrepareReduced | null {+ return core.tryCall<PrepareReduced>("prepare.reduce", { state, action }) ?? null;+}++export function prepareView(core: CoreClient, state: PrepareState | null): PrepareView | null {+ return core.tryCall<PrepareView>("prepare.view", { state }) ?? null;+}++export function prepareMetrics(core: CoreClient, state: PrepareState | null): PrepareMetrics | null {+ return core.tryCall<PrepareMetrics>("prepare.metrics", { state }) ?? null;+}++/** The Spaces no list shows (`prepare.hidden`): the home warming for Home's box until a person wrote into it. */+export function prepareHidden(core: CoreClient, state: PrepareState | null): string[] {+ return core.tryCall<string[]>("prepare.hidden", { state }) ?? [];+}++/** `ids` as a list shows them (`prepare.listed`): without the hidden ones. */+export function prepareListed(core: CoreClient, state: PrepareState | null, ids: string[]): string[] {+ return core.tryCall<string[]>("prepare.listed", { state, ids }) ?? ids;+}diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.tsindex d41e36df76..199ee08136 100644--- a/apps/cua-spaces-web/src/bridge/store.ts+++ b/apps/cua-spaces-web/src/bridge/store.ts@@ -9,6 +9,7 @@* `state/cloud.tsx` does. Hooks read it with `useSyncExternalStore`.*/+import { hiddenSpaceIdsNow, onHiddenSpacesChange } from "../lib/prepare/store";import { cloudsInput, cloudsView } from "./clouds";import { hostOs } from "./host-os";import { spokenName } from "./space-names";@@ -186,6 +187,9 @@ export interface CreateSpaceRequest extends SpaceCreateConfig {/** The host also posts a system notification when it is ready (the* first run's extra Space, which keeps going after the window closes). */notifyWhenReady?: boolean;+ /** The image is the app's own choice (the agent home's), not a reference the person typed: it is not+ * checked against the catalog's published list, and a pull that cannot happen says why in plain words. */+ appImage?: boolean;}export interface StoreOptions {@@ -311,8 +315,14 @@ export class BridgeStore {this.details = new SpaceDetailStore(adapter, core);this.thisMachine = new ThisMachineStore(adapter, core, () => this.refresh("machines"));this.telemetry = new TelemetryForwarder(adapter, () => this.telemetryView());+ // The Machines page follows what the lists hide (the warming home appears once a person wrote into it).+ this.offHidden = onHiddenSpacesChange(() => {+ if (!this.disposed && this.resources.spaces.data) this.publishMachines();+ });}+ private offHidden?: () => void;+/* ---- usage events (telemetry.ts) ---- *//** Records `app_launched` where the host doesn't (BridgeProvider, once per page). */@@ -587,6 +597,8 @@ export class BridgeStore {const shown = (this.resources.spaces.data as Space[] | undefined)?.find((s) => s.id === p.id);const name = shown?.name || p.name.trim() || "a Space";// Why, in the words the failed row shows.+ // The warming home's failure is Home's to say (Try again there), not a notification.+ if (hiddenSpaceIdsNow(this.core).includes(p.id)) continue;this.extras.record({ kind: "error", title: `Couldn't create ${name}`, body: shown?.progress?.error ?? p.error });}}@@ -626,7 +638,7 @@ export class BridgeStore {}private beginCreate(req: CreateSpaceRequest, id?: string): { pendingId: string; done: Promise<Space> } {- if (req.image) {+ if (req.image && !req.appImage) {const problem = validateImageRef(this.core, req.image);if (problem) return { pendingId: "", done: Promise.reject(new Error(problem)) };}@@ -636,7 +648,7 @@ export class BridgeStore {}private async runCreate(req: CreateSpaceRequest, pendingId: string): Promise<Space> {- const { os: _os, notifyWhenReady, ...config } = req;+ const { os: _os, notifyWhenReady, appImage: _appImage, ...config } = req;const os = osOf(req);const on = config.on ?? this.settingsSnap?.values.defaultLocation ?? "local";// A Space on one of your machines or in your own cloud lists as a relay machine.@@ -671,7 +683,8 @@ export class BridgeStore {// Plain words: a fresh computer inside this one (never "VM" or "container").const system = space.os === "macos" ? "macOS" : space.os === "windows" ? "Windows" : space.os === "linux" ? "Linux" : null;const body = system ? `A fresh ${system} computer inside ${({ macos: "this Mac", windows: "this PC", linux: "this machine" } as const)[hostOs()]}. Your agent can use it now.` : undefined;- this.extras.record({ kind: "message", title: `${spokenName(space.name)} is ready`, ...(body && !machine ? { body } : {}), space: space.id });+ // Nor is the warming home "ready" news until a person wrote into it.+ if (!hiddenSpaceIdsNow(this.core).some((h) => h === space.id || h === pendingId)) this.extras.record({ kind: "message", title: `${spokenName(space.name)} is ready`, ...(body && !machine ? { body } : {}), space: space.id });return space;} catch (e) {const message = toError(e).message;@@ -850,7 +863,9 @@ export class BridgeStore {/* ---- machines ---- */private publishMachines(): void {- const spaces = (this.resources.spaces.data as Space[] | undefined) ?? [];+ // The home warming for Home's box is on no machine's list until a person wrote into it (the core's rule).+ const warming = new Set(hiddenSpaceIdsNow(this.core));+ const spaces = ((this.resources.spaces.data as Space[] | undefined) ?? []).filter((s) => !warming.has(s.id));let machines: Machine[] = toMachines(this.machineRows, spaces, this.core, this.machinesNow);const override = this.hostOverride;if (override) {@@ -1594,6 +1609,7 @@ export class BridgeStore {dispose(): void {this.disposed = true;+ this.offHidden?.();this.extras.dispose();this.unsubscribe?.();this.details.dispose();diff --git a/apps/cua-spaces-web/src/components/ask-first/home.tsx b/apps/cua-spaces-web/src/components/ask-first/home.tsxindex eaa94c59f2..62d32d98f8 100644--- a/apps/cua-spaces-web/src/components/ask-first/home.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/home.tsx@@ -16,6 +16,8 @@ import { YourAgents, YourSpaces as YourSpacesRow } from "./home-sections";import { useWherePick } from "./this-mac-confirm";import { useStartTask } from "./use-start-task";import { useWhereOptions } from "./where-options";+import { PrepareLine } from "@/components/prepare/prepare-line";+import { usePrepare } from "@/lib/prepare/store";/** The run a task follows, from the runs in your running Spaces. */export function taskRun(runs: readonly AgentRunSummary[] | undefined, task: AskTask): AgentRunSummary | undefined {@@ -65,6 +67,8 @@ export function AskFirstHome() {const chosenAgent = agent ?? mostUsed ?? TASK_AGENTS.find((a) => installed.has(a.id))?.id ?? "claude-code";// A new Linux computer unless you pick; a pick that's no longer offered falls back to it.const [picked, setWhere] = useState<TaskWhere | null>(null);+ // The first Space being prepared since launch (Labs, the new setup): silent unless it fails.+ const prep = usePrepare();const [whereOpen, setWhereOpen] = useState(false);const pick = useWherePick(agentName(chosenAgent));const where = currentWhere(picked, kinds, pickable);@@ -78,7 +82,10 @@ export function AskFirstHome() {// or tasks whose Spaces are gone), Home is the welcome again.const attempts = useAgentAttempts();const { chats } = useAgentChats(attempts);- const first = !chats?.length && listed.counted.length === 0;+ // The home being prepared since launch, and the agent waiting in it, are not "yours" yet: until a job+ // is asked for, the welcome and its suggestions stay.+ const prepared = (id: string) => Boolean(prep.state?.wanted && (id === prep.state.homeSpaceId || id === prep.state.pendingId));+ const first = prep.state?.wanted ? tasks.length === 0 && listed.counted.every((c) => prepared(c.id)) : !chats?.length && listed.counted.length === 0;return (<div className="h-full overflow-y-auto [scrollbar-gutter:stable]" data-ask-first-home="">@@ -102,6 +109,8 @@ export function AskFirstHome() {compact={!first}autoFocus/>+ {/* Preparing is silent: only a failed prepare says so, with Try again. */}+ <PrepareLine view={prep.view} onRetry={() => prep.driver?.retry()} />{first ? (<><div className="grid gap-4 sm:grid-cols-3">@@ -109,6 +118,7 @@ export function AskFirstHome() {<buttontype="button"key={s.title}+ data-home-card=""onClick={() => {setText(s.prompt);setWhere({ kind: "new", os: kinds.some((k) => k.os === s.os) ? s.os : "linux" });diff --git a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts b/apps/cua-spaces-web/src/components/ask-first/use-start-task.tsindex 16f7fee7b7..9f4e2cc21a 100644--- a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts+++ b/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts@@ -3,10 +3,11 @@import { useNavigate, useRouter } from "@tanstack/react-router";-import { firstMessage, newPendingId, threadOpAvailable, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useSpaces, type AgentMember, type HostStatus } from "@/bridge";+import { firstMessage, newPendingId, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useSpaces, type HostStatus } from "@/bridge";+import { useSummonIn } from "@/components/ask-first/use-summon-in";import { enqueue, flushQueue, resolveQueue } from "@/components/space-thread/queued";-import { sendWithSummon } from "@/components/space-thread/summon";import { useConnectors } from "@/hooks/use-connectors";+import { getDriver } from "@/lib/prepare/store";import { addAskTask, askTask, HOST_NOT_SHARED, hostSpaceId, postToSpaceThread, retryTarget, taskTarget, updateAskTask, whereOs, type AskTask, type TaskTarget, type TaskWhere } from "@/lib/ask-first";/** Task and Space pairs whose thread already has the task's job. */@@ -36,24 +37,7 @@ export function useStartTask(): {// the job is its first message, @mentioning the agent (the same summon as the composer's).const { input: connectors } = useConnectors();- /** What summoning reads for `spaceId`: its agents now and this device's connectors. */- const summonInput = async (spaceId: string) => {- const members = ((await host!.call("thread.members", { spaceId }).catch(() => null))?.members ?? []) as AgentMember[];- return { members: members.map((m) => ({ handle: m.name, harness: m.harness, label: m.name })), people: [], canAdd: true, connectors };- };- const send = (spaceId: string, input: Awaited<ReturnType<typeof summonInput>>) => (text: string) =>- sendWithSummon({ core, data: host!, spaceId, input, text, post: (t) => host!.call("thread.post", { spaceId, text: t }) });- const canSummon = () => !!host && threadOpAvailable(host.mode, "thread.agentAdd");-- /** The job as the Space's first message, through the summon; false when this agent can't join a Space. */- const summonIn = async (spaceId: string, agent: string, prompt: string): Promise<boolean> => {- if (!canSummon()) return false;- const input = await summonInput(spaceId);- const first = firstMessage(core, input, agent, prompt);- if (!first?.handle) return false;- await send(spaceId, input)(first.text);- return true;- };+ const { summonInput, send, summonIn, canSummon } = useSummonIn();const run = (id: string, target: TaskTarget, place?: { pendingId?: string; queued?: boolean; onCreated?: (spaceId: string) => void }) =>void (async () => {@@ -103,6 +87,18 @@ export function useStartTask(): {return {start: ({ prompt, agent, where }) => {const target = taskTarget(where);+ // The new setup (Labs) made a Linux Space for this agent while the person was in the first run: the job is+ // kept by the preparing driver, which sends it exactly once when the agent is ready, even across a quit.+ const preparing = getDriver();+ const prep = preparing?.state;+ if (preparing && prep?.wanted && prep.harness === agent && target.kind === "create" && target.os === "linux") {+ const spaceId = prep.homeSpaceId;+ const task = addAskTask({ prompt: prompt.trim(), agent, os: "linux", spaceId, pendingId: spaceId ? null : prep.pendingId, onHost: false });+ record("ask_first_task_started");+ preparing.send({ id: task.id, text: prompt.trim(), agent });+ void navigate({ to: "/spaces/$spaceId", params: { spaceId: spaceId ?? prep.pendingId! } });+ return;+ }const task = addAskTask({ prompt: prompt.trim(), agent, os: whereOs(where), spaceId: target.kind === "space" ? target.spaceId : null, onHost: target.kind === "host" });record("ask_first_task_started");// Straight to the Space: the one picked or the one being made (its page follows the create); this Mac opens the task's page.diff --git a/apps/cua-spaces-web/src/components/ask-first/use-summon-in.ts b/apps/cua-spaces-web/src/components/ask-first/use-summon-in.tsnew file mode 100644index 0000000000..2b701ffefa--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/use-summon-in.ts@@ -0,0 +1,49 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { firstMessage, threadOpAvailable, useBridge, type AgentMember } from "@/bridge";+import { sendWithSummon } from "@/components/space-thread/summon";+import { useConnectors } from "@/hooks/use-connectors";++/**+ * Putting a message in a Space's thread the way the composer does: through+ * the summon, so `@claude ...` adds the agent when it is not a member yet.+ * Ask first's box and the preparing driver both post through this, so a+ * message queued while the home was made and one typed once it was ready go+ * the same way.+ */+export function useSummonIn() {+ const { data: host, core } = useBridge();+ const { input: connectors } = useConnectors();++ /** What summoning reads for `spaceId`: its agents now and this device's connectors. */+ const summonInput = async (spaceId: string) => {+ const members = ((await host!.call("thread.members", { spaceId }).catch(() => null))?.members ?? []) as AgentMember[];+ return { members: members.map((m) => ({ handle: m.name, harness: m.harness, label: m.name })), people: [], canAdd: true, connectors };+ };+ const send = (spaceId: string, input: Awaited<ReturnType<typeof summonInput>>) => (text: string) =>+ sendWithSummon({ core, data: host!, spaceId, input, text, post: (t) => host!.call("thread.post", { spaceId, text: t }) });+ const canSummon = () => !!host && threadOpAvailable(host.mode, "thread.agentAdd");++ /**+ * The job as the Space's first message, through the summon; false when this agent can't join a Space. A+ * home's agent is kept on standby with the picked model (adding it again updates it), so its session is open+ * before the first words and the model it asks for is the one its next turn uses.+ */+ const summonIn = async (spaceId: string, agent: string, prompt: string, model?: string, standby = false, brief?: string): Promise<boolean> => {+ if (!canSummon()) return false;+ const input = await summonInput(spaceId);+ const first = firstMessage(core, input, agent, prompt);+ if (!first?.handle) return false;+ if (standby || model || brief) {+ await host!+ .call("thread.agentAdd", { spaceId, name: first.handle, harness: first.harness || agent, ...(model ? { model } : {}), ...(standby ? { standby: true } : {}), ...(brief ? { brief } : {}) })+ .catch(() => null);+ }+ // The member is in now: the message goes with it listed.+ await send(spaceId, standby || model || brief ? await summonInput(spaceId) : input)(first.text);+ return true;+ };++ return { summonInput, send, summonIn, canSummon };+}diff --git a/apps/cua-spaces-web/src/components/ask-first/where-options.ts b/apps/cua-spaces-web/src/components/ask-first/where-options.tsindex e35ea24197..2c5c3ef378 100644--- a/apps/cua-spaces-web/src/components/ask-first/where-options.ts+++ b/apps/cua-spaces-web/src/components/ask-first/where-options.ts@@ -3,7 +3,8 @@import { useMemo } from "react";-import { useFirstSpaceOffers, useSpaces, type Space } from "@/bridge";+import { useBridge, useFirstSpaceOffers, useSpaces, type Space } from "@/bridge";+import { useHiddenSpaceIds } from "@/lib/prepare/store";import { pickableSpaces, type NewKind } from "@/lib/ask-first";/** What "Where it runs" offers: the kinds of new computer this Mac can make, and the running Spaces you have. */@@ -14,6 +15,8 @@ export function useWhereOptions(): { kinds: NewKind[]; spaces: Space[] } {const k = offers.map((o) => ({ os: o.os, note: `Free. Ready in ${o.time}${o.size ? ` (${o.size})` : ""}.`, blocked: o.blocked }));return k.length ? k : [{ os: "linux", note: "Free. Ready in a few minutes.", blocked: null }];}, [offers]);- const spaces = useMemo(() => pickableSpaces(data), [data]);+ const { core } = useBridge();+ const warming = useHiddenSpaceIds(core);+ const spaces = useMemo(() => pickableSpaces(data?.filter((s) => !warming.has(s.id))), [data, warming]);return { kinds, spaces };}diff --git a/apps/cua-spaces-web/src/components/prepare/prepare-line.test.tsx b/apps/cua-spaces-web/src/components/prepare/prepare-line.test.tsxnew file mode 100644index 0000000000..6bb213690e--- /dev/null+++ b/apps/cua-spaces-web/src/components/prepare/prepare-line.test.tsx@@ -0,0 +1,29 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { PrepareView } from "@/bridge";++import { PrepareLine } from "./prepare-line";++const view = (phase: string, extra: Partial<PrepareView> = {}) =>+ ({ phase, line: "Preparing stopped: disk is full", action: null, steps: [], queued: [], title: "", composerHint: null, ...extra }) as unknown as PrepareView;++afterEach(cleanup);++describe("PrepareLine", () => {+ it.each(["preparing", "pulling", "booting", "waiting", "ready", "idle"])("shows nothing while %s", (phase) => {+ const { container } = render(<PrepareLine view={view(phase, { line: "anything" })} />);+ expect(container.innerHTML).toBe("");+ });++ it("shows a quiet error with Try again only when failed", () => {+ const retry = vi.fn();+ const { container, getByText } = render(<PrepareLine view={view("failed", { action: { id: "retry", label: "Try again" } as never })} onRetry={retry} />);+ expect(container.textContent).toContain("Preparing stopped");+ fireEvent.click(getByText("Try again"));+ expect(retry).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/cua-spaces-web/src/components/prepare/prepare-line.tsx b/apps/cua-spaces-web/src/components/prepare/prepare-line.tsxnew file mode 100644index 0000000000..39c245b49d--- /dev/null+++ b/apps/cua-spaces-web/src/components/prepare/prepare-line.tsx@@ -0,0 +1,24 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import type { PrepareView } from "@/bridge";++/**+ * Warming happens silently: this shows nothing in any state but one. When preparing failed and will not clear+ * by itself, Home says so quietly with Try again, because the first agent must stay recoverable. The words are+ * the core's (`prepare.view`: "Preparing stopped: ...").+ */+export function PrepareLine({ view, onRetry }: { view: PrepareView | null; onRetry?: () => void }) {+ if (!view || view.phase !== "failed") return null;+ return (+ <p data-prepare-line="" data-prepare-phase="failed" role="status" className="flex items-center gap-2 px-2 text-[12px] text-muted-foreground">+ <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-destructive" />+ <span className="min-w-0 truncate">{view.line ?? "Preparing stopped"}</span>+ {view.action && onRetry ? (+ <button type="button" onClick={onRetry} data-prepare-action={view.action.id} className="shrink-0 text-foreground underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring/60">+ {view.action.label}+ </button>+ ) : null}+ </p>+ );+}diff --git a/apps/cua-spaces-web/src/components/prepare/prepare-panel.test.tsx b/apps/cua-spaces-web/src/components/prepare/prepare-panel.test.tsxnew file mode 100644index 0000000000..7eedb33455--- /dev/null+++ b/apps/cua-spaces-web/src/components/prepare/prepare-panel.test.tsx@@ -0,0 +1,59 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { cleanup, render } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { prepareReduce, prepareView, type PrepareAction, type PrepareState } from "@/bridge";+import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";++import { PreparePanel } from "./prepare-panel";++afterEach(cleanup);++async function stateAfter(...actions: PrepareAction[]): Promise<PrepareState> {+ const core = await testCore();+ let s: PrepareState | null = null;+ for (const a of actions) s = prepareReduce(core, s, a)!.state;+ return s!;+}++const MB = 1_048_576;++describe.skipIf(!wasmBuilt)("the preparing block", () => {+ it("is plain text and one thin bar: four lines, a bar under the current step only, no boxes, no nested cards", async () => {+ const core = await testCore();+ const s = await stateAfter(+ { type: "start", nowMs: 1, harness: "claude-code", pendingId: "p" },+ { type: "phase", nowMs: 2, phase: "preparing", detail: "Setting up the Linux runtime", done: 176 * MB, total: 440 * MB, perSecond: 5 * MB },+ );+ const { container } = render(<PreparePanel view={prepareView(core, s)!} />);+ const rows = [...container.querySelectorAll("[data-prepare-step]")].map((e) => e.getAttribute("data-prepare-step"));+ expect(rows).toEqual(["runtime", "image", "home", "agent"]);+ // One bar, under the Linux runtime row, and no per-row bars.+ const bars = container.querySelectorAll("[data-prepare-bar]");+ expect(bars).toHaveLength(1);+ expect(bars[0]!.closest("[data-prepare-step]")!.getAttribute("data-prepare-step")).toBe("runtime");+ // No headline sentence repeating the row: the row says the bytes once.+ expect(container.textContent!.match(/176 MB of 440 MB/g)).toHaveLength(1);+ expect(container.querySelector("[data-prepare-line]")).toBeNull();+ expect(container.textContent).toContain("Your message sends as soon as your agent is ready");+ // No bordered cell, card or table: no element draws a border or a grouped container, and nothing nests a card.+ expect(container.querySelector("[data-grouped]")).toBeNull();+ const boxed = [...container.querySelectorAll("*")].filter((e) => /(^|\s)(border|border-[trblxy]|divide-|rounded-(lg|xl|2xl)|bg-card|shadow)/.test(e.getAttribute("class") ?? ""));+ expect(boxed).toEqual([]);+ expect(container.textContent).not.toContain("·");+ });++ it("a connection that dropped says so once above the steps, and Try again shows only after a failure", async () => {+ const core = await testCore();+ const waiting = await stateAfter({ type: "start", nowMs: 1, harness: "claude-code" }, { type: "failed", nowMs: 2, message: "reset", network: true });+ const a = render(<PreparePanel view={prepareView(core, waiting)!} onRetry={() => {}} />);+ expect(a.container.querySelector("[data-prepare-line]")!.textContent).toContain("connection dropped");+ expect(a.container.querySelector("[data-prepare-action]")).toBeNull();+ a.unmount();+ const failed = await stateAfter({ type: "start", nowMs: 1, harness: "claude-code" }, { type: "failed", nowMs: 2, message: "disk full" }, { type: "tick", nowMs: 10_000 }, { type: "failed", nowMs: 10_001, message: "disk full" });+ const b = render(<PreparePanel view={prepareView(core, failed)!} onRetry={() => {}} />);+ expect(b.container.querySelector("[data-prepare-action]")!.textContent).toBe("Try again");+ });+});diff --git a/apps/cua-spaces-web/src/components/prepare/prepare-panel.tsx b/apps/cua-spaces-web/src/components/prepare/prepare-panel.tsxnew file mode 100644index 0000000000..2e39c1732a--- /dev/null+++ b/apps/cua-spaces-web/src/components/prepare/prepare-panel.tsx@@ -0,0 +1,64 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { CheckIcon, LoaderCircleIcon } from "lucide-react";++import type { PrepareStepState, PrepareView } from "@/bridge";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";++/** One mark per step state: a check when done, a turning ring while it runs, a quiet dot while it waits. */+function Mark({ state }: { state: PrepareStepState }) {+ if (state === "done" || state === "skipped") return <CheckIcon aria-hidden className="size-3.5 text-success" />;+ if (state === "running") return <LoaderCircleIcon aria-hidden className="size-3.5 animate-spin text-muted-foreground" />;+ if (state === "failed") return <span aria-hidden className="size-1.5 rounded-full bg-destructive" />;+ if (state === "waiting") return <span aria-hidden className="size-1.5 rounded-full bg-warning" />;+ return <span aria-hidden className="size-1.5 rounded-full bg-foreground/20" />;+}++/**+ * Where the first Space is, as one quiet block like the sidebar's "Making"+ * item: four plain lines (Linux runtime, Agent image, Home Space, the coding+ * agent), each a small mark, its label and muted detail, and one thin bar+ * under the current step only. No boxes, no borders, no rows between lines.+ * Every word is the core's (`prepare.view`); this only draws it.+ */+export function PreparePanel({ view, onRetry }: { view: PrepareView; onRetry?: () => void }) {+ return (+ <div data-prepare={view.phase} role="group" aria-label={view.title} className="flex w-full max-w-[420px] flex-col px-6 text-left">+ {view.line ? (+ <p data-prepare-line="" role="status" className="mb-3 text-center text-[13px] text-muted-foreground">+ {view.line}+ </p>+ ) : null}+ <ol data-prepare-steps="" className="flex flex-col gap-2.5">+ {view.steps.map((s) => (+ <li key={s.id} data-prepare-step={s.id} data-state={s.state}>+ <div className="flex items-center gap-2.5 text-[13px]">+ <span className="flex w-4 shrink-0 items-center justify-center">+ <Mark state={s.state} />+ </span>+ <span className={cn("min-w-0 flex-1 whitespace-nowrap", s.state === "pending" ? "text-muted-foreground" : "")}>{s.label}</span>+ {s.detail ? <span className="shrink-0 text-xs text-muted-foreground tabular-nums">{s.detail}</span> : null}+ </div>+ {s.fraction != null ? (+ <div data-prepare-bar="" className="mt-1.5 ml-[26px] h-1 overflow-hidden rounded-full bg-foreground/10" aria-hidden>+ <div className="h-full rounded-full bg-brand transition-[width]" style={{ width: `${Math.round(s.fraction * 100)}%` }} />+ </div>+ ) : null}+ </li>+ ))}+ </ol>+ {view.composerHint ? (+ <p data-prepare-hint="" className="mt-4 text-center text-xs text-muted-foreground">+ {view.composerHint}+ </p>+ ) : null}+ {view.action && onRetry ? (+ <Button className="mx-auto mt-3" variant="outline" onClick={onRetry} data-prepare-action={view.action.id}>+ {view.action.label}+ </Button>+ ) : null}+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsxindex 7fd3a000f1..b4381c451c 100644--- a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx+++ b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx@@ -139,6 +139,7 @@ function thisMacAskRow(asks: boolean): CoreRow {function Labs() {const { data, chooseExperiment } = useExperiments();const askFirst = useFlag("spaces_ask_first_home");+ const newSetup = useFlag("spaces_new_onboarding");const thisMacOk = useThisMacConfirmed();const rows = (data?.page?.sections.flatMap((s) => s.rows) ?? []).filter((r) => LABS.has(r.id) && (!SHOWN_ONCE_ON.has(r.id) || isOn(r)));const note: Record<string, string> = {@@ -153,6 +154,14 @@ function Labs() {description="Home asks what you want done, then does it on a fresh computer you can watch. On this device only."onChoose={(_, option) => setFlagOverride("spaces_ask_first_home", option === "on")}/>+ <CoreSettingsRow+ row={flagRow("spaces_new_onboarding", "Try the new setup", newSetup && askFirst)}+ description="Your first Linux Space and Claude Code get ready while you go through setup, which ends on the new Home. Turns on the new Home too. On this device only."+ onChoose={(_, option) => {+ setFlagOverride("spaces_new_onboarding", option === "on");+ if (option === "on") setFlagOverride("spaces_ask_first_home", true);+ }}+ />{askFirst ? (<CoreSettingsRowrow={thisMacAskRow(!thisMacOk)}diff --git a/apps/cua-spaces-web/src/components/shell/command-palette.tsx b/apps/cua-spaces-web/src/components/shell/command-palette.tsxindex ed45cfd6a3..cefde91e8a 100644--- a/apps/cua-spaces-web/src/components/shell/command-palette.tsx+++ b/apps/cua-spaces-web/src/components/shell/command-palette.tsx@@ -17,10 +17,11 @@ import {SunIcon,type LucideIcon,} from "lucide-react";-import { useState, type KeyboardEvent } from "react";+import { useMemo, useState, type KeyboardEvent } from "react";import { useBridge, useKeyvault, useMachines, useSession, useSpaces } from "@/bridge";import { OsIcon } from "@/components/os-icon";+import { useHiddenSpaceIds } from "@/lib/prepare/store";import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { Kbd, Shortcut } from "@/components/ui/kbd";import { toast, toastError } from "@/components/ui/toast";@@ -54,14 +55,17 @@ const icon = (Icon: LucideIcon) => <Icon className="size-4 text-muted-foregroundfunction PaletteBody({ onClose }: { onClose: () => void }) {const router = useRouter();const navigate = useNavigate();- const { data: spaces = [], startSpace, stopSpace } = useSpaces();+ const { core } = useBridge();+ const { data: allSpaces = [], startSpace, stopSpace } = useSpaces();+ // The home warming for Home's box is not a command until a person wrote into it.+ const warming = useHiddenSpaceIds(core);+ const spaces = useMemo(() => allSpaces.filter((s) => !warming.has(s.id)), [allSpaces, warming]);const { data: machines = [] } = useMachines();const newSpace = useNewSpace();const { data: keyvault, lockItems } = useKeyvault();const { data: session, signIn, signOut } = useSession();const { preference, resolved, setPreference } = useTheme();const toggleSidebar = useUiStore((s) => s.toggleSidebar);- const { core } = useBridge();const [query, setQuery] = useState("");const [active, setActive] = useState(0);diff --git a/apps/cua-spaces-web/src/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/components/shell/sidebar.tsxindex a7a2688758..2dde85fe0c 100644--- a/apps/cua-spaces-web/src/components/shell/sidebar.tsx+++ b/apps/cua-spaces-web/src/components/shell/sidebar.tsx@@ -15,6 +15,7 @@ import { Button } from "@/components/ui/button";import { toast } from "@/components/ui/toast";import { bindingFor } from "@/lib/keybindings";import { useListedSpaces } from "@/components/spaces/listed";+import { useHiddenSpaceIds } from "@/lib/prepare/store";import { spaceState } from "@/lib/spaces";import { cn } from "@/lib/utils";import { SIDEBAR_DEFAULT, useUiStore } from "@/stores/ui";@@ -30,10 +31,13 @@ export function Sidebar() {const width = useUiStore((s) => s.sidebarWidth);const { data: spaces, listStatus } = useSpaces();const { data: machines } = useMachines();+ const { core } = useBridge();const notifications = useNotifications();// No count before the list was read (not "0" while the daemon starts); while computers still answer, the// Spaces known so far.const { counted } = useListedSpaces(spaces);+ // The home warming for Home's box is no "Making" item either: Home's own line says how it goes.+ const warming = useHiddenSpaceIds(core);const spacesCount = spaces && listStatus.loaded ? counted.length : undefined;// Machines waiting to be added show beside the item, so they are seen from every page.const { pending } = useMachinesAccount();@@ -89,7 +93,7 @@ export function Sidebar() {{/* A spacer, not a wrapper pushed down: what appears at the foot (a tip, the account) growsupward without moving anything already drawn (CUA-1951). */}<div className="flex-1" />- <SidebarCreating spaces={spaces ?? []} />+ <SidebarCreating spaces={(spaces ?? []).filter((s) => !warming.has(s.id))} /><SidebarTip />{/* Free only: "Run more Spaces at once with Pro", right above the account line. */}<ProBanner />diff --git a/apps/cua-spaces-web/src/components/space-thread/queued.ts b/apps/cua-spaces-web/src/components/space-thread/queued.tsindex 5c81b46d5a..54337d74ec 100644--- a/apps/cua-spaces-web/src/components/space-thread/queued.ts+++ b/apps/cua-spaces-web/src/components/space-thread/queued.ts@@ -13,6 +13,7 @@ import { useMemo } from "react";import { create } from "zustand";import type { SpaceThread, ThreadEntry, ThreadItem } from "@/bridge";+import { usePreparedQueue } from "@/lib/prepare/store";interface Queued {id: string;@@ -24,6 +25,21 @@ const useQueue = create<{ byPending: Record<string, Queued[]>; resolved: Record<let n = 0;+/**+ * Where messages for the home being prepared go instead of the in-memory+ * queue: the preparing driver keeps them (so a quit loses none) and sends+ * each exactly once. Set by `PrepareRoot`.+ */+export interface PrepareSink {+ /** The row (or Space) is the home being prepared. */+ owns(spaceId: string): boolean;+ send(text: string): void;+}+let prepareSink: PrepareSink | null = null;+export function setPrepareSink(sink: PrepareSink | null): void {+ prepareSink = sink;+}+/** Queues `text` for the Space being made under `pendingId`. */export function enqueue(pendingId: string, text: string): void {const q: Queued = { id: `q${++n}`, text: text.trim(), tsMs: Date.now() };@@ -77,7 +93,15 @@ function entryOf(q: Queued, i: number, me: string, name = ""): ThreadEntry {/** The queued messages that belong to `spaceId` (its own pending id, or a pending id that became it). */export function useQueued(spaceId: string): Queued[] {const { byPending, resolved } = useQueue();- return useMemo(() => Object.entries(byPending).flatMap(([pending, qs]) => (pending === spaceId || resolved[pending] === spaceId ? qs : [])), [byPending, resolved, spaceId]);+ const prepared = usePreparedQueue(spaceId);+ return useMemo(+ () => [+ ...Object.entries(byPending).flatMap(([pending, qs]) => (pending === spaceId || resolved[pending] === spaceId ? qs : [])),+ // The home's messages kept by the preparing driver, until each is in the thread.+ ...prepared.map((m): Queued => ({ id: m.id, text: m.text, tsMs: m.sentMs })),+ ],+ [byPending, resolved, spaceId, prepared],+ );}/** Queued messages as thread items. */@@ -102,7 +126,11 @@ export function creatingThread(pendingId: string): SpaceThread {error: null,hasMoreBefore: false,loadEarlier: async () => {},- post: async (text) => (enqueue(pendingId, text), null),+ post: async (text) => {+ if (prepareSink?.owns(pendingId)) prepareSink.send(text.trim());+ else enqueue(pendingId, text);+ return null;+ },answer: async () => {},setRights: async () => {},removeAgent: null,diff --git a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx b/apps/cua-spaces-web/src/components/space-thread/space-call.tsxindex 37a11cae27..8bff182a00 100644--- a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/space-call.tsx@@ -9,6 +9,7 @@ import { Minimize2Icon } from "lucide-react";import { Tooltip } from "@/components/ui/tooltip";import { isMacPlatform } from "@/lib/utils";+import { markAsked, usePreparedQueue, usePrepare } from "@/lib/prepare/store";import { harnessName, queuedNote, summonPlan, useBridge, type SpaceFact, type SpaceThread, type StreamRow, type ThreadAttachment, type ThreadView as PostView } from "@/bridge";import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { toast } from "@/components/ui/toast";@@ -157,12 +158,16 @@ export function SpaceCall({const queued = useQueued(spaceId);const myName = roster.people.find((p) => p.me)?.label ?? "";const queuedLine = queuedNote(core, creating);+ // Messages kept for the home being prepared send when its agent is ready, which is later than the Space.+ const prepared = usePrepare();+ const preparedQueue = usePreparedQueue(spaceId);+ const preparedWords = preparedQueue.length ? prepared.view?.queued[0]?.note : undefined;const items = useMemo(() => [...thread.items, ...queuedItems(queued, thread.me ?? "me", myName)], [thread.items, thread.me, queued, myName]);const after = (seq: number) =>seq < 0 ? (<div data-queued-note="" data-only-you="" className="-mt-0.5 mb-1 ml-11 w-fit rounded-lg bg-brand-surface px-2.5 py-1.5"><OnlyYou label={queuedLine?.onlyYouLabel ?? ""} />- <p className="text-xs text-muted-foreground">{queuedLine?.text}</p>+ <p className="text-xs text-muted-foreground">{preparedWords ?? queuedLine?.text}</p></div>) : (notes?.filter((n) => n.seq === seq).map(noteView)@@ -293,7 +298,7 @@ export function SpaceCall({? undefined: { handles: addressee.handles, label: nameOf, problem: problemOf, agentHandles, onRemove: (h) => unpinAgent(spaceId, h, addressee.source) }}- onSend={(text) => (creating ? thread.post(text).then(() => undefined) : sendResolved(text))}+ onSend={(text) => (creating ? thread.post(text).then(() => undefined) : (markAsked(spaceId), sendResolved(text)))}disabled={thread.status !== "ready"}disabledReason={thread.role === "guest" ? GUEST_COMPOSER : null}/>diff --git a/apps/cua-spaces-web/src/components/spaces/listed.ts b/apps/cua-spaces-web/src/components/spaces/listed.tsindex 9e035251a0..28a67b8398 100644--- a/apps/cua-spaces-web/src/components/spaces/listed.ts+++ b/apps/cua-spaces-web/src/components/spaces/listed.ts@@ -5,6 +5,7 @@ import { useMemo } from "react";import { sharesDesktop, useBridge, type Space } from "@/bridge";import { useHiddenDesktops } from "@/lib/hidden-desktops";+import { useHiddenSpaceIds } from "@/lib/prepare/store";import { countedSpaces, listedSpaces } from "@/lib/spaces";/**@@ -16,12 +17,14 @@ import { countedSpaces, listedSpaces } from "@/lib/spaces";export function useListedSpaces(all: readonly Space[] | undefined): { listed: Space[]; counted: Space[]; hiddenCount: number } {const hidden = useHiddenDesktops();const { core } = useBridge();+ // The home warming in the background is not on any list until a person wrote into it.+ const warming = useHiddenSpaceIds(core);return useMemo(() => {- const roster = all ?? [];+ const roster = (all ?? []).filter((s) => !warming.has(s.id));// Another machine's desktop shows only while it shares it and answers.const shares = (s: Space) => sharesDesktop(core, s) !== false && s.sdk?.reachable !== false;const listed = listedSpaces(roster, hidden, shares);const all_ = listedSpaces(roster, new Set(), shares);return { listed, counted: countedSpaces(listed), hiddenCount: all_.length - listed.length };- }, [all, hidden, core]);+ }, [all, hidden, core, warming]);}diff --git a/apps/cua-spaces-web/src/components/tips.tsx b/apps/cua-spaces-web/src/components/tips.tsxindex 7419ca141b..d87780f3da 100644--- a/apps/cua-spaces-web/src/components/tips.tsx+++ b/apps/cua-spaces-web/src/components/tips.tsx@@ -37,6 +37,7 @@ import {type TipPlace,} from "@/bridge";import { Button } from "@/components/ui/button";+import { useHiddenSpaceIds } from "@/lib/prepare/store";import { canDelete, canPower, realSpaces, spaceState } from "@/lib/spaces";import { cn } from "@/lib/utils";@@ -106,7 +107,11 @@ export function useTipsLoaded(): boolean {/** What the tips read, from the page's data. `space`: the Space page's Space. */export function useTipFacts(space?: Space): TipFacts | null {- const { data: all = [] } = useSpaces();+ const { data: everything = [] } = useSpaces();+ // The home warming for Home's box is not something to try until a person wrote into it.+ const { core: bridgeCore } = useBridge();+ const warming = useHiddenSpaceIds(bridgeCore);+ const all = useMemo(() => everything.filter((s) => !warming.has(s.id)), [everything, warming]);const { data: machines = [] } = useMachines();const resources = useResources();const agents = useAgentSetup();diff --git a/apps/cua-spaces-web/src/lib/prepare/__tests__/driver.test.ts b/apps/cua-spaces-web/src/lib/prepare/__tests__/driver.test.tsnew file mode 100644index 0000000000..225bcdfd02--- /dev/null+++ b/apps/cua-spaces-web/src/lib/prepare/__tests__/driver.test.ts@@ -0,0 +1,323 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { PrepareMessage, PrepareState } from "@/bridge";+import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";++import { isNetworkFailure, PrepareDriver, type PrepareEnv, type PrepareStorage } from "../driver";++/** A host that does what the test says: a create that can drop, an agent, a thread. */+function fakeHost() {+ const calls = { create: 0, attach: 0, post: [] as string[], verify: 0 };+ const thread: string[] = [];+ let creates: ((id: string) => Promise<string>)[] = [];+ const host = {+ calls,+ thread,+ /** The next creates, in order: each resolves with an id or rejects. */+ nextCreates(...fns: ((id: string) => Promise<string>)[]) {+ creates = fns;+ },+ online: true,+ home: null as { id: string; running: boolean; creating?: boolean } | null,+ follows: 0,+ followResult: null as Error | null,+ exists: true as boolean | null,+ postFails: false,+ hold: null as Promise<void> | null,+ env(): PrepareEnv {+ return {+ now: () => Date.now(),+ online: () => host.online,+ newPendingId: () => "pending:p1",+ findHome: () => host.home,+ startHome: async () => {},+ followCreate: async () => {+ host.follows += 1;+ if (host.followResult) throw host.followResult;+ },+ createHome: async () => {+ calls.create += 1;+ const f = creates.shift() ?? (async () => "local:home-1");+ return f("pending:p1");+ },+ attachAgent: async () => {+ calls.attach += 1;+ },+ post: async ({ message }: { spaceId: string; message: PrepareMessage }) => {+ if (host.hold) await host.hold;+ if (host.postFails) throw new Error("the Space is not reachable");+ calls.post.push(message.id);+ thread.push(message.text);+ },+ threadHas: async ({ message }) => {+ calls.verify += 1;+ return thread.includes(message.text);+ },+ agentReplied: async () => false,+ homeExists: () => host.exists,+ };+ },+ };+ return host;+}++function memoryStorage(): PrepareStorage & { saved: PrepareState | null } {+ const s: PrepareStorage & { saved: PrepareState | null } = {+ saved: null,+ load: () => (s.saved ? (JSON.parse(JSON.stringify(s.saved)) as PrepareState) : null),+ save: (state) => {+ s.saved = JSON.parse(JSON.stringify(state)) as PrepareState;+ },+ };+ return s;+}++const flush = () => vi.advanceTimersByTimeAsync(0);++describe.skipIf(!wasmBuilt)("the preparing driver (wasm core)", () => {+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date"] });+ vi.setSystemTime(1_800_000_000_000);+ });+ afterEach(() => vi.useRealTimers());++ it("prepares in order and delivers a message sent meanwhile, once", async () => {+ const core = await testCore();+ const host = fakeHost();+ let releaseCreate: (id: string) => void = () => {};+ host.nextCreates(() => new Promise<string>((r) => (releaseCreate = r)));+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ expect(host.calls.create).toBe(1);+ expect(d.view()?.phase).toBe("preparing");+ // The person types while the home is made: kept, nothing posted.+ d.send({ id: "m1", text: "fix the failing tests", agent: "claude-code" });+ await flush();+ expect(host.calls.post).toEqual([]);+ expect(d.view()?.queued.map((q) => q.text)).toEqual(["fix the failing tests"]);+ releaseCreate("local:home-1");+ await flush();+ await flush();+ expect(host.calls.attach).toBe(1);+ expect(host.calls.post).toEqual(["m1"]);+ expect(d.view()?.phase).toBe("ready");+ expect(d.state?.messages[0]?.state).toBe("delivered");+ // More ticks and a second ready change nothing.+ d.tick();+ await flush();+ expect(host.calls.post).toEqual(["m1"]);+ });++ it("a connection that drops twice waits, keeps the message, and carries on by itself", async () => {+ const core = await testCore();+ const host = fakeHost();+ host.nextCreates(+ async () => Promise.reject(new Error("connection reset by peer")),+ async () => Promise.reject(new Error("download the built-in Linux runtime: timed out")),+ async () => "local:home-1",+ );+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ d.send({ id: "m1", text: "hello", agent: "claude-code" });+ await flush();+ expect(d.view()?.phase).toBe("waiting");+ expect(d.view()?.line).toContain("connection dropped");+ expect(host.calls.create).toBe(1);+ // The first wait is 2 s ... the second 4 s.+ await vi.advanceTimersByTimeAsync(2_000);+ expect(host.calls.create).toBe(2);+ expect(d.view()?.phase).toBe("waiting");+ await vi.advanceTimersByTimeAsync(4_000);+ await flush();+ expect(host.calls.create).toBe(3);+ expect(d.view()?.phase).toBe("ready");+ expect(host.calls.post).toEqual(["m1"]);+ });++ it("offline waits without retrying and comes back by itself when the connection does", async () => {+ const core = await testCore();+ const host = fakeHost();+ host.online = false;+ host.nextCreates(async () => Promise.reject(new Error("dns error: failed to lookup address")), async () => "local:home-1");+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ expect(d.view()?.phase).toBe("waiting");+ expect(d.view()?.line).toMatch(/^No internet connection/);+ await vi.advanceTimersByTimeAsync(120_000);+ expect(host.calls.create).toBe(1);+ host.online = true;+ d.online(true);+ await flush();+ await flush();+ expect(host.calls.create).toBe(2);+ expect(d.view()?.phase).toBe("ready");+ });++ it("a quit mid-prepare resumes from the saved record: the create runs again, the message is sent once", async () => {+ const core = await testCore();+ const storage = memoryStorage();+ const host = fakeHost();+ // Run 1: the create never ends (the app is quit while it downloads).+ host.nextCreates(() => new Promise<string>(() => {}));+ const a = new PrepareDriver(core, host.env(), storage);+ a.start("claude-code");+ a.progress({ phase: "pulling", detail: "image", bytesDone: 100, bytesTotal: 400 });+ a.send({ id: "m1", text: "keep me", agent: "claude-code" });+ await flush();+ expect(storage.saved?.messages.map((m) => m.id)).toEqual(["m1"]);+ expect(storage.saved?.image.state).toBe("running");+ // Run 2: a new page load with the same record.+ host.nextCreates(async () => "local:home-1");+ const b = new PrepareDriver(core, host.env(), storage);+ expect(b.state?.messages[0]?.text).toBe("keep me");+ b.resume();+ await flush();+ await flush();+ expect(host.calls.create).toBe(2);+ expect(host.calls.post).toEqual(["m1"]);+ expect(b.view()?.phase).toBe("ready");+ // A third launch with everything ready posts nothing again.+ const c = new PrepareDriver(core, host.env(), storage);+ c.resume();+ await flush();+ expect(host.calls.post).toEqual(["m1"]);+ expect(host.calls.create).toBe(2);+ });++ it("a quit while a message was being posted checks the thread: posted is not posted again, missing is posted once", async () => {+ const core = await testCore();+ for (const alreadyThere of [true, false]) {+ const storage = memoryStorage();+ const host = fakeHost();+ // Run 1: the post hangs (the app is quit before it answers).+ host.hold = new Promise<void>(() => {});+ const a = new PrepareDriver(core, host.env(), storage);+ a.start("claude-code");+ await flush();+ a.send({ id: "m1", text: "once", agent: "claude-code" });+ await flush();+ expect(storage.saved?.messages[0]?.state).toBe("delivering");+ // The post did reach the thread before the quit, or did not.+ if (alreadyThere) host.thread.push("once");+ host.hold = null;+ const b = new PrepareDriver(core, host.env(), storage);+ b.resume();+ await flush();+ await flush();+ expect(host.calls.verify).toBe(1);+ expect(host.thread.filter((t) => t === "once")).toHaveLength(1);+ expect(b.state?.messages[0]?.state).toBe("delivered");+ expect(host.calls.post).toEqual(alreadyThere ? [] : ["m1"]);+ }+ });++ it("a failed post goes back and is posted again later, still once", async () => {+ const core = await testCore();+ const host = fakeHost();+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ await flush();+ expect(d.view()?.phase).toBe("ready");+ host.postFails = true;+ d.send({ id: "m1", text: "later", agent: "claude-code" });+ await flush();+ expect(d.state?.messages[0]?.state).toBe("queued");+ host.postFails = false;+ await vi.advanceTimersByTimeAsync(2_000);+ await flush();+ expect(host.calls.post).toEqual(["m1"]);+ expect(d.state?.messages[0]?.state).toBe("delivered");+ });++ it("a failure that will not clear offers Try again, and Try again runs it", async () => {+ const core = await testCore();+ const host = fakeHost();+ host.nextCreates(+ async () => Promise.reject(new Error("no space left on device")),+ async () => Promise.reject(new Error("no space left on device")),+ async () => "local:home-1",+ );+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ await vi.advanceTimersByTimeAsync(2_000);+ await flush();+ expect(d.view()?.phase).toBe("failed");+ expect(d.view()?.action?.label).toBe("Try again");+ d.retry();+ await flush();+ await flush();+ expect(d.view()?.phase).toBe("ready");+ });++ it("a home that was removed is made again", async () => {+ const core = await testCore();+ const host = fakeHost();+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ await flush();+ expect(d.view()?.phase).toBe("ready");+ host.exists = false;+ host.nextCreates(async () => "local:home-2");+ d.checkHome();+ await flush();+ await flush();+ expect(host.calls.create).toBe(2);+ expect(d.state?.homeSpaceId).toBe("local:home-2");+ expect(d.view()?.phase).toBe("ready");+ });++ it("a create the host kept running while the app was quit is followed, not started a second time", async () => {+ const core = await testCore();+ const host = fakeHost();+ host.home = { id: "local:home-claude-code", running: false, creating: true };+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ await flush();+ expect(host.follows).toBe(1);+ expect(host.calls.create).toBe(0);+ expect(d.state?.homeSpaceId).toBe("local:home-claude-code");+ expect(d.view()?.phase).toBe("ready");+ });++ it("a followed create that fails is a failure with the host's words", async () => {+ const core = await testCore();+ const host = fakeHost();+ host.home = { id: "local:home-claude-code", running: false, creating: true };+ host.followResult = new Error("no space left on device");+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ expect(d.state?.trouble?.message).toBe("no space left on device");+ expect(host.calls.create).toBe(0);+ });++ it("an existing running home is used, not made again", async () => {+ const core = await testCore();+ const host = fakeHost();+ host.home = { id: "local:home-old", running: true };+ const d = new PrepareDriver(core, host.env(), memoryStorage());+ d.start("claude-code");+ await flush();+ await flush();+ expect(host.calls.create).toBe(0);+ expect(d.state?.homeSpaceId).toBe("local:home-old");+ });+});++describe("what counts as the connection's failure", () => {+ it.each(["connection reset by peer", "download the built-in Linux runtime: operation timed out", "dns error: failed to lookup address information", "the registry answered 503", "error sending request for url (https://ghcr.io/)"])("%s", (m) => {+ expect(isNetworkFailure(m)).toBe(true);+ });+ it.each(["no space left on device", "the built-in Linux runtime cannot run from this path", "a disk image did not match its checksum"])("%s is not", (m) => {+ expect(isNetworkFailure(m)).toBe(false);+ });+});diff --git a/apps/cua-spaces-web/src/lib/prepare/driver.ts b/apps/cua-spaces-web/src/lib/prepare/driver.tsnew file mode 100644index 0000000000..db026515e7--- /dev/null+++ b/apps/cua-spaces-web/src/lib/prepare/driver.ts@@ -0,0 +1,352 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Runs the preparing state machine (`prepare.rs` in the app core) against+ * the host: it holds the state, saves it after every step so a quit loses+ * nothing, and does what the core's effects say (make the home Space, open+ * the agent's session, post a message, look in the thread). Every decision+ * is the core's; this file only does the work and reports what happened.+ *+ * Nothing here reads the clock or the host directly: both come in through+ * [`PrepareEnv`], so the driver is tested with a fake host, a fake clock and+ * a connection that drops.+ */++import type { CoreClient } from "@/bridge/core";+import type { PrepareAction, PrepareEffect, PrepareMessage, PrepareMetrics, PrepareState, PrepareView } from "@/bridge/contracts/prepare";+import { prepareMetrics, prepareReduce, prepareView } from "@/bridge/prepare-core";++/** Where the state is kept between launches. */+export interface PrepareStorage {+ load(): PrepareState | null;+ save(state: PrepareState): void;+}++/** What the driver needs from the host. */+export interface PrepareEnv {+ now(): number;+ /** The machine has a connection (the browser's reading). */+ online(): boolean;+ /** A new id for the home's row while it is made. */+ newPendingId(): string;+ /** The home Space for this coding app, when one exists (`creating`: the host is still making it, started before this page loaded). */+ findHome(harness: string): { id: string; running: boolean; creating?: boolean } | null;+ /** Waits for a create the host is running (started before this page loaded) to end; rejects when it fails. */+ followCreate(id: string): Promise<void>;+ /** Turns a stopped home back on. */+ startHome(id: string): Promise<void>;+ /** Makes the home and resolves with its id once it is running. Carries on a create that is already there. */+ createHome(a: { harness: string; pendingId: string }): Promise<string>;+ /** Puts the coding app in the home and resolves once its session is open. */+ attachAgent(a: { spaceId: string; harness: string; model: string | null }): Promise<void>;+ /** Posts a message to the home's thread, as the box does. */+ post(a: { spaceId: string; message: PrepareMessage }): Promise<void>;+ /** Whether the thread already has this message (by its text, from the person, after `sinceMs`). */+ threadHas(a: { spaceId: string; message: PrepareMessage }): Promise<boolean>;+ /** Whether the agent has written since `sinceMs`. */+ agentReplied(a: { spaceId: string; sinceMs: number }): Promise<boolean>;+ /** The home is gone from the list (null: the list is not loaded yet). */+ homeExists(id: string): boolean | null;+ /** A message reached its Space: the app's own record of the task (the Home list) follows. */+ delivered?(m: PrepareMessage, spaceId: string): void;+}++/** Words of a failure that is the connection's, not the machine's. */+const NETWORK = /(network|connection|connect|timed?\s?out|time-?out|offline|dns|resolve|resolving|reset|refused|unreachable|temporary failure|tls|handshake|eof|broken pipe|no route|download|registry|ghcr|socket|try again later|\b50[234]\b)/i;++/** Whether a failure is about the connection (it carries on by itself). */+export function isNetworkFailure(message: string): boolean {+ return NETWORK.test(message);+}++const text = (e: unknown) => (e instanceof Error ? e.message : String(e));++export class PrepareDriver {+ private s: PrepareState | null;+ private listeners = new Set<() => void>();+ private creating = false;+ private attaching = false;+ private readonly inflight = new Set<string>();+ private watching = false;+ private timer: ReturnType<typeof setTimeout> | null = null;+ private v: PrepareView | null = null;++ constructor(+ private readonly core: CoreClient,+ private env: PrepareEnv,+ private readonly store: PrepareStorage,+ ) {+ this.s = store.load();+ this.v = prepareView(core, this.s);+ }++ /** The host's latest closures (the page re-renders with new ones). */+ setEnv(env: PrepareEnv): void {+ this.env = env;+ }++ get state(): PrepareState | null {+ return this.s;+ }++ view(): PrepareView | null {+ return this.v;+ }++ /** The page as a property (a new object each step), for React: a method call would be cached by the compiler. */+ get pageView(): PrepareView | null {+ return this.v;+ }++ metrics(): PrepareMetrics | null {+ return prepareMetrics(this.core, this.s);+ }++ subscribe = (l: () => void): (() => void) => {+ this.listeners.add(l);+ return () => this.listeners.delete(l);+ };++ private emit(): void {+ for (const l of [...this.listeners]) l();+ }++ /** One action through the core; the state is saved, then the effects run. */+ dispatch(action: PrepareAction): void {+ const r = prepareReduce(this.core, this.s, action);+ if (!r) return;+ this.s = r.state;+ this.v = prepareView(this.core, this.s);+ this.store.save(r.state);+ this.emit();+ for (const e of r.effects) this.run(e);+ }++ /** Begins preparing for `harness`; asking again changes nothing. */+ start(harness: string): void {+ if (this.s?.wanted) return;+ this.dispatch({ type: "start", nowMs: this.env.now(), harness, pendingId: this.env.newPendingId() });+ if (!this.env.online()) this.dispatch({ type: "online", nowMs: this.env.now(), online: false });+ }++ /** The app started again with a saved record: whatever was in flight is looked at again. */+ resume(): void {+ if (!this.s?.wanted) return;+ this.dispatch({ type: "resume", nowMs: this.env.now() });+ if (!this.env.online()) this.dispatch({ type: "online", nowMs: this.env.now(), online: false });+ this.watchReplies();+ }++ /** The person sent a message: kept, then delivered when ready, exactly once. */+ send(m: { id: string; text: string; agent: string; model?: string | null; repo?: string | null }): void {+ this.dispatch({ type: "send", nowMs: this.env.now(), id: m.id, text: m.text, agent: m.agent, model: m.model ?? null, repo: m.repo ?? null });+ }++ retry(): void {+ this.dispatch({ type: "retry", nowMs: this.env.now() });+ }++ /** A person wrote into the home's own thread: from now on it is listed like any Space. */+ asked(): void {+ if (this.s?.wanted && this.s.askedMs == null) this.dispatch({ type: "asked", nowMs: this.env.now() });+ }++ onboardingDone(): void {+ this.dispatch({ type: "onboardingDone", nowMs: this.env.now() });+ }++ online(online: boolean): void {+ if (this.s && this.s.online === online) return;+ this.dispatch({ type: "online", nowMs: this.env.now(), online });+ }++ /** A create progress report for the home's row. */+ progress(p: { phase: string; detail?: string; bytesDone?: number | null; bytesTotal?: number | null; bytesPerSecond?: number | null }): void {+ if (!this.s?.wanted || this.s.homeSpaceId) return;+ this.dispatch({+ type: "phase",+ nowMs: this.env.now(),+ phase: p.phase,+ detail: p.detail ?? "",+ done: p.bytesDone ?? null,+ total: p.bytesTotal ?? null,+ perSecond: p.bytesPerSecond != null ? Math.round(p.bytesPerSecond) : null,+ });+ }++ /** The list of Spaces changed: a ready home that is gone is made again. */+ checkHome(): void {+ const s = this.s;+ if (!s?.wanted || !s.homeSpaceId || !s.readyMs) return;+ if (this.env.homeExists(s.homeSpaceId) === false) this.dispatch({ type: "homeGone", nowMs: this.env.now() });+ }++ /** About once a second while something waits: time passes. */+ tick(): void {+ if (this.s?.wanted) this.dispatch({ type: "tick", nowMs: this.env.now() });+ }++ private run(e: PrepareEffect): void {+ switch (e.type) {+ case "create":+ void this.create();+ break;+ case "attachAgent":+ void this.attach();+ break;+ case "deliver":+ void this.deliver(e.id);+ break;+ case "verifyDelivery":+ void this.verify(e.id);+ break;+ case "wakeAt": {+ if (this.timer) clearTimeout(this.timer);+ const wait = Math.max(0, e.atMs - this.env.now());+ this.timer = setTimeout(() => {+ this.timer = null;+ this.tick();+ }, wait);+ break;+ }+ }+ }++ private async create(): Promise<void> {+ if (this.creating) return;+ this.creating = true;+ try {+ const s = this.s!;+ const found = this.env.findHome(s.harness);+ if (found) {+ // A create that outlived the app (the host keeps running it): follow it, never start a second one.+ if (found.creating) await this.env.followCreate(found.id);+ else if (!found.running) await this.env.startHome(found.id);+ this.dispatch({ type: "homeReady", nowMs: this.env.now(), spaceId: found.id });+ return;+ }+ const id = await this.env.createHome({ harness: s.harness, pendingId: s.pendingId ?? this.env.newPendingId() });+ this.dispatch({ type: "homeReady", nowMs: this.env.now(), spaceId: id });+ } catch (e) {+ const message = text(e);+ this.dispatch({ type: "failed", nowMs: this.env.now(), message, network: isNetworkFailure(message) || !this.env.online() });+ } finally {+ this.creating = false;+ }+ }++ private async attach(): Promise<void> {+ if (this.attaching) return;+ this.attaching = true;+ try {+ const s = this.s!;+ const first = s.messages.find((m) => m.state !== "delivered");+ await this.env.attachAgent({ spaceId: s.homeSpaceId!, harness: s.harness, model: first?.model ?? null });+ this.dispatch({ type: "agentReady", nowMs: this.env.now() });+ this.watchReplies();+ } catch (e) {+ const message = text(e);+ this.dispatch({ type: "failed", nowMs: this.env.now(), message, network: isNetworkFailure(message) || !this.env.online() });+ } finally {+ this.attaching = false;+ }+ }++ private message(id: string): PrepareMessage | undefined {+ return this.s?.messages.find((m) => m.id === id);+ }++ private async deliver(id: string): Promise<void> {+ if (this.inflight.has(id)) return;+ this.inflight.add(id);+ try {+ const m = this.message(id);+ const space = this.s?.homeSpaceId;+ if (!m || !space) return;+ await this.env.post({ spaceId: space, message: m });+ this.dispatch({ type: "delivered", nowMs: this.env.now(), id });+ this.env.delivered?.(this.message(id) ?? m, space);+ this.watchReplies();+ } catch {+ this.dispatch({ type: "deliveryFailed", nowMs: this.env.now(), id });+ } finally {+ this.inflight.delete(id);+ }+ }++ private async verify(id: string): Promise<void> {+ if (this.inflight.has(id)) return;+ this.inflight.add(id);+ try {+ const m = this.message(id);+ const space = this.s?.homeSpaceId;+ if (!m || !space) return;+ let found = false;+ try {+ found = await this.env.threadHas({ spaceId: space, message: m });+ } catch {+ // Cannot tell: the thread is not asked again blindly; try the check once more soon.+ this.timer = setTimeout(() => {+ this.timer = null;+ this.inflight.delete(id);+ void this.verify(id);+ }, 2000);+ return;+ }+ // The answer can ask for this very message again (not found): it is no longer in flight.+ this.inflight.delete(id);+ this.dispatch({ type: "threadHas", nowMs: this.env.now(), id, found });+ if (found) this.env.delivered?.(this.message(id) ?? m, space);+ } finally {+ this.inflight.delete(id);+ }+ }++ /** Records when the agent first answers each delivered message (for the numbers); stops when none waits. */+ private watchReplies(): void {+ if (this.watching) return;+ this.watching = true;+ const started = this.env.now();+ const step = async () => {+ const waiting = this.s?.messages.filter((m) => m.state === "delivered" && m.firstTokenMs == null && m.deliveredMs != null) ?? [];+ const space = this.s?.homeSpaceId;+ if (!space || this.env.now() - started > 10 * 60_000) {+ this.watching = false;+ return;+ }+ for (const m of waiting) {+ try {+ if (await this.env.agentReplied({ spaceId: space, sinceMs: m.deliveredMs! })) this.dispatch({ type: "firstToken", nowMs: this.env.now(), id: m.id });+ } catch {+ // Asked again next round.+ }+ }+ const more = this.s?.messages.some((m) => m.state !== "delivered" || (m.firstTokenMs == null && m.deliveredMs != null));+ if (more) setTimeout(() => void step(), 700);+ else this.watching = false;+ };+ void step();+ }+}++/** The state kept in `localStorage` (a failing store is only a lost resume). */+export function localPrepareStorage(key = "cua.prepare.v1"): PrepareStorage {+ return {+ load() {+ try {+ const raw = globalThis.localStorage?.getItem(key);+ return raw ? (JSON.parse(raw) as PrepareState) : null;+ } catch {+ return null;+ }+ },+ save(state) {+ try {+ globalThis.localStorage?.setItem(key, JSON.stringify(state));+ } catch {+ // Kept for this run only.+ }+ },+ };+}diff --git a/apps/cua-spaces-web/src/lib/prepare/store.ts b/apps/cua-spaces-web/src/lib/prepare/store.tsnew file mode 100644index 0000000000..45f4362c1f--- /dev/null+++ b/apps/cua-spaces-web/src/lib/prepare/store.ts@@ -0,0 +1,104 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useMemo, useSyncExternalStore } from "react";++import type { CoreClient } from "@/bridge/core";+import type { PrepareMessage, PrepareState, PrepareView } from "@/bridge/contracts/prepare";+import { prepareHidden } from "@/bridge/prepare-core";++import type { PrepareDriver } from "./driver";++/** Where the driver is kept: one for the page, made once the app core is there. */+let driver: PrepareDriver | null = null;++/** The page's driver (none until the app core is there). */+export const getDriver = (): PrepareDriver | null => driver;+export function setDriver(d: PrepareDriver | null): void {+ driver = d;+ d?.subscribe(() => changed());+ notify();+ changed();+}++/** Non-React readers (the bridge store) hear when what the lists hide may have changed. */+const changeListeners = new Set<() => void>();+const changed = () => {+ for (const l of [...changeListeners]) l();+};+export function onHiddenSpacesChange(cb: () => void): () => void {+ changeListeners.add(cb);+ return () => changeListeners.delete(cb);+}++/** The Spaces no list shows right now (the core's `prepare.hidden` over the saved record). */+export function hiddenSpaceIdsNow(core: CoreClient): string[] {+ return prepareHidden(core, driver?.state ?? null);+}+const listeners = new Set<() => void>();+const subscribe = (l: () => void) => {+ listeners.add(l);+ return () => listeners.delete(l);+};+export const notify = () => {+ for (const l of [...listeners]) l();+};++/** A saved record was resumed in this page load (the layout mounts again and again: once is enough). */+let resumedOnce = false;+export const resumedThisLoad = (): boolean => resumedOnce;+export function markResumed(): void {+ resumedOnce = true;+}++/** Tests start clean. */+export function resetPrepare(): void {+ driver = null;+ resumedOnce = false;+ notify();+}++/** The driver's state, as the page reads it. */+export function usePrepare(): { state: PrepareState | null; view: PrepareView | null; driver: PrepareDriver | null } {+ const d = useSyncExternalStore(subscribe, () => driver, () => null);+ useSyncExternalStore(+ d ? d.subscribe : (l) => (listeners.add(l), () => listeners.delete(l)),+ () => d?.state ?? null,+ () => null,+ );+ // Properties, not method calls: they change with every step, and the compiler caches a call by its receiver.+ return { state: d?.state ?? null, view: d?.pageView ?? null, driver: d };+}++/** The id the home's page has now: its Space, else the row it has while it is made. */+export function prepareSpaceId(state: PrepareState | null): string | null {+ return state?.wanted ? (state.homeSpaceId ?? state.pendingId) : null;+}++/** Whether `spaceId` is the home being prepared (its row, or its Space). */+export function usePreparingSpace(spaceId: string | undefined): PrepareState | null {+ const { state } = usePrepare();+ return state?.wanted && spaceId && (state.pendingId === spaceId || state.homeSpaceId === spaceId) ? state : null;+}++/** The messages kept for the home that are not in its thread yet. */+export function usePreparedQueue(spaceId: string): PrepareMessage[] {+ const { state } = usePrepare();+ return useMemo(() => (state?.wanted && (state.pendingId === spaceId || state.homeSpaceId === spaceId) ? state.messages.filter((m) => m.state !== "delivered") : []), [state, spaceId]);+}+++/**+ * The Spaces no list shows: the home that warms for Home's box until a person wrote into it (the core's+ * `prepare.hidden`, one rule for every app). Its own page and Home's preparing line still show it.+ */+export function useHiddenSpaceIds(core: CoreClient): ReadonlySet<string> {+ const { state } = usePrepare();+ return useMemo(() => new Set(prepareHidden(core, state)), [core, state]);+}++/** A person wrote in this Space's own thread: when it is the warming home, it is listed from now on. */+export function markAsked(spaceId: string): void {+ const d = driver;+ if (d?.state?.wanted && (d.state.homeSpaceId === spaceId || d.state.pendingId === spaceId)) d.asked();+}diff --git a/apps/cua-spaces-web/src/lib/prepare/use-prepare.tsx b/apps/cua-spaces-web/src/lib/prepare/use-prepare.tsxnew file mode 100644index 0000000000..e172d8e586--- /dev/null+++ b/apps/cua-spaces-web/src/lib/prepare/use-prepare.tsx@@ -0,0 +1,193 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useEffect, useRef } from "react";++import { firstMessage, newPendingId, useBridge, useFirstSpaceOffers, useSpaces } from "@/bridge";+import { useNewOnboarding } from "@/bridge/flags";+import { useSummonIn } from "@/components/ask-first/use-summon-in";+import { setPrepareSink } from "@/components/space-thread/queued";+import { updateAskTask } from "@/lib/ask-first";+import { spaceState } from "@/lib/spaces";++import { localPrepareStorage, PrepareDriver, type PrepareEnv } from "./driver";+import { getDriver, markResumed, resumedThisLoad, setDriver, usePrepare } from "./store";++/** The coding app the first Space is for until the person picks another. */+export const DEFAULT_HARNESS = "claude-code";++/** How long the agent's session may take to open before preparing says so. */+const SESSION_TIMEOUT_MS = 4 * 60_000;+/** How long a create the host started before this page loaded may take (a slow first run). */+const CREATE_FOLLOW_MS = 40 * 60_000;+/** The name of the Space this prepares: fixed, so a second page load finds the first one's create. */+export const homeNameOf = (harness: string) => `home-${harness}`;+const POLL_MS = 800;++const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));++/**+ * Mounted once at the root: starts preparing at launch (while the person is in+ * onboarding), carries on after a quit, and keeps the driver's view of the host+ * current. It runs only with the new setup on (Settings, Advanced, Labs), which+ * also turns on the "Ask first" Home. The Space it prepares is a fresh Linux+ * Space, the one Home's first Linux job goes to, with the coding agent in it.+ */+export function PrepareRoot(): null {+ const { core, data: host } = useBridge();+ const spacesHook = useSpaces();+ const { data: spaces, createSpace, startSpace } = spacesHook;+ const { offers } = useFirstSpaceOffers();+ const on = useNewOnboarding();+ const { summonInput, summonIn, canSummon } = useSummonIn();+ const latestSpaces = useRef(spaces);+ latestSpaces.current = spaces;++ const env: PrepareEnv = {+ now: () => Date.now(),+ online: () => globalThis.navigator?.onLine !== false,+ newPendingId,+ findHome: (harness) => {+ // The Space this prepares has a fixed name, so a create the host is still running (the app was quit+ // meanwhile) is found by it.+ const row = spaces?.find((s) => s.name === homeNameOf(harness) && spaceState(s) !== "failed");+ if (!row) return null;+ const state = spaceState(row);+ return { id: row.id, running: state === "running", creating: state === "creating" };+ },+ followCreate: async (id) => {+ const begun = Date.now();+ const until = begun + CREATE_FOLLOW_MS;+ for (;;) {+ const row = latestSpaces.current?.find((s) => s.id === id);+ const state = row ? spaceState(row) : null;+ if (state === "running") return;+ if (state === "failed") throw new Error(row?.progress?.error ?? "Making the home failed");+ if (!row && Date.now() - begun > 15_000) throw new Error("The home is gone");+ if (Date.now() > until) throw new Error("Making the home took too long");+ await sleep(POLL_MS);+ }+ },+ startHome: async (id) => {+ await startSpace(id);+ },+ createHome: async ({ pendingId }) => {+ // The same Linux Space Home makes for a job, under the fixed name.+ const offer = offers.find((o) => o.os === "linux");+ const space = await createSpace({ ...(offer ? offer.args : {}), os: "linux", name: homeNameOf(DEFAULT_HARNESS) }, pendingId);+ return space.id;+ },+ attachAgent: async ({ spaceId, harness, model }) => {+ if (!host || !canSummon()) throw new Error("This app can't put an agent in a Space");+ const input = await summonInput(spaceId);+ const first = firstMessage(core, input, harness, "hello");+ if (!first?.handle) throw new Error("This agent can't join a Space");+ void model;+ await host.call("thread.agentAdd", { spaceId, name: first.handle, harness: first.harness || harness });+ const until = Date.now() + SESSION_TIMEOUT_MS;+ for (;;) {+ const { members } = await host.call("thread.members", { spaceId });+ const me = members.find((m) => m.harness === (first.harness || harness));+ if (me?.status === "failed") throw new Error(me.failure?.message ?? "The agent didn't start");+ // A member that joined is ready for its first message: its session opens with it.+ if (me && me.status !== "starting") return;+ if (Date.now() > until) throw new Error("The agent took too long to start");+ await sleep(POLL_MS);+ }+ },+ post: async ({ spaceId, message }) => {+ const ok = await summonIn(spaceId, message.agent, message.text, message.model ?? undefined);+ if (!ok) throw new Error("This agent can't join the Space");+ },+ threadHas: async ({ spaceId, message }) => {+ if (!host) throw new Error("no host");+ const page = await host.call("thread.read", { spaceId, limit: 50 });+ const since = (message.claimedMs ?? message.sentMs) - 2_000;+ return page.entries.some((e) => e.kind === "message" && e.author.kind === "person" && e.tsMs >= since && (e.text ?? "").includes(message.text));+ },+ agentReplied: async ({ spaceId, sinceMs }) => {+ if (!host) return false;+ const page = await host.call("thread.read", { spaceId, limit: 20 });+ return page.live.agents.some((a) => (a.text ?? "").length > 0) || page.entries.some((e) => e.author.kind === "agent" && e.kind === "message" && e.tsMs >= sinceMs);+ },+ homeExists: (id) => (spaces ? spaces.some((s) => s.id === id && s.status !== "deleting") : null),+ delivered: (m, spaceId) => updateAskTask(m.id, { spaceId, pendingId: null, inSpace: true }),+ };++ // One driver for the page; it uses the latest closures.+ getDriver()?.setEnv(env);+ useEffect(() => {+ if (core?.status === "ready" && !getDriver()) setDriver(new PrepareDriver(core, env, localPrepareStorage()));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [core]);++ const ready = Boolean(core && host && spaces && on);++ // Start at launch; a saved record resumes once.+ const driverNow = usePrepare().driver;+ useEffect(() => {+ const d = driverNow;+ if (!ready || !d) return;+ if (d.state?.wanted) {+ // A saved record resumes once per page load, however often the layout mounts.+ if (!resumedThisLoad()) {+ markResumed();+ d.resume();+ }+ } else {+ markResumed();+ d.start(DEFAULT_HARNESS);+ }+ }, [ready, driverNow]);++ // The home's composer sends here while it is being made: kept, then delivered once.+ useEffect(() => {+ if (!ready) return;+ setPrepareSink({+ owns: (id) => Boolean(getDriver()?.state?.wanted && (getDriver()?.state?.pendingId === id || getDriver()?.state?.homeSpaceId === id)),+ send: (text) => {+ const d = getDriver();+ if (!d?.state) return;+ d.send({ id: `m-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, text, agent: d.state.harness });+ },+ });+ return () => setPrepareSink(null);+ }, [ready]);++ // The create's progress feeds the steps.+ useEffect(() => {+ if (!ready || !host) return;+ return host.subscribe((e) => {+ if (e.type !== "spaces.createProgress" || e.progress.retry) return;+ const d = getDriver();+ // This page's own create, or the one the host kept running for the home when the app was quit.+ if (!d?.state?.wanted || (d.state.pendingId !== e.progress.pendingId && e.progress.space !== `local:${homeNameOf(d.state.harness)}`)) return;+ d.progress({ phase: e.progress.phase, detail: e.progress.detail, bytesDone: e.progress.bytesDone, bytesTotal: e.progress.bytesTotal, bytesPerSecond: e.progress.bytesPerSecond });+ });+ }, [ready, host]);++ // The connection: the browser says when it goes and comes back.+ useEffect(() => {+ if (!ready) return;+ const on = () => getDriver()?.online(true);+ const off = () => getDriver()?.online(false);+ globalThis.addEventListener?.("online", on);+ globalThis.addEventListener?.("offline", off);+ return () => {+ globalThis.removeEventListener?.("online", on);+ globalThis.removeEventListener?.("offline", off);+ };+ }, [ready]);++ // The list changed: a home that was removed is made again. A second a tick while it is waiting.+ useEffect(() => {+ if (ready) getDriver()?.checkHome();+ }, [ready, spaces]);+ useEffect(() => {+ if (!ready) return;+ const t = setInterval(() => getDriver()?.tick(), 1_000);+ return () => clearInterval(t);+ }, [ready]);++ return null;+}diff --git a/apps/cua-spaces-web/src/routes/__root.tsx b/apps/cua-spaces-web/src/routes/__root.tsxindex 6a996d4d18..e55e3cf836 100644--- a/apps/cua-spaces-web/src/routes/__root.tsx+++ b/apps/cua-spaces-web/src/routes/__root.tsx@@ -22,14 +22,25 @@ import { useGlobalKeybindings } from "@/hooks/use-global-keybindings";import { useAgentSync } from "@/hooks/use-connected-apps";import { useNotificationToasts } from "@/hooks/use-notification-toasts";import { useThemeHostSync, useThemeSync } from "@/lib/theme";+import { PrepareRoot } from "@/lib/prepare/use-prepare";import { useUiStore } from "@/stores/ui";export const Route = createRootRoute({ component: RootLayout });+/** The page, with the first Space's preparation running behind it from launch (onboarding, then the app). */+function RootLayout() {+ return (+ <>+ <PrepareRoot />+ <RootBody />+ </>+ );+}+// Shown only while the native app is still starting, so it loads then.const StartupScreen = lazy(() => import("@/components/startup/StartupScreen").then((m) => ({ default: m.StartupScreen })));-function RootLayout() {+function RootBody() {useThemeSync();useThemeHostSync();const { mode } = useBridge();diff --git a/apps/cua-spaces-web/src/routes/onboarding/index.tsx b/apps/cua-spaces-web/src/routes/onboarding/index.tsxindex 5f40f0286b..8501d9b705 100644--- a/apps/cua-spaces-web/src/routes/onboarding/index.tsx+++ b/apps/cua-spaces-web/src/routes/onboarding/index.tsx@@ -21,6 +21,7 @@ import { KeySheet } from "@/components/agents/key-sheet";import { setConnectedAppsState, useConnectedAppsState } from "@/hooks/use-connected-apps";import { BY_HAND, failureText, getItUrl } from "@/lib/connected-apps";import { cn } from "@/lib/utils";+import { usePrepare } from "@/lib/prepare/store";export const Route = createFileRoute("/onboarding/")({// `?due=1` is a host opening the first run because it is not done (the Mac@@ -53,8 +54,16 @@ export const Route = createFileRoute("/onboarding/")({* keycap art, as plain rows.*/function OnboardingPage() {- const fr = useFirstRun();const navigate = useNavigate();+ const prepare = usePrepare();+ // The new setup (Labs): the last screen ends on Home, the prompt box and the suggestions, while the+ // first Space keeps getting ready behind it (preparing started at launch). The clock for "setup+ // finished to ready" starts here.+ const openHome = () => {+ prepare.driver?.onboardingDone();+ void navigate({ to: "/home" });+ };+ const fr = useFirstRun(true, undefined, openHome);const { view } = fr;const leave = () => {@@ -63,6 +72,7 @@ function OnboardingPage() {};const finish = async () => {try {+ prepare.driver?.onboardingDone();await fr.finish();await navigate({ to: "/spaces" });} catch (e) {@@ -100,7 +110,7 @@ function OnboardingPage() {{view.later}</button></header>- <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-y-auto pr-10 pb-6 pl-[var(--ob-x)] [@media(min-width:1000px)]:pr-[46%]">+ <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-y-auto pr-10 pl-[var(--ob-x)] [@media(min-width:1000px)]:pr-[46%]">{/* Centre the step on the window, a little above true centre (about 45% from the top). The min heights keep a gap under the logo bar and above the progress dots; tall steps scroll. */}<div aria-hidden data-onboarding-spacer-top="" className="min-h-[clamp(8px,2vh,32px)] shrink-0 grow-[33] basis-0 [@media(max-width:999px)]:grow-[50]" /><div className="flex w-full max-w-[520px] shrink-0 flex-col">@@ -118,6 +128,13 @@ function OnboardingPage() {);}+/**+ * Every page's action row (Set up and Not now, Continue, Sign in ...). It sticks to the bottom of the+ * scrolling content area, so a short window never pushes it out of reach: the page's content scrolls+ * above it. Back and Skip for now stay where they are.+ */+const ACTION_ROW = "sticky bottom-0 z-20 mt-8 flex flex-wrap items-center gap-3 bg-gradient-to-t from-[#F4F5F7] via-[#F4F5F7]/90 to-transparent pt-6 pb-4 dark:from-[#07080a] dark:via-[#07080a]/90";+/** "Skip for now": a ghost pill, readable on the starfield, quieter than Continue. */const SKIP_PILL ="rounded-full border border-foreground/30 px-4 py-1.5 text-[13px] text-foreground/90 outline-none transition-colors hover:border-foreground/50 hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60";@@ -226,7 +243,7 @@ function Welcome({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {<div aria-hidden className="mb-4 h-7" /><Heading>{w.title}</Heading><Lede>{w.lede}</Lede>- <div className="mt-8">+ <div className={ACTION_ROW}><Primary label={w.primary.label} onClick={() => void fr.act(w.primary.id)} /></div></div>@@ -388,7 +405,7 @@ function Connect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {})}<OtherMachineRow /></Rows>- <div className="mt-8 flex flex-wrap items-center gap-3">+ <div className={ACTION_ROW}><Primary label="Check again" onClick={() => void fr.act("recheck")} data-first-run-recheck="" /><Secondary label="Continue without one" onClick={() => void fr.act("skip")} /></div>@@ -455,7 +472,7 @@ function Connect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {})}<OtherMachineRow /></Rows>- <div className="mt-8 flex flex-wrap items-center gap-3">+ <div className={ACTION_ROW}>{all || failed.length ? (<><Primary label="Continue" onClick={() => void fr.act(c.primary.id)} />@@ -606,7 +623,7 @@ function AdvancedConnect({ fr, view }: { fr: FirstRunHook; view: FirstRunView }){c.consent}</p>) : null}- <div className="mt-8 flex flex-wrap items-center gap-3">+ <div className={ACTION_ROW}><Primary label={c.primary.label} onClick={() => void fr.act(c.primary.id)} />{c.secondary ? <Secondary label={c.secondary.label} onClick={() => void fr.act(c.secondary!.id)} /> : null}{c.mode ? (@@ -683,7 +700,7 @@ 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-8 flex flex-wrap items-center gap-3">+ <div className={ACTION_ROW}><Primary label={d.primary.label} onClick={() => void fr.act(d.primary.id)} data-first-run-devices-primary={d.primary.id} />{d.secondary ? <Secondary label={d.secondary.label} onClick={() => void fr.act(d.secondary!.id)} describedBy={d.note ? "first-run-devices-note" : undefined} /> : null}</div>@@ -727,7 +744,7 @@ function CommandLine({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {{c.error}</p>) : null}- <div className="mt-8 flex flex-wrap items-center gap-3">+ <div className={ACTION_ROW}>{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}@@ -753,7 +770,7 @@ function Permissions({ fr, view }: { fr: FirstRunHook; view: FirstRunView }) {<p className="mt-4 text-[13px] text-muted-foreground" data-first-run-permissions-note="">{p.note}</p>- <div className="mt-8 flex flex-wrap items-center gap-3">+ <div className={ACTION_ROW}>{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>@@ -818,7 +835,7 @@ 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-3">+ <div className={ACTION_ROW}><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>diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsxindex 15ab541853..caef7bbe4c 100644--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx@@ -23,6 +23,8 @@ import { ThisMacCall } from "@/components/space-detail/this-mac-desktop";import { StateLabel } from "@/components/state-dot";import { PageTip } from "@/components/tips";import { creatingThread } from "@/components/space-thread/queued";+import { PreparePanel } from "@/components/prepare/prepare-panel";+import { usePrepare } from "@/lib/prepare/store";import { useAskTasks } from "@/lib/ask-first";import { ConfirmDialog } from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";@@ -110,6 +112,8 @@ function SpaceDetailPage() {const askFirstOn = useFlag("spaces_ask_first_home");// Ask first's tasks: a Space being made for one draws as the Space page in its creating state.const tasks = useAskTasks();+ // The first Space being prepared while the person was in onboarding: its page shows what is happening.+ const prep = usePrepare();// Open on a creating row: once the create finished and the registry lists// the Space, its row (and this id) goes; follow it to the Space's own id.// Only a page that showed the row follows: the address of a row that is@@ -320,6 +324,8 @@ function SpaceDetailPage() {<OsIcon os={space.os} className="size-4.5 text-muted-foreground" /></div>);+ const preparing = askFirstOn && space.id.startsWith("pending:") && prep.state?.wanted && prep.state.pendingId === space.id ? prep.view : null;+ const preparePanel = preparing ? <PreparePanel view={preparing} onRetry={() => prep.driver?.retry()} /> : null;const surface = (className: string, windowId?: string | null, windowName?: string | null, interactive = !viewOnly) => (<StreamSurfaceinteractive={interactive}@@ -335,7 +341,7 @@ function SpaceDetailPage() {onAccessAction={enroll}className={className}>- {surfaceState(space, pending, turnOn, start, dismiss, retry, openReport, fix) ?? poppedOutState}+ {preparePanel ?? surfaceState(space, pending, turnOn, start, dismiss, retry, openReport, fix) ?? poppedOutState}</StreamSurface>);// The classic page's sections under the desktop. With the thread they open from Details, More.@@ -439,7 +445,7 @@ function SpaceDetailPage() {// A create still in progress has no thread yet: its progress shows on the classic page.// A Space being made for an Ask-first job: the same page in its creating state (progress on// the stage, the job queued in the thread); a failed create keeps the classic page's fixes.- const creating = space.id.startsWith("pending:") && askFirstOn && state !== "failed" && tasks.some((t) => t.pendingId === space.id);+ const creating = space.id.startsWith("pending:") && askFirstOn && (state !== "failed" || (preparing != null && preparing.phase !== "failed")) && (tasks.some((t) => t.pendingId === space.id) || preparing != null);const callThread = creating ? creatingThread(space.id) : thread;const later = "Available once the Space is ready";// This Mac's own desktop row: a Space's page as any other, with the share prompt where the stream would be.diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lockindex 2f5450d023..e32f56818a 100644--- a/apps/cua-spaces/src-tauri/Cargo.lock+++ b/apps/cua-spaces/src-tauri/Cargo.lock@@ -1968,6 +1968,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]diff --git a/apps/cua-spaces/src/model/parity.test.ts b/apps/cua-spaces/src/model/parity.test.tsindex 42aae4d0df..4e1127caee 100644--- a/apps/cua-spaces/src/model/parity.test.ts+++ b/apps/cua-spaces/src/model/parity.test.ts@@ -255,6 +255,7 @@ describe('app core parity flows (webview)', () => {'tips','pro-banner','connectors',+ 'prepare',]);});diff --git a/docs/content/docs/cua-cli/reference/cli/agents.mdx b/docs/content/docs/cua-cli/reference/cli/agents.mdxindex 1756e25a04..ed6d2b7d65 100644--- a/docs/content/docs/cua-cli/reference/cli/agents.mdx+++ b/docs/content/docs/cua-cli/reference/cli/agents.mdx@@ -1076,6 +1076,7 @@ cua connect setup [OPTIONS]| <span id="cua-connect-setup--force"></span>`--force` | | boolean | `false` | Replace skill folders cua did not write (the old one is backed up). || <span id="cua-connect-setup--cua-driver"></span>`--cua-driver` | | boolean | `false` | Set up background computer-use instead: the cua-driver skill and the cua-driver MCP server (`cua-driver mcp`). --mcp-command then names the cua-driver binary. || <span id="cua-connect-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: the sign-in Claude Code already has (read from where Claude Code keeps it, as an access token only; Claude Code's own sign-in is never changed) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connections). Only Claude Code's own sign-in is read, and only its access token is kept; Codex's own `auth.json` is never read or changed. |+| <span id="cua-connect-setup--sign-in-only"></span>`--sign-in-only` | | boolean | `false` | Only the sign-in, as `--sign-in`, and nothing else: no Cua skills and no MCP entry are added to any agent, Claude Code is never run to refresh its own sign-in, and nothing is written outside the Cua home (the access token goes to Keyvault, never printed). For a demo, or a home Space that only needs the credential. On a Mac, macOS asks once to let Cua read the Keychain item "Claude Code-credentials": that prompt is yours to answer. |**Examples**@@ -1308,6 +1309,7 @@ cua agents setup [OPTIONS]| <span id="cua-agents-setup--force"></span>`--force` | | boolean | `false` | Replace skill folders cua did not write (the old one is backed up). || <span id="cua-agents-setup--cua-driver"></span>`--cua-driver` | | boolean | `false` | Set up background computer-use instead: the cua-driver skill and the cua-driver MCP server (`cua-driver mcp`). --mcp-command then names the cua-driver binary. || <span id="cua-agents-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: the sign-in Claude Code already has (read from where Claude Code keeps it, as an access token only; Claude Code's own sign-in is never changed) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connections). Only Claude Code's own sign-in is read, and only its access token is kept; Codex's own `auth.json` is never read or changed. |+| <span id="cua-agents-setup--sign-in-only"></span>`--sign-in-only` | | boolean | `false` | Only the sign-in, as `--sign-in`, and nothing else: no Cua skills and no MCP entry are added to any agent, Claude Code is never run to refresh its own sign-in, and nothing is written outside the Cua home (the access token goes to Keyvault, never printed). For a demo, or a home Space that only needs the credential. On a Mac, macOS asks once to let Cua read the Keychain item "Claude Code-credentials": that prompt is yours to answer. |**Examples**diff --git a/docs/content/docs/spaces/guides/connect-your-agent.mdx b/docs/content/docs/spaces/guides/connect-your-agent.mdxindex bed70493b5..39aeb80175 100644--- a/docs/content/docs/spaces/guides/connect-your-agent.mdx+++ b/docs/content/docs/spaces/guides/connect-your-agent.mdx@@ -120,6 +120,26 @@ codex mcp add cua -- cua daemon mcp`cua daemon mcp` starts `cua daemon` if it is not running, so every agent onthis computer shares the same Spaces, sandboxes and streams.+### Only the sign-in++Sometimes you want the Claude sign-in for the Spaces and nothing else, for+example for a demo, or for a home Space that runs Claude Code and must not touch+how Claude Code on your Mac is set up. Add `--sign-in-only`:++```bash skip="third-party-cli"+cua connect setup --sign-in-only+```++It does what **Use my sign-in** does and no more. It adds no Cua skills and no+Cua server to Claude Code, so `~/.claude.json` and `~/.claude/skills` are not+changed, and it never starts Claude Code to refresh its sign-in: a sign-in that+has run out is refused with a plain sentence, and you open Claude Code once and+try again. It keeps the access token only, in Keyvault on this Mac, and never+prints it. The only things it writes are inside the Cua folder. On a Mac, macOS+asks once whether Cua may read the Keychain item "Claude Code-credentials":+that question is yours to answer, and Cua has no way around it. Undo it with+`cua connect remove --sign-in`.+## Check that it works1. If your agent was already running, start a new session. Agents load theirdiff --git a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lockindex 696fa77e3b..7d0372eb6f 100644--- a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock+++ b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock@@ -1958,6 +1958,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lockindex 1e48f094a4..02b23c69fd 100644--- a/examples/streaming/rust/Cargo.lock+++ b/examples/streaming/rust/Cargo.lock@@ -1592,6 +1592,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lockindex 0563856206..dbb0055b62 100644--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock@@ -2442,6 +2442,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex df2f3b9330..673b1dd772 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2803,6 +2803,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]diff --git a/libs/cua/crates/cua-agent-setup/src/connection.rs b/libs/cua/crates/cua-agent-setup/src/connection.rsindex 600742c572..68d2f8f21d 100644--- a/libs/cua/crates/cua-agent-setup/src/connection.rs+++ b/libs/cua/crates/cua-agent-setup/src/connection.rs@@ -818,6 +818,23 @@ impl ConnectParts {mcp: true,sign_in: true,};++ /// Only the sign-in: Cua's skills and MCP entry are not added to the agent, and+ /// nothing is written outside the Cua home (the copy goes to Keyvault, the note+ /// of it to `<cua home>/agent-setup.json`). For a demo or a home Space that needs+ /// the credential and must not touch the person's agent configuration. Claude+ /// Code is never run to refresh its own sign-in either (an expired one is+ /// refused), see [`Self::tools_free`].+ pub const SIGN_IN_ONLY: ConnectParts = ConnectParts {+ skills: false,+ mcp: false,+ sign_in: true,+ };++ /// Neither skills nor MCP: the agent's own files and programs are left alone.+ pub fn tools_free(self) -> bool {+ !self.skills && !self.mcp+ }}impl AgentSetup {@@ -961,6 +978,13 @@ impl AgentSetup {wait: Duration,mut show: Option<ShowDeviceSignIn<'_>>,) -> crate::Result<Vec<ConnectResult>> {+ // A sign-in-only connect leaves the agent's own files and programs alone: Claude+ // Code is not run to refresh its sign-in (a zero wait means never).+ let wait = if parts.tools_free() {+ Duration::ZERO+ } else {+ wait+ };let mut out = Vec::new();for id in agents {let a = registry::find(id).ok_or_else(|| signin::unknown(id))?;diff --git a/libs/cua/crates/cua-agent-setup/src/signin.rs b/libs/cua/crates/cua-agent-setup/src/signin.rsindex 8f6b772344..78283a890d 100644--- a/libs/cua/crates/cua-agent-setup/src/signin.rs+++ b/libs/cua/crates/cua-agent-setup/src/signin.rs@@ -372,7 +372,8 @@ pub fn find_setup_token(out: &str) -> Option<String> {////// When the copy found has run out, Claude Code is asked to refresh its own/// sign-in (a one-line request through `claude -p`, up to `wait`) and the-/// sign-in is read again.+/// sign-in is read again. A zero `wait` never runs Claude Code (a sign-in-only+/// connect): an expired sign-in is refused instead.fn claude_import(env: &HostEnv,keychain: &dyn claude_login::Keychain,@@ -382,6 +383,7 @@ fn claude_import(let mut lookup = claude_login::lookup(env, keychain, now_ms());if let Lookup::Found(f) = &lookup&& f.oauth.expired(now_ms())+ && !wait.is_zero()&& claude_login::ask_claude_to_refresh(env, wait){lookup = claude_login::lookup(env, keychain, now_ms());diff --git a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rsindex c9b85f93ff..a9b8da0516 100644--- a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs+++ b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs@@ -994,3 +994,101 @@ fn status_is_cached_briefly_and_refresh_asks_again() {#[allow(dead_code)]fn _paths(_: &Path) {}++/// Everything under the fake home outside the Cua home, as path to bytes.+fn outside_cua_home(w: &World) -> std::collections::BTreeMap<PathBuf, Vec<u8>> {+ fn walk(dir: &Path, skip: &Path, out: &mut std::collections::BTreeMap<PathBuf, Vec<u8>>) {+ for e in std::fs::read_dir(dir).unwrap() {+ let p = e.unwrap().path();+ if p.starts_with(skip) {+ continue;+ }+ if p.is_dir() {+ walk(&p, skip, out);+ } else {+ out.insert(p.clone(), std::fs::read(&p).unwrap());+ }+ }+ }+ let mut out = Default::default();+ walk(&w.home, &w.env.cua_home(), &mut out);+ out+}++#[test]+fn a_sign_in_only_connect_changes_nothing_outside_the_cua_home_and_never_prints_the_token() {+ let w = World::new();+ w.install("claude-code", "2.1.299");+ w.sign_in("claude-code");+ let before = outside_cua_home(&w);+ assert!(+ before+ .keys()+ .any(|p| p.ends_with(".claude/.credentials.json"))+ );+ let mut env = w.env.clone();+ env.run_agent_clis = true;+ let r = AgentSetup::new(env)+ .connect(+ &["claude-code".into()],+ &w.server(),+ ConnectParts::SIGN_IN_ONLY,+ Some(&w.vault),+ Duration::from_secs(10),+ )+ .unwrap();+ let sign_in = r[0].sign_in.as_ref().unwrap();+ assert!(sign_in.imported.is_some(), "{r:?}");+ // No skills, no MCP entry, nothing created or changed in the agent's own files or anywhere else.+ assert!(r[0].outcomes.is_empty(), "{:?}", r[0].outcomes);+ assert_eq!(+ outside_cua_home(&w),+ before,+ "a file outside the Cua home was created or changed"+ );+ assert!(!w.home.join(".claude/skills").exists());+ // The access token is kept, the refresh token never, and neither is in anything the connect says.+ assert_eq!(w.vault.value("claude-code").as_deref(), Some(CLAUDE_ACCESS));+ let said = format!("{r:?}{}", serde_json::to_string(&r).unwrap());+ assert!(+ !said.contains(CLAUDE_ACCESS)+ && !said.contains("sk-ant-oat")+ && !said.contains(CLAUDE_REFRESH),+ "{said}"+ );+}++#[test]+fn a_sign_in_only_connect_never_runs_claude_code_to_refresh_an_expired_sign_in() {+ let w = World::new();+ // A claude that leaves a mark when it is run to refresh itself (`-p`).+ w.script(+ "claude",+ "#!/bin/sh\ncase \"$1\" in\n --version) echo 2.1.299 ;;\n -p) echo run > \"$HOME/claude-was-run\" ;;\n auth) echo '{\"authMethod\":\"claude.ai\"}' ;;\nesac\nexit 0\n",+ );+ w.sign_in("claude-code");+ w.write(+ ".claude/.credentials.json",+ &claude_credentials(CLAUDE_ACCESS, 1_000),+ );+ let before = outside_cua_home(&w);+ let mut env = w.env.clone();+ env.run_agent_clis = true;+ let r = AgentSetup::new(env)+ .connect(+ &["claude-code".into()],+ &w.server(),+ ConnectParts::SIGN_IN_ONLY,+ Some(&w.vault),+ Duration::from_secs(10),+ )+ .unwrap();+ let s = r[0].sign_in.as_ref().unwrap();+ assert!(s.imported.is_none() && s.refused.is_some(), "{r:?}");+ assert!(+ !w.home.join("claude-was-run").exists(),+ "Claude Code was run"+ );+ assert_eq!(outside_cua_home(&w), before);+ assert!(w.vault.value("claude-code").is_none());+}diff --git a/libs/cua/crates/cua-cli/src/agents.rs b/libs/cua/crates/cua-cli/src/agents.rsindex 4d0958b393..60a7e50284 100644--- a/libs/cua/crates/cua-cli/src/agents.rs+++ b/libs/cua/crates/cua-cli/src/agents.rs@@ -107,6 +107,14 @@ pub struct SetupCmdArgs {/// kept; Codex's own `auth.json` is never read or changed.#[arg(long, conflicts_with = "cua_driver")]pub sign_in: bool,+ /// Only the sign-in, as `--sign-in`, and nothing else: no Cua skills and no+ /// MCP entry are added to any agent, Claude Code is never run to refresh its+ /// own sign-in, and nothing is written outside the Cua home (the access+ /// token goes to Keyvault, never printed). For a demo, or a home Space that+ /// only needs the credential. On a Mac, macOS asks once to let Cua read the+ /// Keychain item "Claude Code-credentials": that prompt is yours to answer.+ #[arg(long, conflicts_with_all = ["cua_driver", "skills_only", "mcp_only"])]+ pub sign_in_only: bool,}#[derive(Args, Debug)]@@ -723,8 +731,8 @@ pub fn cmd_setup(args: &SetupCmdArgs, json: bool, out: &mut dyn Write) -> Resultif args.cua_driver {return run_driver_setup(&setup, &args.base, &prompt, json, out);}- if args.sign_in {- return run_connect(&setup, &args.base, json, out);+ if args.sign_in || args.sign_in_only {+ return run_connect(&setup, &args.base, args.sign_in_only, json, out);}run_setup(&setup, &args.base, &prompt, json, out)}@@ -734,19 +742,26 @@ pub fn cmd_setup(args: &SetupCmdArgs, json: bool, out: &mut dyn Write) -> Resultfn run_connect(setup: &AgentSetup,args: &SetupArgs,+ only: bool,json: bool,out: &mut dyn Write,) -> Result<i32, CuaError> {let ids = match args.agents.as_deref() {Some(sel) => setup.select(sel).map_err(err)?,+ // Sign-in only is for Claude Code unless an agent is named.+ None if only => setup.select("claude-code").map_err(err)?,None => setup.select("all").map_err(err)?,};let server = mcp_server(setup, args.mcp_command.as_deref());let vault = cua_sdk::sign_in_vault();- let parts = ConnectParts {- skills: !args.mcp_only,- mcp: !args.skills_only,- sign_in: true,+ let parts = if only {+ ConnectParts::SIGN_IN_ONLY+ } else {+ ConnectParts {+ skills: !args.mcp_only,+ mcp: !args.skills_only,+ sign_in: true,+ }};// A sign-in with a code (Codex): the link and the code go to stderr, so// `--json` stays one line on stdout.@@ -783,7 +798,12 @@ fn run_connect((None, Some(s)) if s.imported.is_some() => line(out,format!(- " ✓ {name}: connected; {} copied to Keyvault",+ " ✓ {name}: {}; {} copied to Keyvault",+ if only {+ "sign-in only, nothing changed in its settings"+ } else {+ "connected"+ },s.imported.as_ref().map(|i| i.label.as_str())@@ -800,7 +820,11 @@ fn run_connect(if !res.is_empty() {line(out,- "Restart your agents to load the cua MCP server. Undo with `cua connect remove --sign-in`.",+ if only {+ "Nothing was added to your agents. Undo with `cua connect remove --sign-in`."+ } else {+ "Restart your agents to load the cua MCP server. Undo with `cua connect remove --sign-in`."+ },);}Ok(i32::from(failed))diff --git a/libs/cua/crates/cua-image/Cargo.toml b/libs/cua/crates/cua-image/Cargo.tomlindex 3ac6fd498d..480aed0d40 100644--- a/libs/cua/crates/cua-image/Cargo.toml+++ b/libs/cua/crates/cua-image/Cargo.toml@@ -26,6 +26,7 @@ thiserror = "2"tokio = { version = "1", features = ["fs", "io-util", "macros", "process", "rt-multi-thread", "sync", "time"] }tokio-util = { version = "0.7", features = ["io"] }tracing = "0.1"+zstd = "0.13"[dev-dependencies]proptest = "1"diff --git a/libs/cua/crates/cua-image/src/rootfs.rs b/libs/cua/crates/cua-image/src/rootfs.rsindex 8e57da22a8..33996f33a4 100644--- a/libs/cua/crates/cua-image/src/rootfs.rs+++ b/libs/cua/crates/cua-image/src/rootfs.rs@@ -163,16 +163,19 @@ pub fn apply_layer(layer: impl Read, root: &Path) -> Result<()> {Ok(())}-/// Unpack a list of (possibly gzipped) layer files, bottom first.+/// Unpack a list of (possibly gzip or zstd compressed) layer files, bottom first.pub fn unpack_layers(layers: &[PathBuf], root: &Path) -> Result<()> {std::fs::create_dir_all(root)?;for l in layers {let mut f = std::fs::File::open(l)?;- let mut magic = [0u8; 2];+ let mut magic = [0u8; 4];let n = f.read(&mut magic)?;let f = BufReader::with_capacity(1 << 20, std::fs::File::open(l)?);- if n == 2 && magic == [0x1f, 0x8b] {+ if n >= 2 && magic[..2] == [0x1f, 0x8b] {apply_layer(GzDecoder::new(f), root)?;+ } else if n == 4 && magic == [0x28, 0xb5, 0x2f, 0xfd] {+ // A zstd layer (the headless image's, which downloads about 30 percent fewer bytes).+ apply_layer(zstd::stream::read::Decoder::new(f)?, root)?;} else {apply_layer(f, root)?;}@@ -548,6 +551,29 @@ mod tests {assert_eq!(std::fs::read(root.join("var/cache/b")).unwrap(), b"b");}+ #[test]+ fn a_zstd_layer_unpacks_like_a_gzip_one() {+ let d = tempfile::tempdir().unwrap();+ let tar_bytes = layer(&[+ ("etc/a", Some(b"zstd layer")),+ ("bin/", None),+ ("bin/b", Some(b"b")),+ ]);+ let z = d.path().join("z.tar.zst");+ std::fs::write(&z, zstd::stream::encode_all(&tar_bytes[..], 3).unwrap()).unwrap();+ let g = d.path().join("g.tar.gz");+ let mut gz = GzEncoder::new(Vec::new(), Compression::default());+ gz.write_all(&layer(&[("etc/c", Some(b"gzip layer"))]))+ .unwrap();+ std::fs::write(&g, gz.finish().unwrap()).unwrap();+ let root = d.path().join("root");+ // A gzip layer under a zstd one (and the other way round) in one image.+ unpack_layers(&[g, z], &root).unwrap();+ assert_eq!(std::fs::read(root.join("etc/a")).unwrap(), b"zstd layer");+ assert_eq!(std::fs::read(root.join("etc/c")).unwrap(), b"gzip layer");+ assert_eq!(std::fs::read(root.join("bin/b")).unwrap(), b"b");+ }+#[test]fn traversal_is_rejected() {let d = tempfile::tempdir().unwrap();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 a6827263b8..9fcdbf3b94 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@@ -62,6 +62,12 @@{ "name": "33 offers: an Intel Mac shows Linux only", "patch": { "agents": [], "picked": [], "step": "setup" }, "machine": { "hostOs": "macos", "env": { "hostArch": "x86_64", "localBackends": ["managed"] } } },{ "name": "34 offers: an Intel Mac with QEMU adds Omarchy", "patch": { "agents": [], "picked": [], "step": "setup" }, "machine": { "hostOs": "macos", "env": { "hostArch": "x86_64", "localBackends": ["managed", "qemu"] } } },{ "name": "35 offers: an amd64 Linux PC shows Linux and Omarchy", "patch": { "hostOs": "linux", "agents": [], "picked": [], "step": "setup" }, "machine": { "hostOs": "linux", "env": { "hostArch": "amd64", "localBackends": ["docker", "qemu"], "storage": { "reserveBytes": 5368709120, "lume": null, "qemu": { "availableBytes": 107374182400, "totalBytes": 536870912000, "name": "/" }, "container": { "availableBytes": 107374182400, "totalBytes": 536870912000, "name": "/" }, "pulled": [], "linuxRuntimeDownloadBytes": 0 } } } },- { "name": "36 offers: a Mac still checking shows Linux only", "patch": { "agents": [], "picked": [], "step": "setup" }, "machine": { "hostOs": "macos", "env": { "storage": null } } }+ { "name": "36 offers: a Mac still checking shows Linux only", "patch": { "agents": [], "picked": [], "step": "setup" }, "machine": { "hostOs": "macos", "env": { "storage": null } } },+ { "name": "40 ask first: no Try it screen, a Mac kept for Spaces ends on Add your other machines with Open Cua", "patch": { "step": "devices", "askFirst": true, "picked": ["hermes"], "signedIn": true, "host": { "configured": true, "running": true, "online": true, "shareDesktop": false, "permissions": [] } }, "steps": true },+ { "name": "41 ask first: permissions last, all allowed, Open Cua", "patch": { "step": "permissions", "askFirst": true, "picked": ["hermes"], "signedIn": true, "host": { "configured": true, "running": true, "online": true, "permissions": [] } }, "steps": true },+ { "name": "42 ask first: not signed in, Not now ends the run", "patch": { "step": "devices", "askFirst": true, "picked": ["hermes"] }, "steps": true },+ { "name": "43 ask first: a run saved on the Try it screen shows the last screen", "patch": { "step": "setup", "askFirst": true, "picked": ["hermes"], "signedIn": true, "host": { "configured": true, "running": true, "online": true, "shareDesktop": false, "permissions": [] } }, "steps": true },+ { "name": "44 ask first: Pick your agent keeps its action rows, Continue and Skip", "patch": { "step": "connect", "askFirst": true }, "steps": true },+ { "name": "45 ask first: Pick your agent after Connect, Continue and Back", "patch": { "step": "connect", "askFirst": true, "picked": ["hermes"] }, "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 d19fa75211..82bbb85900 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@@ -716,6 +716,27 @@"linux linux (1.1 GB download; about 2 min)","macos macos (23 GB download; 10 to 30 min the first time)"],+ "prompts": {+ "caps": {+ "kvm": false,+ "macos": true,+ "macosCached": false,+ "windows": false,+ "windowsCached": false+ },+ "cards": [+ "tests-linux-macos",+ "bug-macos",+ "order-tracking"+ ],+ "examples": [+ "price-compare",+ "trip-weekend",+ "two-space-load",+ "cross-os-prices-macos"+ ],+ "lede": "Reproduce this bug on a fresh macOS Space"+ },"setup": {"extra": {"action": "not-now:Not now",@@ -742,6 +763,26 @@"offers": ["linux linux (1.1 GB download; about 2 min)"],+ "prompts": {+ "caps": {+ "kvm": false,+ "macos": false,+ "macosCached": false,+ "windows": false,+ "windowsCached": false+ },+ "cards": [+ "order-tracking",+ "server-ui-load",+ "untrusted-pr"+ ],+ "examples": [+ "price-compare",+ "trip-weekend",+ "two-space-load"+ ],+ "lede": "Reproduce this bug on a fresh Linux Space"+ },"setup": {"extra": {"action": "not-now:Not now",@@ -767,6 +808,26 @@"offers": ["linux linux (1.2 GB download; about 2 min)"],+ "prompts": {+ "caps": {+ "kvm": false,+ "macos": false,+ "macosCached": false,+ "windows": false,+ "windowsCached": false+ },+ "cards": [+ "order-tracking",+ "server-ui-load",+ "untrusted-pr"+ ],+ "examples": [+ "price-compare",+ "trip-weekend",+ "two-space-load"+ ],+ "lede": "Reproduce this bug on a fresh Linux Space"+ },"setup": {"extra": {"action": "not-now:Not now",@@ -793,6 +854,26 @@"linux linux (1.2 GB download; about 2 min)","omarchy linux (1.7 GB download; about 3 min the first time)"],+ "prompts": {+ "caps": {+ "kvm": false,+ "macos": false,+ "macosCached": false,+ "windows": false,+ "windowsCached": false+ },+ "cards": [+ "order-tracking",+ "server-ui-load",+ "untrusted-pr"+ ],+ "examples": [+ "price-compare",+ "trip-weekend",+ "two-space-load"+ ],+ "lede": "Reproduce this bug on a fresh Linux Space"+ },"setup": {"extra": {"action": "not-now:Not now",@@ -820,6 +901,27 @@"linux linux (1.2 GB download; about 2 min)","omarchy linux (1.7 GB download; about 3 min the first time)"],+ "prompts": {+ "caps": {+ "kvm": false,+ "macos": false,+ "macosCached": false,+ "windows": true,+ "windowsCached": false+ },+ "cards": [+ "tests-linux-windows",+ "bug-windows",+ "order-tracking"+ ],+ "examples": [+ "price-compare",+ "trip-weekend",+ "two-space-load",+ "cross-os-prices-windows"+ ],+ "lede": "Reproduce this bug on a fresh Windows Space"+ },"setup": {"extra": {"action": "not-now:Not now",@@ -846,6 +948,26 @@"offers": ["linux linux (1.1 GB download; about 2 min)"],+ "prompts": {+ "caps": {+ "kvm": false,+ "macos": false,+ "macosCached": false,+ "windows": false,+ "windowsCached": false+ },+ "cards": [+ "order-tracking",+ "server-ui-load",+ "untrusted-pr"+ ],+ "examples": [+ "price-compare",+ "trip-weekend",+ "two-space-load"+ ],+ "lede": "Reproduce this bug on a fresh Linux Space"+ },"setup": {"extra": {"action": "not-now:Not now",@@ -864,6 +986,142 @@"title": "Try a first Space."},"step": "setup"+ },+ {+ "art": "hermes on outline",+ "case": "40 ask first: no Try it screen, a Mac kept for Spaces ends on Add your other machines with Open Cua",+ "devices": {+ "lede": "Sign in on your other computers to use its Spaces.",+ "note": null,+ "primary": "continue:Open Cua",+ "rows": [+ "Your other computers — Sign in with the same account",+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"+ ],+ "secondary": "",+ "status": "[ok] Ready to share — Its Spaces appear on every computer signed in to your account.",+ "title": "This Mac is in your account."+ },+ "step": "devices",+ "steps": [+ "welcome",+ "connect",+ "devices"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "41 ask first: permissions last, all allowed, Open Cua",+ "permissions": {+ "lede": "Allow two permissions so your team and agents can see and use this Mac.",+ "note": "Allow opens System Settings, where you turn on Cua Spaces.",+ "primary": "continue:Open Cua",+ "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"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "42 ask first: not signed in, Not now ends the run",+ "devices": {+ "lede": "Sign in to Cua here and on your other computers. Then they can all use this Mac's Spaces.",+ "note": "Not now keeps Cua on this Mac only. You can sign in later.",+ "primary": "sign-in:Sign in",+ "rows": [+ "Your other computers — Sign in with the same account",+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"+ ],+ "secondary": "not-now:Not now",+ "status": null,+ "title": "Add your other computers."+ },+ "step": "devices",+ "steps": [+ "welcome",+ "connect",+ "devices"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "43 ask first: a run saved on the Try it screen shows the last screen",+ "devices": {+ "lede": "Sign in on your other computers to use its Spaces.",+ "note": null,+ "primary": "continue:Open Cua",+ "rows": [+ "Your other computers — Sign in with the same account",+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"+ ],+ "secondary": "",+ "status": "[ok] Ready to share — Its Spaces appear on every computer signed in to your account.",+ "title": "This Mac is in your account."+ },+ "step": "devices",+ "steps": [+ "welcome",+ "connect",+ "devices"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "44 ask first: Pick your agent keeps its action rows, Continue and Skip",+ "connect": {+ "agents": [+ "Hermes connect:Connect",+ "Claude Code connect:Connect",+ "OpenAI Codex connect:Connect"+ ],+ "alternatives": [],+ "credentials": null,+ "error": null,+ "lede": "Cua found these on this Mac. Connect the ones you want to use with Cua.",+ "primary": "continue:Continue",+ "secondary": "",+ "title": "Pick your agent."+ },+ "step": "connect",+ "steps": [+ "welcome",+ "connect",+ "devices"+ ]+ },+ {+ "art": "hermes on outline",+ "case": "45 ask first: Pick your agent after Connect, Continue and Back",+ "connect": {+ "agents": [+ "Hermes [Connected]",+ "Claude Code connect:Connect",+ "OpenAI Codex connect:Connect"+ ],+ "alternatives": [],+ "credentials": null,+ "error": null,+ "lede": "Cua found these on this Mac. Connect the ones you want to use with Cua.",+ "primary": "continue:Continue",+ "secondary": "",+ "title": "Pick your agent."+ },+ "step": "connect",+ "steps": [+ "welcome",+ "connect",+ "devices"+ ]}]}diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/prepare.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/prepare.jsonnew file mode 100644index 0000000000..3bd95fe63a--- /dev/null+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/prepare.json@@ -0,0 +1,698 @@+{+ "flow": "prepare",+ "frames": [+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-"+ ],+ "page": [+ "idle: Getting your agent ready",+ "Linux runtime (pending)",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)"+ ],+ "step": "nothing started"+ },+ {+ "effects": [+ "create"+ ],+ "list": [+ "local:build-box",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - Setting up",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "first launch starts preparing"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - 120 MB of 440 MB, about 1 minute left [bar 27%]",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the Linux runtime downloads"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - 120 MB of 440 MB, about 1 minute left [bar 27%]",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "onboarding ends while it is still downloading"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - 120 MB of 440 MB, about 1 minute left [bar 27%]",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "a message is typed and kept"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - 120 MB of 440 MB, about 1 minute left [bar 27%]",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the same message sent twice is one"+ },+ {+ "effects": [+ "wakeAt at 1042000"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "waiting: Getting your agent ready",+ "The connection dropped. Trying again, nothing downloaded is lost",+ "Linux runtime (waiting) - Waiting for the connection",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the connection drops"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "waiting: Getting your agent ready",+ "The connection dropped. Trying again, nothing downloaded is lost",+ "Linux runtime (waiting) - Waiting for the connection",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "a tick before the retry time does nothing"+ },+ {+ "effects": [+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - 120 MB of 440 MB [bar 27%]",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the retry time comes and it carries on"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "waiting: Getting your agent ready",+ "No internet connection. Preparing carries on when you are back online",+ "Linux runtime (waiting) - Waiting for the connection",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the machine goes offline"+ },+ {+ "effects": [+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - 120 MB of 440 MB [bar 27%]",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "back online resumes at once"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (done)",+ "Agent image (running) - 96 MB of 366 MB, about 1 minute left [bar 26%]",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the runtime is done and the image downloads"+ },+ {+ "effects": [+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (done)",+ "Agent image (running) - 96 MB of 366 MB [bar 26%]",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the app quits and starts again"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (running) - Starting",+ "Claude Code (pending)",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the home Space boots"+ },+ {+ "effects": [+ "attachAgent"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=10000 agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (done)",+ "Claude Code (running) - Getting ready",+ "queued: Fix the failing tests in my repo (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the home is running and the agent is added"+ },+ {+ "effects": [+ "deliver m1"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=10000 agent=3000 prepare=523000 onboarding_to_ready=493000",+ "message m1 delivered=- first_token=-"+ ],+ "page": [+ "ready: Claude Code is ready",+ "Your home Space is running",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (done)",+ "Claude Code (done)",+ "queued: Fix the failing tests in my repo (Sending)"+ ],+ "step": "the agent is ready and the message is sent"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=10000 agent=3000 prepare=523000 onboarding_to_ready=493000",+ "message m1 delivered=492100 first_token=-"+ ],+ "page": [+ "ready: Claude Code is ready",+ "Your home Space is running",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (done)",+ "Claude Code (done)"+ ],+ "step": "the post reached the thread"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=10000 agent=3000 prepare=523000 onboarding_to_ready=493000",+ "message m1 delivered=492100 first_token=494500"+ ],+ "page": [+ "ready: Claude Code is ready",+ "Your home Space is running",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (done)",+ "Claude Code (done)"+ ],+ "step": "the agent's first words arrive"+ },+ {+ "effects": [+ "deliver m2",+ "verifyDelivery m2"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=10000 agent=3000 prepare=523000 onboarding_to_ready=493000",+ "message m1 delivered=492100 first_token=494500",+ "message m2 delivered=100100 first_token=-"+ ],+ "page": [+ "ready: Claude Code is ready",+ "Your home Space is running",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (done)",+ "Claude Code (done)"+ ],+ "step": "a quit during delivery asks the thread first"+ },+ {+ "effects": [+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=492100 first_token=494500",+ "message m2 delivered=100100 first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (running) - Starting",+ "Claude Code (pending)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "the home Space was removed and is made again"+ },+ {+ "effects": [+ "wakeAt at 1812000",+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=492100 first_token=494500",+ "message m2 delivered=100100 first_token=-"+ ],+ "page": [+ "failed: Getting your agent ready stopped",+ "Preparing stopped: the disk is full",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (failed) - Stopped",+ "Claude Code (pending)",+ "hint: Your message sends as soon as your agent is ready",+ "button: Try again"+ ],+ "step": "a failure that will not clear offers Try again"+ },+ {+ "effects": [+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=100000 image=410000 home=- agent=- prepare=- onboarding_to_ready=-",+ "message m1 delivered=492100 first_token=494500",+ "message m2 delivered=100100 first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (done)",+ "Agent image (done)",+ "Home Space (running) - Starting",+ "Claude Code (pending)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "Try again runs it again"+ },+ {+ "effects": [+ "create",+ "attachAgent"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:notes"+ ],+ "metrics": [+ "runtime=5000 image=0 home=0 agent=1000 prepare=6000 onboarding_to_ready=-"+ ],+ "page": [+ "ready: Claude Code is ready",+ "Your home Space is running",+ "Linux runtime (skipped) - Already set up",+ "Agent image (skipped) - Already downloaded",+ "Home Space (done)",+ "Claude Code (done)"+ ],+ "step": "a new install: the home is warm and nothing was asked"+ },+ {+ "effects": [],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:notes"+ ],+ "metrics": [+ "runtime=5000 image=0 home=0 agent=1000 prepare=6000 onboarding_to_ready=-"+ ],+ "page": [+ "ready: Claude Code is ready",+ "Your home Space is running",+ "Linux runtime (skipped) - Already set up",+ "Agent image (skipped) - Already downloaded",+ "Home Space (done)",+ "Claude Code (done)"+ ],+ "step": "the app quits and opens again: still hidden"+ },+ {+ "effects": [+ "create",+ "wakeAt at 3003000",+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-"+ ],+ "page": [+ "failed: Getting your agent ready stopped",+ "Preparing stopped: the disk is full",+ "Linux runtime (failed) - Stopped",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "hint: Your message sends as soon as your agent is ready",+ "button: Try again"+ ],+ "step": "preparing fails on another new install: the error is on Home, the list shows nothing of it"+ },+ {+ "effects": [+ "create"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=- image=- home=- agent=- prepare=- onboarding_to_ready=-",+ "message q1 delivered=- first_token=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (running) - Setting up",+ "Agent image (pending)",+ "Home Space (pending)",+ "Claude Code (pending)",+ "queued: Run my tests (Sends when your agent is ready)",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "a message is queued while the home is still being made: the Space shows at once"+ },+ {+ "effects": [+ "create",+ "attachAgent"+ ],+ "list": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ],+ "metrics": [+ "runtime=5000 image=0 home=0 agent=- prepare=- onboarding_to_ready=-"+ ],+ "page": [+ "preparing: Getting your agent ready",+ "Linux runtime (skipped) - Already set up",+ "Agent image (skipped) - Already downloaded",+ "Home Space (done)",+ "Claude Code (running) - Getting ready",+ "hint: Your message sends as soon as your agent is ready"+ ],+ "step": "a person wrote in the home's own thread: it shows"+ }+ ]+}diff --git a/libs/cua/crates/cua-spaces-app-core/parity/prepare.json b/libs/cua/crates/cua-spaces-app-core/parity/prepare.jsonnew file mode 100644index 0000000000..11557612a4--- /dev/null+++ b/libs/cua/crates/cua-spaces-app-core/parity/prepare.json@@ -0,0 +1,353 @@+{+ "name": "prepare",+ "about": "Preparing the ask-first Space while the person is in onboarding: the Linux runtime, the agent image, the home Space and the coding agent start at first launch, say honestly where they are, carry on after a lost connection or a quit, queue the message the person sends meanwhile and deliver it exactly once when the agent is ready. Times are made up (milliseconds). Each step also shows what a list (Spaces, sidebar, machines, palette) shows of a roster of five Spaces: the home that warms for Home's prompt box is left out until a person has written into it, and comes back when one did.",+ "steps": [+ {+ "step": "nothing started",+ "actions": []+ },+ {+ "step": "first launch starts preparing",+ "actions": [+ {+ "type": "start",+ "nowMs": 1000000,+ "harness": "claude-code",+ "pendingId": "home-pending"+ }+ ]+ },+ {+ "step": "the Linux runtime downloads",+ "actions": [+ {+ "type": "phase",+ "nowMs": 1004000,+ "phase": "preparing",+ "detail": "Setting up the Linux runtime",+ "done": 125829120,+ "total": 461373440,+ "perSecond": 5242880+ }+ ]+ },+ {+ "step": "onboarding ends while it is still downloading",+ "actions": [+ {+ "type": "onboardingDone",+ "nowMs": 1030000+ }+ ]+ },+ {+ "step": "a message is typed and kept",+ "actions": [+ {+ "type": "send",+ "nowMs": 1031000,+ "id": "m1",+ "text": "Fix the failing tests in my repo",+ "agent": "claude-code",+ "model": "claude-sonnet-5"+ }+ ]+ },+ {+ "step": "the same message sent twice is one",+ "actions": [+ {+ "type": "send",+ "nowMs": 1031500,+ "id": "m1",+ "text": "Fix the failing tests in my repo",+ "agent": "claude-code"+ }+ ]+ },+ {+ "step": "the connection drops",+ "actions": [+ {+ "type": "failed",+ "nowMs": 1040000,+ "message": "connection reset by peer",+ "network": true+ }+ ]+ },+ {+ "step": "a tick before the retry time does nothing",+ "actions": [+ {+ "type": "tick",+ "nowMs": 1041000+ }+ ]+ },+ {+ "step": "the retry time comes and it carries on",+ "actions": [+ {+ "type": "tick",+ "nowMs": 1042000+ }+ ]+ },+ {+ "step": "the machine goes offline",+ "actions": [+ {+ "type": "online",+ "nowMs": 1050000,+ "online": false+ }+ ]+ },+ {+ "step": "back online resumes at once",+ "actions": [+ {+ "type": "online",+ "nowMs": 1090000,+ "online": true+ }+ ]+ },+ {+ "step": "the runtime is done and the image downloads",+ "actions": [+ {+ "type": "phase",+ "nowMs": 1100000,+ "phase": "pulling",+ "detail": "ghcr.io/trycua/linux:24.04-slim",+ "done": 100663296,+ "total": 383778816,+ "perSecond": 4194304+ }+ ]+ },+ {+ "step": "the app quits and starts again",+ "actions": [+ {+ "type": "resume",+ "nowMs": 1500000+ }+ ]+ },+ {+ "step": "the home Space boots",+ "actions": [+ {+ "type": "phase",+ "nowMs": 1510000,+ "phase": "booting"+ }+ ]+ },+ {+ "step": "the home is running and the agent is added",+ "actions": [+ {+ "type": "homeReady",+ "nowMs": 1520000,+ "spaceId": "local:home-fix-the-failing-tests"+ }+ ]+ },+ {+ "step": "the agent is ready and the message is sent",+ "actions": [+ {+ "type": "agentReady",+ "nowMs": 1523000+ }+ ]+ },+ {+ "step": "the post reached the thread",+ "actions": [+ {+ "type": "delivered",+ "nowMs": 1523100,+ "id": "m1"+ }+ ]+ },+ {+ "step": "the agent's first words arrive",+ "actions": [+ {+ "type": "firstToken",+ "nowMs": 1525500,+ "id": "m1"+ }+ ]+ },+ {+ "step": "a quit during delivery asks the thread first",+ "actions": [+ {+ "type": "send",+ "nowMs": 1600000,+ "id": "m2",+ "text": "And the lint errors",+ "agent": "claude-code"+ },+ {+ "type": "resume",+ "nowMs": 1700000+ },+ {+ "type": "threadHas",+ "nowMs": 1700100,+ "id": "m2",+ "found": true+ }+ ]+ },+ {+ "step": "the home Space was removed and is made again",+ "actions": [+ {+ "type": "homeGone",+ "nowMs": 1800000+ }+ ]+ },+ {+ "step": "a failure that will not clear offers Try again",+ "actions": [+ {+ "type": "failed",+ "nowMs": 1810000,+ "message": "the disk is full"+ },+ {+ "type": "tick",+ "nowMs": 1820000+ },+ {+ "type": "failed",+ "nowMs": 1821000,+ "message": "the disk is full"+ }+ ]+ },+ {+ "step": "Try again runs it again",+ "actions": [+ {+ "type": "retry",+ "nowMs": 1830000+ }+ ]+ },+ {+ "step": "a new install: the home is warm and nothing was asked",+ "fresh": true,+ "actions": [+ {+ "type": "start",+ "nowMs": 2000000,+ "harness": "claude-code",+ "pendingId": "pending:home-pending"+ },+ {+ "type": "homeReady",+ "nowMs": 2005000,+ "spaceId": "local:home-claude-code"+ },+ {+ "type": "agentReady",+ "nowMs": 2006000+ }+ ]+ },+ {+ "step": "the app quits and opens again: still hidden",+ "actions": [+ {+ "type": "resume",+ "nowMs": 2100000+ }+ ]+ },+ {+ "step": "preparing fails on another new install: the error is on Home, the list shows nothing of it",+ "fresh": true,+ "actions": [+ {+ "type": "start",+ "nowMs": 3000000,+ "harness": "claude-code",+ "pendingId": "pending:home-pending"+ },+ {+ "type": "failed",+ "nowMs": 3001000,+ "message": "the disk is full"+ },+ {+ "type": "tick",+ "nowMs": 3010000+ },+ {+ "type": "failed",+ "nowMs": 3011000,+ "message": "the disk is full"+ }+ ]+ },+ {+ "step": "a message is queued while the home is still being made: the Space shows at once",+ "fresh": true,+ "actions": [+ {+ "type": "start",+ "nowMs": 4000000,+ "harness": "claude-code",+ "pendingId": "pending:home-pending"+ },+ {+ "type": "send",+ "nowMs": 4001000,+ "id": "q1",+ "text": "Run my tests",+ "agent": "claude-code"+ }+ ]+ },+ {+ "step": "a person wrote in the home's own thread: it shows",+ "fresh": true,+ "actions": [+ {+ "type": "start",+ "nowMs": 5000000,+ "harness": "claude-code",+ "pendingId": "pending:home-pending"+ },+ {+ "type": "homeReady",+ "nowMs": 5005000,+ "spaceId": "local:home-claude-code"+ },+ {+ "type": "asked",+ "nowMs": 5010000+ }+ ]+ }+ ],+ "roster": [+ "local:build-box",+ "home-pending",+ "pending:home-pending",+ "local:home-fix-the-failing-tests",+ "local:home-claude-code",+ "local:notes"+ ]+}diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex 3bff07bd4f..752619c99c 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -19,9 +19,9 @@ use crate::{CoreError, about, account, agent_keys, agents, bulk_confirm, checklist, cloud_connect,cloud_page, cloud_sheet, connectors, devices, diagnostics, drive_mount_preview, drive_page,drive_settings, driver_preview, experiments, host, local_network, login_item, machines, notch,- notifications, nudges, onboarding, onboarding_preview, palette, paths, persistent, presence,- relay_usage, resources, runtimes, settings, share, sign_in, space_menu, summon, telemetry,- tips, upsell, window, wizard,+ notifications, nudges, onboarding, onboarding_preview, palette, paths, persistent, prepare,+ presence, relay_usage, resources, runtimes, settings, share, sign_in, space_menu, summon,+ telemetry, tips, upsell, window, wizard,};use serde::Serialize;use serde::de::DeserializeOwned;@@ -79,6 +79,7 @@ pub const METHODS: &[&str] = &["wizard.view","wizard.createArgs","wizard.firstSpaceOffers",+ "firstPrompts.choose","wizard.pickerImages","wizard.pickerGroups","wizard.findImage",@@ -330,6 +331,11 @@ pub const METHODS: &[&str] = &["checklist.reduce","checklist.view","checklist.observeFrom",+ "prepare.reduce",+ "prepare.view",+ "prepare.metrics",+ "prepare.hidden",+ "prepare.listed","palette.keybindings","palette.rank","telemetry.experimentsChanged",@@ -573,6 +579,11 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {a.get::<Option<SpaceOs>>("hostOs")?.unwrap_or(SpaceOs::Macos),)),+ "firstPrompts.choose" => out(crate::first_prompts::choose_for(+ &a.get("env")?,+ a.get::<Option<SpaceOs>>("hostOs")?+ .unwrap_or(SpaceOs::Macos),+ )),"wizard.placementOptions" => out(wizard::placement_options_on(&a.get("state")?,&a.get("env")?,@@ -1453,6 +1464,28 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {&a.get::<Option<checklist::ChecklistSeen>>("seen")?.unwrap_or_default(),)),+ "prepare.reduce" => out(prepare::reduce(+ &a.get::<Option<prepare::State>>("state")?+ .unwrap_or_default(),+ &a.get::<prepare::Action>("action")?,+ )),+ "prepare.view" => out(prepare::view(+ &a.get::<Option<prepare::State>>("state")?+ .unwrap_or_default(),+ )),+ "prepare.hidden" => out(prepare::hidden_spaces(+ &a.get::<Option<prepare::State>>("state")?+ .unwrap_or_default(),+ )),+ "prepare.listed" => out(prepare::listed(+ &a.get::<Option<prepare::State>>("state")?+ .unwrap_or_default(),+ &a.get::<Vec<String>>("ids")?,+ )),+ "prepare.metrics" => out(prepare::metrics(+ &a.get::<Option<prepare::State>>("state")?+ .unwrap_or_default(),+ )),"palette.keybindings" => out(palette::keybindings()),"palette.rank" => out(palette::rank(&a.get::<Vec<palette::PaletteEntry>>("entries")?,diff --git a/libs/cua/crates/cua-spaces-app-core/src/first_prompts.rs b/libs/cua/crates/cua-spaces-app-core/src/first_prompts.rsnew file mode 100644index 0000000000..0926a2f02c--- /dev/null+++ b/libs/cua/crates/cua-spaces-app-core/src/first_prompts.rs@@ -0,0 +1,667 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! The example jobs the app hands a new user: the prompt to copy once a coding+//! app is connected (onboarding page 2 shows one fragment of the first as a sentence), and+//! the suggestion cards on an empty Home. One library, one capability filter:+//! every surface draws from [`LIBRARY`] through [`choose`], so no shell keeps a+//! sentence of its own and none can offer a job this machine cannot do.+//!+//! The point of an example is inspiration: each one is a job people really+//! have (see [`FAMILIES`] for where each need came from), written the way an+//! agent can finish it with Cua: make Spaces, work in them, compare, report+//! with screenshots, delete them. X+//!+//! The rules:+//! - Each entry names what it needs ([`Cap`]). A host gets an entry only when+//! it has all of it, from the facts the New Space wizard already reads+//! ([`crate::wizard::first_space_offers`], the runtime doctor, storage).+//! - A copyable example needs no repo and no account, uses a public page that+//! needs no login, and names no issue number or repository.+//! - A Home card may end with ": " to be filled in through the box (the+//! "Add a repo" pattern); it needs [`Cap::FillIn`], and [`Cap::Account`] when+//! a site may ask for a login.+//! - [`FALLBACK`] needs only a Linux Space and works on every host (default+//! secure network: internet and child Spaces, nothing else).++use crate::model::SpaceOs;+use crate::wizard::{FirstSpaceOffer, WizardEnv, first_space_offers, local_microvm_runtimes};+use serde::{Deserialize, Serialize};++/// What an example needs from the machine or the person.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum Cap {+ /// A Linux Space (every host can make one, or asks a machine that can).+ LinuxSpace,+ /// A macOS Space, made here now (Apple silicon, runtime ready, room).+ MacosSpace,+ /// A Windows Space, made here now (QEMU ready, room).+ WindowsSpace,+ /// MicroVMs: many small Spaces at once (KVM or Apple's container services).+ Kvm,+ /// A fill-in the person completes in the box: a project, a link, a site or a place.+ FillIn,+ /// The person's own account, signed in once with their approval.+ Account,+}++/// What this machine can do now.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct HostCaps {+ pub macos: bool,+ pub windows: bool,+ pub kvm: bool,+ /// The macOS image is already downloaded here.+ #[serde(default)]+ pub macos_cached: bool,+ /// The Windows image is already downloaded here.+ #[serde(default)]+ pub windows_cached: bool,+}++impl HostCaps {+ /// Whether the entry needs a macOS or Windows image that is not here yet,+ /// so its first run downloads one.+ fn downloads(&self, e: &Entry) -> bool {+ (e.needs.contains(&Cap::MacosSpace) && !self.macos_cached)+ || (e.needs.contains(&Cap::WindowsSpace) && !self.windows_cached)+ }++ fn has(&self, c: Cap) -> bool {+ match c {+ Cap::LinuxSpace | Cap::FillIn | Cap::Account => true,+ Cap::MacosSpace => self.macos,+ Cap::WindowsSpace => self.windows,+ Cap::Kvm => self.kvm,+ }+ }+}++/// One example in the library.+pub struct Entry {+ pub id: &'static str,+ /// The workflow family ([`FAMILIES`]).+ pub family: &'static str,+ pub needs: &'static [Cap],+ /// One plain line: why this is useful.+ pub why: &'static str,+ /// The example sentence onboarding shows ("things like ..."): only the bug-on-platform entries have one.+ pub lede: &'static str,+ /// The card's title.+ pub title: &'static str,+ /// The card's line under the title.+ pub detail: &'static str,+ /// The prompt. A card's ends with ": " when the person fills in the rest.+ pub text: &'static str,+ /// Home card order (higher first); 0 is never a card.+ pub card: u8,+}++/// The workflows the examples come from, with where each need came from. The+/// starters of other assistant apps could not be read verbatim (their pages+/// were not reachable), so a note says what is known of them, not their words.+pub const FAMILIES: &[(&str, &str)] = &[+ (+ "shopping-research",+ "Muse's starter tasks are buying groceries and comparing options (Meta's Muse post, mobile-rn REFERENCES 1.2); Dots research with visible updates (1.3); the first-run price-research jobs people ask coding apps for",+ ),+ (+ "trip-planning",+ "Muse books restaurant tables and plans from live availability (REFERENCES 1.2); Dots plans end to end and stops for approval (1.3)",+ ),+ (+ "orders-claims-forms",+ "FRICTION item 1 (site sign-in through the Keyvault, not a personal browser profile); Muse's approval card before checkout and its client-owned password entry (REFERENCES 1.2)",+ ),+ (+ "paperwork",+ "Keyvault and Cua Volume guides (files an agent collects and keeps); Muse's inspect and download files (REFERENCES 1.2)",+ ),+ (+ "research-brief",+ "Dots research with sources and visible updates (REFERENCES 1.3); the provenance-review retro (clone, scan, report with evidence)",+ ),+ (+ "watch-and-tell",+ "Schedules guide (recurring work whether or not an app is open); Keep an agent running guide; Dots always-on agents (REFERENCES 1.3)",+ ),+ (+ "two-space-dev",+ "Boat head-to-head retro (many jobs, two kinds of computer); Child Spaces guide (a Space makes Spaces); E2B-migration prospect running many environments",+ ),+ (+ "cross-platform-verify",+ "Public issues that name their platform (Windows 11 Edge, macOS 27, Fedora KDE Wayland); the Home Safari card; release-verification retro (clean Mac, clean Windows)",+ ),+ (+ "bug-on-platform",+ "Public bug reports each name the platform they happen on; the Hermes plugin retro (read the report, reproduce, fix, test, release)",+ ),+ (+ "untrusted-code",+ "Cua CI guide (a fresh Space per job, deleted afterwards); the provenance-review retro; the secure default Space (no host, no LAN)",+ ),+ (+ "long-job",+ "Keep an agent running guide; FRICTION item 7 (a laptop's network change pausing a task); the durable-agent battle tests",+ ),+ (+ "fan-out-research",+ "Child Spaces guide; Boat head-to-head retro (80 jobs at once); E2B-migration (256 environments)",+ ),+];++const L: Cap = Cap::LinuxSpace;+const M: Cap = Cap::MacosSpace;+const W: Cap = Cap::WindowsSpace;++/// The library. Order matters inside a family and for copyable examples of+/// equal reach: earlier is preferred. No entry names an issue number, a+/// repository, or a system its `needs` do not list; a login is always asked+/// for through the Keyvault or the visible browser window; none merely opens a+/// public page and describes it (tests hold all of this).+pub const LIBRARY: &[Entry] = &[+ Entry {+ id: "price-compare",+ lede: "",+ family: "shopping-research",+ needs: &[L],+ why: "Real research with prices, reviews and screenshots, done while you do something else.",+ title: "Research a purchase across several stores",+ detail: "It compares prices and reviews and writes you a buying guide with sources.",+ text: "Make a fresh Linux Space with Cua and use its browser to research the three best-reviewed noise cancelling headphones under 300 dollars right now. Compare their prices at four stores, including the maker's own site, read the most recent reviews, and screenshot each price you rely on. Then write me a short buying guide with the sources linked. Do not buy anything, and do not sign in anywhere. Delete the Space when you are done.",+ card: 0,+ },+ Entry {+ id: "trip-weekend",+ lede: "",+ family: "trip-planning",+ needs: &[L],+ why: "A trip planned from live availability, with a stop before anything costs money.",+ title: "Plan a weekend from live availability",+ detail: "It compares hotels on several sites and writes a one page itinerary.",+ text: "Plan a long weekend in Lisbon for two, three weeks from now. In a fresh Linux Space with a browser, compare live hotel prices and availability for three nights on at least three booking sites, check which neighborhoods have the best recent reviews, and screenshot your top three options. Write me a one page itinerary with links and a total cost estimate. Stop and ask me before anything that costs money. Delete the Space when you are done.",+ card: 0,+ },+ Entry {+ id: "two-space-load",+ lede: "",+ family: "two-space-dev",+ needs: &[L],+ why: "A server and its users in two separate Spaces, which is how it fails for real.",+ title: "Load test a web app from a second Space",+ detail: "One Space runs the app, another one uses it and pushes it until it slows.",+ text: "Make two fresh Linux Spaces with Cua. In the first, write and start a small web app that serves a page with a thousand generated rows and a search box, and tell me its address inside the network. From the second Space, open it in a browser and use the search box, then load test it with a growing number of parallel requests until responses slow down. Send me the screenshots, a table of response times for each load level, and the point where it started to struggle. Delete both Spaces when you are done.",+ card: 0,+ },+ Entry {+ id: "fan-out-pricing",+ lede: "",+ family: "fan-out-research",+ needs: &[L, Cap::Kvm],+ why: "Ten Spaces at once, one tool each, one table back.",+ title: "Compare ten tools at once, one Space each",+ detail: "Ten Spaces open ten pricing pages side by side and you get one table.",+ text: "Compare the pricing of ten popular project management tools at the same time. Make ten fresh Linux Spaces with Cua, one per tool: Asana, Trello, Monday, ClickUp, Notion, Linear, Jira, Basecamp, Smartsheet and Wrike. In each, open the tool's pricing page, screenshot every plan and note its price per person per month, what the free plan includes, and any limit that matters for a team of ten. Give me one table with a link to each source and tell me which three fit a team of ten best. Do not sign up for anything. Delete the Spaces when you are done.",+ card: 0,+ },+ Entry {+ id: "cross-os-prices-macos",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, M],+ why: "The same shopping page on two systems, side by side, with screenshots.",+ title: "Compare store pages on Linux and macOS",+ detail: "It searches the same stores on both systems and shows what differs.",+ text: "Make a fresh Linux Space and a fresh macOS Space with Cua. In the browser of each (Safari on the Mac), open the same three large electronics stores, search for wireless earbuds under 100 dollars and screenshot the first page of results. Tell me where the prices, the ordering or the page itself differ between the two systems, and which store has the best deal today. Do not sign in or buy anything. Delete both Spaces when you are done.",+ card: 0,+ },+ Entry {+ id: "cross-os-prices-windows",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, W],+ why: "The same shopping page on two systems, side by side, with screenshots.",+ title: "Compare store pages on Linux and Windows",+ detail: "It searches the same stores on both systems and shows what differs.",+ text: "Make a fresh Linux Space and a fresh Windows Space with Cua. In the browser of each (Edge on Windows), open the same three large electronics stores, search for wireless earbuds under 100 dollars and screenshot the first page of results. Tell me where the prices, the ordering or the page itself differ between the two systems, and which store has the best deal today. Do not sign in or buy anything. Delete both Spaces when you are done.",+ card: 0,+ },+ Entry {+ id: "order-tracking",+ lede: "",+ family: "orders-claims-forms",+ needs: &[L, Cap::FillIn, Cap::Account],+ why: "Finds out where your order is without you opening a thing, and signs in without seeing a password.",+ title: "Find out where my order is",+ detail: "It signs in the safe way, reads the tracking page and tells you if it is late.",+ text: "Find out where my latest order is. In a fresh Linux Space with a browser, open the store site below. If it needs me to sign in, ask for the login through the Keyvault, or show me the browser window so I can sign in myself, and never ask me to type a password to you. Then tell me the order's status and expected delivery date, screenshot the tracking page, and say if anything looks late. The store: ",+ card: 85,+ },+ Entry {+ id: "claim-status",+ lede: "",+ family: "orders-claims-forms",+ needs: &[L, Cap::FillIn, Cap::Account],+ why: "Reads a claim or case page for you and lists what it is waiting on.",+ title: "Check on my claim or case",+ detail: "It reads the status and tells you what it is waiting for from you.",+ text: "Check on my open claim. In a fresh Linux Space with a browser, open the claims site below. If it needs me to sign in, ask for the login through the Keyvault, or show me the browser window so I can sign in myself, and never ask me to type a password to you. Then list what the claim is waiting on from me, the dates it shows and who to contact, with a screenshot of each page. Do not submit or change anything. The site: ",+ card: 45,+ },+ Entry {+ id: "fill-form",+ lede: "",+ family: "orders-claims-forms",+ needs: &[L, Cap::FillIn, Cap::Account],+ why: "Does the typing and stops before the part that cannot be undone.",+ title: "Fill in a form and stop before sending",+ detail: "It fills every page, shows you each one, and waits for your yes.",+ text: "Fill in the form at the address below with the details I give you in this chat. Use a fresh Linux Space with a browser. If it needs me to sign in, ask for the login through the Keyvault, or show me the browser window so I can sign in myself, and never ask me to type a password to you. Screenshot every page as you go, stop before the final submit, and ask me to confirm. The form: ",+ card: 40,+ },+ Entry {+ id: "receipts",+ lede: "",+ family: "paperwork",+ needs: &[L, Cap::FillIn, Cap::Account],+ why: "Gathers a year of receipts into one place and one spreadsheet.",+ title: "Collect my receipts into one place",+ detail: "It downloads your last receipts into your Cua Volume and lists them.",+ text: "Collect my receipts. In a fresh Linux Space with a browser, open the account page below. If it needs me to sign in, ask for the login through the Keyvault, or show me the browser window so I can sign in myself, and never ask me to type a password to you. Download the last twelve receipts or invoices into my Cua Volume, and make a spreadsheet with the date, vendor, amount and file name of each. The account: ",+ card: 55,+ },+ Entry {+ id: "book-table",+ lede: "",+ family: "trip-planning",+ needs: &[L, Cap::FillIn, Cap::Account],+ why: "Compares real availability and stops before booking.",+ title: "Find a table for Friday night",+ detail: "It compares booking sites and waits for your pick before booking.",+ text: "Find a table for four on Friday evening near the place below. In a fresh Linux Space with a browser, compare availability on at least two booking sites and pick the three best-reviewed places that have a table around 7 pm, with a screenshot of each. If it needs me to sign in, ask for the login through the Keyvault, or show me the browser window so I can sign in myself, and never ask me to type a password to you. Stop before booking anything and ask me which one. The place: ",+ card: 70,+ },+ Entry {+ id: "price-watch",+ lede: "",+ family: "watch-and-tell",+ needs: &[L, Cap::FillIn],+ why: "Keeps watching while your laptop is closed, and tells you only when it matters.",+ title: "Watch a page and tell me when it changes",+ detail: "It checks twice a day and messages you with a screenshot.",+ text: "Watch the product page below for me in a Linux Space that keeps running when I close my laptop. Check the price twice a day, and message me with a screenshot as soon as it falls below the price I tell you, or when something else that matters changes, like it going out of stock or a new model replacing it. The page: ",+ card: 65,+ },+ Entry {+ id: "research-brief",+ lede: "",+ family: "research-brief",+ needs: &[L, Cap::FillIn],+ why: "A sourced brief instead of ten open tabs.",+ title: "Research a topic with sources",+ detail: "It reads at least six sources and writes a two page brief with links.",+ text: "Research the topic below. In a fresh Linux Space with a browser, read at least six sources, screenshot the passage you rely on in each, and write me a two page brief that says what is agreed, what is disputed and what you could not confirm, with every claim linked to its source. The topic: ",+ card: 50,+ },+ Entry {+ id: "server-ui-load",+ lede: "",+ family: "two-space-dev",+ needs: &[L, Cap::FillIn],+ why: "Finds out how your app behaves under real users, from a separate Space.",+ title: "Run my app in one Space and load test it from another",+ detail: "It drives the screens in a browser and pushes the server until it slows.",+ text: "Run my app's server in one Space and test it from another. Make two fresh Linux Spaces, install what the project needs and start the server in the first, then from the second drive its main screens in a browser and load test it with a growing number of parallel users. Give me screenshots, a table of response times for each level, and where it starts to break. My project: ",+ card: 80,+ },+ Entry {+ id: "tests-linux-macos",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, M, Cap::FillIn],+ why: "Finds what only breaks on one system, in clean Spaces of each kind.",+ title: "Verify a change on Linux and on macOS",+ detail: "Clean Spaces of each kind run the same steps and you see what differs.",+ text: "Bring up my project's services in a clean Linux Space and run its tests there, then verify the same change on a fresh macOS Space with the same steps. Compare the two runs and show me anything that behaves differently, with logs and a screenshot where it matters. My project: ",+ card: 95,+ },+ Entry {+ id: "tests-linux-windows",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, W, Cap::FillIn],+ why: "Finds what only breaks on one system, in clean Spaces of each kind.",+ title: "Verify a change on Linux and on Windows",+ detail: "Clean Spaces of each kind run the same steps and you see what differs.",+ text: "Bring up my project's services in a clean Linux Space and run its tests there, then verify the same change on a fresh Windows Space with the same steps. Compare the two runs and show me anything that behaves differently, with logs and a screenshot where it matters. My project: ",+ card: 94,+ },+ Entry {+ id: "site-linux-macos",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, M, Cap::FillIn],+ why: "See your site the way each system's visitors do.",+ title: "Check my site on Linux and in Safari",+ detail: "It clicks through your site on both and lists every difference.",+ text: "Check how my site looks and works on a fresh Linux Space and in Safari on a fresh macOS Space. Click through the main pages and forms in each, take screenshots, and list every difference you find. My site: ",+ card: 88,+ },+ Entry {+ id: "site-linux-windows",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, W, Cap::FillIn],+ why: "See your site the way each system's visitors do.",+ title: "Check my site on Linux and in Edge",+ detail: "It clicks through your site on both and lists every difference.",+ text: "Check how my site looks and works on a fresh Linux Space and in Edge on a fresh Windows Space. Click through the main pages and forms in each, take screenshots, and list every difference you find. My site: ",+ card: 87,+ },+ Entry {+ id: "installer-linux-macos",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, M, Cap::FillIn],+ why: "Learn the installer fails before your users do.",+ title: "Build my installer and test it on Linux and macOS",+ detail: "It installs and starts the app in a clean Space of each kind and compares.",+ text: "Build my app's installer on a fresh Linux Space and on a fresh macOS Space, install it on each, start the app and smoke test its main flow, then compare the behavior between the two and show me a screenshot of each. My project: ",+ card: 86,+ },+ Entry {+ id: "installer-linux-windows",+ lede: "",+ family: "cross-platform-verify",+ needs: &[L, W, Cap::FillIn],+ why: "Learn the installer fails before your users do.",+ title: "Build my installer and test it on Linux and Windows",+ detail: "It installs and starts the app in a clean Space of each kind and compares.",+ text: "Build my app's installer on a fresh Linux Space and on a fresh Windows Space, install it on each, start the app and smoke test its main flow, then compare the behavior between the two and show me a screenshot of each. My project: ",+ card: 85,+ },+ Entry {+ id: "bug-macos",+ lede: "Reproduce this bug on a fresh macOS Space",+ family: "bug-on-platform",+ needs: &[M, Cap::FillIn],+ why: "Proves a fix on the platform the bug was reported on.",+ title: "Reproduce a bug on macOS, fix it, prove it",+ detail: "It follows the report on a fresh macOS Space and shows the fix there.",+ text: "Reproduce a bug a user reported on their platform, then fix it and prove the fix there. Make a fresh macOS Space, follow the report's steps exactly and screenshot what happens, make the fix in my project, and run the same steps again to show it is gone. The report: ",+ card: 90,+ },+ Entry {+ id: "bug-windows",+ lede: "Reproduce this bug on a fresh Windows Space",+ family: "bug-on-platform",+ needs: &[W, Cap::FillIn],+ why: "Proves a fix on the platform the bug was reported on.",+ title: "Reproduce a bug on Windows, fix it, prove it",+ detail: "It follows the report on a fresh Windows Space and shows the fix there.",+ text: "Reproduce a bug a user reported on their platform, then fix it and prove the fix there. Make a fresh Windows Space, follow the report's steps exactly and screenshot what happens, make the fix in my project, and run the same steps again to show it is gone. The report: ",+ card: 89,+ },+ Entry {+ id: "bug-linux",+ lede: "Reproduce this bug on a fresh Linux Space",+ family: "bug-on-platform",+ needs: &[L, Cap::FillIn],+ why: "Proves a fix in a clean Space, not just on your own computer.",+ title: "Reproduce a bug in a clean Space, fix it, prove it",+ detail: "It follows the report on a fresh Linux Space and shows the fix there.",+ text: "Reproduce a bug a user reported, then fix it and prove the fix in a clean Space. Make a fresh Linux Space, follow the report's steps exactly and screenshot what happens, make the fix in my project, and run the same steps again to show it is gone. The report: ",+ card: 35,+ },+ Entry {+ id: "untrusted-pr",+ lede: "",+ family: "untrusted-code",+ needs: &[L, Cap::FillIn],+ why: "See what unfamiliar code touches before it gets near your machine.",+ title: "Try an unfamiliar change in a sandbox",+ detail: "It builds it with no access to your machine and reports what it touches.",+ text: "Try an unfamiliar change in a sandbox. Make a fresh Linux Space with no access to my machine, check out the pull request or package below, build it and run its tests, and tell me every network address it contacted and every file it wrote outside its own folder, so I can decide whether to merge or install it. The link: ",+ card: 75,+ },+ Entry {+ id: "long-job",+ lede: "",+ family: "long-job",+ needs: &[L, Cap::FillIn],+ why: "A long job keeps going when you close the laptop, and finds you when it is done.",+ title: "Run a long job and hand it off if I close my laptop",+ detail: "It keeps going on another machine of yours and messages you when done.",+ text: "Run the job below in a Linux Space that keeps going if I close my laptop, and hand it over to another of my machines if this one goes to sleep. Check on it now and then and message me when it finishes or fails, with the last lines of its log. The job: ",+ card: 60,+ },+];++/// The example that works on every host: a Linux Space, one public page, no+/// repo, no account, nothing private.+pub const FALLBACK: &str = "price-compare";++/// The Windows image a Windows Space is made from.+const WINDOWS_IMAGE: &str = "ghcr.io/trycua/windows:2022";++/// What this machine can do now, from the facts the wizard reads.+pub fn host_caps(env: &WizardEnv, host_os: SpaceOs, offers: &[FirstSpaceOffer]) -> HostCaps {+ let macos = offers+ .iter()+ .any(|o| o.id == "macos" && o.blocked.is_none());+ // Windows runs in QEMU on a PC (a Mac does not offer it yet), once the+ // doctor and storage are read and there is room.+ let checked = env.storage.is_some() && env.local_backends.is_some();+ let local = WizardEnv {+ default_location: crate::model::Location::Local,+ ..env.clone()+ };+ let windows = checked+ && host_os != SpaceOs::Macos+ && crate::wizard::local_plan(&local, host_os, WINDOWS_IMAGE)+ .is_some_and(|(_, blocked)| blocked.is_none());+ let pulled = |r: &str| {+ env.storage+ .as_ref()+ .is_some_and(|st| st.pulled.iter().any(|p| p == r))+ };+ let macos_cached = macos+ && offers+ .iter()+ .any(|o| o.id == "macos" && o.size.as_deref() == Some("Already downloaded"));+ let windows_cached = windows && pulled(WINDOWS_IMAGE);+ let kvm = local_microvm_runtimes(env).is_some_and(|r| !r.is_empty());+ HostCaps {+ macos,+ windows,+ kvm,+ macos_cached,+ windows_cached,+ }+}++fn fits(e: &Entry, caps: &HostCaps) -> bool {+ e.needs.iter().all(|c| caps.has(*c))+}++fn platforms(e: &Entry) -> usize {+ e.needs+ .iter()+ .filter(|c| matches!(c, Cap::LinuxSpace | Cap::MacosSpace | Cap::WindowsSpace))+ .count()+}++fn copyable(e: &Entry) -> bool {+ !e.needs+ .iter()+ .any(|c| matches!(c, Cap::FillIn | Cap::Account))+}++/// The system an entry's icon shows: the system for a one-system job, Linux+/// for one that uses several.+fn icon_os(e: &Entry) -> SpaceOs {+ match (+ platforms(e),+ e.needs.contains(&Cap::MacosSpace),+ e.needs.contains(&Cap::WindowsSpace),+ ) {+ (1, true, _) => SpaceOs::Macos,+ (1, _, true) => SpaceOs::Windows,+ _ => SpaceOs::Linux,+ }+}++/// One example to copy.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Example {+ pub id: String,+ pub family: String,+ pub text: String,+ /// "Why this is useful", one line.+ pub why: String,+ pub needs: Vec<Cap>,+}++/// One card on an empty Home.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Suggestion {+ pub id: String,+ pub family: String,+ pub title: String,+ pub detail: String,+ /// The system the job runs on (its icon).+ pub os: SpaceOs,+ /// What goes into the box when the card is picked; ends with ": " when+ /// the person fills in the rest.+ pub prompt: String,+ pub why: String,+ pub needs: Vec<Cap>,+}++/// Everything chosen for this machine.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FirstPrompts {+ /// What this machine can do now.+ pub caps: HostCaps,+ /// Onboarding's one example sentence, chosen from the bug-on-platform entries:+ /// Windows where a Windows Space can be made, else macOS where a macOS Space+ /// can, else Linux. Never a system this machine cannot make.+ pub lede: String,+ /// The examples to copy, best fit first, one per family, with the+ /// fallback somewhere in it. Never empty. The first is the one onboarding shows; the rest+ /// are what the Agents page offers after it.+ pub examples: Vec<Example>,+ /// The cards for an empty Home, best fit first.+ pub suggestions: Vec<Suggestion>,+}++/// What a first run downloading an image adds to the why-line.+const DOWNLOADS: &str = " The first run downloads an image.";++fn why_of(e: &Entry, caps: &HostCaps) -> String {+ if caps.downloads(e) {+ format!("{}{DOWNLOADS}", e.why)+ } else {+ e.why.into()+ }+}++fn example(e: &Entry, caps: &HostCaps) -> Example {+ Example {+ id: e.id.into(),+ family: e.family.into(),+ text: e.text.into(),+ why: why_of(e, caps),+ needs: e.needs.to_vec(),+ }+}++/// How many cards Home shows.+pub const CARDS: usize = 3;++/// The examples and cards for a machine with `caps`.+pub fn choose_with(caps: HostCaps) -> FirstPrompts {+ // Copyable: jobs that need no download first (the most systems first, then library order,+ // so the plain fallback leads), then the ones that download a macOS or Windows image on+ // their first run, which lead as soon as the image is here; one per family so the list varies.+ let mut order: Vec<usize> = (0..LIBRARY.len())+ .filter(|&i| copyable(&LIBRARY[i]) && fits(&LIBRARY[i], &caps))+ .collect();+ order.sort_by_key(|&i| {+ (+ caps.downloads(&LIBRARY[i]),+ std::cmp::Reverse(platforms(&LIBRARY[i])),+ i,+ )+ });+ let mut seen: Vec<&str> = vec![];+ let mut examples: Vec<Example> = vec![];+ for i in order {+ let e = &LIBRARY[i];+ if e.id != FALLBACK && seen.contains(&e.family) {+ continue;+ }+ // The fallback shares its family with the two-system page jobs: it does not hide them.+ if e.id != FALLBACK {+ seen.push(e.family);+ }+ examples.push(example(e, &caps));+ }+ // The fallback is always in the list, whatever else fits.+ if !examples.iter().any(|x| x.id == FALLBACK)+ && let Some(f) = LIBRARY.iter().find(|e| e.id == FALLBACK)+ {+ examples.push(example(f, &caps));+ }+ // Cards: highest priority first among what fits, one per family.+ let mut cards: Vec<&Entry> = LIBRARY+ .iter()+ .filter(|e| e.card > 0 && fits(e, &caps))+ .collect();+ cards.sort_by_key(|e| std::cmp::Reverse(e.card));+ let mut seen: Vec<&str> = vec![];+ let mut suggestions = vec![];+ for e in cards {+ if seen.contains(&e.family) {+ continue;+ }+ seen.push(e.family);+ suggestions.push(Suggestion {+ id: e.id.into(),+ family: e.family.into(),+ title: e.title.into(),+ detail: e.detail.into(),+ os: icon_os(e),+ prompt: e.text.into(),+ why: why_of(e, &caps),+ needs: e.needs.to_vec(),+ });+ if suggestions.len() == CARDS {+ break;+ }+ }+ let lede = ["bug-windows", "bug-macos", "bug-linux"]+ .iter()+ .filter_map(|id| LIBRARY.iter().find(|e| e.id == *id))+ .find(|e| fits(e, &caps))+ .map(|e| e.lede)+ .unwrap_or("Reproduce this bug on a fresh Linux Space");+ FirstPrompts {+ caps,+ lede: lede.into(),+ examples,+ suggestions,+ }+}++/// The examples and cards for the machine described by `env`, running `host_os`.+pub fn choose_for(env: &WizardEnv, host_os: SpaceOs) -> FirstPrompts {+ let offers = first_space_offers(env, host_os);+ choose_with(host_caps(env, host_os, &offers))+}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 5a89986e1f..2c78454b2f 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@@ -168,7 +168,10 @@ pub fn steps(input: &FirstRunInput) -> Vec<FirstRunStep> {if asks_permissions(input) {out.push(FirstRunStep::Permissions);}- out.push(FirstRunStep::Setup);+ // Ask first has no "Try it" screen: the person asks in the ask-first Space.+ if !input.ask_first {+ out.push(FirstRunStep::Setup);+ }out}@@ -335,6 +338,21 @@ pub struct FirstRunInput {/// The CLI's name (`SettingsSnapshot.cli`: `CuaChannel::cli_name`);/// none: the install plan's file name, else `cua`.pub cli_name: Option<String>,+ /// Ask first is on: there is no "Try it in your agent" screen. The last+ /// screen's button opens the ask-first Space, which is already being+ /// prepared, and the person asks there.+ #[serde(default)]+ pub ask_first: bool,+}++/// The label of the button that ends the first run: "Open Cua" on the last+/// screen of an ask-first run, "Continue" on every other.+fn continue_label(input: &FirstRunInput, step: FirstRunStep) -> &'static str {+ if input.ask_first && steps(input).last() == Some(&step) {+ "Open Cua"+ } else {+ "Continue"+ }}/// The CLI's name for `input`: the host's, else the install plan's file@@ -1237,7 +1255,7 @@ fn devices_view(input: &FirstRunInput) -> DevicesView {lede: "Sign in on your other computers to use its Spaces.".into(),rows,status,- primary: button("continue", "Continue"),+ primary: button("continue", continue_label(input, FirstRunStep::Devices)),secondary: None,note: None,};@@ -1364,7 +1382,7 @@ pub fn permissions_view(input: &FirstRunInput) -> PermissionsView {},rows,note: format!("Allow opens System Settings, where you turn on {app}."),- primary: all.then(|| button("continue", "Continue")),+ primary: all.then(|| button("continue", continue_label(input, FirstRunStep::Permissions))),secondary: (!all).then(|| button("not-now", "Not now")),}}@@ -1744,6 +1762,8 @@ pub fn view(input: &FirstRunInput) -> FirstRunView {// its screen is not shared) shows the try screen instead.let step = if all.contains(&input.step) {input.step+ } else if input.ask_first {+ all.last().copied().unwrap_or(FirstRunStep::Welcome)} else {FirstRunStep::Setup};@@ -2071,6 +2091,123 @@ mod tests {c.agents.iter().map(|a| a.agent.clone()).collect()}+ #[test]+ fn ask_first_has_no_try_it_screen_and_the_last_screen_opens_cua() {+ let mut i = input(FirstRunStep::Devices, vec![claude(true)]);+ // Off: the Try it screen is last, as before.+ assert_eq!(steps(&i).last(), Some(&FirstRunStep::Setup));+ i.ask_first = true;+ // Signed out: no permissions screen, so Add your other machines is last.+ assert_eq!(+ steps(&i),+ vec![+ FirstRunStep::Welcome,+ FirstRunStep::Connect,+ FirstRunStep::Devices+ ]+ );+ assert!(!steps(&i).contains(&FirstRunStep::Setup));+ assert_eq!(view(&i).dots, 3);+ // Signed in and not sharing the screen: still no permissions screen; the button ends the run.+ i.signed_in = true;+ i.host = Some(FirstRunHost {+ configured: true,+ share_desktop: Some(false),+ ..Default::default()+ });+ assert_eq!(view(&i).devices.unwrap().primary.label, "Open Cua");+ // A Mac that shares its screen asks for permissions last: Continue on Devices, Open Cua there.+ i.host = Some(FirstRunHost {+ configured: true,+ ..Default::default()+ });+ assert_eq!(steps(&i).last(), Some(&FirstRunStep::Permissions));+ assert_eq!(view(&i).devices.unwrap().primary.label, "Continue");+ i.step = FirstRunStep::Permissions;+ assert_eq!(+ view(&i).permissions.unwrap().primary.map(|b| b.label),+ Some("Open Cua".to_string())+ );+ // A run saved on the removed screen shows the last one.+ i.step = FirstRunStep::Setup;+ assert_eq!(view(&i).step, FirstRunStep::Permissions);+ }++ #[test]+ fn every_page_in_every_branch_has_its_action_and_every_agent_row_its_state_or_action() {+ for ask_first in [false, true] {+ for signed_in in [false, true] {+ for cli_missing in [false, true] {+ let mut base = input(+ FirstRunStep::Welcome,+ vec![claude(false), codex(false, false), hermes()],+ );+ base.ask_first = ask_first;+ base.signed_in = signed_in;+ if signed_in {+ base.host = Some(FirstRunHost {+ configured: true,+ ..Default::default()+ });+ }+ if cli_missing {+ base.cli.plan = Some(crate::installer::CliInstallPlan {+ source: Some("/app/cua".into()),+ target: "/usr/local/bin/cua".into(),+ ..Default::default()+ });+ }+ let all = steps(&base);+ assert_eq!(all.contains(&FirstRunStep::Setup), !ask_first);+ for st in all {+ let mut i = base.clone();+ i.step = st;+ let v = view(&i);+ let what = format!(+ "ask_first {ask_first}, signed_in {signed_in}, cli_missing {cli_missing}, {st:?}"+ );+ assert_eq!(v.step, st, "{what}");+ match st {+ FirstRunStep::Welcome => {+ assert!(!v.welcome.unwrap().primary.label.is_empty(), "{what}")+ }+ FirstRunStep::Connect => {+ let c = v.connect.unwrap();+ assert!(!c.primary.label.is_empty(), "{what}: Continue");+ assert!(!c.agents.is_empty(), "{what}");+ for a in &c.agents {+ assert!(+ a.connected || a.action.is_some() || a.note.is_some(),+ "{what}: {} has no state or action",+ a.name+ );+ }+ }+ FirstRunStep::Cli => {+ let c = v.cli.unwrap();+ assert!(c.primary.is_some(), "{what}");+ }+ FirstRunStep::Devices => {+ let d = v.devices.unwrap();+ assert!(!d.primary.label.is_empty(), "{what}");+ }+ FirstRunStep::Permissions => {+ let p = v.permissions.unwrap();+ assert!(+ p.primary.is_some() || p.secondary.is_some(),+ "{what}: no Continue and no Not now"+ );+ }+ FirstRunStep::Setup => {+ assert!(v.setup.is_some(), "{what}");+ }+ }+ }+ }+ }+ }+ }+#[test]fn four_screens_in_order_and_a_fresh_run_starts_on_welcome() {assert_eq!(FirstRunInput::default().step, FirstRunStep::Welcome);diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rsindex 3b20d6637a..42cb81453f 100644--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs@@ -82,6 +82,7 @@ pub mod drive_settings;pub mod driver_preview;pub mod errors;pub mod experiments;+pub mod first_prompts;pub mod first_run;pub mod host;pub mod installer;@@ -103,6 +104,7 @@ pub mod palette;pub mod parity;pub mod paths;pub mod persistent;+pub mod prepare;pub mod presence;pub mod profile_card;pub mod relay_usage;diff --git a/libs/cua/crates/cua-spaces-app-core/src/parity.rs b/libs/cua/crates/cua-spaces-app-core/src/parity.rsindex 8a93a1db16..7e5d325561 100644--- a/libs/cua/crates/cua-spaces-app-core/src/parity.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/parity.rs@@ -253,6 +253,11 @@ pub const FLOWS: &[(&str, &str, &str)] = &[include_str!("../parity/connectors.json"),include_str!("../parity/golden/connectors.json"),),+ (+ "prepare",+ include_str!("../parity/prepare.json"),+ include_str!("../parity/golden/prepare.json"),+ ),];/// The core calls a flow makes, over JSON. A host implements it with its@@ -815,6 +820,90 @@ pub mod frame {Value::Array(out)}+ /// The preparing block, as lines: the headline, a status line only when the+ /// steps cannot say it, each step with its state, detail and (the current+ /// one only) its thin bar, each queued+ /// message with its note, the hint under the box and the button.+ pub fn prepare(v: &Value) -> Value {+ let mut out: Vec<Value> = Vec::new();+ out.push(Value::String(format!(+ "{}: {}",+ str_of(&v["phase"]),+ str_of(&v["title"])+ )));+ if let Some(l) = v["line"].as_str() {+ out.push(Value::String(l.to_string()));+ }+ for st in v["steps"].as_array().into_iter().flatten() {+ let mut l = format!("{} ({})", str_of(&st["label"]), str_of(&st["state"]));+ if let Some(d) = st["detail"].as_str() {+ l.push_str(&format!(" - {d}"));+ }+ if let Some(f) = st["fraction"].as_f64() {+ l.push_str(&format!(" [bar {}%]", (f * 100.0).round() as i64));+ }+ out.push(Value::String(l));+ }+ for q in v["queued"].as_array().into_iter().flatten() {+ out.push(Value::String(format!(+ "queued: {} ({})",+ str_of(&q["text"]),+ str_of(&q["note"])+ )));+ }+ if let Some(h) = v["composerHint"].as_str() {+ out.push(Value::String(format!("hint: {h}")));+ }+ if let Some(a) = v["action"]["label"].as_str() {+ out.push(Value::String(format!("button: {a}")));+ }+ Value::Array(out)+ }++ /// What the host was told to do, one line each.+ pub fn prepare_effects(effects: &[Value]) -> Value {+ Value::Array(+ effects+ .iter()+ .map(|e| {+ let mut l = str_of(&e["type"]).to_string();+ if let Some(id) = e["id"].as_str() {+ l.push_str(&format!(" {id}"));+ }+ if let Some(at) = e["atMs"].as_i64() {+ l.push_str(&format!(" at {at}"));+ }+ Value::String(l)+ })+ .collect(),+ )+ }++ /// The numbers, as `name=value` lines (`-` for not reached).+ pub fn prepare_metrics(m: &Value) -> Value {+ let n = |v: &Value| match v.as_i64() {+ Some(x) => x.to_string(),+ None => "-".to_string(),+ };+ let mut out = vec![Value::String(format!(+ "runtime={} image={} home={} agent={} prepare={} onboarding_to_ready={}",+ n(&m["runtimeMs"]),+ n(&m["imageMs"]),+ n(&m["homeMs"]),+ n(&m["agentMs"]),+ n(&m["prepareMs"]),+ n(&m["onboardingToReadyMs"])+ ))];+ for x in m["messages"].as_array().into_iter().flatten() {+ out.push(Value::String(format!(+ "message {} delivered={} first_token={}",+ str_of(&x["id"]),+ n(&x["sendToDeliveredMs"]),+ n(&x["sendToFirstTokenMs"])+ )));+ }+ Value::Array(out)+ }/// One Settings row: `- id kind: label = value ~placeholder [button] {options} (disabled) ?help <link>`.pub fn setting_row(r: &Value) -> String {let options = r["options"]@@ -1998,6 +2087,7 @@ pub fn run(name: &str, flow_json: &str, h: &dyn Host) -> Result<Value, String> {"tips" => run_tips(&flow, h),"pro-banner" => run_pro_banner(&flow, h),"connectors" => run_connectors(&flow, h),+ "prepare" => run_prepare(&flow, h),other => Err(format!("unknown flow {other}")),}}@@ -3490,6 +3580,7 @@ fn run_first_run(f: &Value, h: &dyn Host) -> Result<Value, String> {// A machine: its one-click offers are the wizard's for that// machine's env (`wizard.firstSpaceOffers`), as the page reads them.let mut offered = Value::Null;+ let mut prompts = Value::Null;if case["machine"].is_object() {let m = &case["machine"];let env = patched(&f["machineBase"], &m["env"]);@@ -3523,6 +3614,20 @@ fn run_first_run(f: &Value, h: &dyn Host) -> Result<Value, String> {);input["offers"] = json!(list);input["hostOs"] = m["hostOs"].clone();+ // The example jobs for that machine (`firstPrompts.choose`).+ let p = c(+ h,+ "firstPrompts.choose",+ json!({ "env": env, "hostOs": m["hostOs"] }),+ )?;+ prompts = json!({+ "caps": p["caps"],+ "lede": p["lede"],+ "examples": p["examples"].as_array().into_iter().flatten()+ .map(|x| x["id"].clone()).collect::<Vec<_>>(),+ "cards": p["suggestions"].as_array().into_iter().flatten()+ .map(|x| x["id"].clone()).collect::<Vec<_>>(),+ });}let v = c(h, "firstRun.view", json!({ "input": input }))?;let s = |v: &Value| v.as_str().unwrap_or("").to_string();@@ -3541,6 +3646,9 @@ fn run_first_run(f: &Value, h: &dyn Host) -> Result<Value, String> {if !offered.is_null() {frame["offers"] = offered;}+ if !prompts.is_null() {+ frame["prompts"] = prompts;+ }let row = |r: &Value| {format!("[{}] {} — {}{}",@@ -5001,6 +5109,43 @@ fn run_tips(f: &Value, h: &dyn Host) -> Result<Value, String> {Ok(json!({ "flow": "tips", "frames": frames }))}+/// Preparing the ask-first Space: each step sends actions (`prepare.reduce`),+/// then draws the page (`prepare.view`), what the host is told to do next+/// and the numbers (`prepare.metrics`).+fn run_prepare(f: &Value, h: &dyn Host) -> Result<Value, String> {+ let mut frames = Vec::new();+ let mut state = Value::Null;+ let roster = f["roster"].clone();+ for step in f["steps"].as_array().into_iter().flatten() {+ // A step may begin on a fresh install.+ if step["fresh"].as_bool() == Some(true) {+ state = Value::Null;+ }+ let mut effects: Vec<Value> = Vec::new();+ for a in step["actions"].as_array().into_iter().flatten() {+ let r = c(h, "prepare.reduce", json!({ "state": state, "action": a }))?;+ state = r["state"].clone();+ effects.extend(r["effects"].as_array().cloned().unwrap_or_default());+ }+ let v = c(h, "prepare.view", json!({ "state": state }))?;+ let m = c(h, "prepare.metrics", json!({ "state": state }))?;+ // What a list shows of the roster: the warming home is not in it until a person wrote into it.+ let listed = c(+ h,+ "prepare.listed",+ json!({ "state": state, "ids": roster }),+ )?;+ frames.push(json!({+ "step": step["step"],+ "page": frame::prepare(&v),+ "list": listed,+ "effects": frame::prepare_effects(&effects),+ "metrics": frame::prepare_metrics(&m),+ }));+ }+ Ok(json!({ "flow": "prepare", "frames": frames }))+}+/// The account area: the Pro banner (Free only, not closable) and the/// account menu.fn run_pro_banner(f: &Value, h: &dyn Host) -> Result<Value, String> {diff --git a/libs/cua/crates/cua-spaces-app-core/src/prepare.rs b/libs/cua/crates/cua-spaces-app-core/src/prepare.rsnew file mode 100644index 0000000000..80e3d597d0--- /dev/null+++ b/libs/cua/crates/cua-spaces-app-core/src/prepare.rs@@ -0,0 +1,1890 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Preparing the ask-first Space while the person is still in onboarding.+//!+//! The first Space that has a coding agent ready needs four things that take+//! minutes on a new Mac and a slow network: the **Linux runtime** (a small VM+//! the Mac runs Linux Spaces in), the **agent image** (the headless Linux+//! the agent's home runs on), the **home Space** itself, and the **agent**+//! (the coding app installed, its session open). This module is the one+//! state machine for all four, so every app starts them as early as it can+//! (first launch, sign-in, onboarding), says honestly where they are, never+//! loses a message typed meanwhile, and carries on from wherever it was after+//! a lost connection or a quit.+//!+//! * [`reduce`] moves a [`State`] by one [`Action`] and says what the host+//! does next ([`Effect`]). It never reads a clock, a disk or a network: the+//! host passes the time in every action and does what the effects say.+//! * [`view`] is what the page draws: the step list, the one honest status+//! line, the progress, the queued messages and the one button (Try again),+//! in the core's words, the same on every app.+//!+//! The state is plain JSON (`schema` 1): the host keeps it between launches.+//! It is a record of progress, not the truth: what exists (the Space, its+//! agent) is read from the host, and a state that says more than the host+//! knows is corrected by [`Action::Resume`] and [`Action::HomeGone`].+//!+//! # Messages+//!+//! A message sent while the Space is not ready is **queued**: kept in the+//! state (so a quit does not lose it) and delivered, in order, once the agent+//! is ready, **exactly once**:+//!+//! * a message is claimed (`delivering`) before the host posts it, and is+//! marked delivered when the post returned;+//! * a claimed message found after a quit or a crash is never posted again+//! blindly: [`Action::Resume`] asks the host to look in the Space's thread+//! ([`Effect::VerifyDelivery`]) and the answer+//! ([`Action::ThreadHas`]) decides: found is delivered, not found goes back+//! to the queue;+//! * a message id seen twice ([`Action::Send`]) is one message.+//!+//! # Time+//!+//! The state records when each step began and ended and, per message, when it+//! was sent, delivered and first answered, so "onboarding finished to ready",+//! "send to the agent session" and "send to the first model token" are+//! measured the same way everywhere ([`metrics`]).++use serde::{Deserialize, Serialize};++/// The state's schema; a state of another schema is dropped (preparing starts over).+pub const SCHEMA: u32 = 1;++/// Seconds before the first retry after a lost connection; it doubles up to+/// [`RETRY_MAX_MS`].+pub const RETRY_FIRST_MS: u64 = 2_000;+/// The longest wait between two retries.+pub const RETRY_MAX_MS: u64 = 60_000;+/// Failed attempts that are not the network's (a full disk, a refused pull)+/// before the page stops retrying and offers Try again.+pub const OTHER_ATTEMPTS: u32 = 2;+/// Times a message is posted again after its post failed, before it stays+/// queued with an error (the person can retry the whole thing).+pub const DELIVERY_ATTEMPTS: u32 = 5;++/// The four steps, in the order they run.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum Step {+ /// The Linux runtime (the VM Linux Spaces run in on a Mac).+ Runtime,+ /// The agent image.+ Image,+ /// The home Space.+ Home,+ /// The coding agent in it.+ Agent,+}++/// The steps in order.+pub const STEPS: [Step; 4] = [Step::Runtime, Step::Image, Step::Home, Step::Agent];++impl Step {+ fn rank(self) -> usize {+ STEPS.iter().position(|s| *s == self).unwrap_or(0)+ }++ /// The step's name in the list.+ pub fn label(self) -> &'static str {+ match self {+ Step::Runtime => "Linux runtime",+ Step::Image => "Agent image",+ Step::Home => "Home Space",+ Step::Agent => "Coding agent",+ }+ }++ fn id(self) -> &'static str {+ match self {+ Step::Runtime => "runtime",+ Step::Image => "image",+ Step::Home => "home",+ Step::Agent => "agent",+ }+ }+}++/// Where one step is.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum StepState {+ /// Not started.+ #[default]+ Pending,+ /// Running.+ Running,+ /// Waiting for the network (it carries on by itself).+ Waiting,+ /// Stopped with an error the person can retry.+ Failed,+ /// Done.+ Done,+ /// Not needed on this machine (a Docker engine is already there).+ Skipped,+}++/// One step's record.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct StepRecord {+ pub state: StepState,+ /// Bytes done and in all, while it downloads.+ pub done: u64,+ pub total: u64,+ /// Bytes per second, smoothed (none: not known).+ pub per_second: Option<u64>,+ /// When it began and ended (ms since the epoch).+ pub started_ms: Option<u64>,+ pub finished_ms: Option<u64>,+}++/// Why preparing is not moving.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct Trouble {+ /// A lost or missing connection (carries on by itself).+ pub network: bool,+ /// What went wrong, as the host said it.+ pub message: String,+}++/// Where a message is.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum MessageState {+ /// Waiting for the agent.+ #[default]+ Queued,+ /// Claimed: the host is posting it.+ Delivering,+ /// In the Space's thread.+ Delivered,+}++/// A message the person sent.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct Message {+ /// The caller's id for it; the same id is the same message.+ pub id: String,+ pub text: String,+ /// The coding app and model the person chose, and the repository.+ pub agent: String,+ pub model: Option<String>,+ pub repo: Option<String>,+ pub state: MessageState,+ /// Posts that failed.+ pub attempts: u32,+ pub sent_ms: u64,+ pub claimed_ms: Option<u64>,+ pub delivered_ms: Option<u64>,+ /// The agent's first words in answer.+ pub first_token_ms: Option<u64>,+}++/// The whole record.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct State {+ pub schema: u32,+ /// Preparing was asked for (at first launch).+ pub wanted: bool,+ /// When it began, and when onboarding ended (none: still in it).+ pub started_ms: Option<u64>,+ pub onboarding_done_ms: Option<u64>,+ pub runtime: StepRecord,+ pub image: StepRecord,+ pub home: StepRecord,+ pub agent: StepRecord,+ /// The coding app the home is for (`claude-code`).+ pub harness: String,+ /// The home Space, once it exists; the id its row has while it is made.+ pub home_space_id: Option<String>,+ pub pending_id: Option<String>,+ /// Lost connections since the last success (the retry wait's counter).+ pub attempt: u32,+ /// Non-network failures in a row.+ pub failures: u32,+ pub retry_at_ms: Option<u64>,+ pub trouble: Option<Trouble>,+ /// The machine has a connection (the host's reading).+ pub online: bool,+ /// Everything is ready.+ pub ready_ms: Option<u64>,+ /// When a person first wrote into the home (a message sent from Home, or one written in its own+ /// thread). Until then the home is invisible infrastructure: see [`hidden_spaces`].+ pub asked_ms: Option<u64>,+ pub messages: Vec<Message>,+}++impl Default for State {+ fn default() -> Self {+ Self {+ schema: SCHEMA,+ wanted: false,+ started_ms: None,+ onboarding_done_ms: None,+ runtime: StepRecord::default(),+ image: StepRecord::default(),+ home: StepRecord::default(),+ agent: StepRecord::default(),+ harness: "claude-code".into(),+ home_space_id: None,+ pending_id: None,+ attempt: 0,+ failures: 0,+ retry_at_ms: None,+ trouble: None,+ online: true,+ ready_ms: None,+ asked_ms: None,+ messages: Vec::new(),+ }+ }+}++impl State {+ fn rec(&self, s: Step) -> &StepRecord {+ match s {+ Step::Runtime => &self.runtime,+ Step::Image => &self.image,+ Step::Home => &self.home,+ Step::Agent => &self.agent,+ }+ }++ fn rec_mut(&mut self, s: Step) -> &mut StepRecord {+ match s {+ Step::Runtime => &mut self.runtime,+ Step::Image => &mut self.image,+ Step::Home => &mut self.home,+ Step::Agent => &mut self.agent,+ }+ }++ /// Every step is done (or not needed).+ pub fn is_ready(&self) -> bool {+ STEPS+ .iter()+ .all(|s| matches!(self.rec(*s).state, StepState::Done | StepState::Skipped))+ }++ /// The step in progress: the first that is not done.+ fn current(&self) -> Option<Step> {+ STEPS+ .iter()+ .copied()+ .find(|s| !matches!(self.rec(*s).state, StepState::Done | StepState::Skipped))+ }++ fn delivering(&self) -> Option<&Message> {+ self.messages+ .iter()+ .find(|m| m.state == MessageState::Delivering)+ }+}++/// What the host reports or the person does.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(+ tag = "type",+ rename_all = "camelCase",+ rename_all_fields = "camelCase"+)]+pub enum Action {+ /// Begin preparing (at first launch). Asking again changes nothing.+ Start {+ now_ms: u64,+ /// The coding app (`claude-code`); none keeps the last.+ #[serde(default)]+ harness: Option<String>,+ /// The id the home's row has while it is made.+ #[serde(default)]+ pending_id: Option<String>,+ },+ /// Onboarding ended (the clock for "onboarding finished to ready").+ OnboardingDone { now_ms: u64 },+ /// The create's progress: the daemon's phase word (`preparing`,+ /// `pulling`, `creating`, `booting`, `waiting_for_services`,+ /// `connecting`, `ready`), its detail line and bytes.+ Phase {+ now_ms: u64,+ phase: String,+ #[serde(default)]+ detail: String,+ #[serde(default)]+ done: Option<u64>,+ #[serde(default)]+ total: Option<u64>,+ #[serde(default)]+ per_second: Option<u64>,+ },+ /// The machine already has a Linux engine: the runtime step is not needed.+ RuntimeNotNeeded { now_ms: u64 },+ /// The home Space exists and is running.+ HomeReady { now_ms: u64, space_id: String },+ /// The coding app is in the home with its session open.+ AgentReady { now_ms: u64 },+ /// A step failed. `network` is a lost or missing connection.+ Failed {+ now_ms: u64,+ message: String,+ #[serde(default)]+ network: bool,+ },+ /// The machine went offline or came back.+ Online { now_ms: u64, online: bool },+ /// Time passed (the host calls it about once a second while waiting).+ Tick { now_ms: u64 },+ /// The person pressed Try again.+ Retry { now_ms: u64 },+ /// The app started again with this record: whatever was in flight is+ /// looked at again.+ Resume { now_ms: u64 },+ /// The home Space is gone (removed, or never made): start that part over.+ HomeGone { now_ms: u64 },+ /// The person sent a message.+ Send {+ now_ms: u64,+ id: String,+ text: String,+ #[serde(default)]+ agent: String,+ #[serde(default)]+ model: Option<String>,+ #[serde(default)]+ repo: Option<String>,+ },+ /// The host posted a claimed message.+ Delivered { now_ms: u64, id: String },+ /// Posting a claimed message failed.+ DeliveryFailed { now_ms: u64, id: String },+ /// The answer to [`Effect::VerifyDelivery`]: the message is (or is not)+ /// already in the Space's thread.+ ThreadHas {+ now_ms: u64,+ id: String,+ found: bool,+ },+ /// The agent's first words in answer to a message.+ FirstToken { now_ms: u64, id: String },+ /// A person wrote into the home's own thread (not through the box on Home).+ Asked { now_ms: u64 },+}++/// What the host does next.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(+ tag = "type",+ rename_all = "camelCase",+ rename_all_fields = "camelCase"+)]+pub enum Effect {+ /// Make (or find, or carry on making) the home Space. It is safe to+ /// ask while one is being made: the host follows that one.+ Create,+ /// Put the coding app in the home and open its session.+ AttachAgent,+ /// Post this claimed message to the home's thread, then answer+ /// [`Action::Delivered`] (or [`Action::DeliveryFailed`]).+ Deliver { id: String },+ /// Look for this message in the thread and answer [`Action::ThreadHas`].+ VerifyDelivery { id: String },+ /// Call [`Action::Tick`] at this time.+ WakeAt { at_ms: u64 },+}++/// A step and what the host does.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Reduced {+ pub state: State,+ pub effects: Vec<Effect>,+}++fn backoff(attempt: u32) -> u64 {+ let shift = attempt.saturating_sub(1).min(16);+ (RETRY_FIRST_MS << shift).min(RETRY_MAX_MS)+}++/// A step ends. The runtime and the image that moved no bytes were already+/// there: the page says so (skipped) rather than claiming a download.+fn finish(s: &mut State, step: Step, now: u64) {+ let downloads = matches!(step, Step::Runtime | Step::Image);+ let rec = s.rec_mut(step);+ if !matches!(rec.state, StepState::Done | StepState::Skipped) {+ rec.state = if downloads && rec.total == 0 {+ StepState::Skipped+ } else {+ StepState::Done+ };+ rec.finished_ms = Some(now);+ rec.started_ms.get_or_insert(now);+ rec.per_second = None;+ }+}++/// Marks `step` running and every step before it done.+fn enter(s: &mut State, step: Step, now: u64) {+ for earlier in STEPS.iter().copied().filter(|e| e.rank() < step.rank()) {+ finish(s, earlier, now);+ }+ let r = s.rec_mut(step);+ if matches!(+ r.state,+ StepState::Pending | StepState::Waiting | StepState::Failed+ ) {+ r.state = StepState::Running;+ r.started_ms.get_or_insert(now);+ }+}++/// The step a daemon phase belongs to.+fn step_of(phase: &str, detail: &str) -> Option<Step> {+ match phase {+ "preparing" => {+ let d = detail.to_ascii_lowercase();+ if d.contains("runtime") {+ Some(Step::Runtime)+ } else {+ None+ }+ }+ "pulling" => Some(Step::Image),+ "creating" | "booting" | "waiting_for_services" | "connecting" => Some(Step::Home),+ _ => None,+ }+}++fn claim_next(s: &mut State, now: u64, effects: &mut Vec<Effect>) {+ if !s.is_ready() || s.delivering().is_some() || s.home_space_id.is_none() {+ return;+ }+ if let Some(m) = s+ .messages+ .iter_mut()+ .find(|m| m.state == MessageState::Queued)+ {+ m.state = MessageState::Delivering;+ m.claimed_ms = Some(now);+ effects.push(Effect::Deliver { id: m.id.clone() });+ }+}++fn mark_ready_if_done(s: &mut State, now: u64) {+ if s.is_ready() && s.ready_ms.is_none() {+ s.ready_ms = Some(now);+ s.trouble = None;+ s.retry_at_ms = None;+ s.attempt = 0;+ s.failures = 0;+ }+}++/// The failing step: the one running, else the first not done.+fn failing(s: &State) -> Step {+ STEPS+ .iter()+ .copied()+ .find(|st| {+ matches!(+ s.rec(*st).state,+ StepState::Running | StepState::Waiting | StepState::Failed+ )+ })+ .or_else(|| s.current())+ .unwrap_or(Step::Home)+}++/// One action. Pure: the same state and action give the same answer.+pub fn reduce(state: &State, action: &Action) -> Reduced {+ let mut s = state.clone();+ if s.schema != SCHEMA {+ s = State::default();+ }+ let mut fx: Vec<Effect> = Vec::new();+ match action {+ Action::Start {+ now_ms,+ harness,+ pending_id,+ } => {+ if let Some(h) = harness.as_ref().filter(|h| !h.is_empty())+ && !s.wanted+ {+ s.harness = h.clone();+ }+ if !s.wanted {+ s.wanted = true;+ s.started_ms = Some(*now_ms);+ s.pending_id = pending_id.clone().or(s.pending_id.take());+ s.attempt = 0;+ enter(&mut s, Step::Runtime, *now_ms);+ fx.push(Effect::Create);+ }+ }+ Action::OnboardingDone { now_ms } => {+ s.onboarding_done_ms.get_or_insert(*now_ms);+ }+ Action::Phase {+ now_ms,+ phase,+ detail,+ done,+ total,+ per_second,+ } => {+ if phase == "ready" {+ // The create is over; HomeReady says so with the Space's id.+ } else if let Some(step) = step_of(phase, detail)+ .filter(|st| !matches!(s.rec(*st).state, StepState::Done | StepState::Skipped))+ {+ // Progress after a pause is the end of the pause. A report+ // of a step that is done is late and changes nothing.+ s.trouble = None;+ s.retry_at_ms = None;+ enter(&mut s, step, *now_ms);+ let r = s.rec_mut(step);+ r.state = StepState::Running;+ if let Some(d) = done {+ r.done = *d;+ }+ if let Some(t) = total.filter(|t| *t > 0) {+ r.total = t;+ }+ r.per_second = *per_second;+ }+ }+ Action::RuntimeNotNeeded { now_ms } => {+ if !matches!(s.runtime.state, StepState::Done | StepState::Skipped) {+ s.runtime.state = StepState::Skipped;+ s.runtime.finished_ms = Some(*now_ms);+ }+ }+ Action::HomeReady { now_ms, space_id } => {+ s.home_space_id = Some(space_id.clone());+ s.pending_id = None;+ s.trouble = None;+ s.retry_at_ms = None;+ for st in [Step::Runtime, Step::Image, Step::Home] {+ finish(&mut s, st, *now_ms);+ }+ if s.agent.state != StepState::Done {+ enter(&mut s, Step::Agent, *now_ms);+ fx.push(Effect::AttachAgent);+ }+ }+ Action::AgentReady { now_ms } => {+ for st in STEPS {+ finish(&mut s, st, *now_ms);+ }+ mark_ready_if_done(&mut s, *now_ms);+ claim_next(&mut s, *now_ms, &mut fx);+ }+ Action::Failed {+ now_ms,+ message,+ network,+ } => {+ let step = failing(&s);+ if *network || !s.online {+ s.attempt = s.attempt.saturating_add(1);+ s.rec_mut(step).state = StepState::Waiting;+ s.rec_mut(step).per_second = None;+ s.trouble = Some(Trouble {+ network: true,+ message: message.clone(),+ });+ if s.online {+ let at = now_ms + backoff(s.attempt);+ s.retry_at_ms = Some(at);+ fx.push(Effect::WakeAt { at_ms: at });+ } else {+ // Offline: nothing to retry until the connection is back.+ s.retry_at_ms = None;+ }+ } else {+ s.failures += 1;+ s.trouble = Some(Trouble {+ network: false,+ message: message.clone(),+ });+ if s.failures < OTHER_ATTEMPTS {+ s.rec_mut(step).state = StepState::Waiting;+ let at = now_ms + backoff(s.failures);+ s.retry_at_ms = Some(at);+ fx.push(Effect::WakeAt { at_ms: at });+ } else {+ s.rec_mut(step).state = StepState::Failed;+ s.retry_at_ms = None;+ }+ }+ }+ Action::Online { online, .. } => {+ let was = s.online;+ s.online = *online;+ if !online {+ // The retry timer is moot; the step says it is waiting.+ if let Some(step) = s.current().filter(|_| s.wanted && !s.is_ready())+ && s.rec(step).state == StepState::Running+ {+ s.rec_mut(step).state = StepState::Waiting;+ }+ if s.wanted && !s.is_ready() {+ s.trouble.get_or_insert(Trouble {+ network: true,+ message: String::new(),+ });+ }+ s.retry_at_ms = None;+ } else if !was && s.wanted && !s.is_ready() {+ let waiting = matches!(&s.trouble, Some(t) if t.network)+ || STEPS+ .iter()+ .any(|st| s.rec(*st).state == StepState::Waiting);+ if waiting {+ s.retry_at_ms = None;+ s.trouble = None;+ s.attempt = s.attempt.saturating_add(1);+ let step = failing(&s);+ s.rec_mut(step).state = StepState::Running;+ fx.push(Effect::Create);+ }+ }+ }+ Action::Tick { now_ms } => {+ if s.online+ && s.wanted+ && !s.is_ready()+ && s.retry_at_ms.is_some_and(|at| at <= *now_ms)+ {+ s.retry_at_ms = None;+ s.trouble = None;+ let step = failing(&s);+ s.rec_mut(step).state = StepState::Running;+ fx.push(Effect::Create);+ }+ // A message whose post failed waits a little, then goes again.+ if s.delivering().is_none() {+ claim_next(&mut s, *now_ms, &mut fx);+ }+ }+ Action::Retry { now_ms } => {+ if s.wanted && !s.is_ready() {+ s.failures = 0;+ s.attempt = 0;+ s.trouble = None;+ s.retry_at_ms = None;+ let step = failing(&s);+ s.rec_mut(step).state = StepState::Pending;+ enter(&mut s, step, *now_ms);+ fx.push(Effect::Create);+ }+ }+ Action::Resume { now_ms } => {+ if s.wanted && !s.is_ready() {+ // Whatever was running was interrupted: it runs again, from+ // where the host finds it (the Space, the downloaded bytes).+ s.trouble = None;+ s.retry_at_ms = None;+ let step = failing(&s);+ s.rec_mut(step).state = StepState::Pending;+ s.rec_mut(step).per_second = None;+ enter(&mut s, step, *now_ms);+ s.attempt = 0;+ fx.push(Effect::Create);+ } else if s.wanted && s.agent.state == StepState::Done {+ // Ready last time: the host checks the Space is still there+ // with HomeGone, otherwise nothing runs.+ }+ if let Some(m) = s.delivering() {+ fx.push(Effect::VerifyDelivery { id: m.id.clone() });+ }+ }+ Action::HomeGone { now_ms } => {+ if s.wanted {+ s.home_space_id = None;+ s.pending_id = None;+ s.ready_ms = None;+ s.home = StepRecord::default();+ s.agent = StepRecord::default();+ // The image is probably still cached: the create finds out.+ s.attempt = 0;+ s.failures = 0;+ s.trouble = None;+ enter(&mut s, Step::Home, *now_ms);+ // Delivering messages may be lost with the Space: back in the queue.+ for m in &mut s.messages {+ if m.state == MessageState::Delivering {+ m.state = MessageState::Queued;+ }+ }+ fx.push(Effect::Create);+ }+ }+ Action::Send {+ now_ms,+ id,+ text,+ agent,+ model,+ repo,+ } => {+ let text = text.trim();+ if !text.is_empty() && !s.messages.iter().any(|m| &m.id == id) {+ s.asked_ms.get_or_insert(*now_ms);+ s.messages.push(Message {+ id: id.clone(),+ text: text.to_string(),+ agent: agent.clone(),+ model: model.clone(),+ repo: repo.clone(),+ state: MessageState::Queued,+ attempts: 0,+ sent_ms: *now_ms,+ claimed_ms: None,+ delivered_ms: None,+ first_token_ms: None,+ });+ // A message before anything started is what starts it.+ if !s.wanted {+ s.wanted = true;+ s.started_ms = Some(*now_ms);+ s.attempt = 0;+ enter(&mut s, Step::Runtime, *now_ms);+ fx.push(Effect::Create);+ }+ claim_next(&mut s, *now_ms, &mut fx);+ }+ }+ Action::Delivered { now_ms, id } => {+ if let Some(m) = s+ .messages+ .iter_mut()+ .find(|m| &m.id == id && m.state != MessageState::Delivered)+ {+ m.state = MessageState::Delivered;+ m.delivered_ms = Some(*now_ms);+ }+ claim_next(&mut s, *now_ms, &mut fx);+ }+ Action::DeliveryFailed { now_ms, id } => {+ let mut wake = None;+ if let Some(m) = s+ .messages+ .iter_mut()+ .find(|m| &m.id == id && m.state == MessageState::Delivering)+ {+ m.state = MessageState::Queued;+ m.attempts += 1;+ if m.attempts < DELIVERY_ATTEMPTS {+ wake = Some(now_ms + backoff(m.attempts));+ }+ }+ if let Some(at) = wake {+ fx.push(Effect::WakeAt { at_ms: at });+ }+ }+ Action::ThreadHas { now_ms, id, found } => {+ if let Some(m) = s+ .messages+ .iter_mut()+ .find(|m| &m.id == id && m.state == MessageState::Delivering)+ {+ if *found {+ m.state = MessageState::Delivered;+ m.delivered_ms = Some(*now_ms);+ } else {+ m.state = MessageState::Queued;+ }+ }+ claim_next(&mut s, *now_ms, &mut fx);+ }+ Action::Asked { now_ms } => {+ s.asked_ms.get_or_insert(*now_ms);+ }+ Action::FirstToken { now_ms, id } => {+ if let Some(m) = s.messages.iter_mut().find(|m| &m.id == id) {+ m.first_token_ms.get_or_insert(*now_ms);+ }+ }+ }+ Reduced {+ state: s,+ effects: fx,+ }+}++// ---------------------------------------------------------------------+// The page+// ---------------------------------------------------------------------++/// A step in the list.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct StepView {+ pub id: String,+ pub label: String,+ /// `pending`, `running`, `waiting`, `failed`, `done`, `skipped`.+ pub state: String,+ /// Muted text beside the label, while it has something to say ("120 MB of 440 MB, about 1 minute left").+ pub detail: Option<String>,+ /// 0 to 1 for the step that downloads, when its size is known: the one thin bar of the block, drawn+ /// under the current step only.+ pub fraction: Option<f64>,+}++/// A queued message, as the thread shows it.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct QueuedView {+ pub id: String,+ pub text: String,+ /// "Sends when your agent is ready", "Sending", "Sent".+ pub note: String,+}++/// What the page draws.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct View {+ /// `idle`, `preparing`, `waiting`, `failed` or `ready`.+ pub phase: String,+ /// The heading.+ pub title: String,+ /// A line for what the steps cannot say: the connection is lost, preparing stopped, the+ /// home is ready. None while preparing (the current step's row says it).+ pub line: Option<String>,+ pub steps: Vec<StepView>,+ pub queued: Vec<QueuedView>,+ /// Under the message box while it is not ready.+ pub composer_hint: Option<String>,+ /// Try again, only after a failure that will not clear by itself.+ pub action: Option<ActionView>,+}++/// A button.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ActionView {+ pub id: String,+ pub label: String,+}++/// "120 MB", "1.4 GB": binary units named MB and GB, as the apps size downloads.+pub fn bytes(n: u64) -> String {+ const MIB: f64 = 1_048_576.0;+ const GIB: f64 = 1_073_741_824.0;+ let f = n as f64;+ if f >= GIB {+ format!("{:.1} GB", f / GIB)+ } else if f >= MIB {+ if f / MIB < 10.0 {+ format!("{:.1} MB", f / MIB)+ } else {+ format!("{:.0} MB", f / MIB)+ }+ } else if n >= 1024 {+ format!("{:.0} KB", f / 1024.0)+ } else if n == 0 {+ "0 MB".to_string()+ } else {+ format!("{n} bytes")+ }+}++fn time_left(secs: u64) -> String {+ if secs < 45 {+ "less than a minute left".into()+ } else if secs < 90 {+ "about 1 minute left".into()+ } else if secs < 3600 {+ format!("about {} minutes left", (secs + 30) / 60)+ } else {+ format!("about {} hours left", (secs + 1800) / 3600)+ }+}++fn app_name(harness: &str) -> &'static str {+ match harness {+ "claude-code" => "Claude Code",+ "codex" => "Codex",+ "hermes" => "Hermes",+ "pi" => "Pi",+ "cursor" => "Cursor",+ _ => "your coding agent",+ }+}++fn transfer_line(r: &StepRecord) -> Option<String> {+ if r.total == 0 {+ return None;+ }+ let mut out = format!("{} of {}", bytes(r.done.min(r.total)), bytes(r.total));+ if let Some(rate) = r.per_second.filter(|r| *r > 0) {+ let left = r.total.saturating_sub(r.done) / rate;+ out.push_str(", ");+ out.push_str(&time_left(left));+ }+ Some(out)+}++fn step_detail(s: &State, step: Step) -> Option<String> {+ let r = s.rec(step);+ match r.state {+ StepState::Running => match step {+ Step::Runtime | Step::Image => transfer_line(r).or_else(|| {+ Some(+ if step == Step::Runtime {+ "Setting up"+ } else {+ "Getting the image"+ }+ .into(),+ )+ }),+ Step::Home => Some("Starting".into()),+ Step::Agent => Some("Getting ready".into()),+ },+ StepState::Waiting => Some(if s.trouble.as_ref().is_some_and(|t| t.network) {+ "Waiting for the connection".into()+ } else {+ "Trying again".into()+ }),+ StepState::Failed => Some("Stopped".into()),+ StepState::Skipped => match step {+ Step::Runtime => Some("Already set up".into()),+ Step::Image => Some("Already downloaded".into()),+ _ => None,+ },+ _ => None,+ }+}++fn state_word(st: StepState) -> &'static str {+ match st {+ StepState::Pending => "pending",+ StepState::Running => "running",+ StepState::Waiting => "waiting",+ StepState::Failed => "failed",+ StepState::Done => "done",+ StepState::Skipped => "skipped",+ }+}++fn note_of(m: &Message) -> &'static str {+ match m.state {+ MessageState::Queued => "Sends when your agent is ready",+ MessageState::Delivering => "Sending",+ MessageState::Delivered => "Sent",+ }+}++/// The page for a state. Delivered messages are the thread's, not shown here.+pub fn view(s: &State) -> View {+ let app = app_name(&s.harness);+ let current = s.current();+ let steps: Vec<StepView> = STEPS+ .iter()+ .map(|st| {+ let r = s.rec(*st);+ StepView {+ id: st.id().into(),+ label: match st {+ Step::Agent => app.to_string(),+ _ => st.label().to_string(),+ },+ state: state_word(r.state).into(),+ detail: step_detail(s, *st),+ // One thin bar, under the current step that is downloading.+ fraction: (Some(*st) == current && r.state == StepState::Running && r.total > 0)+ .then(|| (r.done as f64 / r.total as f64).clamp(0.0, 1.0)),+ }+ })+ .collect();+ let queued: Vec<QueuedView> = s+ .messages+ .iter()+ .filter(|m| m.state != MessageState::Delivered)+ .map(|m| QueuedView {+ id: m.id.clone(),+ text: m.text.clone(),+ note: note_of(m).into(),+ })+ .collect();+ let failed = STEPS.iter().any(|st| s.rec(*st).state == StepState::Failed);+ let waiting_net = s.trouble.as_ref().is_some_and(|t| t.network);++ let (phase, title, line): (&str, String, Option<String>) = if !s.wanted {+ ("idle", "Getting your agent ready".into(), None)+ } else if s.is_ready() {+ (+ "ready",+ format!("{app} is ready"),+ Some("Your home Space is running".into()),+ )+ } else if failed {+ let why = s+ .trouble+ .as_ref()+ .map(|t| t.message.trim())+ .filter(|m| !m.is_empty())+ .map(|m| format!(": {m}"))+ .unwrap_or_default();+ (+ "failed",+ "Getting your agent ready stopped".into(),+ Some(format!("Preparing stopped{why}")),+ )+ } else if !s.online || waiting_net {+ let line = if !s.online {+ "No internet connection. Preparing carries on when you are back online".to_string()+ } else {+ "The connection dropped. Trying again, nothing downloaded is lost".to_string()+ };+ ("waiting", "Getting your agent ready".into(), Some(line))+ } else {+ ("preparing", "Getting your agent ready".into(), None)+ };++ let composer_hint = match phase {+ "ready" | "idle" => None,+ _ => Some("Your message sends as soon as your agent is ready".to_string()),+ };+ let action = (phase == "failed").then(|| ActionView {+ id: "retry".into(),+ label: "Try again".into(),+ });+ View {+ phase: phase.into(),+ title,+ line,+ steps,+ queued,+ composer_hint,+ action,+ }+}++// ---------------------------------------------------------------------+// What the lists do not show+// ---------------------------------------------------------------------++/// The Spaces no list shows: the home that warms in the background for Home's prompt box, until a person+/// has written into it. Before that it is invisible infrastructure: not on the Spaces list, in the sidebar,+/// the machine lists, the palette or the Where menu; its own page (reached from Home's preparing line) and+/// that line still show it, and it still counts toward the budget and usage, which are the host's numbers.+///+/// The rule, once, for every app:+/// * it is the home this record prepares (the Space once made, and the row it has while it is made, a+/// failed one too: the error shows on Home, not in a list);+/// * it stops being hidden when a person writes into it: a message sent from Home counts at once, even+/// while it is only queued (the message belongs to that Space and its page says it sends when the agent+/// is ready), and so does one written in the home's own thread ([`Action::Asked`]);+/// * the record is kept across a quit, so a relaunch with a warm home and no message still hides it;+/// * a home this record did not prepare (made before, or by another path) is never hidden.+pub fn hidden_spaces(s: &State) -> Vec<String> {+ if !s.wanted || s.asked_ms.is_some() {+ return Vec::new();+ }+ s.home_space_id+ .iter()+ .chain(s.pending_id.iter())+ .cloned()+ .collect()+}++/// `ids` without the hidden Spaces, in their order: what a list shows.+pub fn listed(s: &State, ids: &[String]) -> Vec<String> {+ let hidden = hidden_spaces(s);+ ids.iter()+ .filter(|i| !hidden.contains(i))+ .cloned()+ .collect()+}++// ---------------------------------------------------------------------+// The numbers+// ---------------------------------------------------------------------++/// How long each part took, in milliseconds (none: not reached). Each is+/// what it says and nothing more: preparing time is not a message's latency.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Metrics {+ pub runtime_ms: Option<u64>,+ pub image_ms: Option<u64>,+ pub home_ms: Option<u64>,+ pub agent_ms: Option<u64>,+ /// From the start of preparing to everything ready.+ pub prepare_ms: Option<u64>,+ /// From the end of onboarding to everything ready: zero when it was+ /// ready before onboarding ended.+ pub onboarding_to_ready_ms: Option<u64>,+ /// Per message: send to the agent session (the post reached the thread),+ /// and send to the agent's first words.+ pub messages: Vec<MessageMetrics>,+}++/// One message's numbers.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MessageMetrics {+ pub id: String,+ pub send_to_delivered_ms: Option<u64>,+ pub send_to_first_token_ms: Option<u64>,+}++fn span(r: &StepRecord) -> Option<u64> {+ Some(r.finished_ms?.saturating_sub(r.started_ms?))+}++/// The numbers of a state.+pub fn metrics(s: &State) -> Metrics {+ Metrics {+ runtime_ms: span(&s.runtime),+ image_ms: span(&s.image),+ home_ms: span(&s.home),+ agent_ms: span(&s.agent),+ prepare_ms: s+ .started_ms+ .zip(s.ready_ms)+ .map(|(a, b)| b.saturating_sub(a)),+ onboarding_to_ready_ms: s+ .onboarding_done_ms+ .zip(s.ready_ms)+ .map(|(a, b)| b.saturating_sub(a)),+ messages: s+ .messages+ .iter()+ .map(|m| MessageMetrics {+ id: m.id.clone(),+ send_to_delivered_ms: m.delivered_ms.map(|d| d.saturating_sub(m.sent_ms)),+ send_to_first_token_ms: m.first_token_ms.map(|d| d.saturating_sub(m.sent_ms)),+ })+ .collect(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn go(s: &State, a: Action) -> Reduced {+ reduce(s, &a)+ }++ fn start() -> State {+ go(+ &State::default(),+ Action::Start {+ now_ms: 1_000,+ harness: Some("claude-code".into()),+ pending_id: Some("pending-1".into()),+ },+ )+ .state+ }++ fn ready() -> State {+ let s = start();+ let s = go(+ &s,+ Action::HomeReady {+ now_ms: 9_000,+ space_id: "local:home-1".into(),+ },+ )+ .state;+ go(&s, Action::AgentReady { now_ms: 10_000 }).state+ }++ #[test]+ fn start_begins_the_runtime_once_and_creates() {+ let r = go(+ &State::default(),+ Action::Start {+ now_ms: 5,+ harness: None,+ pending_id: None,+ },+ );+ assert_eq!(r.effects, vec![Effect::Create]);+ assert_eq!(r.state.runtime.state, StepState::Running);+ assert_eq!(r.state.started_ms, Some(5));+ // Asking again changes nothing and starts nothing.+ let again = go(+ &r.state,+ Action::Start {+ now_ms: 99,+ harness: Some("codex".into()),+ pending_id: None,+ },+ );+ assert_eq!(again.state, r.state);+ assert!(again.effects.is_empty());+ }++ #[test]+ fn phases_walk_the_steps_and_finish_the_earlier_ones() {+ let s = start();+ let s = go(+ &s,+ Action::Phase {+ now_ms: 2_000,+ phase: "preparing".into(),+ detail: "Setting up the Linux runtime".into(),+ done: Some(100),+ total: Some(400),+ per_second: Some(10),+ },+ )+ .state;+ assert_eq!(s.runtime.state, StepState::Running);+ assert_eq!((s.runtime.done, s.runtime.total), (100, 400));+ let s = go(+ &s,+ Action::Phase {+ now_ms: 3_000,+ phase: "pulling".into(),+ detail: "ghcr.io/trycua/linux:24.04-slim".into(),+ done: Some(1),+ total: Some(300),+ per_second: None,+ },+ )+ .state;+ assert_eq!(s.runtime.state, StepState::Done);+ assert_eq!(s.image.state, StepState::Running);+ let s = go(+ &s,+ Action::Phase {+ now_ms: 4_000,+ phase: "booting".into(),+ detail: String::new(),+ done: None,+ total: None,+ per_second: None,+ },+ )+ .state;+ assert_eq!(s.image.state, StepState::Done);+ assert_eq!(s.home.state, StepState::Running);+ // A later report of an earlier phase does not move a step backwards.+ let s = go(+ &s,+ Action::Phase {+ now_ms: 4_500,+ phase: "pulling".into(),+ detail: String::new(),+ done: Some(5),+ total: Some(300),+ per_second: None,+ },+ )+ .state;+ assert_eq!(s.image.state, StepState::Done);+ assert_eq!(s.home.state, StepState::Running);+ }++ #[test]+ fn lost_connection_waits_with_backoff_and_resumes_when_online() {+ let s = start();+ let r = go(+ &s,+ Action::Failed {+ now_ms: 10_000,+ message: "connection reset".into(),+ network: true,+ },+ );+ assert_eq!(r.state.runtime.state, StepState::Waiting);+ assert_eq!(r.effects, vec![Effect::WakeAt { at_ms: 12_000 }]);+ // Too early: nothing.+ assert!(+ go(&r.state, Action::Tick { now_ms: 11_000 })+ .effects+ .is_empty()+ );+ // On time: create again (the host resumes the transfer).+ let t = go(&r.state, Action::Tick { now_ms: 12_000 });+ assert_eq!(t.effects, vec![Effect::Create]);+ assert_eq!(t.state.runtime.state, StepState::Running);+ // Failing again waits longer, up to the cap.+ let mut s = t.state;+ let mut last = 0;+ for i in 0..12 {+ let r = go(+ &s,+ Action::Failed {+ now_ms: 100_000 + i,+ message: "x".into(),+ network: true,+ },+ );+ let Effect::WakeAt { at_ms } = r.effects[0] else {+ panic!()+ };+ last = at_ms - (100_000 + i);+ s = go(&r.state, Action::Tick { now_ms: at_ms }).state;+ }+ assert_eq!(last, RETRY_MAX_MS);+ // Network trouble never ends in Failed.+ assert_ne!(s.runtime.state, StepState::Failed);+ }++ #[test]+ fn offline_waits_without_a_timer_and_resumes_on_online() {+ let s = start();+ let off = go(+ &s,+ Action::Online {+ now_ms: 2_000,+ online: false,+ },+ );+ assert_eq!(off.state.runtime.state, StepState::Waiting);+ assert!(off.effects.is_empty());+ let v = view(&off.state);+ assert_eq!(v.phase, "waiting");+ assert!(+ v.line+ .as_deref()+ .unwrap()+ .starts_with("No internet connection")+ );+ // A failure while offline sets no timer either.+ let f = go(+ &off.state,+ Action::Failed {+ now_ms: 2_500,+ message: "dns".into(),+ network: true,+ },+ );+ assert_eq!(f.state.retry_at_ms, None);+ assert!(f.effects.is_empty());+ let on = go(+ &f.state,+ Action::Online {+ now_ms: 9_000,+ online: true,+ },+ );+ assert_eq!(on.effects, vec![Effect::Create]);+ assert_eq!(on.state.runtime.state, StepState::Running);+ assert_eq!(view(&on.state).phase, "preparing");+ }++ #[test]+ fn other_failures_retry_once_then_offer_try_again() {+ let s = start();+ let r = go(+ &s,+ Action::Failed {+ now_ms: 1,+ message: "the disk is full".into(),+ network: false,+ },+ );+ assert_eq!(r.state.runtime.state, StepState::Waiting);+ let t = go(&r.state, Action::Tick { now_ms: 5_000 });+ assert_eq!(t.effects, vec![Effect::Create]);+ let r2 = go(+ &t.state,+ Action::Failed {+ now_ms: 6_000,+ message: "the disk is full".into(),+ network: false,+ },+ );+ assert_eq!(r2.state.runtime.state, StepState::Failed);+ let v = view(&r2.state);+ assert_eq!(v.phase, "failed");+ assert_eq!(+ v.line.as_deref(),+ Some("Preparing stopped: the disk is full")+ );+ assert_eq!(v.action.as_ref().unwrap().label, "Try again");+ // Try again runs it again from the failed step.+ let again = go(&r2.state, Action::Retry { now_ms: 7_000 });+ assert_eq!(again.effects, vec![Effect::Create]);+ assert_eq!(again.state.runtime.state, StepState::Running);+ assert!(view(&again.state).action.is_none());+ }++ #[test]+ fn quit_mid_prepare_resumes_from_the_failing_step_not_the_start() {+ let mut s = start();+ s = go(+ &s,+ Action::Phase {+ now_ms: 2_000,+ phase: "pulling".into(),+ detail: String::new(),+ done: Some(50),+ total: Some(300),+ per_second: Some(5),+ },+ )+ .state;+ // Saved, the app quit, started again.+ let saved = serde_json::to_string(&s).unwrap();+ let loaded: State = serde_json::from_str(&saved).unwrap();+ let r = go(&loaded, Action::Resume { now_ms: 50_000 });+ assert_eq!(r.effects, vec![Effect::Create]);+ assert_eq!(+ r.state.runtime.state,+ StepState::Skipped,+ "a runtime that moved no bytes was already there"+ );+ assert_eq!(r.state.image.state, StepState::Running);+ assert_eq!(r.state.started_ms, Some(1_000), "the clock is not reset");+ // A ready state does nothing on resume.+ let ok = go(&ready(), Action::Resume { now_ms: 60_000 });+ assert!(ok.effects.is_empty());+ }++ #[test]+ fn a_message_queues_until_ready_then_is_delivered_once() {+ let s = start();+ let sent = go(+ &s,+ Action::Send {+ now_ms: 2_000,+ id: "m1".into(),+ text: " fix the failing tests ".into(),+ agent: "claude-code".into(),+ model: Some("claude-sonnet-5".into()),+ repo: None,+ },+ );+ assert!(sent.effects.is_empty(), "nothing is posted before ready");+ assert_eq!(sent.state.messages[0].text, "fix the failing tests");+ let v = view(&sent.state);+ assert_eq!(v.queued.len(), 1);+ assert_eq!(v.queued[0].note, "Sends when your agent is ready");+ assert!(v.composer_hint.is_some());+ // The same id again is the same message.+ let dup = go(+ &sent.state,+ Action::Send {+ now_ms: 2_100,+ id: "m1".into(),+ text: "fix the failing tests".into(),+ agent: "claude-code".into(),+ model: None,+ repo: None,+ },+ );+ assert_eq!(dup.state.messages.len(), 1);+ // Ready: the first is claimed and delivered.+ let home = go(+ &dup.state,+ Action::HomeReady {+ now_ms: 8_000,+ space_id: "local:home".into(),+ },+ );+ assert_eq!(home.effects, vec![Effect::AttachAgent]);+ let agent = go(&home.state, Action::AgentReady { now_ms: 9_000 });+ assert_eq!(agent.effects, vec![Effect::Deliver { id: "m1".into() }]);+ assert_eq!(agent.state.messages[0].state, MessageState::Delivering);+ // Ticks and a second AgentReady do not claim it again.+ assert!(+ go(&agent.state, Action::Tick { now_ms: 9_500 })+ .effects+ .is_empty()+ );+ assert!(+ go(&agent.state, Action::AgentReady { now_ms: 9_600 })+ .effects+ .is_empty()+ );+ let done = go(+ &agent.state,+ Action::Delivered {+ now_ms: 9_700,+ id: "m1".into(),+ },+ );+ assert_eq!(done.state.messages[0].state, MessageState::Delivered);+ assert!(done.effects.is_empty());+ // Delivered twice is still one delivery.+ let twice = go(+ &done.state,+ Action::Delivered {+ now_ms: 9_900,+ id: "m1".into(),+ },+ );+ assert_eq!(twice.state.messages[0].delivered_ms, Some(9_700));+ assert!(view(&twice.state).queued.is_empty());+ }++ #[test]+ fn messages_go_one_at_a_time_in_order() {+ let mut s = ready();+ for (i, id) in ["a", "b", "c"].iter().enumerate() {+ s = go(+ &s,+ Action::Send {+ now_ms: 20_000 + i as u64,+ id: (*id).into(),+ text: format!("job {id}"),+ agent: "claude-code".into(),+ model: None,+ repo: None,+ },+ )+ .state;+ }+ assert_eq!(+ s.messages.iter().map(|m| m.state).collect::<Vec<_>>(),+ vec![+ MessageState::Delivering,+ MessageState::Queued,+ MessageState::Queued+ ],+ "ready: the first goes at once, the others wait their turn"+ );+ let r = go(+ &s,+ Action::Delivered {+ now_ms: 21_000,+ id: "a".into(),+ },+ );+ assert_eq!(r.effects, vec![Effect::Deliver { id: "b".into() }]);+ }++ #[test]+ fn quit_while_delivering_checks_the_thread_before_posting_again() {+ let mut s = ready();+ s = go(+ &s,+ Action::Send {+ now_ms: 20_000,+ id: "m1".into(),+ text: "hello".into(),+ agent: "claude-code".into(),+ model: None,+ repo: None,+ },+ )+ .state;+ assert_eq!(s.messages[0].state, MessageState::Delivering);+ let loaded: State = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();+ let r = go(&loaded, Action::Resume { now_ms: 90_000 });+ assert_eq!(r.effects, vec![Effect::VerifyDelivery { id: "m1".into() }]);+ // It was posted before the quit: delivered, not posted again.+ let found = go(+ &r.state,+ Action::ThreadHas {+ now_ms: 90_100,+ id: "m1".into(),+ found: true,+ },+ );+ assert_eq!(found.state.messages[0].state, MessageState::Delivered);+ assert!(found.effects.is_empty());+ // It was not: back to the queue and delivered now.+ let missing = go(+ &r.state,+ Action::ThreadHas {+ now_ms: 90_100,+ id: "m1".into(),+ found: false,+ },+ );+ assert_eq!(missing.effects, vec![Effect::Deliver { id: "m1".into() }]);+ }++ #[test]+ fn a_failed_post_goes_back_and_is_retried_with_a_wait() {+ let mut s = ready();+ s = go(+ &s,+ Action::Send {+ now_ms: 20_000,+ id: "m1".into(),+ text: "hello".into(),+ agent: "claude-code".into(),+ model: None,+ repo: None,+ },+ )+ .state;+ let f = go(+ &s,+ Action::DeliveryFailed {+ now_ms: 20_100,+ id: "m1".into(),+ },+ );+ assert_eq!(f.state.messages[0].state, MessageState::Queued);+ assert_eq!(f.state.messages[0].attempts, 1);+ assert_eq!(f.effects, vec![Effect::WakeAt { at_ms: 22_100 }]);+ let t = go(&f.state, Action::Tick { now_ms: 22_100 });+ assert_eq!(t.effects, vec![Effect::Deliver { id: "m1".into() }]);+ }++ #[test]+ fn a_removed_home_is_made_again_and_claimed_messages_are_not_lost() {+ let mut s = ready();+ s = go(+ &s,+ Action::Send {+ now_ms: 20_000,+ id: "m1".into(),+ text: "hello".into(),+ agent: "claude-code".into(),+ model: None,+ repo: None,+ },+ )+ .state;+ let r = go(&s, Action::HomeGone { now_ms: 30_000 });+ assert_eq!(r.effects, vec![Effect::Create]);+ assert_eq!(r.state.messages[0].state, MessageState::Queued);+ assert_eq!(r.state.home.state, StepState::Running);+ assert_eq!(r.state.runtime.state, StepState::Skipped, "kept as it was");+ assert_eq!(r.state.ready_ms, None);+ assert_eq!(view(&r.state).phase, "preparing");+ }++ #[test]+ fn steps_that_downloaded_are_done_and_steps_that_did_not_are_already_there() {+ let s = start();+ let s = go(+ &s,+ Action::Phase {+ now_ms: 2_000,+ phase: "preparing".into(),+ detail: "Setting up the Linux runtime".into(),+ done: Some(10),+ total: Some(400),+ per_second: None,+ },+ )+ .state;+ // The image never reported bytes (cached): the home's boot ends both.+ let s = go(+ &s,+ Action::Phase {+ now_ms: 3_000,+ phase: "booting".into(),+ detail: String::new(),+ done: None,+ total: None,+ per_second: None,+ },+ )+ .state;+ assert_eq!(s.runtime.state, StepState::Done);+ assert_eq!(s.image.state, StepState::Skipped);+ let v = view(&s);+ assert_eq!(v.steps[1].detail.as_deref(), Some("Already downloaded"));+ assert_eq!(v.steps[0].detail, None);+ }++ #[test]+ fn a_machine_with_its_own_engine_skips_the_runtime() {+ let s = start();+ let s = go(&s, Action::RuntimeNotNeeded { now_ms: 1_500 }).state;+ assert_eq!(s.runtime.state, StepState::Skipped);+ let v = view(&s);+ assert_eq!(v.steps[0].state, "skipped");+ // The next step runs; the skipped one is never marked done later.+ let s = go(+ &s,+ Action::Phase {+ now_ms: 2_000,+ phase: "pulling".into(),+ detail: String::new(),+ done: Some(1),+ total: Some(10),+ per_second: None,+ },+ )+ .state;+ assert_eq!(s.runtime.state, StepState::Skipped);+ assert_eq!(s.image.state, StepState::Running);+ }++ #[test]+ fn a_message_before_anything_started_starts_it() {+ let r = go(+ &State::default(),+ Action::Send {+ now_ms: 5,+ id: "m".into(),+ text: "go".into(),+ agent: String::new(),+ model: None,+ repo: None,+ },+ );+ assert!(r.state.wanted);+ assert_eq!(r.effects, vec![Effect::Create]);+ }++ #[test]+ fn metrics_say_what_each_span_is() {+ let mut s = start();+ s = go(&s, Action::OnboardingDone { now_ms: 6_000 }).state;+ s = go(+ &s,+ Action::Send {+ now_ms: 7_000,+ id: "m1".into(),+ text: "hi".into(),+ agent: "claude-code".into(),+ model: None,+ repo: None,+ },+ )+ .state;+ s = go(+ &s,+ Action::Phase {+ now_ms: 2_000,+ phase: "pulling".into(),+ detail: String::new(),+ done: None,+ total: None,+ per_second: None,+ },+ )+ .state;+ s = go(+ &s,+ Action::HomeReady {+ now_ms: 9_000,+ space_id: "h".into(),+ },+ )+ .state;+ s = go(&s, Action::AgentReady { now_ms: 10_000 }).state;+ s = go(+ &s,+ Action::Delivered {+ now_ms: 10_050,+ id: "m1".into(),+ },+ )+ .state;+ s = go(+ &s,+ Action::FirstToken {+ now_ms: 11_200,+ id: "m1".into(),+ },+ )+ .state;+ let m = metrics(&s);+ assert_eq!(m.prepare_ms, Some(9_000));+ assert_eq!(m.onboarding_to_ready_ms, Some(4_000));+ assert_eq!(m.messages[0].send_to_delivered_ms, Some(3_050));+ assert_eq!(m.messages[0].send_to_first_token_ms, Some(4_200));+ // Ready before onboarding ended: zero, never negative.+ let mut early = ready();+ early = go(&early, Action::OnboardingDone { now_ms: 99_000 }).state;+ assert_eq!(metrics(&early).onboarding_to_ready_ms, Some(0));+ }++ #[test]+ fn every_step_has_a_mark_and_only_the_current_one_a_bar() {+ let mut s = start();+ // Running with no size yet: a word, no bar.+ let v = view(&s);+ assert_eq!(v.steps[0].detail.as_deref(), Some("Setting up"));+ assert!(v.steps.iter().all(|x| x.fraction.is_none()));+ s = go(+ &s,+ Action::Phase {+ now_ms: 2_000,+ phase: "pulling".into(),+ detail: String::new(),+ done: Some(1 << 20),+ total: Some(300 << 20),+ per_second: None,+ },+ )+ .state;+ let v = view(&s);+ let bars: Vec<_> = v+ .steps+ .iter()+ .filter(|x| x.fraction.is_some())+ .map(|x| x.id.as_str())+ .collect();+ assert_eq!(bars, ["image"]);+ assert_eq!(+ v.steps[2].detail, None,+ "a waiting step is just the dot and the label"+ );+ assert_eq!(+ v.steps[0].detail.as_deref(),+ Some("Already set up"),+ "a done step is a check"+ );+ }++ #[test]+ fn a_state_of_another_schema_starts_over() {+ let mut old = start();+ old.schema = 0;+ let r = go(&old, Action::Tick { now_ms: 1 });+ assert_eq!(r.state, State::default());+ }++ #[test]+ fn the_words_have_no_middle_dots_and_the_honest_progress_line() {+ let s = start();+ let s = go(+ &s,+ Action::Phase {+ now_ms: 2_000,+ phase: "preparing".into(),+ detail: "Setting up the Linux runtime".into(),+ done: Some(120 << 20),+ total: Some(440 << 20),+ per_second: Some(5 << 20),+ },+ )+ .state;+ let v = view(&s);+ // One quiet block: no headline sentence repeating the row, the row says it, one thin bar.+ assert_eq!(v.line, None);+ assert_eq!(+ v.steps[0].detail.as_deref(),+ Some("120 MB of 440 MB, about 1 minute left")+ );+ assert!((v.steps[0].fraction.unwrap() - 120.0 / 440.0).abs() < 1e-9);+ assert!(+ v.steps[1..].iter().all(|x| x.fraction.is_none()),+ "a bar under the current step only"+ );+ let all = serde_json::to_string(&v).unwrap();+ assert!(!all.contains('\u{b7}'));+ for st in [+ view(&State::default()),+ view(&ready()),+ view(+ &go(+ &s,+ Action::Online {+ now_ms: 3,+ online: false,+ },+ )+ .state,+ ),+ ] {+ assert!(!serde_json::to_string(&st).unwrap().contains('\u{b7}'));+ }+ assert_eq!(view(&ready()).title, "Claude Code is ready");+ assert!(view(&ready()).composer_hint.is_none());+ }+}diff --git a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs b/libs/cua/crates/cua-spaces-app-core/src/wizard.rsindex cd00c825fd..24ce4525da 100644--- a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs@@ -4328,7 +4328,7 @@ pub fn first_space_offers(env: &WizardEnv, host_os: SpaceOs) -> Vec<FirstSpaceOf/// The wizard's own plan for `image_ref` on this machine with its defaults,/// and why it can't be created here (a system this machine can't run, no/// runtime, no room), or none. `None` when the catalog has no such image.-fn local_plan(+pub(crate) fn local_plan(env: &WizardEnv,host_os: SpaceOs,image_ref: &str,@@ -7121,4 +7121,390 @@ mod tests {assert_eq!(name_row(&v).as_deref(), Some("Chosen automatically"));assert_eq!(v.plan.name, None);}++ // ---- the example prompts, per host (`first_prompts`) -----------------------++ use crate::first_prompts::{self as fp, Cap, FALLBACK, FirstPrompts, LIBRARY};++ fn prompts_for(env: &WizardEnv, os: SpaceOs) -> FirstPrompts {+ fp::choose_for(env, os)+ }++ fn example_ids(p: &FirstPrompts) -> Vec<&str> {+ p.examples.iter().map(|e| e.id.as_str()).collect()+ }++ fn card_ids(p: &FirstPrompts) -> Vec<&str> {+ p.suggestions.iter().map(|s| s.id.as_str()).collect()+ }++ /// A PC (Windows or Linux) as the app sees it after its probes.+ fn pc(arch: &str, backends: &[&str]) -> WizardEnv {+ WizardEnv {+ local_backends: Some(backends.iter().map(|b| b.to_string()).collect()),+ host_arch: Some(arch.into()),+ storage: Some(LocalStorage {+ reserve_bytes: 5 * GIB,+ lume: None,+ qemu: Some(vol(200, "/")),+ container: Some(vol(200, "/")),+ pulled: vec![],+ linux_runtime_download_bytes: 0,+ }),+ ..env()+ }+ }++ /// Every host profile the choice is tested on, with the os it runs.+ fn profiles() -> Vec<(&'static str, WizardEnv, SpaceOs)> {+ let mut mac_none = probed_mac(200, "arm64");+ mac_none.local_backends = Some(vec![]);+ mac_none.storage = None;+ let mut no_macos_room = probed_mac(30, "arm64");+ no_macos_room.local_backends = Some(vec!["lume".into(), "managed".into()]);+ let mut mac_vm = probed_mac(200, "arm64");+ mac_vm.local_backends = Some(vec![+ "lume".into(),+ "managed".into(),+ "containerization".into(),+ ]);+ vec![+ (+ "mac arm64 with macOS",+ probed_mac(200, "arm64"),+ SpaceOs::Macos,+ ),+ ("mac arm64 with microVM", mac_vm, SpaceOs::Macos),+ (+ "mac arm64 without room for macOS",+ no_macos_room,+ SpaceOs::Macos,+ ),+ ("mac intel", probed_mac(200, "x86_64"), SpaceOs::Macos),+ (+ "windows with qemu",+ pc("amd64", &["qemu", "docker"]),+ SpaceOs::Windows,+ ),+ (+ "windows without qemu",+ pc("amd64", &["docker"]),+ SpaceOs::Windows,+ ),+ (+ "linux with kvm",+ pc("amd64", &["qemu", "docker", "firecracker"]),+ SpaceOs::Linux,+ ),+ (+ "linux without kvm",+ pc("amd64", &["docker"]),+ SpaceOs::Linux,+ ),+ ("linux arm64", pc("arm64", &["docker"]), SpaceOs::Linux),+ ("no runtime read yet", env(), SpaceOs::Macos),+ ("no runtime at all", mac_none, SpaceOs::Macos),+ ]+ }++ #[test]+ fn the_examples_per_host_profile() {+ let by = |name: &str| {+ let (_, e, os) = profiles().into_iter().find(|p| p.0 == name).unwrap();+ prompts_for(&e, os)+ };+ const REAL: [&str; 3] = [FALLBACK, "trip-weekend", "two-space-load"];+ let with = |extra: &[&str]| -> Vec<String> {+ REAL.iter()+ .chain(extra.iter())+ .map(|s| s.to_string())+ .collect()+ };+ let ids = |p: &FirstPrompts| {+ example_ids(p)+ .into_iter()+ .map(String::from)+ .collect::<Vec<_>>()+ };+ // A Mac that can make a macOS Space, image not downloaded: the fast Linux job leads; the two-system one is still reachable.+ let mac = by("mac arm64 with macOS");+ assert!(mac.caps.macos && !mac.caps.windows && !mac.caps.macos_cached);+ assert_eq!(ids(&mac), with(&["cross-os-prices-macos"]));+ assert_eq!(+ card_ids(&mac),+ ["tests-linux-macos", "bug-macos", "order-tracking"]+ );+ let slow = mac+ .examples+ .iter()+ .find(|x| x.id == "cross-os-prices-macos")+ .unwrap();+ assert!(slow.why.ends_with("The first run downloads an image."));+ assert!(!mac.examples[0].why.contains("downloads an image"));+ // The macOS image is already downloaded: the two-system job leads and says nothing of a download.+ let mut cached = probed_mac(20, "arm64");+ cached.storage.as_mut().unwrap().pulled = vec!["ghcr.io/trycua/macos:26".into()];+ let c = prompts_for(&cached, SpaceOs::Macos);+ assert!(c.caps.macos_cached);+ assert_eq!(example_ids(&c)[0], "cross-os-prices-macos");+ assert!(!c.examples[0].why.contains("downloads an image"));+ // A Windows image already pulled leads on a PC.+ let mut wc = pc("amd64", &["qemu", "docker"]);+ wc.storage.as_mut().unwrap().pulled = vec!["ghcr.io/trycua/windows:2022".into()];+ assert_eq!(+ example_ids(&prompts_for(&wc, SpaceOs::Windows))[0],+ "cross-os-prices-windows"+ );+ // With microVMs too: ten Spaces at once is on offer.+ let vm = by("mac arm64 with microVM");+ assert!(vm.caps.kvm);+ assert_eq!(+ ids(&vm),+ with(&["fan-out-pricing", "cross-os-prices-macos"])+ );+ // No room for the macOS image, or an Intel Mac: no macOS example or card.+ for name in ["mac arm64 without room for macOS", "mac intel"] {+ let p = by(name);+ assert!(!p.caps.macos, "{name}");+ assert_eq!(ids(&p), with(&[]), "{name}");+ assert_eq!(+ card_ids(&p),+ ["order-tracking", "server-ui-load", "untrusted-pr"],+ "{name}"+ );+ }+ // A Windows PC with QEMU: Linux and Windows jobs are on offer.+ let win = by("windows with qemu");+ assert!(win.caps.windows);+ assert_eq!(ids(&win), with(&["cross-os-prices-windows"]));+ assert_eq!(+ card_ids(&win),+ ["tests-linux-windows", "bug-windows", "order-tracking"]+ );+ let nowin = by("windows without qemu");+ assert!(!nowin.caps.windows);+ assert_eq!(ids(&nowin), with(&[]));+ // Linux with and without KVM.+ let kvm = by("linux with kvm");+ assert!(kvm.caps.kvm);+ assert_eq!(example_ids(&kvm)[0], FALLBACK);+ let nokvm = by("linux without kvm");+ assert!(!nokvm.caps.kvm && !nokvm.caps.macos);+ // Nothing read yet, or no runtime: the fallback leads, alone with the plain Linux jobs.+ for name in ["no runtime read yet", "no runtime at all"] {+ let p = by(name);+ assert_eq!(ids(&p), with(&[]), "{name}");+ assert!(!p.caps.macos && !p.caps.windows && !p.caps.kvm, "{name}");+ }+ }++ #[test]+ fn the_lede_names_only_a_system_this_host_can_run() {+ const WIN: &str = "Reproduce this bug on a fresh Windows Space";+ const MAC: &str = "Reproduce this bug on a fresh macOS Space";+ const LIN: &str = "Reproduce this bug on a fresh Linux Space";+ for (name, e, os) in profiles() {+ let p = prompts_for(&e, os);+ let want = if p.caps.windows {+ WIN+ } else if p.caps.macos {+ MAC+ } else {+ LIN+ };+ assert_eq!(p.lede, want, "{name}");+ // Never a system the host cannot make.+ assert!(!p.lede.contains("Windows") || p.caps.windows, "{name}");+ assert!(!p.lede.contains("macOS") || p.caps.macos, "{name}");+ }+ let lede = |n: &str| {+ let (_, e, os) = profiles().into_iter().find(|p| p.0 == n).unwrap();+ prompts_for(&e, os).lede+ };+ assert_eq!(lede("mac arm64 with macOS"), MAC);+ assert_eq!(lede("windows with qemu"), WIN);+ assert_eq!(lede("linux with kvm"), WIN);+ for n in [+ "mac intel",+ "mac arm64 without room for macOS",+ "linux without kvm",+ "windows without qemu",+ "no runtime read yet",+ ] {+ assert_eq!(lede(n), LIN, "{n}");+ }+ }++ #[test]+ fn every_host_always_has_the_fallback_and_never_a_job_it_cannot_do() {+ for (name, e, os) in profiles() {+ let p = prompts_for(&e, os);+ assert!(+ p.examples[0].id == FALLBACK || p.caps.macos_cached || p.caps.windows_cached,+ "{name}"+ );+ assert!(p.examples.iter().any(|x| x.id == FALLBACK), "{name}");+ assert!(p.suggestions.len() >= 3, "{name}");+ for x in p+ .examples+ .iter()+ .map(|x| (&x.id, &x.needs))+ .chain(p.suggestions.iter().map(|s| (&s.id, &s.needs)))+ {+ for c in x.1 {+ let ok = match c {+ Cap::MacosSpace => p.caps.macos,+ Cap::WindowsSpace => p.caps.windows,+ Cap::Kvm => p.caps.kvm,+ _ => true,+ };+ assert!(ok, "{name}: {} needs {c:?}", x.0);+ }+ }+ // The first example never needs a download: only an image already here leads.+ let lead = LIBRARY.iter().find(|e| e.id == p.examples[0].id).unwrap();+ let needs_image = (lead.needs.contains(&Cap::MacosSpace) && !p.caps.macos_cached)+ || (lead.needs.contains(&Cap::WindowsSpace) && !p.caps.windows_cached);+ assert!(!needs_image, "{name}");+ }+ }++ #[test]+ fn the_library_is_valid_for_a_real_host_and_its_tags_match_its_words() {+ let mut seen = std::collections::HashSet::new();+ for e in LIBRARY {+ assert!(seen.insert(e.id), "duplicate {}", e.id);+ let has = |c: Cap| e.needs.contains(&c);+ // Valid for at least one host profile.+ let fits_some = profiles().into_iter().any(|(_, env, os)| {+ let p = prompts_for(&env, os);+ e.needs.iter().all(|c| match c {+ Cap::MacosSpace => p.caps.macos,+ Cap::WindowsSpace => p.caps.windows,+ Cap::Kvm => p.caps.kvm,+ _ => true,+ })+ });+ assert!(fits_some, "{} fits no host profile", e.id);+ // Tags match the words.+ assert_eq!(+ has(Cap::MacosSpace),+ e.text.contains("macOS") || e.text.contains("Safari"),+ "{}",+ e.id+ );+ assert_eq!(+ has(Cap::WindowsSpace),+ e.text.contains("Windows") || e.text.contains("Edge"),+ "{}",+ e.id+ );+ assert_eq!(has(Cap::LinuxSpace), e.text.contains("Linux"), "{}", e.id);+ assert_eq!(has(Cap::Kvm), e.id == "fan-out-pricing", "{}", e.id);+ // A prompt the person completes ends with ': ' and is tagged for it; a copyable one is complete.+ assert_eq!(e.text.ends_with(": "), has(Cap::FillIn), "{}", e.id);+ // A login is always asked for through the Keyvault or the visible browser window, never typed to the agent.+ assert_eq!(has(Cap::Account), e.text.contains("Keyvault"), "{}", e.id);+ let asks_login = has(Cap::Account)+ || (e.text.contains("sign in") && !e.text.contains("not sign in"));+ if asks_login {+ assert!(+ e.text.contains("browser window")+ && e.text.contains("never ask me to type a password"),+ "{}",+ e.id+ );+ }+ // Real tasks, not a toy: no stand-in page that only gets fetched and described, and long enough to be specific.+ let l = e.text.to_lowercase();+ assert!(+ !l.contains("example.com")+ && !l.contains("example.org")+ && !l.contains("page's title")+ && !l.contains("first sentence"),+ "{} is a toy page",+ e.id+ );+ assert!(+ e.text.len() >= 200,+ "{} is too short to be a real task",+ e.id+ );+ let does = [+ "compare",+ "write",+ "load test",+ "download",+ "reproduce",+ "build",+ "find out",+ "tell me",+ "research",+ "watch",+ "check",+ "fill in",+ "bring up",+ "run the job",+ "try an unfamiliar",+ ];+ assert!(+ does.iter().any(|w| l.contains(w)),+ "{} asks for no real work",+ e.id+ );+ // Never a made-up issue number, repository, vendor claim, brand of model or middle dot.+ assert!(+ !l.contains('#')+ && !l.contains("issue ")+ && !l.contains("github.com/")+ && !e.text.contains('\u{b7}'),+ "{}",+ e.id+ );+ assert!(+ !l.contains("claude")+ && !l.contains("gpt")+ && !l.contains("openai")+ && !l.contains("device"),+ "{}",+ e.id+ );+ assert!(+ fp::FAMILIES+ .iter()+ .any(|f| f.0 == e.family && !f.1.is_empty()),+ "{} has no provenance note",+ e.id+ );+ // Onboarding's one example sentence: only the bug-on-platform entries have one, naming exactly their system.+ assert_eq!(+ e.lede.is_empty(),+ e.family != "bug-on-platform",+ "{} lede",+ e.id+ );+ assert!(+ e.lede.is_empty() || has(Cap::MacosSpace) == e.lede.contains("macOS"),+ "{} lede",+ e.id+ );+ assert!(+ e.lede.is_empty() || has(Cap::WindowsSpace) == e.lede.contains("Windows"),+ "{} lede",+ e.id+ );+ assert!(!e.why.is_empty() && !e.title.is_empty() && !e.detail.is_empty());+ }+ assert!(fp::FAMILIES.len() >= 8 && fp::FAMILIES.len() <= 12);+ for (f, _) in fp::FAMILIES {+ assert!(+ LIBRARY.iter().any(|e| e.family == *f),+ "family {f} has no entry"+ );+ }+ // The fallback: Linux only, copyable, no login, a real task.+ let fb = LIBRARY.iter().find(|e| e.id == FALLBACK).unwrap();+ assert_eq!(fb.needs, &[Cap::LinuxSpace]);+ assert!(!fb.text.ends_with(": "));+ }}diff --git a/libs/cua/crates/cua-spaces-ext/tests/upgrade_from_070.rs b/libs/cua/crates/cua-spaces-ext/tests/upgrade_from_070.rsindex 7be5108c47..311c5fff85 100644--- a/libs/cua/crates/cua-spaces-ext/tests/upgrade_from_070.rs+++ b/libs/cua/crates/cua-spaces-ext/tests/upgrade_from_070.rs@@ -183,7 +183,14 @@ async fn current_names_read_the_same_070_data() {let server = McpServer::new(spaces);let old = call(&server, "routine_list", &json!({})).await;let new = call(&server, "agent_schedule_list", &json!({})).await;- assert_eq!(old, new);+ // next_fire is computed from the clock, so the two calls can straddle a second.+ let strip = |mut v: Value| {+ for r in v["routines"].as_array_mut().unwrap() {+ r.as_object_mut().unwrap().remove("next_fire");+ }+ v+ };+ assert_eq!(strip(old), strip(new.clone()));assert_eq!(new["routines"].as_array().unwrap().len(), 3);// The off routine stays off, the others have a next firing.for r in new["routines"].as_array().unwrap() {diff --git a/libs/cua/crates/cua-vmm/src/containerization/install.rs b/libs/cua/crates/cua-vmm/src/containerization/install.rsindex 376f4af7c1..1d0d1ebe2c 100644--- a/libs/cua/crates/cua-vmm/src/containerization/install.rs+++ b/libs/cua/crates/cua-vmm/src/containerization/install.rs@@ -5,8 +5,6 @@use std::path::{Path, PathBuf};-use sha2::{Digest, Sha256};-use crate::error::{Result, VmmError};use crate::host;use crate::types::Arch;@@ -85,7 +83,11 @@ pub async fn install(root: &Path) -> Result<PathBuf> {let _ = std::fs::remove_dir_all(&staging);std::fs::create_dir_all(&staging)?;let result = async {- let pkg = staging.join("container.pkg");+ // The package is kept (as a partial file) between tries and runs: a+ // dropped connection or a quit resumes it instead of fetching 118 MB again.+ let dl = root.join("install").join(".download");+ std::fs::create_dir_all(&dl)?;+ let pkg = dl.join(format!("container-{VERSION}.pkg"));download(&pkg_url(), &pkg, PKG_SHA256).await?;let expanded = staging.join("x");let out = tokio::process::Command::new("/usr/sbin/pkgutil")@@ -115,35 +117,28 @@ pub async fn install(root: &Path) -> Result<PathBuf> {.await;let _ = std::fs::remove_dir_all(&staging);let bin = result?;+ let _ = std::fs::remove_dir_all(root.join("install").join(".download"));tracing::info!(bin = %bin.display(), version = VERSION, "installed Apple container");Ok(bin)}-/// Streams `url` into `dest`, checking its SHA-256 against `sha256`.+/// Downloads `url` into `dest` (resuming and retrying, [`crate::fetch`]),+/// checking its SHA-256 against `sha256`.async fn download(url: &str, dest: &Path, sha256: &str) -> Result<()> {- use tokio::io::AsyncWriteExt;tracing::info!(url, dest = %dest.display(), "downloading");- let fail = |e: reqwest::Error| VmmError::other(format!("download {url}: {e}"));- let mut resp = reqwest::get(url)- .await- .map_err(fail)?- .error_for_status()- .map_err(fail)?;- let mut f = tokio::fs::File::create(dest).await?;- let mut h = Sha256::new();- while let Some(chunk) = resp.chunk().await.map_err(fail)? {- h.update(&chunk);- f.write_all(&chunk).await?;- }- f.flush().await?;- let got = format!("{:x}", h.finalize());- if got != sha256 {- let _ = std::fs::remove_file(dest);- return Err(VmmError::other(format!(- "download {url}: SHA-256 {got} does not match the pinned {sha256}"- )));- }- Ok(())+ crate::fetch::fetch(+ &crate::fetch::Fetch {+ url,+ bearer: None,+ size: Some(PKG_BYTES),+ sha256,+ },+ dest,+ &crate::fetch::Policy::default(),+ &mut |_| {},+ )+ .await+ .map_err(Into::into)}pub use crate::auto::ContainerizationReport;diff --git a/libs/cua/crates/cua-vmm/src/fetch.rs b/libs/cua/crates/cua-vmm/src/fetch.rsnew file mode 100644index 0000000000..de6048c2af--- /dev/null+++ b/libs/cua/crates/cua-vmm/src/fetch.rs@@ -0,0 +1,547 @@+//! Resumable, retrying downloads of the pinned files cua fetches itself (the+//! built-in Linux runtime's tools and disk, Apple's `container` package).+//!+//! These are hundreds of megabytes fetched on a first run, often over a+//! network that drops. A download therefore:+//!+//! * writes to `<file>.partial` and **resumes** from it with an HTTP `Range`+//! request, in the same run after a lost connection and in the next one+//! after a quit (the bytes already there are hashed again, so the file is+//! still checked end to end against its SHA-256);+//! * **retries** a lost connection, a timeout and a 5xx or 429 answer with a+//! growing wait, instead of failing the create;+//! * starts over, once, when the server ignores `Range` or the finished file+//! does not match its checksum (a bad resume must never be a bad install);+//! * tells the caller about a 401 or 403 ([`FetchError::Unauthorized`]), so a+//! registry token that ran out can be asked for again and the download+//! carries on from the same place.+//!+//! `on_bytes` hears every byte once: those already in the partial file when+//! the download starts, then each new chunk. A retry does not count a byte+//! twice.++use std::path::{Path, PathBuf};+use std::time::Duration;++use sha2::{Digest, Sha256};+use tokio::io::AsyncWriteExt as _;++use crate::error::VmmError;++/// What to fetch.+pub struct Fetch<'a> {+ pub url: &'a str,+ /// A bearer token (a registry blob), when it needs one.+ pub bearer: Option<&'a str>,+ /// The size it must have, when known.+ pub size: Option<u64>,+ /// The SHA-256 (lowercase hex) it must have.+ pub sha256: &'a str,+}++/// How hard to try.+#[derive(Clone, Debug)]+pub struct Policy {+ /// Tries in all (the first included).+ pub attempts: u32,+ /// The wait before the second try; it doubles up to `max_wait`.+ pub first_wait: Duration,+ pub max_wait: Duration,+ pub connect_timeout: Duration,+ /// Longest silence on an open connection before it counts as lost.+ pub read_timeout: Duration,+}++impl Default for Policy {+ fn default() -> Self {+ Self {+ attempts: 8,+ first_wait: Duration::from_secs(2),+ max_wait: Duration::from_secs(30),+ connect_timeout: Duration::from_secs(20),+ read_timeout: Duration::from_secs(30),+ }+ }+}++/// Why a fetch ended.+#[derive(Debug)]+pub enum FetchError {+ /// The server refused the token (401 or 403): ask for a new one and call again.+ Unauthorized,+ /// Anything else, in words.+ Failed(VmmError),+}++impl From<FetchError> for VmmError {+ fn from(e: FetchError) -> Self {+ match e {+ FetchError::Unauthorized => VmmError::other("the registry refused the download token"),+ FetchError::Failed(e) => e,+ }+ }+}++impl From<std::io::Error> for FetchError {+ fn from(e: std::io::Error) -> Self {+ FetchError::Failed(e.into())+ }+}++/// Where the partial bytes of `to` are kept.+pub fn partial_path(to: &Path) -> PathBuf {+ let mut p = to.as_os_str().to_owned();+ p.push(".partial");+ PathBuf::from(p)+}++enum Once {+ Done,+ /// Lost connection, timeout, 5xx or 429: try again from the partial file.+ Retry(String),+ /// The partial file is not usable: delete it and start over.+ Restart(String),+ Unauthorized,+ Fatal(VmmError),+}++fn sha256_of_prefix(path: &Path) -> std::io::Result<Sha256> {+ use std::io::Read as _;+ let mut f = std::fs::File::open(path)?;+ let mut h = Sha256::new();+ let mut buf = vec![0u8; 256 * 1024];+ loop {+ let n = f.read(&mut buf)?;+ if n == 0 {+ return Ok(h);+ }+ h.update(&buf[..n]);+ }+}++fn client(p: &Policy) -> Result<reqwest::Client, FetchError> {+ reqwest::Client::builder()+ .connect_timeout(p.connect_timeout)+ .read_timeout(p.read_timeout)+ .build()+ .map_err(|e| FetchError::Failed(VmmError::other(format!("download: {e}"))))+}++async fn once(+ f: &Fetch<'_>,+ client: &reqwest::Client,+ partial: &Path,+ to: &Path,+ credited: &mut u64,+ on_bytes: &mut (dyn FnMut(u64) + Send),+) -> Once {+ let have = std::fs::metadata(partial).map(|m| m.len()).unwrap_or(0);+ if f.size.is_some_and(|s| have > s) {+ return Once::Restart("the partial file is larger than the file".into());+ }+ let mut req = client.get(f.url);+ if let Some(t) = f.bearer {+ req = req.bearer_auth(t);+ }+ if have > 0 {+ req = req.header(reqwest::header::RANGE, format!("bytes={have}-"));+ }+ let res = match req.send().await {+ Ok(r) => r,+ Err(e) => return Once::Retry(e.to_string()),+ };+ let status = res.status();+ let resumed = match status.as_u16() {+ 206 => true,+ 200 => false,+ 401 | 403 => return Once::Unauthorized,+ // The partial file is complete or past the end: look at it afresh.+ 416 => return Once::Restart("the server could not resume the download".into()),+ 408 | 429 | 500..=599 => return Once::Retry(format!("the server answered {status}")),+ _ => return Once::Fatal(VmmError::other(format!("download {}: {status}", f.url))),+ };+ if resumed && have > 0 {+ // Content-Range must start where the partial file ends.+ let ok = res+ .headers()+ .get(reqwest::header::CONTENT_RANGE)+ .and_then(|v| v.to_str().ok())+ .is_some_and(|v| v.starts_with(&format!("bytes {have}-")));+ if !ok {+ return Once::Restart("the server resumed from somewhere else".into());+ }+ }+ let (mut file, mut hash, mut got) = if resumed && have > 0 {+ let hash = match sha256_of_prefix(partial) {+ Ok(h) => h,+ Err(e) => return Once::Fatal(e.into()),+ };+ let file = match tokio::fs::OpenOptions::new()+ .append(true)+ .open(partial)+ .await+ {+ Ok(f) => f,+ Err(e) => return Once::Fatal(e.into()),+ };+ (file, hash, have)+ } else {+ // A server that ignores Range sends the whole file again.+ let file = match tokio::fs::File::create(partial).await {+ Ok(f) => f,+ Err(e) => return Once::Fatal(e.into()),+ };+ (file, Sha256::new(), 0)+ };+ // Bytes already in the partial file count once, on the first look at them.+ if got > *credited {+ on_bytes(got - *credited);+ *credited = got;+ }+ let mut res = res;+ loop {+ match res.chunk().await {+ Ok(Some(chunk)) => {+ got += chunk.len() as u64;+ if f.size.is_some_and(|s| got > s) {+ return Once::Restart("the download is larger than the file".into());+ }+ hash.update(&chunk);+ if let Err(e) = file.write_all(&chunk).await {+ return Once::Fatal(e.into());+ }+ if got > *credited {+ on_bytes(got - *credited);+ *credited = got;+ }+ }+ Ok(None) => break,+ Err(e) => {+ let _ = file.flush().await;+ return Once::Retry(e.to_string());+ }+ }+ }+ if let Err(e) = file.flush().await {+ return Once::Fatal(e.into());+ }+ drop(file);+ if f.size.is_some_and(|s| got < s) {+ // The connection ended early without an error: keep what came, ask for the rest.+ return Once::Retry("the connection closed before the end of the file".into());+ }+ let digest: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();+ if digest != f.sha256 {+ return Once::Restart(format!(+ "the file did not match its checksum (got {digest})"+ ));+ }+ match tokio::fs::rename(partial, to).await {+ Ok(()) => Once::Done,+ Err(e) => Once::Fatal(e.into()),+ }+}++/// Downloads `f` to `to` (through `to` + `.partial`), resuming and retrying+/// as the module says. `on_bytes` hears each byte once.+pub async fn fetch(+ f: &Fetch<'_>,+ to: &Path,+ policy: &Policy,+ on_bytes: &mut (dyn FnMut(u64) + Send),+) -> Result<(), FetchError> {+ let partial = partial_path(to);+ let client = client(policy)?;+ let mut credited = 0u64;+ let mut wait = policy.first_wait;+ let mut restarts = 0u32;+ let mut last = String::new();+ for attempt in 1..=policy.attempts.max(1) {+ match once(f, &client, &partial, to, &mut credited, on_bytes).await {+ Once::Done => return Ok(()),+ Once::Unauthorized => return Err(FetchError::Unauthorized),+ Once::Fatal(e) => return Err(FetchError::Failed(e)),+ Once::Restart(why) => {+ // Once: a second bad resume is a real failure, not something to loop on.+ restarts += 1;+ last = why;+ let _ = tokio::fs::remove_file(&partial).await;+ credited = 0;+ if restarts > 1 {+ break;+ }+ }+ Once::Retry(why) => {+ last = why;+ if attempt < policy.attempts {+ tracing::warn!(url = f.url, attempt, reason = %last, "download interrupted, resuming");+ tokio::time::sleep(wait).await;+ wait = (wait * 2).min(policy.max_wait);+ }+ }+ }+ }+ let kept = if partial.exists() {+ " (what was downloaded is kept)"+ } else {+ ""+ };+ Err(FetchError::Failed(VmmError::other(format!(+ "download {}: {last}; check the connection and try again{kept}",+ f.url+ ))))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::Arc;+ use std::sync::Mutex;+ use tokio::io::AsyncReadExt as _;+ use tokio::net::TcpListener;++ /// A tiny HTTP server: serves `blob` with Range, and for each of its+ /// first requests drops the connection after sending `cut[i]` bytes of+ /// the body (usize::MAX: no cut). Records each request's Range header.+ struct Server {+ url: String,+ ranges: Arc<Mutex<Vec<Option<String>>>>,+ }++ async fn serve(blob: Vec<u8>, cut: Vec<usize>, honour_range: bool) -> Server {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}/blob", listener.local_addr().unwrap());+ let ranges = Arc::new(Mutex::new(Vec::new()));+ let seen = ranges.clone();+ tokio::spawn(async move {+ let mut n = 0usize;+ loop {+ let (mut s, _) = listener.accept().await.unwrap();+ let mut buf = vec![0u8; 4096];+ let k = s.read(&mut buf).await.unwrap();+ let head = String::from_utf8_lossy(&buf[..k]).to_string();+ let range = head+ .lines()+ .find(|l| l.to_ascii_lowercase().starts_with("range:"))+ .map(|l| l.split_once(':').unwrap().1.trim().to_string());+ seen.lock().unwrap().push(range.clone());+ let start = match (&range, honour_range) {+ (Some(r), true) => r+ .trim_start_matches("bytes=")+ .trim_end_matches('-')+ .parse::<usize>()+ .unwrap_or(0),+ _ => 0,+ };+ let body = &blob[start..];+ let (status, extra) = if start > 0 {+ (+ "206 Partial Content",+ format!(+ "Content-Range: bytes {start}-{}/{}\r\n",+ blob.len() - 1,+ blob.len()+ ),+ )+ } else {+ ("200 OK", String::new())+ };+ let head = format!(+ "HTTP/1.1 {status}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n",+ body.len()+ );+ let limit = cut.get(n).copied().unwrap_or(usize::MAX);+ n += 1;+ let _ = s.write_all(head.as_bytes()).await;+ let send = body.len().min(limit);+ let _ = s.write_all(&body[..send]).await;+ let _ = s.flush().await;+ // Dropping the socket mid-body is a lost connection.+ drop(s);+ }+ });+ Server { url, ranges }+ }++ fn blob(n: usize) -> (Vec<u8>, String) {+ let b: Vec<u8> = (0..n).map(|i| (i * 31 % 251) as u8).collect();+ let h = Sha256::digest(&b)+ .iter()+ .map(|x| format!("{x:02x}"))+ .collect::<String>();+ (b, h)+ }++ fn fast() -> Policy {+ Policy {+ attempts: 6,+ first_wait: Duration::from_millis(5),+ max_wait: Duration::from_millis(20),+ connect_timeout: Duration::from_secs(5),+ read_timeout: Duration::from_secs(5),+ }+ }++ #[tokio::test]+ async fn a_connection_dropped_twice_resumes_from_what_arrived() {+ let (b, sha) = blob(3_000_000);+ let srv = serve(b.clone(), vec![1_000_000, 900_000], true).await;+ let dir = tempfile::tempdir().unwrap();+ let to = dir.path().join("f.bin");+ let mut counted = 0u64;+ fetch(+ &Fetch {+ url: &srv.url,+ bearer: None,+ size: Some(b.len() as u64),+ sha256: &sha,+ },+ &to,+ &fast(),+ &mut |n| counted += n,+ )+ .await+ .unwrap();+ assert_eq!(std::fs::read(&to).unwrap(), b);+ assert!(!partial_path(&to).exists());+ assert_eq!(counted, b.len() as u64, "every byte is counted once");+ let r = srv.ranges.lock().unwrap().clone();+ assert_eq!(r.len(), 3, "two drops, one finish: {r:?}");+ assert_eq!(r[0], None);+ assert!(+ r[1].as_deref().unwrap().starts_with("bytes=") && r[1].as_deref() != Some("bytes=0-")+ );+ assert!(r[2].is_some(), "the third request resumed too");+ }++ #[tokio::test]+ async fn a_partial_file_from_an_earlier_run_is_resumed_and_counted() {+ let (b, sha) = blob(2_000_000);+ let srv = serve(b.clone(), vec![], true).await;+ let dir = tempfile::tempdir().unwrap();+ let to = dir.path().join("f.bin");+ std::fs::write(partial_path(&to), &b[..700_000]).unwrap();+ let mut counted = 0u64;+ fetch(+ &Fetch {+ url: &srv.url,+ bearer: None,+ size: Some(b.len() as u64),+ sha256: &sha,+ },+ &to,+ &fast(),+ &mut |n| counted += n,+ )+ .await+ .unwrap();+ assert_eq!(std::fs::read(&to).unwrap(), b);+ assert_eq!(counted, b.len() as u64);+ let r = srv.ranges.lock().unwrap().clone();+ assert_eq!(r.len(), 1);+ assert_eq!(r[0].as_deref(), Some("bytes=700000-"));+ }++ #[tokio::test]+ async fn a_server_that_ignores_range_restarts_cleanly() {+ let (b, sha) = blob(1_500_000);+ // First request is cut; the server never honours Range.+ let srv = serve(b.clone(), vec![500_000], false).await;+ let dir = tempfile::tempdir().unwrap();+ let to = dir.path().join("f.bin");+ fetch(+ &Fetch {+ url: &srv.url,+ bearer: None,+ size: Some(b.len() as u64),+ sha256: &sha,+ },+ &to,+ &fast(),+ &mut |_| {},+ )+ .await+ .unwrap();+ assert_eq!(+ std::fs::read(&to).unwrap(),+ b,+ "the whole file, not the cut one glued on"+ );+ }++ #[tokio::test]+ async fn a_corrupt_partial_file_is_never_installed() {+ let (b, sha) = blob(1_000_000);+ let srv = serve(b.clone(), vec![], true).await;+ let dir = tempfile::tempdir().unwrap();+ let to = dir.path().join("f.bin");+ // Garbage that is not a prefix of the file: the resume fails its checksum, starts over once.+ std::fs::write(partial_path(&to), vec![7u8; 300_000]).unwrap();+ fetch(+ &Fetch {+ url: &srv.url,+ bearer: None,+ size: Some(b.len() as u64),+ sha256: &sha,+ },+ &to,+ &fast(),+ &mut |_| {},+ )+ .await+ .unwrap();+ assert_eq!(std::fs::read(&to).unwrap(), b);+ }++ #[tokio::test]+ async fn the_wrong_checksum_is_an_error_not_an_install() {+ let (b, _sha) = blob(100_000);+ let srv = serve(b.clone(), vec![], true).await;+ let dir = tempfile::tempdir().unwrap();+ let to = dir.path().join("f.bin");+ let e = fetch(+ &Fetch {+ url: &srv.url,+ bearer: None,+ size: Some(b.len() as u64),+ sha256: &"0".repeat(64),+ },+ &to,+ &fast(),+ &mut |_| {},+ )+ .await+ .unwrap_err();+ assert!(matches!(e, FetchError::Failed(_)));+ assert!(!to.exists());+ assert!(!partial_path(&to).exists());+ }++ #[tokio::test]+ async fn a_server_that_is_gone_fails_in_words_and_keeps_the_partial_file() {+ let (b, sha) = blob(400_000);+ // Every request is cut after 100 KB and the budget is two tries.+ let srv = serve(b.clone(), vec![100_000; 10], true).await;+ let dir = tempfile::tempdir().unwrap();+ let to = dir.path().join("f.bin");+ let mut p = fast();+ p.attempts = 2;+ let e = fetch(+ &Fetch {+ url: &srv.url,+ bearer: None,+ size: Some(b.len() as u64),+ sha256: &sha,+ },+ &to,+ &p,+ &mut |_| {},+ )+ .await+ .unwrap_err();+ let FetchError::Failed(e) = e else { panic!() };+ assert!(e.to_string().contains("what was downloaded is kept"), "{e}");+ assert_eq!(std::fs::metadata(partial_path(&to)).unwrap().len(), 200_000);+ assert!(!to.exists());+ }+}diff --git a/libs/cua/crates/cua-vmm/src/lib.rs b/libs/cua/crates/cua-vmm/src/lib.rsindex f736f55819..ff2c55f1bb 100644--- a/libs/cua/crates/cua-vmm/src/lib.rs+++ b/libs/cua/crates/cua-vmm/src/lib.rs@@ -38,6 +38,8 @@ pub mod elf;pub mod error;pub mod exec;pub mod experiments;+#[cfg(any(feature = "lume", feature = "containerization"))]+pub mod fetch;pub mod filetable;pub mod gpu;pub mod host;diff --git a/libs/cua/crates/cua-vmm/src/managed.rs b/libs/cua/crates/cua-vmm/src/managed.rsindex b87bf9d1d3..edb6912a9d 100644--- a/libs/cua/crates/cua-vmm/src/managed.rs+++ b/libs/cua/crates/cua-vmm/src/managed.rs@@ -1208,9 +1208,34 @@ async fn ensure_disk(dl: &mut Downloads) -> Result<PathBuf> {"https://ghcr.io/v2/{DISK_REPOSITORY}/blobs/sha256:{}",pin.sha256);- let token = ghcr_token().await?;- download(Pin { url: "", ..pin }, Some((&url, &token)), &path, dl).await?;- Ok(path)+ // A registry token is short-lived: on a slow connection it can run out+ // mid-download, and the download carries on from the same place with a new one.+ for attempt in 1..=3 {+ let token = ghcr_token().await?;+ let r = crate::fetch::fetch(+ &crate::fetch::Fetch {+ url: &url,+ bearer: Some(&token),+ size: Some(pin.size),+ sha256: pin.sha256,+ },+ &path,+ &crate::fetch::Policy::default(),+ &mut |n| dl.add(n),+ )+ .await;+ match r {+ Ok(()) => return Ok(path),+ Err(crate::fetch::FetchError::Unauthorized) if attempt < 3 => continue,+ Err(crate::fetch::FetchError::Failed(e)) => {+ return Err(VmmError::other(format!(+ "download the built-in Linux runtime: {e}"+ )));+ }+ Err(e) => return Err(e.into()),+ }+ }+ unreachable!("the loop returns on its last try")}/// A pull token for [`DISK_REPOSITORY`]: anonymous, or with the@@ -1250,8 +1275,9 @@ fn http() -> Result<reqwest::Client> {.map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))}-/// Streams a pinned file to `to` (via `<to>.partial`), checking its size-/// and SHA-256 before it is renamed into place.+/// Downloads a pinned file to `to` (via `<to>.partial`), resuming from what+/// is there and retrying a lost connection ([`crate::fetch`]); its size and+/// SHA-256 are checked before it is renamed into place.#[cfg(feature = "lume")]async fn download(pin: Pin,@@ -1259,52 +1285,28 @@ async fn download(to: &Path,dl: &mut Downloads,) -> Result<()> {- use sha2::{Digest, Sha256};- use tokio::io::AsyncWriteExt as _;let (url, token) = match bearer {Some((u, t)) => (u, Some(t)),None => (pin.url, None),};- let mut req = http()?.get(url);- if let Some(t) = token {- req = req.bearer_auth(t);- }- let mut res = req- .send()- .await- .and_then(|r| r.error_for_status())- .map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))?;- let partial = to.with_extension("partial");- let mut file = tokio::fs::File::create(&partial).await?;- let mut hash = Sha256::new();- let mut got = 0u64;- while let Some(chunk) = res- .chunk()- .await- .map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))?- {- got += chunk.len() as u64;- if got > pin.size {- let _ = tokio::fs::remove_file(&partial).await;- return Err(VmmError::other(- "a built-in Linux runtime download is larger than its pin",- ));+ crate::fetch::fetch(+ &crate::fetch::Fetch {+ url,+ bearer: token,+ size: Some(pin.size),+ sha256: pin.sha256,+ },+ to,+ &crate::fetch::Policy::default(),+ &mut |n| dl.add(n),+ )+ .await+ .map_err(|e| match e {+ crate::fetch::FetchError::Failed(e) => {+ VmmError::other(format!("download the built-in Linux runtime: {e}"))}- hash.update(&chunk);- file.write_all(&chunk).await?;- dl.add(chunk.len() as u64);- }- file.flush().await?;- drop(file);- let digest: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();- if digest != pin.sha256 || got != pin.size {- let _ = tokio::fs::remove_file(&partial).await;- return Err(VmmError::other(format!(- "a built-in Linux runtime download did not match its checksum (got {digest}); try again"- )));- }- tokio::fs::rename(&partial, to).await?;- Ok(())+ e => e.into(),+ })}fn sha256_file(path: &Path) -> Result<String> {diff --git a/libs/images/tools/cua-image-pack/Cargo.lock b/libs/images/tools/cua-image-pack/Cargo.lockindex 2103cf1285..929e35876e 100644--- a/libs/images/tools/cua-image-pack/Cargo.lock+++ b/libs/images/tools/cua-image-pack/Cargo.lock@@ -427,6 +427,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex c8a919763e..99f08675f4 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -461,6 +461,17 @@"repeatable": false,"short_name": null,"takes_value": false+ },+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "Only the sign-in, as `--sign-in`, and nothing else: no Cua skills and no MCP entry are added to any agent, Claude Code is never run to refresh its own sign-in, and nothing is written outside the Cua home (the access token goes to Keyvault, never printed). For a demo, or a home Space that only needs the credential. On a Mac, macOS asks once to let Cua read the Keychain item \"Claude Code-credentials\": that prompt is yours to answer",+ "hidden": false,+ "name": "sign-in-only",+ "repeatable": false,+ "short_name": null,+ "takes_value": false}],"hidden": false,@@ -735,6 +746,17 @@"repeatable": false,"short_name": null,"takes_value": false+ },+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "Only the sign-in, as `--sign-in`, and nothing else: no Cua skills and no MCP entry are added to any agent, Claude Code is never run to refresh its own sign-in, and nothing is written outside the Cua home (the access token goes to Keyvault, never printed). For a demo, or a home Space that only needs the credential. On a Mac, macOS asks once to let Cua read the Keychain item \"Claude Code-credentials\": that prompt is yours to answer",+ "hidden": false,+ "name": "sign-in-only",+ "repeatable": false,+ "short_name": null,+ "takes_value": false}],"hidden": false,diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lockindex 04b7f621de..21ba0c8eed 100644--- a/tests/e2e/cua-sdk/rust/Cargo.lock+++ b/tests/e2e/cua-sdk/rust/Cargo.lock@@ -1592,6 +1592,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lockindex 5bd5d08885..f16b0e15f1 100644--- a/tests/e2e/local-runtimes/Cargo.lock+++ b/tests/e2e/local-runtimes/Cargo.lock@@ -1385,6 +1385,7 @@ dependencies = ["tokio","tokio-util","tracing",+ "zstd",][[package]]