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
Spaces Connected apps: one switch per coding app, new apps set up with Undo (CUA-2315) (#5984)
cua-agents[bot]4970dc74b430
diff --git a/apps/cua-spaces-desktop/src/model/agent-backups.ts b/apps/cua-spaces-desktop/src/model/agent-backups.tsnew file mode 100644index 0000000000..f2bd5001e0--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/agent-backups.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Agent setup keeps a copy of a config file the first time it edits it+// (`<file>.cua-backup-<time>`). Once Cua is taken out of an app's settings the+// copy has no use, and it only clutters the person's home folder, so removal+// deletes them. Only files Cua named this way, next to a config file Cua edits.+import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import * as os from "node:os";+import * as path from "node:path";++/** `config.toml.cua-backup-20261025T101500Z`: the base name, then the marker and a time. */+const BACKUP = /\.cua-backup-[0-9A-Za-z._-]+$/;++/** Deletes the backups Cua made of `config`; the files removed. */+export function removeBackups(config: string): string[] {+ const dir = path.dirname(config);+ const base = path.basename(config);+ let names: string[];+ try {+ names = readdirSync(dir);+ } catch {+ return [];+ }+ const gone: string[] = [];+ for (const name of names) {+ if (!name.startsWith(`${base}.cua-backup-`) || !BACKUP.test(name)) continue;+ try {+ rmSync(path.join(dir, name), { force: true });+ gone.push(path.join(dir, name));+ } catch {+ // A file we can't delete stays; nothing depends on it.+ }+ }+ return gone;+}++/**+ * The one-time sweep of the leftovers earlier versions left (every config file+ * Cua edits, whether or not Cua is still in it): done once per install, kept+ * in a marker file in the cua folder.+ */+export function sweepBackupsOnce(configs: string[], home: string = os.homedir()): string[] {+ const marker = path.join(home, ".cua", "agent-backups-swept");+ if (existsSync(marker)) return [];+ const gone = configs.flatMap(removeBackups);+ try {+ mkdirSync(path.dirname(marker), { recursive: true });+ writeFileSync(marker, new Date().toISOString());+ } catch {+ // The sweep runs again next time; it only deletes what is named above.+ }+ return gone;+}diff --git a/apps/cua-spaces-desktop/src/model/agents.ts b/apps/cua-spaces-desktop/src/model/agents.tsindex 3922b66e53..d09d2f64a7 100644--- a/apps/cua-spaces-desktop/src/model/agents.ts+++ b/apps/cua-spaces-desktop/src/model/agents.ts@@ -25,6 +25,7 @@ import type {AppAgentsView,AppSpaceAgentRun,} from "../native/generated/index";+import { removeBackups, sweepBackupsOnce } from "./agent-backups";import { ToolError } from "./backend";import { words } from "./errors";import { NotStarted, type LiveGate, type LiveServices } from "./pending";@@ -378,6 +379,8 @@ export interface AgentSetupRunning {remove(agents: string[]): Promise<AppAgentSetupOutcomeInput[]>;/** Starts `agent`'s own sign-in on this computer (`codex login`); returns once it runs. */signIn(agent: string): Promise<void>;+ /** Deletes the config copies (`.cua-backup-*`) earlier versions left, once per install. */+ sweepLeftovers?(): void;}/**@@ -421,12 +424,28 @@ export class LiveAgentSetup implements AgentSetupRunning {}async remove(agents: string[]): Promise<AppAgentSetupOutcomeInput[]> {- return this.outcomes(await this.inner.remove(agents, true, true));+ const configs = this.configsOf(agents);+ const out = this.outcomes(await this.inner.remove(agents, true, true));+ // The copies setup made of each config file are no use once Cua is out of it.+ for (const c of configs) removeBackups(c);+ return out;+ }++ /** The config files Cua edits for `agents` (every agent: none named). */+ configsOf(agents?: string[]): string[] {+ return this.inner+ .detect()+ .filter((i) => !agents || agents.includes(i.id))+ .flatMap((i) => (i.mcpConfig ? [i.mcpConfig] : []));}async signIn(agent: string): Promise<void> {this.inner.signIn(agent);}++ sweepLeftovers(): void {+ sweepBackupsOnce(this.configsOf());+ }}/** The coding agents' setup until the SDK is in. */@@ -451,6 +470,7 @@ export class PendingAgentSetup implements AgentSetupRunning {setUpCuaDriver = async (agents: string[]) => (await this.s()).setUpCuaDriver(agents);remove = async (agents: string[]) => (await this.s()).remove(agents);signIn = async (agent: string) => (await this.s()).signIn(agent);+ sweepLeftovers = () => this.gate.current?.agentSetup?.sweepLeftovers?.();}/** The Settings rows for the coding agents, and the changes made to them (the SwiftUI app's `AppModel.agentRows`, `configureAllAgents`, `agentAction`). */@@ -462,6 +482,7 @@ export class CodingAgents {pending: string[] = [];/** Why the last change failed, per agent. */private readonly failures = new Map<string, string>();+ private swept = false;onChange: () => void = () => {};constructor(@@ -476,6 +497,15 @@ export class CodingAgents {return;}const rows = this.native.appAgentSettingsRows(await this.setup.statuses(), this.setup.skillsTotal());+ // Once per run: the copies of config files that setup left behind in earlier versions.+ if (!this.swept) {+ this.swept = true;+ try {+ this.setup.sweepLeftovers?.();+ } catch {+ // Clutter, not a failure.+ }+ }this.rows = rows.map((r) => {const why = this.failures.get(r.agent);return why === undefined ? r : { ...r, configured: false, detail: why };diff --git a/apps/cua-spaces-desktop/test/agent-backups.test.ts b/apps/cua-spaces-desktop/test/agent-backups.test.tsnew file mode 100644index 0000000000..ecabd7979c--- /dev/null+++ b/apps/cua-spaces-desktop/test/agent-backups.test.ts@@ -0,0 +1,50 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Removing Cua from an app also deletes the `.cua-backup-*` copies setup made+// of its config, and only those.+import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import * as os from "node:os";+import * as path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { removeBackups, sweepBackupsOnce } from "../src/model/agent-backups";++const dirs: string[] = [];+const tmp = () => {+ const d = mkdtempSync(path.join(os.tmpdir(), "cua-backups-"));+ dirs.push(d);+ return d;+};+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++describe("removeBackups", () => {+ it("deletes Cua's copies of that config, and nothing else", () => {+ const d = tmp();+ const config = path.join(d, "config.toml");+ for (const f of ["config.toml", "config.toml.cua-backup-20261025T101500Z", "config.toml.cua-backup-1", "other.toml.cua-backup-1", "config.toml.bak", "config.toml.cua-backup"]) writeFileSync(path.join(d, f), "x");+ const gone = removeBackups(config);+ expect(gone.map((g) => path.basename(g)).sort()).toEqual(["config.toml.cua-backup-1", "config.toml.cua-backup-20261025T101500Z"]);+ expect(readdirSync(d).sort()).toEqual(["config.toml", "config.toml.bak", "config.toml.cua-backup", "other.toml.cua-backup-1"]);+ });++ it("is quiet when the folder is gone", () => {+ expect(removeBackups(path.join(tmp(), "nope", "config.json"))).toEqual([]);+ });+});++describe("sweepBackupsOnce", () => {+ it("clears the leftovers once per install", () => {+ const home = tmp();+ const config = path.join(home, ".claude.json");+ writeFileSync(`${config}.cua-backup-1`, "x");+ expect(sweepBackupsOnce([config], home)).toHaveLength(1);+ // A backup made after the sweep is left alone: the marker says it ran.+ writeFileSync(`${config}.cua-backup-2`, "x");+ expect(sweepBackupsOnce([config], home)).toEqual([]);+ expect(readdirSync(home)).toContain(".claude.json.cua-backup-2");+ mkdirSync(path.join(home, ".cua"), { recursive: true });+ });+});diff --git a/apps/cua-spaces-web/e2e/volume.ts b/apps/cua-spaces-web/e2e/volume.tsindex 8a78f1967f..d2abb306f8 100644--- a/apps/cua-spaces-web/e2e/volume.ts+++ b/apps/cua-spaces-web/e2e/volume.ts@@ -164,6 +164,12 @@ async function checkOnboardingDrive(page: Page, cps: ParityCheckpoint[]): Promisasync function checkDriverCard(page: Page, cps: ParityCheckpoint[]): Promise<number> {let checked = 0;+ // Background computer use sits behind "Show all" on Settings, Connected apps,+ // which draws once the coding apps have loaded.+ const showAll = page.locator("[data-connected-show-all]");+ await expect(showAll).toBeVisible();+ if ((await showAll.getAttribute("aria-expanded")) !== "true") await showAll.click();+ await expect(showAll).toHaveAttribute("aria-expanded", "true");const card = page.locator("[data-driver-card]").first();for (const c of of(cps, "driver-copy").slice(0, 1)) {await expect(card.locator("[data-driver-label]")).toHaveText(c.agentsDriver);diff --git a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsxindex a384380147..42ce25855b 100644--- a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx@@ -1,27 +1,29 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-// Settings, AI agents, as the SwiftUI app's: each coding agent on this-// machine with what cua set up for it and Configure or Remove, "Configure-// all detected agents" in the header (the core's `agents` section over the-// host's `agents.setup`); the cua-driver card follows in its own group.+// Settings, Connected apps: each coding app on this computer with one+// switch (`agents.setup`, `agents.configure` and the host's own row press),+// "Set up new apps automatically", and the sync that sets up a newly+// installed app with a notice and Undo.import { createMemoryHistory, createRootRoute, createRouter, RouterProvider } from "@tanstack/react-router";-import { cleanup, fireEvent, render, waitFor, within } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";import { BridgeProvider } from "@/bridge";import { createDemoAdapter } from "@/bridge/adapters/demo";import { noCore, wasmBuilt } from "@/bridge/__tests__/testCore";import { ConnectAgentDialog } from "@/components/agents/connect-dialog";import { RunAgentDialog } from "@/components/agents/run-agent-dialog";+import { connectedAppsState, resetConnectedAppsState, setConnectedAppsState } from "@/hooks/use-connected-apps";import { mountApp, stubBrowserApis } from "./app-harness";-afterEach(cleanup);+afterEach(() => {+ cleanup();+ localStorage.clear();+ resetConnectedAppsState();+});stubBrowserApis();-const section = () => document.querySelector<HTMLElement>('[data-settings-section="agents"]');-const row = (agent: string) => section()?.querySelector<HTMLElement>(`[data-setting-row="agent:${agent}"]`) ?? null;-describe("configured agents without binary evidence", () => {it.each(["connect", "run"])("shows a configured agent as ready in the %s dialog", async (dialog) => {const demo = createDemoAdapter({ latencyMs: 0 });@@ -49,26 +51,92 @@ describe("configured agents without binary evidence", () => {});});-describe.skipIf(!wasmBuilt)("Settings, AI agents", () => {- it("lists each detected agent with its status, configures one, removes it, and configures all", { timeout: 20_000 }, async () => {+const app = (id: string) => document.querySelector<HTMLElement>(`[data-connected-app="${id}"]`);+const switchOf = (id: string) => within(app(id)!).getByRole("switch");++describe.skipIf(!wasmBuilt)("Settings, Connected apps", () => {+ it("lists the coding apps on this computer with one switch each, and the rest behind Show all", { timeout: 20_000 }, async () => {await mountApp("/settings/connected-apps", { failsCreates: false, listsGhost: false });- await waitFor(() => expect(row("hermes")).not.toBeNull(), { timeout: 8000 });- const s = section()!;- expect(within(s).getByText("AI agents")).toBeTruthy();- expect(within(row("claude-code")!).getByText("Claude Code")).toBeTruthy();- expect(within(row("hermes")!).getByText("Not set up")).toBeTruthy();- // Not installed: no button, greyed.- expect(row("gemini-cli")!.getAttribute("data-enabled")).toBe("false");+ await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });+ expect(within(app("claude-code")!).getByText("Claude Code")).toBeTruthy();+ expect(switchOf("claude-code").getAttribute("aria-checked")).toBe("true");+ expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false");+ // No file paths, skill counts or "Not installed" rows until Show all.+ expect(document.body.textContent).not.toMatch(/\.claude\.json|Not installed|skills/);+ expect(document.querySelector('[data-connected-missing="gemini-cli"]')).toBeNull();+ fireEvent.click(document.querySelector("[data-connected-show-all]")!);+ await waitFor(() => expect(document.querySelector('[data-connected-missing="gemini-cli"]')).not.toBeNull());+ expect(app("claude-code")!.textContent).toContain("~/.claude.json");+ expect(document.querySelector("[data-connected-by-hand]")).not.toBeNull();+ });- fireEvent.click(within(row("hermes")!).getByRole("button", { name: "Configure" }));- await waitFor(() => expect(within(row("hermes")!).getByRole("button", { name: "Remove" })).toBeTruthy());- expect(within(row("hermes")!).getByText("Skills and MCP server set up")).toBeTruthy();- fireEvent.click(within(row("hermes")!).getByRole("button", { name: "Remove" }));- await waitFor(() => expect(within(row("hermes")!).getByRole("button", { name: "Configure" })).toBeTruthy());+ it("switches one app on and off, remembers an app turned off, and offers Undo", { timeout: 20_000 }, async () => {+ await mountApp("/settings/connected-apps", { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });+ fireEvent.click(switchOf("hermes"));+ await waitFor(() => expect(switchOf("hermes").getAttribute("aria-checked")).toBe("true"));+ fireEvent.click(switchOf("hermes"));+ await waitFor(() => expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false"));+ expect(connectedAppsState().off).toContain("hermes");+ // The notice says what happened and how to take it back.+ const undo = await screen.findByRole("button", { name: "Undo" });+ expect(document.body.textContent).toContain("Hermes turned off");+ expect(document.body.textContent).toContain("Cua took itself out of Hermes's settings");+ fireEvent.click(undo);+ await waitFor(() => expect(switchOf("hermes").getAttribute("aria-checked")).toBe("true"));+ expect(connectedAppsState().off).not.toContain("hermes");+ });- fireEvent.click(within(s).getByRole("button", { name: "Configure all detected agents" }));- await waitFor(() => {- for (const a of ["hermes", "openclaw"]) expect(within(row(a)!).getByRole("button", { name: "Remove" })).toBeTruthy();+ it("says why a setup failed in plain words, and offers Try again and the file to edit by hand", { timeout: 20_000 }, async () => {+ await mountApp("/settings/connected-apps", { failsCreates: false, listsGhost: false, demo: { agentsReadOnly: ["hermes"] } });+ await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });+ fireEvent.click(switchOf("hermes"));+ const failure = await waitFor(() => {+ const f = document.querySelector<HTMLElement>('[data-connected-failure="hermes"]');+ expect(f).not.toBeNull();+ return f!;});+ expect(failure.textContent).toContain("Couldn't set up Hermes. Cua can't change this file because it is read-only or belongs to another user.");+ expect(document.body.textContent).not.toMatch(/os error/);+ expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false");+ expect(within(failure).getByRole("button", { name: "Try again" })).toBeTruthy();+ fireEvent.click(within(failure).getByRole("button", { name: "Add it by hand" }));+ expect(failure.textContent).toContain("mcp_servers:");+ expect(failure.textContent).toContain("Paste this into the file, then restart Hermes.");+ });++ it("keeps Set up new apps automatically in the saved state", { timeout: 20_000 }, async () => {+ await mountApp("/settings/connected-apps", { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(document.querySelector("[data-connected-auto]")).not.toBeNull(), { timeout: 8000 });+ expect(connectedAppsState().auto).toBeNull();+ fireEvent.click(document.querySelector("[data-connected-auto]")!);+ await waitFor(() => expect(connectedAppsState().auto).toBe(true));+ expect(JSON.parse(localStorage.getItem("cua.connectedApps")!).auto).toBe(true);+ });+});++describe.skipIf(!wasmBuilt)("a newly installed coding app", () => {+ const seen = ["claude-code", "codex", "openclaw", "cursor"];++ it("is set up with a notice and Undo when the person said yes", { timeout: 20_000 }, async () => {+ setConnectedAppsState({ known: seen, off: [], auto: true });+ await mountApp("/spaces", { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(document.body.textContent).toContain("Hermes can now use Cua"), { timeout: 8000 });+ expect(document.body.textContent).toContain("Restart Hermes to use it.");+ expect(connectedAppsState().known).toContain("hermes");+ fireEvent.click(await screen.findByRole("button", { name: "Undo" }));+ await waitFor(() => expect(connectedAppsState().off).toContain("hermes"));+ });++ it("is left alone without a yes, and when it was turned off", { timeout: 20_000 }, async () => {+ for (const state of [{ known: seen, off: [], auto: null }, { known: seen, off: ["hermes"], auto: true }]) {+ cleanup();+ setConnectedAppsState(state);+ const { router } = await mountApp("/settings/connected-apps", { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(app("hermes")).not.toBeNull(), { timeout: 8000 });+ await router.load();+ expect(switchOf("hermes").getAttribute("aria-checked")).toBe("false");+ expect(document.body.textContent).not.toContain("can now use Cua");+ }});});diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 4ea2c49eb7..bbbe55d4d6 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -87,6 +87,8 @@ export interface DemoOptions {usage?: "idle" | "warn" | "limit" | "pro" | "teams";/** Which agents are on this computer (`?demo=agents-none`, `?demo=agents-codex`); all of them by default. `unset`: all found, none set up for Cua yet, without the first-run onboarding. */agents?: "none" | "codex" | "unset";+ /** Coding agents whose config file Cua can't write (setup fails with a permission error), by id. */+ agentsReadOnly?: string[];/** This Mac's free disk: `low` (`?demo=low-disk`) or `full` (`?demo=disk-full`). */disk?: "low" | "full";/** The machine the demo runs on: a Mac on Apple silicon unless set (the@@ -119,6 +121,7 @@ const DEMO_NOTES = "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3* `?demo=empty` (no Spaces yet), `?demo=keychain` (the startup screen),* `?demo=mac-host` (New Space options and the Keyvault's Settings rows in the* SwiftUI host's shape), `?demo=unenrolled` (this device not enrolled),+ * `?demo=agents-readonly` (Cua can't write Hermes's config),* `?demo=update-ready` (an update is downloaded), `?demo=update-downloading`,* and `?demo=low-disk` / `?demo=disk-full` (This Mac almost out of space). */export function demoOptionsFromSearch(search: string): DemoOptions {@@ -138,6 +141,8 @@ export function demoOptionsFromSearch(search: string): DemoOptions {unenrolled: flags.has("unenrolled"),usage: (["idle", "warn", "limit", "pro", "teams"] as const).find((u) => flags.has(`usage-${u}`)),agents: (["none", "codex"] as const).find((a) => flags.has(`agents-${a}`)),+ // `?demo=agents-readonly`: Hermes's config file can't be written, so setting it up fails.+ ...(flags.has("agents-readonly") ? { agentsReadOnly: ["hermes"] } : {}),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,@@ -193,6 +198,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reagents: demoPersistentAgents(now()),// A named allowance is for showing the prompts, which wait for no agent run.runs: options.usage ? [] : demoRunRecords(now()),+ readOnlyAgents: options.agentsReadOnly ?? [],agentSetup: demoAgentSetup(options.onboarded === false || options.agents === "unset", options.agents === "none" ? [] : options.agents === "codex" ? ["codex"] : null),platform: options.platform ?? MAC_DEMO_PLATFORM,paired: [],@@ -594,7 +600,11 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reawait wait(step);const wanted = (r: AgentSetupRow) => r.installed && (agents === null || agents.includes(r.agent));state.agentSetup = state.agentSetup.map((r) =>- wanted(r) ? { ...r, configured: true, skillsInstalled: r.skillsTotal, detail: "Skills and MCP server set up" } : r,+ wanted(r)+ ? state.readOnlyAgents.includes(r.agent)+ ? { ...r, configured: false, skillsInstalled: 0, detail: "Permission denied (os error 13)" }+ : { ...r, configured: true, skillsInstalled: r.skillsTotal, detail: "Skills and MCP server set up" }+ : r,);// The demo plays the agent's first request a little later: a line in this computer's access log.const used = state.agentSetup.find(wanted);@@ -676,6 +686,7 @@ export interface DemoState extends DemoLinksStateField, DemoTelemetryState, Demoagents: PersistentAgent[];runs: DemoRunRecord[];agentSetup: AgentSetupRow[];+ readOnlyAgents: string[];volume: DemoVolumeState;platform: DemoPlatform;/** Machines added with a pairing code ("Add a machine"). */diff --git a/apps/cua-spaces-web/src/components/settings/agents-section.tsx b/apps/cua-spaces-web/src/components/settings/agents-section.tsxdeleted file mode 100644index 1f825a0226..0000000000--- a/apps/cua-spaces-web/src/components/settings/agents-section.tsx+++ /dev/null@@ -1,27 +0,0 @@-// SPDX-License-Identifier: FSL-1.1-MIT-// Copyright (c) 2026 Cua AI, Inc.--import { useSettings, type SettingsSection } from "@/bridge";-import { CoreSettingsSection } from "@/components/settings/core-section";-import { toastError } from "@/components/ui/toast";--/**- * Settings, AI agents, as the SwiftUI app's (the core's `agents` section):- * each coding agent on this machine with what cua set up for it ("skills- * 0/5, MCP not configured") and Configure or Remove, and "Configure all- * detected agents" in the header. The agents are read when this shows- * (`agents.setup`); a row's button is the host's `press` (`settings.choose`),- * the header `agents.configure`; "working…" and "Configuring…" show while- * they run.- */-export function AgentsSettingsSection({ section }: { section: SettingsSection }) {- const { configureAllAgents, pressAgentRow } = useSettings();-- return (- <CoreSettingsSection- section={section}- onHeaderButton={() => void configureAllAgents().catch(toastError("Couldn't configure the agents"))}- onPress={(row) => void pressAgentRow(row.id).catch(toastError(`Couldn't change ${row.label}`))}- />- );-}diff --git a/apps/cua-spaces-web/src/components/settings/coding-apps-section.tsx b/apps/cua-spaces-web/src/components/settings/coding-apps-section.tsxindex be50e4bf2c..3bca42edaa 100644--- a/apps/cua-spaces-web/src/components/settings/coding-apps-section.tsx+++ b/apps/cua-spaces-web/src/components/settings/coding-apps-section.tsx@@ -1,29 +1,169 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { lazy, Suspense } from "react";+import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";+import { lazy, Suspense, useState } from "react";-import { useSettings } from "@/bridge";-import { SettingsGroup } from "@/components/settings-group";-import { AgentsSettingsSection } from "@/components/settings/agents-section";+import type { AgentSetupRow } from "@/bridge";+import { HarnessMark } from "@/components/agents/harness-mark";+import { SettingsGroup, SettingsRow } from "@/components/settings-group";+import { Snippet } from "@/components/settings/snippet";+import { Button } from "@/components/ui/button";+import { Segmented } from "@/components/ui/segmented";+import { Switch } from "@/components/ui/switch";+import { useBridge } from "@/bridge";+import type { ConnectedApps } from "@/hooks/use-connected-apps";+import { BY_HAND, getItUrl, missingApps, shownApps } from "@/lib/connected-apps";+import { cn } from "@/lib/utils";// Its miniature and setup load with the card.const DriverSettingsCard = lazy(() => import("@/components/volume/driver-card").then((m) => ({ default: m.DriverSettingsCard })));/**- * Settings, Connected apps, "Coding apps": the coding apps on this computer- * and whether Cua is set up in each one.+ * Settings, Connected apps, "Coding apps": the coding apps on this computer,+ * one switch each for Cua being set up in it (with Background computer use),+ * and "Set up new apps automatically". "Show all" opens file paths, the apps+ * that aren't installed, and adding Cua by hand.*/-export function CodingAppsSection() {- const section = useSettings().data?.page?.sections.find((s) => s.id === "agents");+export function CodingAppsSection({ apps }: { apps: ConnectedApps }) {+ const { openExternal } = useExternal();+ const [all, setAll] = useState(false);+ const shown = shownApps(apps.rows ?? []);+ const missing = missingApps(apps.rows ?? []);++ if (apps.rows === null) return <div className="mb-8 h-48" aria-busy="true" />;+return (- <>- {section ? <AgentsSettingsSection section={section} /> : null}- <SettingsGroup title="Background computer use">- <Suspense fallback={<div className="h-48" />}>- <DriverSettingsCard />- </Suspense>+ <div data-connected-apps="">+ <SettingsGroup title="Coding apps">+ {shown.length === 0 ? (+ <div className="px-4 py-3 text-[13px] text-muted-foreground" data-connected-none="">+ We didn't find a coding app yet. Install one and Cua will notice.+ </div>+ ) : (+ shown.map((row) => <AppRow key={row.agent} row={row} apps={apps} showPath={all} />)+ )}+ <SettingsRow+ label="Set up new apps automatically"+ description="When you install another coding app, Cua adds itself and tells you."+ htmlFor="connected-auto"+ control={<Switch id="connected-auto" data-connected-auto="" checked={apps.state.auto === true} onCheckedChange={apps.setAuto} />}+ />+ {all && missing.length > 0 ? (+ <>+ <div className="bg-muted/40 px-4 py-3 text-xs text-muted-foreground">Not installed</div>+ {missing.map((row) => {+ const url = getItUrl(row.agent);+ return (+ <div key={row.agent} data-connected-missing={row.agent} className="flex min-h-12 items-center gap-3 px-4 py-2.5 text-muted-foreground">+ <HarnessMark agent={row.agent} name={row.name} />+ <span className="min-w-0 flex-1 text-[13px]">{row.name}</span>+ {url ? (+ <button type="button" className="text-xs hover:text-foreground hover:underline" onClick={() => void openExternal(url)}>+ Get it+ </button>+ ) : null}+ </div>+ );+ })}+ </>+ ) : null}</SettingsGroup>- </>+ <button+ type="button"+ data-connected-show-all=""+ aria-expanded={all}+ onClick={() => setAll(!all)}+ className="-mt-4 mb-8 flex items-center gap-1 px-1 text-[13px] text-muted-foreground outline-none hover:text-foreground focus-visible:text-foreground"+ >+ {all ? "Show fewer" : "Show all"} {all ? <ChevronUpIcon className="size-3.5" /> : <ChevronDownIcon className="size-3.5" />}+ </button>+ {all ? (+ <>+ <ByHand />+ <SettingsGroup title="Background computer use">+ <Suspense fallback={<div className="h-48" />}>+ <DriverSettingsCard />+ </Suspense>+ </SettingsGroup>+ </>+ ) : null}+ </div>+ );+}++function useExternal() {+ const { data } = useBridge();+ return { openExternal: async (url: string) => void (await data?.call("session.openExternal", { url }).catch(() => {})) };+}++function AppRow({ row, apps, showPath }: { row: AgentSetupRow; apps: ConnectedApps; showPath: boolean }) {+ const busy = apps.pending.includes(row.agent);+ const failure = apps.failures[row.agent];+ const on = row.configured && !failure;+ const justOff = !row.configured && apps.state.off.includes(row.agent);+ const note = failure ? null : justOff ? "Off." : showPath && row.mcpConfig ? row.mcpConfig : null;+ return (+ <div data-connected-app={row.agent} data-on={String(on)} data-failed={failure ? "" : undefined} className={cn(failure && "bg-destructive/5")}>+ <div className="flex min-h-12 items-center gap-3 px-4 py-2.5">+ <HarnessMark agent={row.agent} name={row.name} />+ <div className="min-w-0 flex-1">+ <label htmlFor={`app-${row.agent}`} className="block truncate text-[13px]">+ {row.name}+ </label>+ {note ? <p className={cn("mt-0.5 truncate text-xs text-muted-foreground", showPath && !justOff && "font-mono")}>{note}</p> : null}+ </div>+ <Switch id={`app-${row.agent}`} checked={on} disabled={busy} onCheckedChange={(next) => void apps.toggle(row, next)} />+ </div>+ {failure ? <Failure row={row} text={failure} busy={busy} onRetry={() => void apps.toggle(row, true)} /> : null}+ </div>+ );+}++/** A setup that didn't work: why, Try again, and the by-hand snippet for this app. */+function Failure({ row, text, busy, onRetry }: { row: AgentSetupRow; text: string; busy: boolean; onRetry: () => void }) {+ const [hand, setHand] = useState(false);+ const snippet = BY_HAND[row.agent];+ return (+ <div className="px-4 pb-4 pl-14" data-connected-failure={row.agent}>+ {row.mcpConfig ? <p className="-mt-1 mb-1 font-mono text-xs text-muted-foreground">{row.mcpConfig}</p> : null}+ <p className="text-[13px] text-destructive">{text}</p>+ <div className="mt-3 flex gap-2">+ <Button size="sm" variant="outline" disabled={busy} onClick={onRetry}>+ Try again+ </Button>+ {snippet ? (+ <Button size="sm" variant="outline" aria-expanded={hand} onClick={() => setHand(!hand)}>+ Add it by hand+ </Button>+ ) : null}+ </div>+ {hand && snippet ? (+ <>+ <Snippet file={snippet.file} text={snippet.snippet} />+ <p className="mt-2 text-xs text-muted-foreground">Paste this into the file, then restart {row.name}.</p>+ </>+ ) : null}+ </div>+ );+}++/** "Add it by hand": for an app in an unusual place, another computer, or a work laptop where Cua may not edit settings. */+function ByHand() {+ const ids = Object.keys(BY_HAND);+ const [id, setId] = useState(ids[0]!);+ const entry = BY_HAND[id]!;+ const label: Record<string, string> = { "claude-code": "Claude Code", codex: "Codex", hermes: "Hermes", openclaw: "OpenClaw", cursor: "Cursor" };+ return (+ <section className="mb-8" data-connected-by-hand="">+ <h2 className="mb-2 px-1 text-xs font-semibold text-muted-foreground">Add it by hand</h2>+ <div className="rounded-xl border bg-card p-4 shadow-xs">+ <Segmented aria-label="App" value={id} options={ids.map((value) => ({ value, label: label[value] ?? value }))} onValueChange={setId} />+ <Snippet file={entry.file} text={entry.snippet} />+ <p className="mt-2 text-xs text-muted-foreground">+ Use the full path to <code className="font-mono">cua</code> if the app runs without your shell's PATH, as apps opened from the Dock do.+ </p>+ </div>+ </section>);}diff --git a/apps/cua-spaces-web/src/components/settings/snippet.tsx b/apps/cua-spaces-web/src/components/settings/snippet.tsxnew file mode 100644index 0000000000..dd1a581362--- /dev/null+++ b/apps/cua-spaces-web/src/components/settings/snippet.tsx@@ -0,0 +1,29 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { CheckIcon, CopyIcon } from "lucide-react";+import { useState } from "react";++import { Button } from "@/components/ui/button";++/** A file name over text to paste into it, with a Copy button. */+export function Snippet({ file, text }: { file: string; text: string }) {+ const [copied, setCopied] = useState(false);+ const copy = () => {+ void navigator.clipboard?.writeText(text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1200);+ });+ };+ return (+ <div className="mt-2.5 overflow-hidden rounded-lg border bg-muted/40" data-snippet="">+ <div className="flex h-8 items-center justify-between border-b pr-1 pl-3">+ <span className="font-mono text-2xs text-muted-foreground">{file}</span>+ <Button size="icon-sm" variant="ghost" aria-label="Copy" onClick={copy}>+ {copied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}+ </Button>+ </div>+ <pre className="overflow-x-auto px-3 py-2.5 font-mono text-xs leading-[1.55]">{text}</pre>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/hooks/use-connected-apps.ts b/apps/cua-spaces-web/src/hooks/use-connected-apps.tsnew file mode 100644index 0000000000..d2ab6393f8--- /dev/null+++ b/apps/cua-spaces-web/src/hooks/use-connected-apps.ts@@ -0,0 +1,192 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useLocation } from "@tanstack/react-router";+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";++import { isUnsupported, useBridge, type AgentSetupRow, type DataAdapter } from "@/bridge";+import { toast, toastError } from "@/components/ui/toast";+import { failureText as failureOf, planSync, readState, withSwitch, writeState, type ConnectedAppsState } from "@/lib/connected-apps";++/* ---- What Cua remembers: one local key, shared by Settings, onboarding and the sync ---- */++const storage = () => (typeof localStorage === "undefined" ? null : localStorage);+let state: ConnectedAppsState = readState(storage());+const listeners = new Set<() => void>();++export const connectedAppsState = () => state;++export function setConnectedAppsState(next: ConnectedAppsState): void {+ state = next;+ writeState(storage(), next);+ for (const l of listeners) l();+}++/** Tests start from a clean slate. */+export function resetConnectedAppsState(): void {+ state = readState(storage());+ for (const l of listeners) l();+}++export function useConnectedAppsState(): ConnectedAppsState {+ return useSyncExternalStore(+ (l) => {+ listeners.add(l);+ return () => listeners.delete(l);+ },+ () => state,+ () => state,+ );+}++/* ---- Doing it ---- */++/** The apps on this computer; null when this app can't look (nothing to show then). */+async function readRows(data: DataAdapter): Promise<AgentSetupRow[] | null> {+ try {+ return await data.call("agents.setup", {});+ } catch (e) {+ if (isUnsupported(e)) return null;+ throw e;+ }+}++/** Cua in `agent`'s settings: on adds it (with Background computer use, best effort), off takes out only what Cua added. */+async function setApp(data: DataAdapter, row: AgentSetupRow, on: boolean): Promise<AgentSetupRow[]> {+ if (on) {+ const rows = await data.call("agents.configure", { agents: [row.agent] });+ try {+ // One switch, one consent: the same apps may also use the computer in the background.+ await data.call("agents.setupDriver", { agents: [row.agent] });+ } catch {+ // Cua Driver is its own install; without it the app still has Cua.+ }+ return rows;+ }+ // The host's own Settings row: removes what Cua added, nothing else.+ await data.call("settings.choose", { row: `agent:${row.agent}`, option: "press" });+ return (await readRows(data)) ?? [];+}++export interface ConnectedApps {+ /** Null until read; an empty list when this app can't look. */+ rows: AgentSetupRow[] | null;+ /** The apps with a change running. */+ pending: string[];+ /** Why the last change to an app failed (a sentence), by app. */+ failures: Record<string, string>;+ state: ConnectedAppsState;+ toggle(row: AgentSetupRow, on: boolean): Promise<void>;+ /** "Set up new apps automatically". */+ setAuto(on: boolean): void;+ reload(): Promise<void>;+}++/** Settings, Connected apps. */+export function useConnectedApps(): ConnectedApps {+ const { data } = useBridge();+ const app = useConnectedAppsState();+ const [rows, setRows] = useState<AgentSetupRow[] | null>(null);+ const [pending, setPending] = useState<string[]>([]);+ const [failures, setFailures] = useState<Record<string, string>>({});++ const reload = useCallback(async () => {+ if (!data) return;+ try {+ setRows((await readRows(data)) ?? []);+ } catch {+ setRows((r) => r ?? []);+ }+ }, [data]);++ useEffect(() => {+ void reload();+ window.addEventListener("focus", reload);+ return () => window.removeEventListener("focus", reload);+ }, [reload]);++ const toggle = useCallback(+ async (row: AgentSetupRow, on: boolean) => {+ if (!data || pending.includes(row.agent)) return;+ setPending((p) => [...p, row.agent]);+ setFailures(({ [row.agent]: _gone, ...rest }) => rest);+ try {+ const after = await setApp(data, row, on);+ setRows(after);+ const now = after.find((r) => r.agent === row.agent);+ if (on && !now?.configured) {+ setFailures((f) => ({ ...f, [row.agent]: failureOf(row.name, now?.detail ?? "") }));+ return;+ }+ setConnectedAppsState(withSwitch(connectedAppsState(), row.agent, on));+ if (!on) {+ toast(`${row.name} turned off`, {+ description: `Cua took itself out of ${row.name}'s settings. Restart ${row.name} to finish. Its past runs stay on the Agents page.`,+ fromCua: true,+ group: `app:${row.agent}`,+ action: { label: "Undo", onClick: () => void toggle(row, true) },+ });+ }+ } catch (e) {+ toastError(`Couldn't change ${row.name}`)(e);+ } finally {+ setPending((p) => p.filter((a) => a !== row.agent));+ }+ },+ [data, pending],+ );++ return { rows, pending, failures, state: app, toggle, setAuto: (on) => setConnectedAppsState({ ...connectedAppsState(), auto: on }), reload };+}++/**+ * Keeps new coding apps connected: when the app starts and when its window+ * gets focus, read the apps on this computer and set up any newly installed+ * one the person said yes to, with a notice and Undo. Never touches an app+ * that was turned off, and does nothing during the first run (it asks there).+ */+export function useAgentSync(): void {+ const { data } = useBridge();+ const { pathname } = useLocation();+ const busy = useRef(false);+ const inOnboarding = pathname.startsWith("/onboarding");++ useEffect(() => {+ if (!data || inOnboarding) return;+ const run = async () => {+ if (busy.current) return;+ busy.current = true;+ try {+ const rows = await readRows(data);+ if (!rows) return;+ const plan = planSync(rows, connectedAppsState());+ setConnectedAppsState(plan.state);+ if (plan.setUp.length === 0) return;+ const after = await data.call("agents.configure", { agents: plan.setUp });+ for (const id of plan.setUp) {+ const row = after.find((r) => r.agent === id);+ if (!row?.configured) continue;+ toast(`${row.name} can now use Cua`, {+ description: `Cua added itself to ${row.name}'s settings. Restart ${row.name} to use it.`,+ fromCua: true,+ group: `app:${id}`,+ action: {+ label: "Undo",+ onClick: () => {+ setConnectedAppsState(withSwitch(connectedAppsState(), id, false));+ void data.call("settings.choose", { row: `agent:${id}`, option: "press" }).catch(toastError(`Couldn't undo ${row.name}`));+ },+ },+ });+ }+ } catch {+ // A read that fails is tried again at the next focus.+ } finally {+ busy.current = false;+ }+ };+ void run();+ window.addEventListener("focus", run);+ return () => window.removeEventListener("focus", run);+ }, [data, inOnboarding]);+}diff --git a/apps/cua-spaces-web/src/lib/connected-apps.test.ts b/apps/cua-spaces-web/src/lib/connected-apps.test.tsnew file mode 100644index 0000000000..b9794dd14b--- /dev/null+++ b/apps/cua-spaces-web/src/lib/connected-apps.test.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";++import type { AgentSetupRow } from "@/bridge";+import { demoAgentSetup } from "@/bridge/adapters/demo-agents";+import { EMPTY_STATE, failureText, getItUrl, missingApps, planSync, readState, shownApps, STATE_KEY, withSwitch, writeState } from "./connected-apps";++const rows = (...over: Partial<AgentSetupRow>[]): AgentSetupRow[] =>+ over.map((o) => ({ ...demoAgentSetup()[0]!, ...o }) as AgentSetupRow);++describe("planSync", () => {+ it("only records what is installed on the first read, even with consent", () => {+ const r = rows({ agent: "claude-code", installed: true, configured: false }, { agent: "cursor", installed: true, configured: false });+ const plan = planSync(r, { ...EMPTY_STATE, auto: true });+ expect(plan.setUp).toEqual([]);+ expect(plan.state.known).toEqual(["claude-code", "cursor"]);+ });++ it("sets up a newly installed app when the person said yes", () => {+ const r = rows({ agent: "claude-code", installed: true, configured: true }, { agent: "cursor", installed: true, configured: false });+ const plan = planSync(r, { known: ["claude-code"], off: [], auto: true });+ expect(plan.setUp).toEqual(["cursor"]);+ expect(plan.state.known).toEqual(["claude-code", "cursor"]);+ });++ it("sets up nothing without a yes, and says the app is known so it is not new again", () => {+ const r = rows({ agent: "cursor", installed: true, configured: false });+ for (const auto of [null, false]) {+ const plan = planSync(r, { known: [], off: [], auto });+ expect(plan.setUp).toEqual([]);+ expect(plan.state.known).toEqual(["cursor"]);+ }+ });++ it("never touches an app that was turned off, or one that is already set up", () => {+ const r = rows({ agent: "cursor", installed: true, configured: false }, { agent: "hermes", installed: true, configured: true });+ expect(planSync(r, { known: [], off: ["cursor"], auto: true }).setUp).toEqual([]);+ });++ it("ignores apps that are not installed", () => {+ const r = rows({ agent: "kiro", installed: false, configured: false });+ expect(planSync(r, { known: [], off: [], auto: true })).toEqual({ state: { known: [], off: [], auto: true }, setUp: [] });+ });+});++describe("withSwitch", () => {+ it("remembers off and forgets it on on", () => {+ const off = withSwitch(EMPTY_STATE, "cursor", false);+ expect(off.off).toEqual(["cursor"]);+ expect(withSwitch(off, "cursor", false).off).toEqual(["cursor"]);+ expect(withSwitch(off, "cursor", true).off).toEqual([]);+ });+});++describe("the saved state", () => {+ const store = () => {+ const m = new Map<string, string>();+ return { getItem: (k: string) => m.get(k) ?? null, setItem: (k: string, v: string) => void m.set(k, v), m };+ };+ it("round-trips and survives a damaged value", () => {+ const s = store();+ writeState(s, { known: ["a"], off: ["b"], auto: true });+ expect(readState(s)).toEqual({ known: ["a"], off: ["b"], auto: true });+ s.m.set(STATE_KEY, "{nope");+ expect(readState(s)).toEqual(EMPTY_STATE);+ s.m.set(STATE_KEY, JSON.stringify({ known: "x", off: [1, "c"], auto: "yes" }));+ expect(readState(s)).toEqual({ known: null, off: ["c"], auto: null });+ expect(readState(null)).toEqual(EMPTY_STATE);+ });+});++describe("what is listed", () => {+ const r = rows({ agent: "a", installed: true }, { agent: "b", installed: false, configured: true }, { agent: "c", installed: false, configured: false });+ it("lists installed apps and ones still set up; the rest are missing", () => {+ expect(shownApps(r).map((x) => x.agent)).toEqual(["a", "b"]);+ expect(missingApps(r).map((x) => x.agent)).toEqual(["c"]);+ });+ it("links only the apps we are sure of", () => {+ expect(getItUrl("cursor")).toMatch(/^https:\/\/cursor\.com/);+ expect(getItUrl("pi")).toBeNull();+ });+});++describe("failureText", () => {+ it("says a read-only file plainly and never shows an os error", () => {+ expect(failureText("Hermes", "Permission denied (os error 13)")).toBe("Couldn't set up Hermes. Cua can't change this file because it is read-only or belongs to another user.");+ expect(failureText("Hermes", "boom")).toBe("Couldn't set up Hermes. Cua said: boom.");+ expect(failureText("Hermes", "Not set up")).toBe("Couldn't set up Hermes.");+ });+});diff --git a/apps/cua-spaces-web/src/lib/connected-apps.ts b/apps/cua-spaces-web/src/lib/connected-apps.tsnew file mode 100644index 0000000000..982da02a99--- /dev/null+++ b/apps/cua-spaces-web/src/lib/connected-apps.ts@@ -0,0 +1,116 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Connected apps: which coding apps Cua is set up in, and the rules for+ * setting up newly installed ones. Pure: the hook in `hooks/use-connected-apps`+ * reads the apps and writes the state; this decides.+ */++import type { AgentSetupRow } from "@/bridge";++/** What Cua remembers between runs (one local key, `cua.connectedApps`). */+export interface ConnectedAppsState {+ /** Apps seen installed so far: only an app not in here is "new". Null before the first read. */+ known: string[] | null;+ /** Apps the person turned off: never set up again on its own. */+ off: string[];+ /**+ * The person said yes to setting up apps they install later (onboarding's+ * Set up, or the switch in Settings). Null: never asked, so Cua sets up+ * nothing on its own.+ */+ auto: boolean | null;+}++export const EMPTY_STATE: ConnectedAppsState = { known: null, off: [], auto: null };++export const STATE_KEY = "cua.connectedApps";++export function readState(storage: Pick<Storage, "getItem"> | null): ConnectedAppsState {+ try {+ const raw = storage?.getItem(STATE_KEY);+ if (!raw) return EMPTY_STATE;+ const v = JSON.parse(raw) as Partial<ConnectedAppsState>;+ const list = (x: unknown) => (Array.isArray(x) ? x.filter((s): s is string => typeof s === "string") : []);+ return {+ known: Array.isArray(v.known) ? list(v.known) : null,+ off: list(v.off),+ auto: typeof v.auto === "boolean" ? v.auto : null,+ };+ } catch {+ return EMPTY_STATE;+ }+}++export function writeState(storage: Pick<Storage, "setItem"> | null, state: ConnectedAppsState): void {+ try {+ storage?.setItem(STATE_KEY, JSON.stringify(state));+ } catch {+ // Without storage Cua asks again next time; nothing is lost.+ }+}++export interface SyncPlan {+ /** The state to keep. */+ state: ConnectedAppsState;+ /** The new apps to set up now (each gets a notice with Undo). */+ setUp: string[];+}++/**+ * What to do after reading the apps on this computer. The first read only+ * records what is there. After that, an app that was not there before is set+ * up when the person said yes to that, unless they turned it off.+ */+export function planSync(rows: AgentSetupRow[], state: ConnectedAppsState): SyncPlan {+ const installed = rows.filter((r) => r.installed);+ const ids = installed.map((r) => r.agent);+ if (state.known === null) return { state: { ...state, known: ids }, setUp: [] };+ const known = new Set(state.known);+ const fresh = installed.filter((r) => !known.has(r.agent));+ const setUp = state.auto === true ? fresh.filter((r) => !r.configured && !state.off.includes(r.agent)).map((r) => r.agent) : [];+ return { state: { ...state, known: [...new Set([...state.known, ...ids])] }, setUp };+}++/** Turning an app on or off: off remembers it, on forgets that. */+export function withSwitch(state: ConnectedAppsState, agent: string, on: boolean): ConnectedAppsState {+ const off = on ? state.off.filter((a) => a !== agent) : [...new Set([...state.off, agent])];+ return { ...state, off };+}++/** The apps the person can switch: installed, or set up before the app went away. */+export const shownApps = (rows: AgentSetupRow[]) => rows.filter((r) => r.installed || r.configured);++/** Apps Cua knows that are not on this computer. */+export const missingApps = (rows: AgentSetupRow[]) => rows.filter((r) => !r.installed && !r.configured);++/** Where to get an app, for the ones we are sure of; the rest show no link. */+const GET_IT: Record<string, string> = {+ "claude-code": "https://claude.com/product/claude-code",+ codex: "https://developers.openai.com/codex",+ cursor: "https://cursor.com/download",+ vscode: "https://code.visualstudio.com/download",+ "gemini-cli": "https://github.com/google-gemini/gemini-cli",+};+export const getItUrl = (agent: string): string | null => GET_IT[agent] ?? null;++/** What to paste by hand for an app, when Cua can't edit its file. */+export const BY_HAND: Record<string, { file: string; snippet: string }> = {+ "claude-code": { file: "Terminal (writes ~/.claude.json)", snippet: "claude mcp add --scope user cua -- cua mcp" },+ codex: { file: "~/.codex/config.toml", snippet: '[mcp_servers.cua]\ncommand = "cua"\nargs = ["mcp"]' },+ hermes: { file: "~/.hermes/config.yaml", snippet: "mcp_servers:\n cua:\n command: cua\n args: [mcp]" },+ openclaw: { file: "~/.openclaw/openclaw.json", snippet: '{\n "mcp": {\n "servers": {\n "cua": { "command": "cua", "args": ["mcp"] }\n }\n }\n}' },+ cursor: { file: "~/.cursor/mcp.json", snippet: '{\n "mcpServers": {\n "cua": { "command": "cua", "args": ["mcp"] }\n }\n}' },+};++/**+ * Why a setup failed, in a sentence a person can use. The setup's own words+ * ("Permission denied (os error 13)") stay out of sight.+ */+export function failureText(name: string, detail: string): string {+ if (/permission|read-only|readonly|EACCES|EPERM|os error 13|not writable/i.test(detail)) {+ return `Couldn't set up ${name}. Cua can't change this file because it is read-only or belongs to another user.`;+ }+ return `Couldn't set up ${name}. ${/^not set up$/i.test(detail) ? "" : "Cua said: " + detail.replace(/\.$/, "") + "."}`.trim();+}diff --git a/apps/cua-spaces-web/src/routes/__root.tsx b/apps/cua-spaces-web/src/routes/__root.tsxindex 6dc60ca5fa..0de7fbd029 100644--- a/apps/cua-spaces-web/src/routes/__root.tsx+++ b/apps/cua-spaces-web/src/routes/__root.tsx@@ -20,6 +20,7 @@ import { UsageLinkNotice } from "@/components/usage-link-notice";import { TopBar } from "@/components/shell/top-bar";import { ThisMacNudges } from "@/components/this-mac-nudges";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 { useUiStore } from "@/stores/ui";@@ -40,6 +41,7 @@ function RootLayout() {useGlobalKeybindings();useFirstRun();useNotificationToasts();+ useAgentSync();const sidebarOpen = useUiStore((s) => s.sidebarOpen);const { pathname } = useLocation();// The app shows as usual until the host says it is still starting.diff --git a/apps/cua-spaces-web/src/routes/settings/connected-apps.tsx b/apps/cua-spaces-web/src/routes/settings/connected-apps.tsxindex f7155d8478..273c8e3f3a 100644--- a/apps/cua-spaces-web/src/routes/settings/connected-apps.tsx+++ b/apps/cua-spaces-web/src/routes/settings/connected-apps.tsx@@ -2,12 +2,12 @@// Copyright (c) 2026 Cua AI, Inc.import { createFileRoute } from "@tanstack/react-router";-import { useEffect } from "react";import { useAgentKeys, useCliInstall, useSettings } from "@/bridge";import { AccountKeysSection } from "@/components/settings/account-keys";import { CliSettingsSection } from "@/components/settings/cli-section";import { CodingAppsSection } from "@/components/settings/coding-apps-section";+import { useConnectedApps } from "@/hooks/use-connected-apps";import { useQuiet } from "@/hooks/use-quiet";export const Route = createFileRoute("/settings/connected-apps")({ component: ConnectedAppsPage });@@ -17,19 +17,15 @@ export const Route = createFileRoute("/settings/connected-apps")({ component: Co* Its parts come from separate host reads; the page draws once they have answered, not one by one with the page jumping at each (CUA-1951).*/function ConnectedAppsPage() {- const { data, loadAgentRows } = useSettings();- // The apps are read here, before the page draws, so their rows are not what arrives late.- useEffect(() => {- void loadAgentRows().catch(() => {});- // eslint-disable-next-line react-hooks/exhaustive-deps -- once per showing- }, []);+ const { data } = useSettings();+ const apps = useConnectedApps();const keys = useAgentKeys({ watch: true });const cli = useCliInstall();- const settled = useQuiet(`${data?.page?.sections.length ?? 0}|${data?.cli ? 1 : 0}|${keys.view?.rows.length ?? 0}|${cli.state.plan ? 1 : 0}|${data?.page?.sections.find((s) => s.id === "agents")?.rows.length ?? 0}`);+ const settled = useQuiet(`${apps.rows?.length ?? -1}|${data?.cli ? 1 : 0}|${keys.view?.rows.length ?? 0}|${cli.state.plan ? 1 : 0}`);if (!settled) return <div className="h-96" aria-busy="true" />;return (<div data-settings-tab="connected-apps">- <CodingAppsSection />+ <CodingAppsSection apps={apps} /><AccountKeysSection /><CliSettingsSection /></div>diff --git a/apps/cua-spaces-web/src/routes/spaces/index.tsx b/apps/cua-spaces-web/src/routes/spaces/index.tsxindex dd52f14a34..1cad8329fa 100644--- a/apps/cua-spaces-web/src/routes/spaces/index.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/index.tsx@@ -1,13 +1,12 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { createFileRoute, Link } from "@tanstack/react-router";+import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";import { ArrowDownCircleIcon, KeyRoundIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, PowerIcon, SearchIcon } from "lucide-react";import { useEffect, useRef, useState, type DragEvent } from "react";import { emptyHome, listView, spaceResources, useAgents, useBridge, useChecklist, useResources, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaceFiles, useSpaces, useSpaceThumbnail, useWindowDropTarget, type Space } from "@/bridge";import { EmptyHome } from "@/components/empty-home";-import { ConnectAgentDialog } from "@/components/agents/connect-dialog";import { RunAgentDialog } from "@/components/agents/run-agent-dialog";import { SpaceReadyCard, useAgentOffer } from "@/components/space-ready-card";import { useFirstRunStep, useFirstSpaceMilestones } from "@/components/first-run-guide";@@ -87,7 +86,7 @@ function SpacesPage() {const [runPrompt, setRunPrompt] = useState<string | undefined>();const firstRunStep = useFirstRunStep();useFirstSpaceMilestones(spaces);- const [connectOpen, setConnectOpen] = useState(false);+ const navigate = useNavigate();// The cards above the list (ready, checklist, computers) and the list come from separate host reads. Draw them// together once those have answered, not one by one with the page jumping at each (CUA-1951).const settled = useQuiet(@@ -119,8 +118,7 @@ function SpacesPage() {/> : null}{readySpace ? (<>- <RunAgentDialog open={runOpen} space={readySpace} prompt={runPrompt} onOpenChange={setRunOpen} onManual={() => setConnectOpen(true)} onConnected={offer.completed} />- <ConnectAgentDialog open={connectOpen} onOpenChange={setConnectOpen} />+ <RunAgentDialog open={runOpen} space={readySpace} prompt={runPrompt} onOpenChange={setRunOpen} onManual={() => void navigate({ to: "/settings/connected-apps" })} onConnected={offer.completed} /></>) : null}<ComputerWarnings snapshot={resources} machines={machines} />