Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces): three first-run fixes for the new setup (CUA-3193) (#6409)
Francesco Bonaccia6005a4a490e
diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.tsindex ec83fa7e24..8c3a5e8a5a 100644--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts@@ -17,6 +17,9 @@ import { validate, type Schema } from "../../cua-spaces-web/src/bridge/contractsimport { OP_SHAPES, SHAPE_DEFS } from "../../cua-spaces-web/src/bridge/contracts/shapes";import { HOST_COVERAGE } from "../../cua-spaces-web/src/bridge/coverage";import { THREAD_OPERATIONS } from "../../cua-spaces-web/src/bridge/ops/thread";+import { testCore, wasmBuilt } from "../../cua-spaces-web/src/bridge/__tests__/testCore";+import type { WizardEnv } from "../../cua-spaces-web/src/bridge/contracts/new-space";+import { homeCreateRequest, type HomeOffer } from "../../cua-spaces-web/src/lib/prepare/home-request";import { OPERATIONS, type OpArgs, type OpName } from "../../cua-spaces-web/src/bridge/protocol";import { createBridge, type Bridge } from "../src/bridge";import { runtimeWord } from "../src/model/backend";@@ -268,6 +271,21 @@ describe.skipIf(!built)("the bridge on the app core", () => {await create;});+ // CUA-3193: the new setup ended on "Preparing stopped: config.image: string". The page's+ // first-Space create, from the wizard's Linux offer (the real core), through this host's create.+ it.skipIf(!wasmBuilt)("makes the new setup's first Space through the real create", async () => {+ const core = await testCore();+ const mac = JSON.parse(readFileSync(path.resolve(__dirname, "../../../libs/cua/crates/cua-spaces-app-core/parity/first-run.json"), "utf8")).machineBase as WizardEnv;+ // The page's offers (`firstSpaceOffers`): the core's, for this machine's env.+ const offers = core.call<HomeOffer[]>("wizard.firstSpaceOffers", { env: mac, hostOs: "macos" });+ const { os, ...config } = homeCreateRequest(offers, "home-claude-code");+ const made = (await call("spaces.create", { pendingId: "pending:home", config, os })) as { id: string; name: string };+ expect(made).toMatchObject({ name: "home-claude-code" });+ expect(backend.created.at(-1)).toMatchObject({ image: config.image, name: "home-claude-code", on: "local" });+ // What it used to send: no image, which this host refuses with its argument check.+ expect(await code("spaces.create", { pendingId: "pending:old", config: { os: "linux", name: "home-claude-code" }, os: "linux" })).toBe("bad_args");+ });+it("refuses a create it cannot run", async () => {expect(await code("spaces.create", { pendingId: "nope", config: { image: "x", kind: "container" } })).toBe("bad_args");expect(await code("spaces.create", { pendingId: "pending:2", config: { image: "x", kind: "box" } })).toBe("bad_args");diff --git a/apps/cua-spaces-web/src/__tests__/home-agent-picker.test.tsx b/apps/cua-spaces-web/src/__tests__/home-agent-picker.test.tsxnew file mode 100644index 0000000000..f9b13c05cd--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/home-agent-picker.test.tsx@@ -0,0 +1,66 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// CUA-3193: Home's "Who does it" offers only the agents on this computer. With none, it says+// "Install Claude Code" instead of @claude, Start stays off, and the new setup prepares no agent.++import { cleanup, fireEvent, screen, 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 { resetPrepare } from "@/lib/prepare/store";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetAskTasks();+ resetConnectState();+ resetPrepare();+ setFlagOverride("spaces_ask_first_home", true);+});+afterEach(() => {+ cleanup();+ resetPrepare();+ vi.unstubAllEnvs();+});++const q = (s: string) => document.querySelector<HTMLElement>(s);+type Call = { op: string; args: Record<string, unknown> };++describe.skipIf(!wasmBuilt)("Home's agent picker", () => {+ it("with no agent on this computer: Install Claude Code, no @claude, Start off, nothing prepared", { timeout: 30000 }, async () => {+ setFlagOverride("spaces_new_onboarding", true);+ const calls: Call[] = [];+ await mountApp("/home", { failsCreates: false, listsGhost: false, demo: { onboarded: true, agents: "none" }, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await waitFor(() => expect(calls.some((c) => c.op === "agents.setup")).toBe(true));+ await waitFor(() => expect(q("[data-ask-install]")?.textContent).toBe("Install Claude Code"));+ expect(q("[data-ask-mention]")).toBeNull();+ expect(q('[data-picker="who"]')?.textContent).not.toContain("@");+ fireEvent.change(await screen.findByLabelText("What do you want to do?"), { target: { value: "fix the build" } });+ expect((screen.getByRole("button", { name: "Start" }) as HTMLButtonElement).disabled).toBe(true);+ // The new setup does not make a home for an agent that isn't there.+ await new Promise((r) => setTimeout(r, 500));+ expect(calls.some((c) => c.op === "thread.agentAdd")).toBe(false);+ expect(calls.some((c) => c.op === "spaces.create" && (c.args.config as { name?: string } | undefined)?.name === "home-claude-code")).toBe(false);+ });++ it("with only Codex on this computer: Codex, never Claude Code", { timeout: 30000 }, async () => {+ await mountApp("/home", { failsCreates: false, listsGhost: false, demo: { onboarded: true, agents: "codex" } });+ const mention = await waitFor(() => {+ const el = q("[data-ask-mention]");+ expect(el).not.toBeNull();+ return el!;+ });+ expect(mention.textContent).not.toMatch(/claude/i);+ expect(q("[data-ask-install]")).toBeNull();+ });++ it("with Claude Code on this computer: @claude", { timeout: 30000 }, async () => {+ await mountApp("/home", { failsCreates: false, listsGhost: false, demo: { onboarded: true } });+ await waitFor(() => expect(q("[data-ask-mention]")?.textContent?.toLowerCase()).toContain("@claude"));+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/prepare-cant-run.test.tsx b/apps/cua-spaces-web/src/__tests__/prepare-cant-run.test.tsxnew file mode 100644index 0000000000..22997fe843--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/prepare-cant-run.test.tsx@@ -0,0 +1,74 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// CUA-3193: on a Mac that can't run Spaces itself, the new setup stopped on+// "Preparing stopped: local runtime: This Mac can't run Spaces itself, ..." with Try again.+// No raw runtime error reaches Home: the core's sentence shows, with "Add a computer".++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 { 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();+});++/** `cua_create_failure::preflight::MAC_UNSUPPORTED`, the daemon's refusal (#6323). */+const MAC_UNSUPPORTED =+ "This Mac can't run Spaces itself, because it can't run virtual computers. That happens when the Mac is itself a virtual machine, or is an older Intel Mac. Add another computer to your account, or link your own cloud, and create the Space there.";++/** What the SDK's errors start with: internal words a person never reads. */+const RAW = [/local runtime:/i, /\[local\]/i, /config\.\w+:/, /os error/i, /exit(ing)?,? status/i];++describe.skipIf(!wasmBuilt)("preparing on a Mac that can't run Spaces", () => {+ for (const raw of [`local runtime: ${MAC_UNSUPPORTED}`, `local runtime: [local] ${MAC_UNSUPPORTED}`]) {+ it(`says so in plain words with Add a computer (${raw.slice(0, 22)})`, { timeout: 40000 }, async () => {+ const { router } = await mountApp("/home", {+ failsCreates: false,+ listsGhost: false,+ demo: { onboarded: true },+ intercept: (op) => {+ if (op === "spaces.create") throw new Error(raw);+ return undefined;+ },+ });+ const line = await waitFor(+ () => {+ const el = document.querySelector<HTMLElement>("[data-prepare-line]");+ expect(el).not.toBeNull();+ return el!;+ },+ { timeout: 20000 },+ );+ const text = line.textContent ?? "";+ expect(text).toContain("This Mac can't run Spaces itself");+ for (const r of RAW) expect(text).not.toMatch(r);+ const button = line.querySelector<HTMLElement>("[data-prepare-action]")!;+ expect(button.dataset.prepareAction).toBe("add-computer");+ expect(button.textContent).toBe("Add a computer");+ await act(async () => {+ fireEvent.click(button);+ await new Promise((r) => setTimeout(r, 20));+ });+ await waitFor(() => expect(router.state.location.pathname).toBe("/machines"));+ expect(router.state.location.search).toMatchObject({ add: true });+ });+ }+});diff --git a/apps/cua-spaces-web/src/components/ask-first/__tests__/task-agents.test.ts b/apps/cua-spaces-web/src/components/ask-first/__tests__/task-agents.test.tsnew file mode 100644index 0000000000..fb134eddaa--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/__tests__/task-agents.test.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// CUA-3193: Home offered @claude on a computer without Claude Code. Only agents the setup found+// on this computer are offered; with none, Home offers to install Claude Code.++import { describe, expect, it } from "vitest";++import type { AgentSetupRow } from "@/bridge";++import { chooseAgent, offeredAgents } from "../task-agents";+import { installedTaskAgents } from "../use-installed-agents";++const row = (agent: string, installed: boolean, configured = false) => ({ agent, name: agent, installed, configured }) as AgentSetupRow;++describe("who does a job on Home", () => {+ it("counts an agent only when it is on this computer, not when Cua only wrote its files", () => {+ // `configured` alone is Cua's own skills and MCP entry (CUA-3063): no Claude Code.+ const set = installedTaskAgents([row("claude-code", false, true), row("codex", true), row("cursor", true)]);+ expect([...set]).toEqual(["openai-codex"]);+ });++ it("offers only installed agents and never falls back to one that isn't", () => {+ const none = new Set<string>();+ expect(offeredAgents(none)).toEqual([]);+ expect(chooseAgent(null, null, none)).toBeNull();+ // A pick or a most-used agent that is gone from this computer is not offered either.+ expect(chooseAgent("claude-code", "claude-code", none)).toBeNull();+ const codex = new Set(["openai-codex"]);+ expect(chooseAgent(null, "claude-code", codex)).toBe("openai-codex");+ const both = new Set(["openai-codex", "claude-code"]);+ expect(offeredAgents(both).map((a) => a.id)).toEqual(["claude-code", "openai-codex"]);+ expect(chooseAgent(null, "openai-codex", both)).toBe("openai-codex");+ expect(chooseAgent("claude-code", "openai-codex", both)).toBe("claude-code");+ });+});diff --git a/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx b/apps/cua-spaces-web/src/components/ask-first/ask-box.tsxindex 9dc584611e..dedfe9efea 100644--- a/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx@@ -5,25 +5,17 @@ import { Menu as MenuPrimitive } from "@base-ui/react/menu";import { ArrowUpIcon, CheckIcon, ChevronDownIcon, LaptopIcon, MonitorIcon } from "lucide-react";import { useEffect, useRef, type ReactElement, type ReactNode } from "react";-import { firstMessage, useBridge, type Space, type SpaceOs } from "@/bridge";+import { firstMessage, useBridge, useSession, type Space, type SpaceOs } from "@/bridge";import { AppMarkImage } from "@/components/agents/harness-mark";import { OsIcon } from "@/components/os-icon";import type { NewKind, TaskWhere } from "@/lib/ask-first";import { cn } from "@/lib/utils";-export type { TaskWhere } from "@/lib/ask-first";+import { agentName, CLAUDE_CODE_URL, offeredAgents } from "./task-agents";-/** The coding apps a task can run with (`agent_start`'s harnesses), in the picker's order. */-export const TASK_AGENTS: { id: string; name: string; setupId: string }[] = [- { id: "claude-code", name: "Claude Code", setupId: "claude-code" },- { id: "openai-codex", name: "Codex", setupId: "codex" },- { id: "gemini-cli", name: "Gemini CLI", setupId: "gemini-cli" },- { id: "opencode", name: "OpenCode", setupId: "opencode" },- { id: "goose", name: "Goose", setupId: "goose" },- { id: "hermes", name: "Hermes", setupId: "hermes" },-];+export type { TaskWhere } from "@/lib/ask-first";-export const agentName = (id: string) => TASK_AGENTS.find((a) => a.id === id)?.name ?? id;+export { agentName, TASK_AGENTS } from "./task-agents";const OS_WORD: Record<SpaceOs, string> = { linux: "Linux", macos: "Mac", windows: "Windows", unknown: "" };@@ -117,9 +109,10 @@ export function AskBox({}: {text: string;onText: (t: string) => void;- agent: string;+ /** Who does it; null when no agent is on this computer (the picker offers to install Claude Code). */+ agent: string | null;onAgent: (a: string) => void;- /** Harness ids found on this computer. */+ /** Harness ids found on this computer: the only ones offered. */installed: ReadonlySet<string>;mostUsed: string | null;where: TaskWhere;@@ -140,11 +133,13 @@ export function AskBox({useEffect(() => {if (autoFocus) ref.current?.focus();}, [autoFocus]);- const ready = text.trim().length > 0 && !busy;+ const ready = text.trim().length > 0 && !busy && agent !== null;+ const session = useSession();// The agent reads as the @mention the thread will show, and where as a Space.const { core } = useBridge();- const handle = firstMessage(core, { members: [], people: [], canAdd: true, connectors: { apps: [], keys: { keys: [] }, shellKeys: [], auto: false, off: [], busy: [], failures: [] } }, agent, "")?.handle ?? null;- const agentNote = (id: string) => (id === mostUsed ? "You use it most" : installed.has(id) ? "On this Mac" : "Runs on the new computer with your saved key");+ const handle = agent ? (firstMessage(core, { members: [], people: [], canAdd: true, connectors: { apps: [], keys: { keys: [] }, shellKeys: [], auto: false, off: [], busy: [], failures: [] } }, agent, "")?.handle ?? null) : null;+ const agentNote = (id: string) => (id === mostUsed ? "You use it most" : "On this computer");+ const offered = offeredAgents(installed);return (<div data-ask-box="" className="rounded-2xl border bg-card shadow-xs dark:bg-white/[0.03]"><textarea@@ -167,8 +162,10 @@ export function AskBox({title="Who does it"trigger={<button type="button" className={pickerButton} data-picker="who">- <AppMark agent={agent} size={24} />- {handle ? (+ <AppMark agent={agent ?? "claude-code"} size={24} />+ {agent === null ? (+ <span data-ask-install="">Install Claude Code</span>+ ) : handle ? (<span data-ask-mention={handle} className="font-medium text-brand-strong">@{handle}</span>@@ -178,11 +175,19 @@ export function AskBox({<ChevronDownIcon className="size-4 text-muted-foreground" /></button>}- footer="It works on the new computer, signed in with the key you saved in Settings → Connections."+ footer={offered.length ? "It works on the new computer, signed in the way it is on this one." : "Cua finds Claude Code once it's installed. Then pick it here."}>- {TASK_AGENTS.map((a) => (- <PickerRow key={a.id} icon={<AppMark agent={a.id} size={28} />} title={a.name} note={agentNote(a.id)} selected={a.id === agent} onSelect={() => onAgent(a.id)} />- ))}+ {offered.length ? (+ offered.map((a) => <PickerRow key={a.id} icon={<AppMark agent={a.id} size={28} />} title={a.name} note={agentNote(a.id)} selected={a.id === agent} onSelect={() => onAgent(a.id)} />)+ ) : (+ <PickerRow+ icon={<AppMark agent="claude-code" size={28} />}+ title="Install Claude Code"+ note="No coding agent is on this computer yet"+ selected={false}+ onSelect={() => void session.openExternal(CLAUDE_CODE_URL).catch(() => {})}+ />+ )}</Picker><span className="px-1 text-[14px] text-muted-foreground">in</span><WherePickerdiff --git a/apps/cua-spaces-web/src/components/ask-first/home.tsx b/apps/cua-spaces-web/src/components/ask-first/home.tsxindex 62d32d98f8..7f67c70335 100644--- a/apps/cua-spaces-web/src/components/ask-first/home.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/home.tsx@@ -1,9 +1,9 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { useEffect, useState } from "react";+import { useState } from "react";-import { useAgentChats, useAgents, useSpaces, type AgentRunSummary } from "@/bridge";+import { useAgentChats, useSpaces, type AgentRunSummary } from "@/bridge";import { CuaKey } from "@/components/cua-key";import { useAgentAttempts } from "@/hooks/use-agent-attempts";import { OsIcon } from "@/components/os-icon";@@ -11,14 +11,19 @@ import { currentWhere, mostUsedAgent, SUGGESTIONS, useAskTasks, type AskTask, tyimport { useListedSpaces } from "@/components/spaces/listed";import { cn } from "@/lib/utils";-import { agentName, AskBox, TASK_AGENTS, type TaskWhere } from "./ask-box";+import { AskBox, type TaskWhere } from "./ask-box";+import { agentName, chooseAgent } from "./task-agents";+import { useInstalledAgents } from "./use-installed-agents";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 { usePrepareAction } from "@/components/prepare/use-prepare-action";import { usePrepare } from "@/lib/prepare/store";+const NONE: ReadonlySet<string> = new Set();+/** The run a task follows, from the runs in your running Spaces. */export function taskRun(runs: readonly AgentRunSummary[] | undefined, task: AskTask): AgentRunSummary | undefined {return task.runId ? runs?.find((r) => r.runId === task.runId && r.spaceId === task.spaceId) : undefined;@@ -43,37 +48,24 @@ export function AskFirstHome() {const tasks = useAskTasks();const { data: spaces } = useSpaces();const listed = useListedSpaces(spaces);- const { agentSetup } = useAgents();const { kinds, spaces: pickable } = useWhereOptions();const { start } = useStartTask();- const [installed, setInstalled] = useState<ReadonlySet<string>>(new Set());- useEffect(() => {- let live = true;- agentSetup()- .then((rows) => {- if (!live) return;- const found = new Set(rows.filter((r) => r.installed).map((r) => r.agent));- setInstalled(new Set(TASK_AGENTS.filter((a) => found.has(a.setupId)).map((a) => a.id)));- })- .catch(() => {});- return () => {- live = false;- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ // Only agents on this computer are offered (the agent setup's detection, which skips files Cua wrote).+ const installed = useInstalledAgents() ?? NONE;const mostUsed = mostUsedAgent(tasks);const [text, setText] = useState("");const [agent, setAgent] = useState<string | null>(null);- const chosenAgent = agent ?? mostUsed ?? TASK_AGENTS.find((a) => installed.has(a.id))?.id ?? "claude-code";+ const chosenAgent = chooseAgent(agent, mostUsed, installed);// 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 onPrepareAction = usePrepareAction();const [whereOpen, setWhereOpen] = useState(false);- const pick = useWherePick(agentName(chosenAgent));+ const pick = useWherePick(chosenAgent ? agentName(chosenAgent) : "Your agent");const where = currentWhere(picked, kinds, pickable);const submit = (prompt = text, w = where) => {- if (!prompt.trim()) return;+ if (!prompt.trim() || !chosenAgent) return;start({ prompt, agent: chosenAgent, where: w });setText("");};@@ -110,7 +102,7 @@ export function AskFirstHome() {autoFocus/>{/* Preparing is silent: only a failed prepare says so, with Try again. */}- <PrepareLine view={prep.view} onRetry={() => prep.driver?.retry()} />+ <PrepareLine view={prep.view} onRetry={onPrepareAction} />{first ? (<><div className="grid gap-4 sm:grid-cols-3">diff --git a/apps/cua-spaces-web/src/components/ask-first/task-agents.ts b/apps/cua-spaces-web/src/components/ask-first/task-agents.tsnew file mode 100644index 0000000000..27d18a6947--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/task-agents.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/** The coding apps a task can run with (`agent_start`'s harnesses), in the picker's order. */+export const TASK_AGENTS: { id: string; name: string; setupId: string }[] = [+ { id: "claude-code", name: "Claude Code", setupId: "claude-code" },+ { id: "openai-codex", name: "Codex", setupId: "codex" },+ { id: "gemini-cli", name: "Gemini CLI", setupId: "gemini-cli" },+ { id: "opencode", name: "OpenCode", setupId: "opencode" },+ { id: "goose", name: "Goose", setupId: "goose" },+ { id: "hermes", name: "Hermes", setupId: "hermes" },+];++export const agentName = (id: string) => TASK_AGENTS.find((a) => a.id === id)?.name ?? id;++/** The agents Home's picker offers: only the ones on this computer, in the picker's order. */+export const offeredAgents = (installed: ReadonlySet<string>) => TASK_AGENTS.filter((a) => installed.has(a.id));++/**+ * Who does a job: the person's pick, else the one they use most, else the+ * first one on this computer, each only while it is on this computer. Null+ * when none is: Home offers to install Claude Code instead of a name it+ * can't run.+ */+export function chooseAgent(picked: string | null, mostUsed: string | null, installed: ReadonlySet<string>): string | null {+ for (const id of [picked, mostUsed]) if (id && installed.has(id)) return id;+ return offeredAgents(installed)[0]?.id ?? null;+}++/** Where Claude Code is installed from, for "Install Claude Code". */+export const CLAUDE_CODE_URL = "https://claude.com/product/claude-code";diff --git a/apps/cua-spaces-web/src/components/ask-first/use-installed-agents.ts b/apps/cua-spaces-web/src/components/ask-first/use-installed-agents.tsnew file mode 100644index 0000000000..39e7076fda--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/use-installed-agents.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useEffect, useState } from "react";++import { useAgents, type AgentSetupRow } from "@/bridge";++import { TASK_AGENTS } from "./task-agents";++/**+ * The task agents (harness ids) on this computer, from the agent setup's+ * detection: `installed` there counts the app itself or files it wrote, never+ * a file Cua wrote for it (CUA-3063). Being set up for Cua (`configured`) is+ * not enough. Null until the setup answered; empty when it could not.+ */+export function installedTaskAgents(rows: readonly AgentSetupRow[]): ReadonlySet<string> {+ const found = new Set(rows.filter((r) => r.installed).map((r) => r.agent));+ return new Set(TASK_AGENTS.filter((a) => found.has(a.setupId)).map((a) => a.id));+}++export function useInstalledAgents(): ReadonlySet<string> | null {+ const { agentSetup } = useAgents();+ const [installed, setInstalled] = useState<ReadonlySet<string> | null>(null);+ useEffect(() => {+ let live = true;+ agentSetup()+ .then((rows) => {+ if (live) setInstalled(installedTaskAgents(rows));+ })+ .catch(() => {+ if (live) setInstalled(new Set());+ });+ return () => {+ live = false;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+ return installed;+}diff --git a/apps/cua-spaces-web/src/components/prepare/use-prepare-action.ts b/apps/cua-spaces-web/src/components/prepare/use-prepare-action.tsnew file mode 100644index 0000000000..4979be1256--- /dev/null+++ b/apps/cua-spaces-web/src/components/prepare/use-prepare-action.ts@@ -0,0 +1,19 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useNavigate } from "@tanstack/react-router";++import { usePrepare } from "@/lib/prepare/store";++/** The failed view's "Add a computer" (`prepare::ADD_COMPUTER_ACTION`): this computer can't run Spaces itself. */+export const ADD_COMPUTER_ACTION = "add-computer";++/** What the failed preparing view's button does: "Add a computer" opens it, anything else tries again. */+export function usePrepareAction(): () => void {+ const prep = usePrepare();+ const navigate = useNavigate();+ return () => {+ if (prep.view?.action?.id === ADD_COMPUTER_ACTION) void navigate({ to: "/machines", search: { add: true } });+ else prep.driver?.retry();+ };+}diff --git a/apps/cua-spaces-web/src/lib/prepare/__tests__/home-request.test.ts b/apps/cua-spaces-web/src/lib/prepare/__tests__/home-request.test.tsnew file mode 100644index 0000000000..1437add659--- /dev/null+++ b/apps/cua-spaces-web/src/lib/prepare/__tests__/home-request.test.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// CUA-3193: the new setup ended on "Preparing stopped: config.image: string". It made the first+// Space before this machine's offers were read, so the create went out without an image and the+// host refused it with its argument check. The create now comes from the wizard's Linux offer.++import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";+import type { WizardEnv } from "@/bridge/contracts/new-space";+import { firstSpaceOffers, type FirstSpaceOffer } from "@/bridge/new-space";++import { homeCreateRequest, NO_LINUX_OFFER } from "../home-request";++/** The first-run parity fixture's Mac (arm64, 200 GB free, Lume and the built-in Linux runtime). */+const MAC = JSON.parse(readFileSync(join(import.meta.dirname, "../../../../../../libs/cua/crates/cua-spaces-app-core/parity/first-run.json"), "utf8")).machineBase as WizardEnv;++describe("the new setup's first Space create", () => {+ it("never goes out without an image", () => {+ expect(() => homeCreateRequest([], "home-claude-code")).toThrow(NO_LINUX_OFFER);+ const blocked = { id: "linux", os: "linux", image: "ghcr.io/trycua/linux:24.04-slim", name: "Ubuntu", size: null, time: "", blocked: "Not enough free disk space.", args: { image: "ghcr.io/trycua/linux:24.04-slim", on: "local", kind: "container", runtime: "auto", spacesd: true } } as FirstSpaceOffer;+ expect(() => homeCreateRequest([blocked], "home-claude-code")).toThrow("Not enough free disk space.");+ // The plain words, never the host's argument check.+ expect(NO_LINUX_OFFER).not.toMatch(/config|image:|string/);+ });++ it.skipIf(!wasmBuilt)("is the wizard's Linux offer for this machine, under the home's name", async () => {+ const core = await testCore();+ const offers = firstSpaceOffers(core, MAC, "macos");+ const linux = offers.find((o) => o.id === "linux")!;+ expect(linux.blocked).toBeNull();+ const req = homeCreateRequest(offers, "home-claude-code");+ expect(typeof req.image).toBe("string");+ expect(req.image).toBe(linux.args.image);+ expect(req.image).toMatch(/^ghcr\.io\/trycua\/linux:/);+ expect(req).toMatchObject({ name: "home-claude-code", os: "linux", kind: linux.args.kind, runtime: linux.args.runtime, on: "local" });+ });+});diff --git a/apps/cua-spaces-web/src/lib/prepare/home-request.ts b/apps/cua-spaces-web/src/lib/prepare/home-request.tsnew file mode 100644index 0000000000..1246cb74b6--- /dev/null+++ b/apps/cua-spaces-web/src/lib/prepare/home-request.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The create the new setup sends for the first Space: the wizard's own+ * Linux offer for this machine (`wizard.firstSpaceOffers`), under the home's+ * fixed name. Kept free of React and the `@/` alias so the desktop app's+ * tests run it against the host's real `spaces.create`.+ */++import type { SpaceCreateConfig } from "../../bridge/contracts/host";+import type { CreateSpaceArgs } from "../../bridge/contracts/new-space";++/** What this reads of a first-Space offer (`bridge/new-space.ts`'s `FirstSpaceOffer`). */+export interface HomeOffer {+ id: string;+ os: string;+ image: string;+ blocked: string | null;+ args: CreateSpaceArgs;+}++/** The page's create request (`bridge/store.ts`'s `CreateSpaceRequest`). */+export type HomeCreateRequest = SpaceCreateConfig & { os: "linux" };++/** The words preparing stops with when this machine has no Linux Space to offer. */+export const NO_LINUX_OFFER = "This computer can't make a Linux Space right now. Open New Space to see why.";++/**+ * The home's create request from the offers, or an error in plain words.+ * Never a request without an image: the host refuses that one with its+ * internal argument check, which is what a person used to see.+ */+export function homeCreateRequest(offers: readonly HomeOffer[], name: string): HomeCreateRequest {+ const linux = offers.find((o) => o.id === "linux") ?? offers.find((o) => o.os === "linux");+ if (!linux) throw new Error(NO_LINUX_OFFER);+ if (linux.blocked) throw new Error(linux.blocked);+ const image = linux.args.image || linux.image;+ if (!image) throw new Error(NO_LINUX_OFFER);+ return { ...linux.args, image, os: "linux", name };+}diff --git a/apps/cua-spaces-web/src/lib/prepare/use-prepare.tsx b/apps/cua-spaces-web/src/lib/prepare/use-prepare.tsxindex e172d8e586..eeab874824 100644--- a/apps/cua-spaces-web/src/lib/prepare/use-prepare.tsx+++ b/apps/cua-spaces-web/src/lib/prepare/use-prepare.tsx@@ -10,10 +10,13 @@ import { setPrepareSink } from "@/components/space-thread/queued";import { updateAskTask } from "@/lib/ask-first";import { spaceState } from "@/lib/spaces";+import { useInstalledAgents } from "@/components/ask-first/use-installed-agents";+import { localPrepareStorage, PrepareDriver, type PrepareEnv } from "./driver";+import { homeCreateRequest } from "./home-request";import { getDriver, markResumed, resumedThisLoad, setDriver, usePrepare } from "./store";-/** The coding app the first Space is for until the person picks another. */+/** The coding app the first Space is for when it is on this computer: the first installed one otherwise. */export const DEFAULT_HARNESS = "claude-code";/** How long the agent's session may take to open before preparing says so. */@@ -37,8 +40,13 @@ export function PrepareRoot(): null {const { core, data: host } = useBridge();const spacesHook = useSpaces();const { data: spaces, createSpace, startSpace } = spacesHook;- const { offers } = useFirstSpaceOffers();+ const { offers, known } = useFirstSpaceOffers();+ const latestOffers = useRef(offers);+ latestOffers.current = offers;const on = useNewOnboarding();+ // Only an agent found on this computer is prepared: one Cua only wrote files for has no sign-in to bring.+ const installed = useInstalledAgents();+ const harness = installed === null ? null : installed.has(DEFAULT_HARNESS) ? DEFAULT_HARNESS : (installed.values().next().value ?? null);const { summonInput, summonIn, canSummon } = useSummonIn();const latestSpaces = useRef(spaces);latestSpaces.current = spaces;@@ -71,10 +79,9 @@ export function PrepareRoot(): null {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);+ createHome: async ({ harness: forApp, pendingId }) => {+ // The same Linux Space Home makes for a job (the wizard's own offer for this machine), under the fixed name.+ const space = await createSpace(homeCreateRequest(latestOffers.current, homeNameOf(forApp)), pendingId);return space.id;},attachAgent: async ({ spaceId, harness, model }) => {@@ -121,7 +128,8 @@ export function PrepareRoot(): null {// eslint-disable-next-line react-hooks/exhaustive-deps}, [core]);- const ready = Boolean(core && host && spaces && on);+ // The offers must be read first: before that there is no image to make the home from.+ const ready = Boolean(core && host && spaces && on && known);// Start at launch; a saved record resumes once.const driverNow = usePrepare().driver;@@ -134,11 +142,11 @@ export function PrepareRoot(): null {markResumed();d.resume();}- } else {+ } else if (harness) {markResumed();- d.start(DEFAULT_HARNESS);+ d.start(harness);}- }, [ready, driverNow]);+ }, [ready, driverNow, harness]);// The home's composer sends here while it is being made: kept, then delivered once.useEffect(() => {diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsxindex caef7bbe4c..0ea4a25efc 100644--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx@@ -25,6 +25,7 @@ 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 { usePrepareAction } from "@/components/prepare/use-prepare-action";import { useAskTasks } from "@/lib/ask-first";import { ConfirmDialog } from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";@@ -114,6 +115,7 @@ function SpaceDetailPage() {const tasks = useAskTasks();// The first Space being prepared while the person was in onboarding: its page shows what is happening.const prep = usePrepare();+ const onPrepareAction = usePrepareAction();// 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@@ -325,7 +327,7 @@ function SpaceDetailPage() {</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 preparePanel = preparing ? <PreparePanel view={preparing} onRetry={onPrepareAction} /> : null;const surface = (className: string, windowId?: string | null, windowName?: string | null, interactive = !viewOnly) => (<StreamSurfaceinteractive={interactive}diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-retry.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-retry.jsonindex 76654cd0d7..914ce92aa0 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-retry.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-retry.json@@ -246,7 +246,7 @@],"fix": "It failed twice for the same reason. Run `cua doctor` in Terminal to check what's wrong, or see the details. [Copy cua doctor: copy-command cua doctor]","id": "pending:1",- "previewText": "local runtime: the built-in Linux runtime did not start: exiting, status 1",+ "previewText": "The built-in Linux runtime did not start: exiting, status 1","progress": null,"progressText": null}@@ -256,7 +256,7 @@],"pending": true,"rows": [- "os-linux Box [spaces.status.failed] - local runtime: the built-in Linux runtime did not start: exiting, status 1"+ "os-linux Box [spaces.status.failed] - The built-in Linux runtime did not start: exiting, status 1"],"tiles": ["os-linux Box, Linux, This Mac, Failed - Failed"diff --git a/libs/cua/crates/cua-spaces-app-core/src/errors.rs b/libs/cua/crates/cua-spaces-app-core/src/errors.rsindex 1cff9b7df5..7d08b757a5 100644--- a/libs/cua/crates/cua-spaces-app-core/src/errors.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/errors.rs@@ -3,7 +3,9 @@//! Error text the shells show. An action that fails because the local//! `cua daemon` does not answer says so in plain words, never as a raw-//! transport error ("transport: Connection refused (os error 61)").+//! transport error ("transport: Connection refused (os error 61)"), and+//! the SDK's internal error tags ("local runtime: ", "[local] ") never reach+//! a person./// What a failed action shows when the Cua daemon is not running. The SDK's/// `CuaError::DaemonNotRunning` carries the same sentence.@@ -15,13 +17,46 @@ pub const DAEMON_NOT_RUNNING: &str =/// is `raw`, trimmed. Only the daemon's own transport errors match (the/// SDK's `transport: <io error>` and `daemon transport: ...` forms and the/// daemon client's messages); a Space's own `transport error: ...` or a-/// bare "connection refused" from a remote machine stays as it is.+/// bare "connection refused" from a remote machine stays as it is. The+/// SDK's error tags in front ([`INTERNAL_TAGS`]) are dropped and the+/// sentence starts with a capital, so "local runtime: This Mac can't run+/// Spaces itself, ..." reads as the sentence it carries (CUA-3193).pub fn plain_error(raw: &str) -> String {let t = raw.trim();if is_daemon_unreachable(t) {- DAEMON_NOT_RUNNING.to_string()- } else {- t.to_string()+ return DAEMON_NOT_RUNNING.to_string();+ }+ let rest = without_tags(t);+ if rest.len() == t.len() {+ return t.to_string();+ }+ let mut chars = rest.chars();+ match chars.next() {+ Some(first) => first.to_uppercase().chain(chars).collect(),+ None => t.to_string(),+ }+}++/// The SDK's error tags: `CuaError::Runtime`'s `local runtime: ` and a local+/// backend's `[local] `. Internal words, never what a person reads.+pub const INTERNAL_TAGS: &[&str] = &["local runtime: ", "[local] "];++/// `t` without the error tags in front of it (in any order, each once or more).+fn without_tags(t: &str) -> &str {+ let mut rest = t;+ loop {+ let before = rest.len();+ for tag in INTERNAL_TAGS {+ if rest+ .get(..tag.len())+ .is_some_and(|h| h.eq_ignore_ascii_case(tag))+ {+ rest = rest[tag.len()..].trim_start();+ }+ }+ if rest.len() == before {+ return rest;+ }}}@@ -80,4 +115,28 @@ mod tests {}assert_eq!(plain_error(" timed out \n"), "timed out");}++ /// CUA-3193: the "can't run Spaces" step read "local runtime: This Mac ...".+ #[test]+ fn the_sdk_error_tags_never_reach_a_person() {+ let mac = cua_create_failure::preflight::MAC_UNSUPPORTED;+ for raw in [+ format!("local runtime: {mac}"),+ format!("local runtime: [local] {mac}"),+ format!(" [local] {mac}"),+ ] {+ assert_eq!(plain_error(&raw), mac, "{raw}");+ }+ assert_eq!(+ plain_error(+ "local runtime: the built-in Linux runtime did not start: exiting, status 1"+ ),+ "The built-in Linux runtime did not start: exiting, status 1"+ );+ // A tag with nothing after it keeps its words rather than showing nothing.+ assert_eq!(plain_error("local runtime: "), "local runtime:");+ for tag in INTERNAL_TAGS {+ assert!(!plain_error(&format!("{tag}{tag}no socket")).contains(tag.trim()));+ }+ }}diff --git a/libs/cua/crates/cua-spaces-app-core/src/prepare.rs b/libs/cua/crates/cua-spaces-app-core/src/prepare.rsindex 80e3d597d0..a42a2ea1a3 100644--- a/libs/cua/crates/cua-spaces-app-core/src/prepare.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/prepare.rs@@ -47,6 +47,7 @@//! "send to the agent session" and "send to the first model token" are//! measured the same way everywhere ([`metrics`]).+use cua_create_failure::preflight::IssueKind;use serde::{Deserialize, Serialize};/// The state's schema; a state of another schema is dropped (preparing starts over).@@ -610,7 +611,9 @@ pub fn reduce(state: &State, action: &Action) -> Reduced {network: false,message: message.clone(),});- if s.failures < OTHER_ATTEMPTS {+ // A refusal the app's own check words (this Mac can't run virtual computers, no+ // engine, no room) does not pass by waiting: it stops at once with its next step.+ if s.failures < OTHER_ATTEMPTS && lasting(message).is_none() {s.rec_mut(step).state = StepState::Waiting;let at = now_ms + backoff(s.failures);s.retry_at_ms = Some(at);@@ -864,6 +867,16 @@ pub struct View {pub action: Option<ActionView>,}+/// The failed view's button when this computer can't run Spaces itself:+/// the app opens "Add a computer".+pub const ADD_COMPUTER_ACTION: &str = "add-computer";++/// The app's own check's refusal `message` is, if it is one (its fixed+/// sentences: [`IssueKind::of_text`]). Waiting does not fix any of them.+fn lasting(message: &str) -> Option<IssueKind> {+ IssueKind::of_text(&crate::errors::plain_error(message))+}+/// A button.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct ActionView {@@ -1024,10 +1037,11 @@ pub fn view(s: &State) -> View {Some("Your home Space is running".into()),)} else if failed {+ // The host's words through the create's own wording: never the SDK's error tags.let why = s.trouble.as_ref()- .map(|t| t.message.trim())+ .map(|t| crate::spaces::creating::failure_text(&t.message, None, None, false)).filter(|m| !m.is_empty()).map(|m| format!(": {m}")).unwrap_or_default();@@ -1051,9 +1065,24 @@ pub fn view(s: &State) -> View {"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(),+ let can_not_run = s+ .trouble+ .as_ref()+ .and_then(|t| lasting(&t.message))+ .is_some_and(|k| k == IssueKind::VirtualizationUnavailable);+ let action = (phase == "failed").then(|| {+ if can_not_run {+ // This computer can't run Spaces itself: the way on is another computer.+ ActionView {+ id: ADD_COMPUTER_ACTION.into(),+ label: "Add a computer".into(),+ }+ } else {+ ActionView {+ id: "retry".into(),+ label: "Try again".into(),+ }+ }});View {phase: phase.into(),@@ -1376,6 +1405,43 @@ mod tests {assert_eq!(view(&on.state).phase, "preparing");}+ #[test]+ /// CUA-3193: a Mac that can't run Spaces stopped on "Preparing stopped: local runtime: ...",+ /// after waiting to try again, with Try again as the only way on.+ fn a_mac_that_cannot_run_spaces_stops_at_once_in_plain_words() {+ let mac = cua_create_failure::preflight::MAC_UNSUPPORTED;+ for raw in [+ format!("local runtime: {mac}"),+ format!("local runtime: [local] {mac}"),+ ] {+ let r = go(+ &start(),+ Action::Failed {+ now_ms: 1,+ message: raw.clone(),+ network: false,+ },+ );+ assert_eq!(r.state.runtime.state, StepState::Failed, "{raw}");+ assert!(+ r.effects+ .iter()+ .all(|e| !matches!(e, Effect::WakeAt { .. }))+ );+ let v = view(&r.state);+ let line = v.line.clone().unwrap();+ assert_eq!(line, format!("Preparing stopped: {mac}"));+ for internal in crate::errors::INTERNAL_TAGS {+ assert!(!line.contains(internal.trim()), "{line}");+ }+ let action = v.action.unwrap();+ assert_eq!(+ (action.id.as_str(), action.label.as_str()),+ (ADD_COMPUTER_ACTION, "Add a computer")+ );+ }+ }+#[test]fn other_failures_retry_once_then_offer_try_again() {let s = start();