Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces): the new prompt box with a model and an optional repo (#6490)
ddupont2ea6cf34dde3
diff --git a/apps/cua-spaces-desktop/src/bridge/agent-keys.ts b/apps/cua-spaces-desktop/src/bridge/agent-keys.tsindex be2bcffb94..0267e20a04 100644--- a/apps/cua-spaces-desktop/src/bridge/agent-keys.ts+++ b/apps/cua-spaces-desktop/src/bridge/agent-keys.ts@@ -53,6 +53,13 @@ export function agentKeysMethods({ model }: BridgeContext): Handlers {if (slot) call.slot = slot;return model.agents.keys.call("agent_keys.use", call);},+ // A saved key or sign-in gets a name (no `slot`: the first saved for `env`).+ "agentKeys.rename": (args) => {+ const call: Record<string, unknown> = { env: string(args, "env"), label: string(args, "label") };+ const slot = optionalString(args, "slot");+ if (slot) call.slot = slot;+ return model.agents.keys.call("agent_keys.rename", call);+ },// Which provider keys your login shell has (names only), and one saved from it (the value never crosses the bridge)."agentKeys.shell": () => model.agents.keys.call("agent_keys.shell"),"agentKeys.fromShell": (args) => model.agents.keys.call("agent_keys.from_shell", { env: string(args, "env"), ...choices(args) }),diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex ff7515c46d..9b6cd3b45e 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -15,13 +15,14 @@ export const METHODS = ["spaces.createOptions", "spaces.create","spaces.setPower", "spaces.delete", "spaces.rename", "spaces.deleteMany", "spaces.leave", "spaces.cancelCreate","network.get", "network.set", "network.log", "network.ackNotice", "spaces.setAccess",+ "spaces.tree", "children.set", "budget.get", "budget.set", "services.list", "services.control","machines.list", "host.status","agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume","agents.setup", "agents.configure", "agents.signIn","agents.status", "agents.connect", "agents.disconnect", "agents.recentThreads", "agents.threadHistory", "agents.signInStart", "agents.signInWait", "agents.start", "agents.message","agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine","agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer",- "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.shell", "agentKeys.fromShell",+ "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.rename", "agentKeys.shell", "agentKeys.fromShell","github.status", "github.rescan", "github.use", "github.enable","spaces.add", "clouds.status", "clouds.test", "clouds.connect", "clouds.disconnect", "clouds.approve","teleport.catalog", "teleport.entryForPath", "teleport.windows", "teleport.remoteWindows",diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.tsindex 848725f6c1..5482229607 100644--- a/apps/cua-spaces-desktop/src/bridge/settings.ts+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts@@ -124,6 +124,8 @@ export function settingsState(model: AppModel, parts: HostParts) {tips: { off: model.settings.tips.off, done: [...model.settings.tips.done] },// The Spaces and machine desktops pinned to the notch, in pin order.notchPinned: [...model.settings.notchPinned],+ // Which coding apps the agent menu shows (`AppSettings.agentMenu*`, the core's `agent_menu`).+ agentMenu: { shown: [...model.settings.agentMenuShown], hidden: [...model.settings.agentMenuHidden], seen: [...model.settings.agentMenuSeen] },};}@@ -142,6 +144,14 @@ export function settingsUpdate(args: Record<string, unknown>): Partial<AppModel[if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) throw Failure.badArgs("notchPinned: string[]");patch.notchPinned = ids as string[];}+ if ("agentMenu" in args) {+ const m = args.agentMenu as { shown?: unknown; hidden?: unknown; seen?: unknown } | null;+ const strings = (v: unknown) => Array.isArray(v) && v.every((x) => typeof x === "string");+ if (!m || typeof m !== "object" || !strings(m.shown) || !strings(m.hidden) || !strings(m.seen)) throw Failure.badArgs("agentMenu: {shown: string[], hidden: string[], seen: string[]}");+ patch.agentMenuShown = m.shown as string[];+ patch.agentMenuHidden = m.hidden as string[];+ patch.agentMenuSeen = m.seen as string[];+ }if (!Object.keys(patch).length) throw Failure.badArgs("tips");return patch;}diff --git a/apps/cua-spaces-desktop/src/bridge/spaces.ts b/apps/cua-spaces-desktop/src/bridge/spaces.tsindex 494da6f978..95340a5074 100644--- a/apps/cua-spaces-desktop/src/bridge/spaces.ts+++ b/apps/cua-spaces-desktop/src/bridge/spaces.ts@@ -9,8 +9,9 @@ import type { Native } from "../native/load";import type { AppCreateSpaceArgs, AppSpace, AppWizardEnv, SpaceCreateProgress } from "../native/generated/index";import { AppModel } from "../model/app-model";import { RUNTIME_FIX_ACTIONS, type RuntimeFix, type RuntimeFixAction } from "../model/windows-runtime";-import { createNetworks, kindOf, osOf, runtimeOf } from "../model/backend";+import { createExtras, createExtrasOf, createNetworks, kindOf, osOf, runtimeOf } from "../model/backend";import { isCancelled } from "../model/errors";+import { cuaHomeOf, homeGrantsOf, writeHomeGrants } from "../model/home-grants";import { bool, string } from "./args";import type { BridgeContext } from "./context";import { Failure, type BridgeArgs, type Handlers } from "./host";@@ -150,6 +151,9 @@ export function spacesMethods(ctx: BridgeContext): Handlers {// The New Space's Network choice goes with the create (by its id).const net = (config as BridgeArgs).network;if (typeof net === "string" && net) createNetworks.set(pendingId, net);+ // An agent home: the spawn capability and its labels (CUA-2630).+ const extras = createExtrasOf(config as BridgeArgs);+ if (Object.keys(extras).length) createExtras.set(pendingId, extras);// The page sends the plan's OS (the pending row's icon).const os = (typeof args.os === "string" ? osOf(native, args.os) : undefined) ?? native.AppSpaceOs.Unknown;let id: string;@@ -167,6 +171,7 @@ export function spacesMethods(ctx: BridgeContext): Handlers {throw error;} finally {createNetworks.delete(pendingId);+ createExtras.delete(pendingId);}const made = model.spaces.find((s) => s.id === id);// A create the first run started: "<Space> is ready", window or not.@@ -223,8 +228,54 @@ export function spacesMethods(ctx: BridgeContext): Handlers {"spaces.setAccess": async (args) => {const b = model.backend;const word = (k: string) => (typeof args[k] === "string" ? (args[k] as string) : null);+ const [clipboard, volume] = [word("clipboard"), word("volume")];+ // An agent home's grants (CUA-2630): the file this machine's daemon reads.+ const home = homeGrantsOf(args.home);+ if (home) await writeHomeGrants(cuaHomeOf(ctx.env), string(args, "spaceId"), home);+ if (home && clipboard === null && volume === null) return {};if (!b.setAccess) throw Failure.unsupported("these settings");- await b.setAccess(string(args, "spaceId"), word("clipboard"), word("volume"));+ await b.setAccess(string(args, "spaceId"), clipboard, volume);+ return {};+ },+ // Child Spaces (the Child Spaces experiment; the daemon refuses them while it is off).+ "spaces.tree": async () => {+ const b = model.backend;+ return b.spaceTree ? await b.spaceTree() : [];+ },+ "children.set": async (args) => {+ const b = model.backend;+ if (!b.setChildren) throw Failure.unsupported("child Spaces");+ await b.setChildren(string(args, "spaceId"), bool(args, "enabled"));+ return {};+ },+ "budget.get": async (args) => {+ const b = model.backend;+ if (!b.treeBudget) throw Failure.unsupported("child Spaces");+ return await b.treeBudget(string(args, "spaceId"));+ },+ "budget.set": async (args) => {+ const b = model.backend;+ if (!b.setTreeBudget) throw Failure.unsupported("child Spaces");+ const l = (args.limits ?? {}) as Record<string, unknown>;+ const n = (k: string) => (typeof l[k] === "number" && Number.isFinite(l[k]) && (l[k] as number) >= 0 ? (l[k] as number) : null);+ return await b.setTreeBudget(string(args, "spaceId"), {+ maxSpaces: n("maxSpaces"),+ maxVcpus: n("maxVcpus"),+ maxMemoryMb: n("maxMemoryMb"),+ usdPerHour: n("usdPerHour"),+ usdTotal: n("usdTotal"),+ });+ },+ "services.list": async (args) => {+ const b = model.backend;+ return b.services ? await b.services(string(args, "spaceId")) : [];+ },+ "services.control": async (args) => {+ const b = model.backend;+ if (!b.controlService) throw Failure.unsupported("services");+ const action = string(args, "action");+ if (!["start", "stop", "restart", "remove"].includes(action)) throw Failure.badArgs(`action: start, stop, restart or remove`);+ await b.controlService(string(args, "spaceId"), string(args, "name"), action);return {};},"spaces.cancelCreate": (args) => {diff --git a/apps/cua-spaces-desktop/src/model/backend.ts b/apps/cua-spaces-desktop/src/model/backend.tsindex e1f21937a5..23d8d23b84 100644--- a/apps/cua-spaces-desktop/src/model/backend.ts+++ b/apps/cua-spaces-desktop/src/model/backend.ts@@ -236,6 +236,17 @@ export interface SpacesBackend {ackNetworkNotice?(id: string): Promise<void>;/** `spaces.setAccess`: a Space's clipboard and/or Volume setting. */setAccess?(id: string, clipboard: string | null, volume: string | null): Promise<void>;+ /** `spaces.tree`: every Space's parent, depth and whether it may make+ * children (the SDK's `Spaces.list`). */+ spaceTree?(): Promise<TreeNodeJson[]>;+ /** `children.set`: lets a Space make child Spaces, or stops it. */+ setChildren?(id: string, enabled: boolean): Promise<void>;+ /** `budget.get` / `budget.set`: a Space's tree's budget and use. */+ treeBudget?(id: string): Promise<TreeBudgetJson>;+ setTreeBudget?(id: string, limits: TreeBudgetLimitsJson): Promise<TreeBudgetJson>;+ /** `services.list` / `services.control`: the commands a Space keeps running. */+ services?(id: string): Promise<ServiceJson[]>;+ controlService?(id: string, name: string, action: string): Promise<void>;/** Takes one of your machines off the relay directory (`relay:<machine>`), refused while it is online. */relayUnregister(machineId: string): Promise<void>;/** A machine's health as its own cua daemon checks it (the SDK's `Spaces.machine_health`): null for this one, else another of yours by id. */@@ -568,6 +579,7 @@ export class LiveSpacesBackend implements SpacesBackend {// The New Space's Network choice (`config.network`), by create id.// Kept until the whole create is over: the model runs a failed one once more.const network = createNetworks.get(createId);+ const extras = createExtras.get(createId) ?? {};const result = await this.cua.spaces().createWithProgress({...(network ? { networkSettings: networkSettingsOf(network, [], []) } : {}),@@ -590,7 +602,8 @@ export class LiveSpacesBackend implements SpacesBackend {createId,durable: false,volumes: [],- labels: new Map(),+ labels: new Map(Object.entries(extras.labels ?? {})),+ ...(extras.children ? { children: true } : {}),},{ onProgress: progress },);@@ -695,6 +708,63 @@ export class LiveSpacesBackend implements SpacesBackend {if (volume) await this.cua.spaces().setVolume(id, volume);}+ async spaceTree(): Promise<TreeNodeJson[]> {+ return (await this.cua.spaces().list()).map((s) => ({+ id: s.id,+ parent: s.parent ?? null,+ depth: Number(s.depth),+ children: Boolean(s.children),+ home: s.labels.get("cua.home") === "1" ? (s.labels.get("cua.home.agent") ?? "") : null,+ }));+ }++ async setChildren(id: string, enabled: boolean): Promise<void> {+ await this.cua.spaces().setChildren(id, enabled);+ }++ async treeBudget(id: string): Promise<TreeBudgetJson> {+ return budgetJson(await this.cua.spaces().treeBudget(id));+ }++ async setTreeBudget(id: string, l: TreeBudgetLimitsJson): Promise<TreeBudgetJson> {+ const big = (v: number | null | undefined) => (v === null || v === undefined ? undefined : BigInt(Math.round(v)));+ const n = (v: number | null | undefined) => (v === null || v === undefined ? undefined : v);+ return budgetJson(+ await this.cua.spaces().setTreeBudget(id, {+ maxSpaces: n(l.maxSpaces),+ maxVcpus: n(l.maxVcpus),+ maxMemoryMb: big(l.maxMemoryMb),+ usdPerHour: n(l.usdPerHour),+ usdTotal: n(l.usdTotal),+ }),+ );+ }++ async services(id: string): Promise<ServiceJson[]> {+ const space = await this.cua.spaces().space(id);+ return (await space.keptServices()).map((s) => ({ name: s.name, command: s.command, state: s.state, restarts: Number(s.restarts), lastEnd: s.lastEnd, probeError: s.probeError }));+ }++ async controlService(id: string, name: string, action: string): Promise<void> {+ const space = await this.cua.spaces().space(id);+ switch (action) {+ case "start":+ await space.startService(name);+ return;+ case "stop":+ await space.stopService(name);+ return;+ case "restart":+ await space.restartService(name);+ return;+ case "remove":+ await space.deleteService(name);+ return;+ default:+ throw new Error(`no service action ${action}`);+ }+ }+async relayUnregister(machineId: string): Promise<void> {await this.cua.spaces().relayUnregister(`relay:${machineId}`);}@@ -982,6 +1052,86 @@ export interface SpaceNetworkJson {volume: string;}+/** A Space's place in its tree, as `spaces.tree` answers it. */+export interface TreeNodeJson {+ id: string;+ parent: string | null;+ depth: number;+ children: boolean;+ /** The agent it is the home of (its `cua.home` labels), or null. */+ home: string | null;+}++/** A tree's limits, as `budget.set` takes them. */+export interface TreeBudgetLimitsJson {+ maxSpaces?: number | null;+ maxVcpus?: number | null;+ maxMemoryMb?: number | null;+ usdPerHour?: number | null;+ usdTotal?: number | null;+}++/** A tree's budget and use, as `budget.get` answers it. */+export interface TreeBudgetJson {+ root: string;+ set: TreeBudgetLimitsJson;+ maxSpaces: number;+ maxVcpus: number;+ maxMemoryMb: number;+ usdPerHour: number;+ usdTotal: number | null;+ spaces: number;+ vcpus: number;+ memoryMb: number;+ usdPerHourUsed: number;+ usdSpent: number;+}++/** A kept command, as `services.list` answers it. */+export interface ServiceJson {+ name: string;+ command: string;+ state: string;+ restarts: number;+ lastEnd: string;+ probeError: string;+}++type SdkLimits = { maxSpaces?: number; maxVcpus?: number; maxMemoryMb?: bigint | number; usdPerHour?: number; usdTotal?: number };+type SdkBudget = {+ root: string;+ set: SdkLimits;+ maxSpaces: number;+ maxVcpus: number;+ maxMemoryMb: bigint | number;+ usdPerHour: number;+ usdTotal?: number;+ spaces: number;+ vcpus: number;+ memoryMb: bigint | number;+ usdPerHourUsed: number;+ usdSpent: number;+};++/** The SDK's `TreeBudget` as JSON (u64s as numbers). */+function budgetJson(b: SdkBudget): TreeBudgetJson {+ const opt = (v: bigint | number | undefined) => (v === undefined || v === null ? null : Number(v));+ return {+ root: b.root,+ set: { maxSpaces: opt(b.set.maxSpaces), maxVcpus: opt(b.set.maxVcpus), maxMemoryMb: opt(b.set.maxMemoryMb), usdPerHour: opt(b.set.usdPerHour), usdTotal: opt(b.set.usdTotal) },+ maxSpaces: Number(b.maxSpaces),+ maxVcpus: Number(b.maxVcpus),+ maxMemoryMb: Number(b.maxMemoryMb),+ usdPerHour: b.usdPerHour,+ usdTotal: opt(b.usdTotal),+ spaces: Number(b.spaces),+ vcpus: Number(b.vcpus),+ memoryMb: Number(b.memoryMb),+ usdPerHourUsed: b.usdPerHourUsed,+ usdSpent: b.usdSpent,+ };+}+/** One kind of blocked connection, as `network.log` answers it. */export interface NetworkEventJson {reason: string;@@ -994,6 +1144,27 @@ export interface NetworkEventJson {/** The New Space's Network choice by create id, until its create runs. */export const createNetworks = new Map<string, string>();+/** What an agent home is created with besides the plan's fields (CUA-2630): the spawn capability and its `cua.home.*` labels. */+export interface CreateExtras {+ children?: boolean;+ labels?: Record<string, string>;+}++/** The extras of a create, by create id, until its create runs. */+export const createExtras = new Map<string, CreateExtras>();++/** The extras in a `spaces.create` config; anything of the wrong type is ignored, a label that is not text is dropped. */+export function createExtrasOf(config: Record<string, unknown>): CreateExtras {+ const out: CreateExtras = {};+ if (config.children === true) out.children = true;+ const l = config.labels;+ if (l && typeof l === "object" && !Array.isArray(l)) {+ const labels = Object.fromEntries(Object.entries(l as Record<string, unknown>).filter(([k, v]) => k !== "" && typeof v === "string" && v !== "")) as Record<string, string>;+ if (Object.keys(labels).length) out.labels = labels;+ }+ return out;+}+/** The SDK's `NetworkSettings` for a preset word (`internet`, `none`,* `localhost:5432,3000`, `localhost:all`, `lan`, `custom`, `custom:none`,* `unprotected`) and lists. `via`: where its internet traffic leavesdiff --git a/apps/cua-spaces-desktop/src/model/home-grants.ts b/apps/cua-spaces-desktop/src/model/home-grants.tsnew file mode 100644index 0000000000..9e555478c7--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/home-grants.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// What the person approved for an agent home while it runs (CUA-2630): see+// every Space, use a machine. It is written to `<cua home>/agent-home/grants.json`,+// which this machine's cua daemon reads each time the home asks+// (`children/home.rs`), so an approval takes effect at once with no restart.+// The file is outside the home Space: the agent in it can never write it.+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import * as os from "node:os";+import * as path from "node:path";++export interface HomeGrantsArg {+ listAll?: boolean;+ machines?: string[];+ /** Spaces and machines @mentioned in a later request (ids and names): an @mention counts as the grant. */+ mentions?: string[];+}++/** The cua home the daemon uses (`CUA_HOME`, else `~/.cua`). */+export function cuaHomeOf(env: NodeJS.ProcessEnv): string {+ return env.CUA_HOME && env.CUA_HOME !== "" ? env.CUA_HOME : path.join(os.homedir(), ".cua");+}++/** The grants in a `spaces.setAccess` request's `home`; the wrong types are ignored. */+export function homeGrantsOf(v: unknown): HomeGrantsArg | null {+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;+ const o = v as Record<string, unknown>;+ const out: HomeGrantsArg = {};+ if (typeof o.listAll === "boolean") out.listAll = o.listAll;+ if (Array.isArray(o.machines)) out.machines = [...new Set(o.machines.filter((m): m is string => typeof m === "string" && m !== ""))].sort();+ if (Array.isArray(o.mentions)) out.mentions = [...new Set(o.mentions.filter((m): m is string => typeof m === "string" && m !== ""))].sort();+ return Object.keys(out).length ? out : null;+}++/** Sets `space`'s grants in the file, keeping the other homes'. */+export async function writeHomeGrants(cuaHome: string, space: string, g: HomeGrantsArg): Promise<void> {+ const dir = path.join(cuaHome, "agent-home");+ const file = path.join(dir, "grants.json");+ let all: Record<string, { list_all?: boolean; machines?: string[]; mentions?: string[] }> = {};+ try {+ const parsed = JSON.parse(await readFile(file, "utf8")) as unknown;+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) all = parsed as typeof all;+ } catch {+ // No file yet, or a broken one: start again.+ }+ const prev = all[space] ?? {};+ // Mentions only accumulate: a later request never forgets what an earlier one named.+ const mentions = [...new Set([...(prev.mentions ?? []), ...(g.mentions ?? [])])].sort();+ all[space] = { list_all: g.listAll ?? prev.list_all ?? false, machines: g.machines ?? prev.machines ?? [], ...(mentions.length ? { mentions } : {}) };+ await mkdir(dir, { recursive: true, mode: 0o700 });+ const tmp = `${file}.${process.pid}.tmp`;+ await writeFile(tmp, JSON.stringify(all), { mode: 0o600 });+ await rename(tmp, file);+}diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.tsindex e16ce8d86d..cf855f7e7a 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts@@ -40887,7 +40887,25 @@ export type AppSettings = {* Tips ([`crate::tips`]): "Don't show tips" and the ones done. An* older settings file without it reads as tips on, none done.*/- tips: AppTipsState+ tips: AppTipsState,+ /**+ * Settings, Connections, Agent menu ([`crate::agent_menu`]): the apps+ * Home's agent menu shows although the default hides them (an app+ * outside Codex, Hermes, Claude Code and OpenCode, not signed in).+ */+ agentMenuShown: Array<string>,+ /**+ * The apps the menu hides although the default shows them. Nothing is+ * signed out: a hidden app keeps its sign-ins and stays on the Agents+ * page and available by name.+ */+ agentMenuHidden: Array<string>,+ /**+ * The working accounts the menu last saw (`app|variable|slot`): a new+ * one is a connect, which shows its app again+ * ([`crate::agent_menu::sync`]).+ */+ agentMenuSeen: Array<string>}/**@@ -40928,7 +40946,10 @@ const FfiConverterTypeAppSettings = (() => {teleportChoices: FfiConverterSequenceTypeAppRememberedChoice.read(from),autoConnect: FfiConverterBool.read(from),currentTeamId: FfiConverterOptionalString.read(from),- tips: FfiConverterTypeAppTipsState.read(from)+ tips: FfiConverterTypeAppTipsState.read(from),+ agentMenuShown: FfiConverterSequenceString.read(from),+ agentMenuHidden: FfiConverterSequenceString.read(from),+ agentMenuSeen: FfiConverterSequenceString.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -40950,6 +40971,9 @@ const FfiConverterTypeAppSettings = (() => {FfiConverterBool.write(value.autoConnect, into);FfiConverterOptionalString.write(value.currentTeamId, into);FfiConverterTypeAppTipsState.write(value.tips, into);+ FfiConverterSequenceString.write(value.agentMenuShown, into);+ FfiConverterSequenceString.write(value.agentMenuHidden, into);+ FfiConverterSequenceString.write(value.agentMenuSeen, into);}allocationSize(value: TypeName): number {return FfiConverterString.allocationSize(value.hotkey) +@@ -40969,7 +40993,10 @@ const FfiConverterTypeAppSettings = (() => {FfiConverterSequenceTypeAppRememberedChoice.allocationSize(value.teleportChoices) +FfiConverterBool.allocationSize(value.autoConnect) +FfiConverterOptionalString.allocationSize(value.currentTeamId) +- FfiConverterTypeAppTipsState.allocationSize(value.tips);+ FfiConverterTypeAppTipsState.allocationSize(value.tips) ++ FfiConverterSequenceString.allocationSize(value.agentMenuShown) ++ FfiConverterSequenceString.allocationSize(value.agentMenuHidden) ++ FfiConverterSequenceString.allocationSize(value.agentMenuSeen);}};diff --git a/apps/cua-spaces-desktop/test/agents-fixtures.ts b/apps/cua-spaces-desktop/test/agents-fixtures.tsindex 3949832988..bc1e344c45 100644--- a/apps/cua-spaces-desktop/test/agents-fixtures.ts+++ b/apps/cua-spaces-desktop/test/agents-fixtures.ts@@ -116,6 +116,12 @@ export class FakeAgentKeysTools {case "agent_keys.remove":this.keys = this.keys.filter((k) => (typeof args.slot === "string" ? !(k.env === args.env && k.slot === args.slot) : k.env !== args.env));break;+ case "agent_keys.rename": {+ const k = this.keys.find((x) => x.env === args.env && (typeof args.slot === "string" ? x.slot === args.slot : !x.slot));+ if (!k) throw new ToolError("that key isn't saved");+ k.label = String(args.label ?? "");+ break;+ }case "agent_keys.use": {const app = String(args.app ?? "");if (typeof args.env === "string") this.uses[app] = { provider: "anthropic", env: args.env, ...(typeof args.slot === "string" ? { slot: args.slot } : {}) };@@ -251,7 +257,7 @@ export const AGENT_METHODS = ["agents.status", "agents.connect", "agents.disconnect", "agents.signInStart", "agents.signInWait",// "Pick up where you left off" (test/agent-threads.test.ts): the daemon's person-only tools agent_threads and agent_thread_history."agents.recentThreads", "agents.threadHistory",- "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.shell", "agentKeys.fromShell",+ "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.rename", "agentKeys.shell", "agentKeys.fromShell",// Settings, Connections, GitHub (test/github.test.ts): answered by the daemon's tools."github.status", "github.rescan", "github.use", "github.enable",];diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.tsindex d362e3836d..6838f51035 100644--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts@@ -196,6 +196,12 @@ describe.skipIf(!built)("the bridge on the app core", () => {["network.log", { spaceId: "local:aurora" }],["network.ackNotice", { spaceId: "local:aurora" }],["spaces.setAccess", { spaceId: "local:aurora", clipboard: "ask" }],+ ["spaces.tree", {}],+ ["children.set", { spaceId: "local:aurora", enabled: true }],+ ["budget.get", { spaceId: "local:aurora" }],+ ["budget.set", { spaceId: "local:aurora", limits: { maxSpaces: 4 } }],+ ["services.list", { spaceId: "local:aurora" }],+ ["services.control", { spaceId: "local:aurora", name: "web", action: "restart" }],["checklist.get", {}],["cli.plan", {}],["checklist.send", { action: { type: "done", step: "teleport" } }],@@ -640,6 +646,11 @@ describe.skipIf(!built)("the bridge on the app core", () => {"network.log": { spaceId: "local:aurora" },"network.ackNotice": { spaceId: "local:aurora" },"spaces.setAccess": { spaceId: "local:aurora", clipboard: "ask" },+ "children.set": { spaceId: "local:aurora", enabled: true },+ "budget.get": { spaceId: "local:aurora" },+ "budget.set": { spaceId: "local:aurora", limits: { maxSpaces: 4 } },+ "services.list": { spaceId: "local:aurora" },+ "services.control": { spaceId: "local:aurora", name: "web", action: "restart" },"checklist.send": { action: { type: "done", step: "teleport" } },"links.approve": { id: "share-000000000001" },"links.deny": { id: "share-000000000001" },diff --git a/apps/cua-spaces-desktop/test/create-extras.test.ts b/apps/cua-spaces-desktop/test/create-extras.test.tsnew file mode 100644index 0000000000..81817b8fbf--- /dev/null+++ b/apps/cua-spaces-desktop/test/create-extras.test.ts@@ -0,0 +1,22 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// What `spaces.create` forwards for an agent home (CUA-2630): the spawn capability and its `cua.home.*` labels.+import { describe, expect, it } from "vitest";+import { createExtrasOf } from "../src/model/backend";++describe("a create's extras", () => {+ it("carry an agent home's children and labels", () => {+ expect(createExtrasOf({ image: "x", children: true, labels: { "cua.home": "1", "cua.home.agent": "claude-code" } })).toEqual({+ children: true,+ labels: { "cua.home": "1", "cua.home.agent": "claude-code" },+ });+ });+ it("are empty for a plain create", () => {+ expect(createExtrasOf({ image: "x", network: "none" })).toEqual({});+ });+ it("ignore the wrong types and labels that are not text", () => {+ expect(createExtrasOf({ children: 1, labels: { a: 1, "": "x", b: "", c: "ok" } })).toEqual({ labels: { c: "ok" } });+ expect(createExtrasOf({ labels: ["a"] })).toEqual({});+ });+});diff --git a/apps/cua-spaces-desktop/test/fixtures.ts b/apps/cua-spaces-desktop/test/fixtures.tsindex 3cac61a265..e092118181 100644--- a/apps/cua-spaces-desktop/test/fixtures.ts+++ b/apps/cua-spaces-desktop/test/fixtures.ts@@ -21,7 +21,21 @@ import type {SpacePresenceLike,TeleportLike,} from "../src/native/generated/index";-import type { BulkResult, LocalRuntimes, MachineHealthReport, NetworkEventJson, ShareLinkRow, ShareSettingsRow, SpaceNetworkJson, SpaceThumbnailData, SpacesBackend } from "../src/model/backend";+import type {+ BulkResult,+ LocalRuntimes,+ MachineHealthReport,+ NetworkEventJson,+ ServiceJson,+ ShareLinkRow,+ ShareSettingsRow,+ SpaceNetworkJson,+ SpaceThumbnailData,+ SpacesBackend,+ TreeBudgetJson,+ TreeBudgetLimitsJson,+ TreeNodeJson,+} from "../src/model/backend";import type { StreamWindow } from "../src/model/streams";import type { AccountProfile, AccountRunning, LinkNoticeView, SignInAttempt, TelemetryRunning } from "../src/model/services";@@ -408,6 +422,33 @@ export class FixtureSpacesBackend implements SpacesBackend {return [...this.exitsNow];}async setAccess(_id: string, _clipboard: string | null, _volume: string | null) {}+ async spaceTree(): Promise<TreeNodeJson[]> {+ return [{ id: "local:aurora", parent: null, depth: 0, children: false, home: null }];+ }+ async setChildren(_id: string, _enabled: boolean) {}+ async treeBudget(id: string): Promise<TreeBudgetJson> {+ return {+ root: id,+ set: {},+ maxSpaces: 8,+ maxVcpus: 16,+ maxMemoryMb: 32768,+ usdPerHour: 5,+ usdTotal: null,+ spaces: 1,+ vcpus: 2,+ memoryMb: 4096,+ usdPerHourUsed: 0,+ usdSpent: 0,+ };+ }+ async setTreeBudget(id: string, limits: TreeBudgetLimitsJson): Promise<TreeBudgetJson> {+ return { ...(await this.treeBudget(id)), set: limits };+ }+ async services(_id: string): Promise<ServiceJson[]> {+ return [];+ }+ async controlService(_id: string, _name: string, _action: string) {}async stopLink(id: string) {const gone = this.linksNow.filter((l) => id === "all" || l.id === id).map((l) => l.id);this.linksNow = this.linksNow.filter((l) => !gone.includes(l.id));diff --git a/apps/cua-spaces-desktop/test/home-grants.test.ts b/apps/cua-spaces-desktop/test/home-grants.test.tsnew file mode 100644index 0000000000..fa51b0a4be--- /dev/null+++ b/apps/cua-spaces-desktop/test/home-grants.test.ts@@ -0,0 +1,46 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// An agent home's grants reach the daemon through a file in the cua home (CUA-2630).+import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";+import { tmpdir } from "node:os";+import * as path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import { cuaHomeOf, homeGrantsOf, writeHomeGrants } from "../src/model/home-grants";++const dir = mkdtempSync(path.join(tmpdir(), "cua-home-grants-"));+afterAll(() => rmSync(dir, { recursive: true, force: true }));+const read = () => JSON.parse(readFileSync(path.join(dir, "agent-home", "grants.json"), "utf8"));++describe("a home's grants file", () => {+ it("reads the request's grants and ignores the wrong types", () => {+ expect(homeGrantsOf({ listAll: true, machines: ["b", "a", "a", 3, ""] })).toEqual({ listAll: true, machines: ["a", "b"] });+ expect(homeGrantsOf({ listAll: "yes" })).toBeNull();+ expect(homeGrantsOf(null)).toBeNull();+ expect(homeGrantsOf([])).toBeNull();+ });++ it("is written per Space, owner only, and keeps what the other homes hold", async () => {+ await writeHomeGrants(dir, "local:home-a", { listAll: true });+ await writeHomeGrants(dir, "local:home-b", { machines: ["m-air"] });+ await writeHomeGrants(dir, "local:home-a", { machines: ["m-mini"] });+ expect(read()).toEqual({+ "local:home-a": { list_all: true, machines: ["m-mini"] },+ "local:home-b": { list_all: false, machines: ["m-air"] },+ });+ if (process.platform !== "win32") expect(statSync(path.join(dir, "agent-home", "grants.json")).mode & 0o077).toBe(0);+ });++ it("keeps what later requests @mention, adding to it and never forgetting it", async () => {+ expect(homeGrantsOf({ mentions: ["ci", "local:ci", "ci", 4] })).toEqual({ mentions: ["ci", "local:ci"] });+ await writeHomeGrants(dir, "local:home-m", { mentions: ["ci", "local:ci"] });+ await writeHomeGrants(dir, "local:home-m", { mentions: ["studio"] });+ await writeHomeGrants(dir, "local:home-m", { listAll: true });+ expect(read()["local:home-m"]).toEqual({ list_all: true, machines: [], mentions: ["ci", "local:ci", "studio"] });+ });++ it("uses CUA_HOME, else ~/.cua", () => {+ expect(cuaHomeOf({ CUA_HOME: "/x/y" })).toBe("/x/y");+ expect(cuaHomeOf({})).toMatch(/\.cua$/);+ });+});diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.tsindex 5b969c7fea..5db92e1f37 100644--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts@@ -596,6 +596,19 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()expect(native.appSettingsLoad(model.settingsPath).notchPinned).toEqual([]);});+ it("keeps which coding apps the agent menu shows in the app settings (`settings.update`), across a restart", async () => {+ const before = (await call("settings.get")) as { agentMenu: { shown: string[]; hidden: string[]; seen: string[] } };+ expect(before.agentMenu).toEqual({ shown: [], hidden: [], seen: [] });+ const menu = { shown: ["goose"], hidden: ["hermes"], seen: ["claude-code|CLAUDE_CODE_OAUTH_TOKEN|"] };+ const after = (await call("settings.update", { agentMenu: menu })) as typeof before;+ expect(after.agentMenu).toEqual(menu);+ const kept = native.appSettingsLoad(model.settingsPath);+ expect([kept.agentMenuShown, kept.agentMenuHidden, kept.agentMenuSeen]).toEqual([menu.shown, menu.hidden, menu.seen]);+ expect(model.settings.tips).toEqual({ off: false, done: [] });+ expect(await code("settings.update", { agentMenu: { shown: [], hidden: "hermes", seen: [] } })).toBe("bad_args");+ expect(await code("settings.update", { agentMenu: null })).toBe("bad_args");+ });+it("keeps the page's tips in the app settings (`settings.update`), and Show tips and Reset tips", async () => {const before = (await call("settings.get")) as { tips: unknown };expect(before.tips).toEqual({ off: false, done: [] });diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swiftindex b1aca9a533..98a591508d 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift@@ -635,6 +635,16 @@ public final class PendingSpacesBackend: SpacesBackend, AgentsToolRunning, Cloudpublic func setAccess(id: String, clipboard: String?, volume: String?) async throws {try await b().setAccess(id: id, clipboard: clipboard, volume: volume)}+ public func spaceTree() async throws -> [[String: Any]] { try await b().spaceTree() }+ public func setChildren(id: String, enabled: Bool) async throws { try await b().setChildren(id: id, enabled: enabled) }+ public func treeBudget(id: String) async throws -> [String: Any] { try await b().treeBudget(id: id) }+ public func setTreeBudget(id: String, limits: [String: Any]) async throws -> [String: Any] {+ try await b().setTreeBudget(id: id, limits: limits)+ }+ public func services(id: String) async throws -> [[String: Any]] { try await b().services(id: id) }+ public func controlService(id: String, name: String, action: String) async throws {+ try await b().controlService(id: id, name: name, action: action)+ }public func setPower(id: String, on: Bool) async throws { try await b().setPower(id: id, on: on) }public func streamProvider(id: String) async throws -> SpaceStreamSourceProviding {try await b().streamProvider(id: id)diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HomeGrants.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HomeGrants.swiftnew file mode 100644index 0000000000..985c20b1e9--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HomeGrants.swift@@ -0,0 +1,61 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation++/// What the person approved for an agent home while it runs (CUA-2630): see+/// every Space, use a machine. Written to `<cua home>/agent-home/grants.json`,+/// which this machine's cua daemon reads each time the home asks+/// (`children/home.rs`), so an approval takes effect at once with no restart.+/// The file is outside the home Space: the agent in it can never write it.+struct HomeGrants: Equatable, Sendable {+ var listAll: Bool?+ var machines: [String]?+ /// Spaces and machines @mentioned in a later request (ids and names): an @mention counts as the grant.+ var mentions: [String]?++ /// The grants in a `spaces.setAccess` request's `home`; the wrong types are ignored.+ static func parse(_ value: Any?) -> HomeGrants? {+ guard let o = value as? [String: Any] else { return nil }+ var g = HomeGrants()+ if let l = o["listAll"] as? Bool { g.listAll = l }+ if let m = o["machines"] as? [Any] {+ g.machines = Array(Set(m.compactMap { $0 as? String }.filter { !$0.isEmpty })).sorted()+ }+ if let m = o["mentions"] as? [Any] {+ g.mentions = Array(Set(m.compactMap { $0 as? String }.filter { !$0.isEmpty })).sorted()+ }+ return g.listAll == nil && g.machines == nil && g.mentions == nil ? nil : g+ }++ /// The cua home the daemon uses (`CUA_HOME`, else `~/.cua`).+ static func cuaHome(_ env: [String: String] = ProcessInfo.processInfo.environment) -> URL {+ if let h = env["CUA_HOME"], !h.isEmpty { return URL(fileURLWithPath: h, isDirectory: true) }+ return URL(fileURLWithPath: env["HOME"] ?? NSHomeDirectory(), isDirectory: true).appendingPathComponent(".cua", isDirectory: true)+ }++ /// Sets `space`'s grants in the file, keeping the other homes'.+ static func write(home: URL, space: String, _ g: HomeGrants) throws {+ let dir = home.appendingPathComponent("agent-home", isDirectory: true)+ let file = dir.appendingPathComponent("grants.json")+ var all: [String: Any] = [:]+ if let data = try? Data(contentsOf: file), let parsed = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] {+ all = parsed+ }+ let prev = all[space] as? [String: Any] ?? [:]+ // Mentions only accumulate: a later request never forgets what an earlier one named.+ let mentions = Array(Set((prev["mentions"] as? [String] ?? []) + (g.mentions ?? []))).sorted()+ var entry: [String: Any] = [+ "list_all": g.listAll ?? (prev["list_all"] as? Bool) ?? false,+ "machines": g.machines ?? (prev["machines"] as? [String]) ?? [],+ ]+ if !mentions.isEmpty { entry["mentions"] = mentions }+ all[space] = entry+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])+ let data = try JSONSerialization.data(withJSONObject: all, options: [.sortedKeys])+ let tmp = dir.appendingPathComponent("grants.json.\(ProcessInfo.processInfo.processIdentifier).tmp")+ try data.write(to: tmp)+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: tmp.path)+ _ = try FileManager.default.replaceItemAt(file, withItemAt: tmp)+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swiftindex 5ef46ade74..b3600fd3ce 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift@@ -94,6 +94,17 @@ public protocol SpacesBackend: AnyObject, Sendable {func exitsThroughThisMachine() async -> [String]/// `spaces.setAccess`: a Space's clipboard and/or Volume setting.func setAccess(id: String, clipboard: String?, volume: String?) async throws+ /// `spaces.tree`: every Space's parent, depth and whether it may make+ /// children (`Spaces.list_known`).+ func spaceTree() async throws -> [[String: Any]]+ /// `children.set`: lets a Space make child Spaces, or stops it.+ func setChildren(id: String, enabled: Bool) async throws+ /// `budget.get` / `budget.set`: a Space's tree's budget and use.+ func treeBudget(id: String) async throws -> [String: Any]+ func setTreeBudget(id: String, limits: [String: Any]) async throws -> [String: Any]+ /// `services.list` / `services.control`: the commands a Space keeps running.+ func services(id: String) async throws -> [[String: Any]]+ func controlService(id: String, name: String, action: String) async throws/// Takes one of your machines (`relay:<machine>`) off the relay/// directory (`Spaces.relay_unregister`): Remove from account on the/// Machines page. The relay refuses one that is online.@@ -426,6 +437,20 @@ public extension SpacesBackend {func setAccess(id: String, clipboard: String?, volume: String?) async throws {throw FixtureError(message: "These settings are not available here")}+ func spaceTree() async throws -> [[String: Any]] { [] }+ func setChildren(id: String, enabled: Bool) async throws {+ throw FixtureError(message: "Child Spaces are not available here")+ }+ func treeBudget(id: String) async throws -> [String: Any] {+ throw FixtureError(message: "Child Spaces are not available here")+ }+ func setTreeBudget(id: String, limits: [String: Any]) async throws -> [String: Any] {+ throw FixtureError(message: "Child Spaces are not available here")+ }+ func services(id: String) async throws -> [[String: Any]] { [] }+ func controlService(id: String, name: String, action: String) async throws {+ throw FixtureError(message: "Services are not available here")+ }func appIcons(id: String, requests: [SpaceAppIconRequest]) async -> [Data?] { requests.map { _ in nil } }func primaryDisplay(id: String) async -> AppStreamDisplay? { nil }func usage(id: String) async -> AppSpaceUsage? { nil }@@ -647,6 +672,11 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {if let word = CreateNetworks.shared.get(createId) {options.networkSettings = Self.networkSettings(word: word, allow: [], deny: [])}+ // An agent home: the spawn capability and its `cua.home.*` labels (CUA-2630).+ if let extras = CreateExtras.shared.get(createId) {+ if extras.children { options.children = true }+ if !extras.labels.isEmpty { options.labels = extras.labels }+ }let result = try await cua.spaces().createWithProgress(options: options, listener: CreateListener(progress))return result.space?.id ?? result.pendingId ?? ""@@ -804,6 +834,71 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {if let volume { try await cua.spaces().setVolume(space: id, volume: volume) }}+ public func spaceTree() async throws -> [[String: Any]] {+ try await cua.spaces().listKnown().spaces.map { s in+ // `home`: the agent an agent home (labelled `cua.home`) was made for, so a home is found again by its label.+ let home: Any = s.labels["cua.home"] == "1" ? (s.labels["cua.home.agent"] ?? "") : NSNull()+ return ["id": s.id, "parent": s.parent as Any, "depth": Int(s.depth), "children": s.children, "home": home]+ }+ }++ public func setChildren(id: String, enabled: Bool) async throws {+ try await cua.spaces().setChildren(space: id, enabled: enabled)+ }++ public func treeBudget(id: String) async throws -> [String: Any] {+ Self.budgetJSON(try await cua.spaces().treeBudget(space: id))+ }++ public func setTreeBudget(id: String, limits: [String: Any]) async throws -> [String: Any] {+ let n = { (k: String) -> Double? in (limits[k] as? NSNumber).map(\.doubleValue).flatMap { $0 >= 0 && $0.isFinite ? $0 : nil } }+ let l = CuaSDK.TreeBudgetLimits(+ maxSpaces: n("maxSpaces").map { UInt32(min($0, Double(UInt32.max))) },+ maxVcpus: n("maxVcpus").map { UInt32(min($0, Double(UInt32.max))) },+ maxMemoryMb: n("maxMemoryMb").map { UInt64($0) },+ usdPerHour: n("usdPerHour"),+ usdTotal: n("usdTotal"))+ return Self.budgetJSON(try await cua.spaces().setTreeBudget(space: id, limits: l))+ }++ public func services(id: String) async throws -> [[String: Any]] {+ try await cua.spaces().space(space: id).keptServices().map { s in+ [+ "name": s.name, "command": s.command, "state": s.state, "restarts": Int(s.restarts),+ "lastEnd": s.lastEnd, "probeError": s.probeError,+ ]+ }+ }++ public func controlService(id: String, name: String, action: String) async throws {+ let space = try await cua.spaces().space(space: id)+ switch action {+ case "start": _ = try await space.startService(name: name)+ case "stop": _ = try await space.stopService(name: name)+ case "restart": _ = try await space.restartService(name: name)+ case "remove": try await space.deleteService(name: name)+ default: throw FixtureError(message: "No service action \(action)")+ }+ }++ /// The SDK's `TreeBudget` as the web page's `budget.get` answers it.+ static func budgetJSON(_ b: CuaSDK.TreeBudget) -> [String: Any] {+ [+ "root": b.root,+ "set": [+ "maxSpaces": b.set.maxSpaces.map { Int($0) } as Any,+ "maxVcpus": b.set.maxVcpus.map { Int($0) } as Any,+ "maxMemoryMb": b.set.maxMemoryMb.map { Int($0) } as Any,+ "usdPerHour": b.set.usdPerHour as Any,+ "usdTotal": b.set.usdTotal as Any,+ ] as [String: Any],+ "maxSpaces": Int(b.maxSpaces), "maxVcpus": Int(b.maxVcpus), "maxMemoryMb": Int(b.maxMemoryMb),+ "usdPerHour": b.usdPerHour, "usdTotal": b.usdTotal as Any,+ "spaces": Int(b.spaces), "vcpus": Int(b.vcpus), "memoryMb": Int(b.memoryMb),+ "usdPerHourUsed": b.usdPerHourUsed, "usdSpent": b.usdSpent,+ ]+ }+/// The SDK's `NetworkSettings` for a preset word (`internet`, `none`,/// `localhost:5432,3000`, `localhost:all`, `lan`, `custom`, `custom:none`,/// `unprotected`) and lists.@@ -1344,7 +1439,7 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {}public func removeShareEdge() async throws -> [String] { [] }- // Network settings: canned answers in the page's shapes.+ // Network, child Spaces and kept commands: canned answers in the page's shapes.public func network(id: String) async throws -> [String: Any] {["preset": "internet", "localhostPorts": [Int](), "allLocalhostPorts": false, "allow": [String](), "deny": [String](),"customBase": "", "widenedBy": NSNull(), "summary": "Internet only", "widenings": [String](),@@ -1353,6 +1448,20 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {}public func setNetwork(id: String, word: String, allow: [String], deny: [String], widen: Bool, tree: Bool, via: String?) async throws -> String { "now" }public func setAccess(id: String, clipboard: String?, volume: String?) async throws {}+ public func spaceTree() async throws -> [[String: Any]] {+ await MainActor.run { fixtureRows.map { ["id": $0.id, "parent": NSNull(), "depth": 0, "children": false] as [String: Any] } }+ }+ public func setChildren(id: String, enabled: Bool) async throws {}+ public func treeBudget(id: String) async throws -> [String: Any] {+ ["root": id, "set": [String: Any](), "maxSpaces": 8, "maxVcpus": 16, "maxMemoryMb": 32768, "usdPerHour": 5.0,+ "usdTotal": NSNull(), "spaces": 1, "vcpus": 2, "memoryMb": 4096, "usdPerHourUsed": 0.0, "usdSpent": 0.0]+ }+ public func setTreeBudget(id: String, limits: [String: Any]) async throws -> [String: Any] {+ var b = try await treeBudget(id: id)+ b["set"] = limits+ return b+ }+ public func controlService(id: String, name: String, action: String) async throws {}public var fixtureRows: [AppSpaceRow]public private(set) var created: [AppCreateSpaceArgs] = []public private(set) var added: [String] = []@@ -1750,7 +1859,7 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {}}-/// The New Space's Network choice by create id, until its create is over+/// The New Space's Network choice by create id, until its create runs/// (the web page sends it with `spaces.create`'s `config.network`).final class CreateNetworks: @unchecked Sendable {static let shared = CreateNetworks()@@ -1772,3 +1881,44 @@ final class CreateNetworks: @unchecked Sendable {words.removeValue(forKey: id)}}++/// What an agent home is created with besides the plan's fields (CUA-2630),+/// by create id, until its create is over (the web page sends it with+/// `spaces.create`'s `config.children` and `labels`).+struct CreateExtrasValue: Equatable, Sendable {+ var children = false+ var labels: [String: String] = [:]++ var isEmpty: Bool { !children && labels.isEmpty }++ /// The extras in a `spaces.create` config; the wrong types are ignored and a label that is not text is dropped.+ static func parse(_ config: [String: Any]) -> CreateExtrasValue {+ var out = CreateExtrasValue()+ out.children = config["children"] as? Bool == true+ if let l = config["labels"] as? [String: Any] {+ for (k, v) in l { if !k.isEmpty, let t = v as? String, !t.isEmpty { out.labels[k] = t } }+ }+ return out+ }+}++final class CreateExtras: @unchecked Sendable {+ static let shared = CreateExtras()+ private let lock = NSLock()+ private var values: [String: CreateExtrasValue] = [:]++ func set(_ id: String, _ v: CreateExtrasValue) {+ lock.lock(); defer { lock.unlock() }+ values[id] = v+ }++ func get(_ id: String) -> CreateExtrasValue? {+ lock.lock(); defer { lock.unlock() }+ return values[id]+ }++ func clear(_ id: String) {+ lock.lock(); defer { lock.unlock() }+ values.removeValue(forKey: id)+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 2c1c400c3b..1388cda91b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -138,6 +138,11 @@ extension WebUIBridge {if let env = args["env"] as? String, !env.isEmpty { useArgs["env"] = env }if let slot = args["slot"] as? String, !slot.isEmpty { useArgs["slot"] = slot }return try await model.agentKeys.call("agent_keys.use", useArgs)+ // A saved key or sign-in gets a name (no slot: the first saved for env).+ case "agentKeys.rename":+ var renameArgs: [String: Any] = ["env": try string(args, "env"), "label": try string(args, "label")]+ if let slot = args["slot"] as? String, !slot.isEmpty { renameArgs["slot"] = slot }+ return try await model.agentKeys.call("agent_keys.rename", renameArgs)// Which provider keys your login shell has (names only), and one saved from it (the value never crosses the bridge).case "agentKeys.shell": return try await model.agentKeys.call("agent_keys.shell")case "agentKeys.fromShell":@@ -560,6 +565,9 @@ extension WebUIBridge {guard let harness = args["harness"] as? String, !harness.isEmpty else { throw Failure.badArgs("harness: string") }out["name"] = nameout["agent"] = harness+ if let model = args["model"] as? String, !model.isEmpty { out["model"] = model }+ if let standby = args["standby"] as? Bool { out["standby"] = standby }+ if let brief = args["brief"] as? String, !brief.isEmpty { out["brief"] = brief }return ("agent_add", out)case "thread.agentRemove":// Member names are unique per machine: the tool takes the name.diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex ee9d6f28be..7afb167eaf 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -72,6 +72,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"spaces.setPower", "spaces.delete", "spaces.rename", "spaces.deleteMany", "spaces.leave", "spaces.cancelCreate",// A Space's network, clipboard and Volume settings (the SDK's)."network.get", "network.set", "network.log", "network.ackNotice", "spaces.setAccess",+ // Child Spaces (the Child Spaces experiment; the daemon refuses them while it is off).+ "spaces.tree", "children.set", "budget.get", "budget.set", "services.list", "services.control","machines.list", "host.status","agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume","agents.setup", "agents.configure", "agents.signIn",@@ -85,7 +87,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {// A persistent agent's Memory, Routines and Access (`PersistentModel`)."agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine","agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer",- "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.shell", "agentKeys.fromShell",+ "agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.rename", "agentKeys.shell", "agentKeys.fromShell",// Settings, Connections, GitHub: the daemon's github.* methods (WebUIBridge+Pages.swift)."github.status", "github.rescan", "github.use", "github.enable",// New Space's address form and Connect a cloud, Teleport and Share,@@ -334,8 +336,34 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {try await model.backend.ackNetworkNotice(id: try string(args, "spaceId"))return [String: Any]()case "spaces.setAccess":+ let space = try string(args, "spaceId")let clipboard = args["clipboard"] as? String, volume = args["volume"] as? String- try await model.backend.setAccess(id: try string(args, "spaceId"), clipboard: clipboard, volume: volume)+ // An agent home's grants (CUA-2630): the file this machine's daemon reads.+ let grants = HomeGrants.parse(args["home"])+ if let grants { try HomeGrants.write(home: HomeGrants.cuaHome(), space: space, grants) }+ if grants != nil && clipboard == nil && volume == nil { return [String: Any]() }+ try await model.backend.setAccess(id: space, clipboard: clipboard, volume: volume)+ return [String: Any]()+ case "spaces.tree":+ return try await model.backend.spaceTree()+ case "children.set":+ guard let enabled = args["enabled"] as? Bool else { throw Failure.badArgs("enabled: boolean") }+ try await model.backend.setChildren(id: try string(args, "spaceId"), enabled: enabled)+ return [String: Any]()+ case "budget.get":+ return try await model.backend.treeBudget(id: try string(args, "spaceId"))+ case "budget.set":+ return try await model.backend.setTreeBudget(+ id: try string(args, "spaceId"), limits: args["limits"] as? [String: Any] ?? [:])+ case "services.list":+ return try await model.backend.services(id: try string(args, "spaceId"))+ case "services.control":+ let action = try string(args, "action")+ guard ["start", "stop", "restart", "remove"].contains(action) else {+ throw Failure.badArgs("action: start, stop, restart or remove")+ }+ try await model.backend.controlService(+ id: try string(args, "spaceId"), name: try string(args, "name"), action: action)return [String: Any]()case "spaces.setPower":let space = try space(args)@@ -661,6 +689,12 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"tips": ["off": model.settings.tips.off, "done": model.settings.tips.done] as [String: Any],// The Spaces and machine desktops pinned to the notch, in pin order."notchPinned": model.settings.notchPinned,+ // Which coding apps the agent menu shows (`AppSettings.agentMenu*`, the core's `agent_menu`).+ "agentMenu": [+ "shown": model.settings.agentMenuShown,+ "hidden": model.settings.agentMenuHidden,+ "seen": model.settings.agentMenuSeen,+ ] as [String: Any],]}@@ -760,6 +794,10 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {CreateNetworks.shared.set(pendingId, word)}defer { CreateNetworks.shared.clear(pendingId) }+ // An agent home: the spawn capability and its labels (CUA-2630).+ let extras = CreateExtrasValue.parse(config)+ if !extras.isEmpty { CreateExtras.shared.set(pendingId, extras) }+ defer { CreateExtras.shared.clear(pendingId) }// The page sends the plan's OS (the pending row's icon).let os = (args["os"] as? String).flatMap(AppSpaceOs.init(word:)) ?? .unknownlet id: String@@ -1247,7 +1285,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {// MARK: - The core's own settings/// `settings.update`: each key given is saved as is (`tips`:- /// `{off, done}`; `notchPinned`: the pinned ids in pin order).+ /// `{off, done}`; `notchPinned`: the pinned ids in pin order; `agentMenu`:+ /// `{shown, hidden, seen}`, which coding apps the agent menu shows).func updateSettings(_ args: [String: Any]) throws {var next = model.settingsif let raw = args["tips"] {@@ -1258,6 +1297,15 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {guard let ids = raw as? [String] else { throw Failure.badArgs("notchPinned: string[]") }next.notchPinned = ids}+ if let raw = args["agentMenu"] {+ guard let m = raw as? [String: Any], let shown = m["shown"] as? [String],+ let hidden = m["hidden"] as? [String], let seen = m["seen"] as? [String] else {+ throw Failure.badArgs("agentMenu: {shown: string[], hidden: string[], seen: string[]}")+ }+ next.agentMenuShown = shown+ next.agentMenuHidden = hidden+ next.agentMenuSeen = seen+ }guard next != model.settings else { return }let pinned = next.notchPinnedmodel.settings = nextdiff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swiftindex 4c22210e3f..a9d0dacf59 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift@@ -31,7 +31,7 @@ final class FakeAgentKeysTools: AgentsToolRunning, @unchecked Sendable {} else {keys.removeAll { $0["env"] as? String == args["env"] as? String }}- case "agent_keys.use": break+ case "agent_keys.use", "agent_keys.rename": break// Your login shell has an Anthropic key: names only, and a copy saved on request.case "agent_keys.shell": return ["names": ["ANTHROPIC_API_KEY"]]case "agent_keys.from_shell":@@ -107,7 +107,7 @@ struct AgentKeysTests {}@Test func theWebBridgeRoutesAgentKeysToTheDaemon() {- for m in ["agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.shell", "agentKeys.fromShell"] {+ for m in ["agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.rename", "agentKeys.shell", "agentKeys.fromShell"] {#expect(WebUIBridge.methods.contains(m))}}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex a0f70a0525..4dde9f6c3c 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -163,6 +163,16 @@ struct BridgeContractTests {func setAccess(id: String, clipboard: String?, volume: String?) async throws {try await inner.setAccess(id: id, clipboard: clipboard, volume: volume)}+ func spaceTree() async throws -> [[String: Any]] { try await inner.spaceTree() }+ func setChildren(id: String, enabled: Bool) async throws { try await inner.setChildren(id: id, enabled: enabled) }+ func treeBudget(id: String) async throws -> [String: Any] { try await inner.treeBudget(id: id) }+ func setTreeBudget(id: String, limits: [String: Any]) async throws -> [String: Any] {+ try await inner.setTreeBudget(id: id, limits: limits)+ }+ func services(id: String) async throws -> [[String: Any]] { try await inner.services(id: id) }+ func controlService(id: String, name: String, action: String) async throws {+ try await inner.controlService(id: id, name: name, action: action)+ }func hosts() async -> [AppSpaceHost] { await inner.hosts() }func reportedHostname(id: String) -> String? { inner.reportedHostname(id: id) }func add(url: String, token: String?, name: String?) async throws { try await inner.add(url: url, token: token, name: name) }@@ -255,7 +265,10 @@ struct BridgeContractTests {("network.get", ["spaceId": space]),("network.set", ["spaceId": space, "network": "internet", "allow": [String](), "deny": [String]()]),("network.log", ["spaceId": space]), ("network.ackNotice", ["spaceId": space]),- ("spaces.setAccess", ["spaceId": space, "clipboard": "ask"]),+ ("spaces.setAccess", ["spaceId": space, "clipboard": "ask"]), ("spaces.tree", [:]),+ ("children.set", ["spaceId": space, "enabled": true]),+ ("budget.get", ["spaceId": space]), ("budget.set", ["spaceId": space, "limits": ["maxSpaces": 4]]),+ ("services.list", ["spaceId": space]), ("services.control", ["spaceId": space, "name": "web", "action": "restart"]),("checklist.get", [:]), ("checklist.send", ["action": ["type": "done", "step": "teleport"]]),("shares.settings.set", ["settings": ["landing": "auto", "relayFallback": true, "dailyCapMib": 2048, "defaultAllow": [String](), "approveAgentShares": true, "alwaysAllowSpaces": [String](), "edgeConsent": [String](), "usedToday": 0]]),("cli.plan", [:]),@@ -280,6 +293,7 @@ struct BridgeContractTests {("agentKeys.list", [:]), ("agentKeys.check", [:]), ("agentKeys.set", ["provider": "anthropic", "value": "sk-ant-test-0000"]),("agentKeys.remove", ["env": "ANTHROPIC_API_KEY"]),("agentKeys.use", ["app": "hermes", "env": "ANTHROPIC_API_KEY"]),+ ("agentKeys.rename", ["env": "ANTHROPIC_API_KEY", "label": "Work key"]),("agentKeys.shell", [:]), ("agentKeys.fromShell", ["env": "ANTHROPIC_API_KEY"]),("github.status", [:]), ("github.rescan", [:]), ("github.use", ["host": "github.com", "login": "ada"]),("github.enable", ["host": "github.com", "enabled": false]),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CreateExtrasTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CreateExtrasTests.swiftnew file mode 100644index 0000000000..dc3aabca8d--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CreateExtrasTests.swift@@ -0,0 +1,38 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++@testable import CuaSpacesMacKit+import Foundation+import Testing++/// What `spaces.create` forwards for an agent home (CUA-2630): the spawn capability and its `cua.home.*` labels.+@Suite("A create's extras")+struct CreateExtrasTests {+ @Test func carryAnAgentHomesChildrenAndLabels() {+ let e = CreateExtrasValue.parse([+ "image": "x", "children": true,+ "labels": ["cua.home": "1", "cua.home.agent": "claude-code"],+ ])+ #expect(e.children)+ #expect(e.labels == ["cua.home": "1", "cua.home.agent": "claude-code"])+ #expect(!e.isEmpty)+ }++ @Test func areEmptyForAPlainCreate() {+ #expect(CreateExtrasValue.parse(["image": "x", "network": "none"]).isEmpty)+ }++ @Test func ignoreTheWrongTypesAndLabelsThatAreNotText() {+ let e = CreateExtrasValue.parse(["children": 1, "labels": ["a": 1, "": "x", "b": "", "c": "ok"]])+ #expect(!e.children)+ #expect(e.labels == ["c": "ok"])+ }++ @Test func areKeptByCreateIdUntilCleared() {+ let id = "pending:\(UUID().uuidString)"+ CreateExtras.shared.set(id, CreateExtrasValue(children: true, labels: ["cua.home": "1"]))+ #expect(CreateExtras.shared.get(id)?.children == true)+ CreateExtras.shared.clear(id)+ #expect(CreateExtras.shared.get(id) == nil)+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HomeGrantsTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HomeGrantsTests.swiftnew file mode 100644index 0000000000..eb3c860666--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HomeGrantsTests.swift@@ -0,0 +1,57 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++@testable import CuaSpacesMacKit+import Foundation+import Testing++/// An agent home's grants reach the daemon through a file in the cua home (CUA-2630).+@Suite("An agent home's grants file")+struct HomeGrantsTests {+ func temp() -> URL {+ FileManager.default.temporaryDirectory.appendingPathComponent("cua-home-grants-\(UUID().uuidString)", isDirectory: true)+ }++ func read(_ home: URL) throws -> [String: Any] {+ let data = try Data(contentsOf: home.appendingPathComponent("agent-home/grants.json"))+ return try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])+ }++ @Test func readsTheRequestsGrantsAndIgnoresTheWrongTypes() {+ #expect(HomeGrants.parse(["listAll": true, "machines": ["b", "a", "a", 3, ""]]) == HomeGrants(listAll: true, machines: ["a", "b"]))+ #expect(HomeGrants.parse(["listAll": "yes"]) == nil)+ #expect(HomeGrants.parse(nil) == nil)+ }++ @Test func isWrittenPerSpaceOwnerOnlyAndKeepsTheOtherHomes() throws {+ let home = temp()+ defer { try? FileManager.default.removeItem(at: home) }+ try HomeGrants.write(home: home, space: "local:home-a", HomeGrants(listAll: true))+ try HomeGrants.write(home: home, space: "local:home-b", HomeGrants(machines: ["m-air"]))+ try HomeGrants.write(home: home, space: "local:home-a", HomeGrants(machines: ["m-mini"]))+ let all = try read(home)+ let a = try #require(all["local:home-a"] as? [String: Any])+ let b = try #require(all["local:home-b"] as? [String: Any])+ #expect(a["list_all"] as? Bool == true && a["machines"] as? [String] == ["m-mini"])+ #expect(b["list_all"] as? Bool == false && b["machines"] as? [String] == ["m-air"])+ let mode = try FileManager.default.attributesOfItem(atPath: home.appendingPathComponent("agent-home/grants.json").path)[.posixPermissions] as? Int+ #expect(mode.map { $0 & 0o077 } == 0)+ }++ @Test func keepsWhatLaterRequestsMentionAddingToItAndNeverForgettingIt() throws {+ #expect(HomeGrants.parse(["mentions": ["ci", "local:ci", "ci", 4]]) == HomeGrants(mentions: ["ci", "local:ci"]))+ let home = temp()+ defer { try? FileManager.default.removeItem(at: home) }+ try HomeGrants.write(home: home, space: "local:home-m", HomeGrants(mentions: ["ci", "local:ci"]))+ try HomeGrants.write(home: home, space: "local:home-m", HomeGrants(mentions: ["studio"]))+ try HomeGrants.write(home: home, space: "local:home-m", HomeGrants(listAll: true))+ let m = try #require(try read(home)["local:home-m"] as? [String: Any])+ #expect(m["list_all"] as? Bool == true)+ #expect(m["mentions"] as? [String] == ["ci", "local:ci", "studio"])+ }++ @Test func usesCuaHomeElseDotCua() {+ #expect(HomeGrants.cuaHome(["CUA_HOME": "/x/y"]).path == "/x/y")+ #expect(HomeGrants.cuaHome(["HOME": "/Users/z"]).path == "/Users/z/.cua")+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swiftindex cf662e953d..e1dca25cdc 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TipsTests.swift@@ -85,6 +85,29 @@ struct TipsTests {#expect(m.settings.tips == AppTipsState(off: false, done: []))}+ /// Which coding apps the agent menu shows rides the same settings path+ /// (`agentMenu`): the page reads and saves it and it survives a restart.+ /// The rule (defaults, the last app, a connect that shows an app again)+ /// is the core's `agent_menu`.+ @Test func theNewUISavesTheAgentMenuChoiceThroughTheBridge() async throws {+ let m = ViewModelTests().makeModel()+ let bridge = WebUIBridge(model: m, allowedOrigins: [])+ let before = try #require(try await bridge.handle("settings.get", [:]) as? [String: Any])+ let none = try #require(before["agentMenu"] as? [String: Any])+ #expect(none["hidden"] as? [String] == [])++ let after = try #require(try await bridge.handle("settings.update", [+ "agentMenu": ["shown": ["goose"], "hidden": ["hermes"], "seen": ["claude-code|CLAUDE_CODE_OAUTH_TOKEN|"]],+ ]) as? [String: Any])+ #expect((after["agentMenu"] as? [String: Any])?["hidden"] as? [String] == ["hermes"])+ #expect(settingsOnDisk(m).agentMenuHidden == ["hermes"])+ #expect(settingsOnDisk(m).agentMenuShown == ["goose"])+ #expect(settingsOnDisk(m).agentMenuSeen == ["claude-code|CLAUDE_CODE_OAUTH_TOKEN|"])+ // The tips are untouched, and a malformed choice is refused.+ #expect(m.settings.tips == AppTipsState(off: false, done: []))+ await #expect(throws: (any Error).self) { try await bridge.handle("settings.update", ["agentMenu": ["hidden": "hermes"]]) }+ }+/// The notch's pins ride the same settings path as the tips: the page reads/// and saves them (`notchPinned`), the notch lists the pinned first at once,/// and they survive a restart.diff --git a/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsxnew file mode 100644index 0000000000..391f48be49--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx@@ -0,0 +1,106 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// With the Ask first and Child Spaces experiments on, the box has no where row: the job goes to the agent's Home+// Space (the slim Linux image), which makes the Spaces it needs. A place is named with @.++import { act, 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 { resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { resetConnectState } from "@/hooks/use-connectors";+import { AGENT_HOME_IMAGE } from "@/lib/agent-home/container";+import { resetGrants } from "@/lib/agent-home/grants";+import { resetHomes } from "@/lib/agent-home/home-space";+import { askTasks, resetAskTasks } from "@/lib/ask-first";+import { resetPickedAgent } from "@/lib/ask-first-model";+import { resetRepos } from "@/lib/ask-first-repo";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetAskTasks();+ resetPickedAgent();+ resetRepos();+ resetHomes();+ resetGrants();+ resetConnectState();+ resetConnectedAppsState();+ setFlagOverride("spaces_ask_first_home", true);+});+afterEach(() => {+ cleanup();+ vi.unstubAllEnvs();+});++const q = (s: string) => document.querySelector<HTMLElement>(s);+const HOME = { failsCreates: false, listsGhost: false, demo: { agentHome: true, accounts: true } };++async function useClaude() {+ await act(async () => {+ fireEvent.click(await waitFor(() => q('[data-picker="agent"]')!));+ });+ await act(async () => {+ fireEvent.click(await waitFor(() => q('[data-agent-group="claude-code"] [data-agent-account="kwork"]')!));+ });+}++describe.skipIf(!wasmBuilt)("the box with an agent home", () => {+ it("shows no where row until a place is named with @", async () => {+ await mountApp("/home", HOME);+ const box = (await screen.findByLabelText("What should it do?")) as HTMLTextAreaElement;+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ expect(q('[data-picker="where"]')).toBeNull();+ expect(q("[data-ask-where]")).toBeNull();+ fireEvent.change(box, { target: { value: "run the tests on @" } });+ await waitFor(() => expect(q('[data-picker="where"]')).not.toBeNull());+ });++ it("sends the job to the agent's Home Space on the slim image, with the spawn capability and a briefing", async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ const { router } = await mountApp("/home", { ...HOME, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ const box = (await screen.findByLabelText("What should it do?")) as HTMLTextAreaElement;+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ fireEvent.change(box, { target: { value: "test my project on a Mac and a Windows computer" } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ });+ await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\//));+ const create = await waitFor(() => {+ const c = calls.find((x) => x.op === "spaces.create");+ expect(c).toBeTruthy();+ return c!;+ });+ const config = (create.args as { config: Record<string, unknown> }).config;+ expect(config).toMatchObject({ image: AGENT_HOME_IMAGE, children: true, name: expect.stringMatching(/^home-/) });+ expect(config.labels).toMatchObject({ "cua.home": "1", "cua.home.agent": "openai-codex" });+ expect(AGENT_HOME_IMAGE).toBe("ghcr.io/trycua/linux:24.04-slim");+ expect(config).not.toHaveProperty("headless");+ // The agent is a member kept on standby with the model and the briefing; the job is the thread's first message.+ await waitFor(() => expect(calls.some((c) => c.op === "thread.agentAdd" && c.args.standby === true && c.args.harness === "openai-codex" && typeof c.args.model === "string" && String(c.args.brief).includes("your own small Linux Space"))).toBe(true), { timeout: 15000 });+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@codex test my project on a Mac and a Windows computer")).toBe(true), { timeout: 15000 });+ await waitFor(() => expect(askTasks()[0]).toMatchObject({ home: true, inSpace: true }));+ });++ it("reuses the agent's Home when it already has one, with no second create", async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ const { router } = await mountApp("/home", { ...HOME, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ const box = (await screen.findByLabelText("What should it do?")) as HTMLTextAreaElement;+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ // The demo's Home was made for Claude Code (its label says so): the next request goes there.+ await useClaude();+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toBe("Claude Code"));+ // The tree is read from the host and the Home is found by its label.+ await new Promise((r) => setTimeout(r, 300));+ fireEvent.change(box, { target: { value: "run the tests" } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ });+ await waitFor(() => expect(router.state.location.pathname).toBe("/spaces/local%3Aagent-home-demo"));+ expect(calls.some((c) => c.op === "spaces.create")).toBe(false);+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@claude run the tests")).toBe(true), { timeout: 15000 });+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/agent-menu-settings.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-menu-settings.test.tsxnew file mode 100644index 0000000000..31072c1c35--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/agent-menu-settings.test.tsx@@ -0,0 +1,133 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Which coding apps Home's agent menu shows: the "Configure agents" button at the foot of the menu+// leads to Settings, Connections, where each app has a switch. The rule (defaults, the last app+// that cannot be hidden, a connect that shows an app again) is the app core's `agent_menu`.++import { act, 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 { resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { resetConnectState } from "@/hooks/use-connectors";+import { resetAskTasks } from "@/lib/ask-first";+import { resetPickedAgent } from "@/lib/ask-first-model";+import { resetRepos } from "@/lib/ask-first-repo";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetAskTasks();+ resetPickedAgent();+ resetRepos();+ resetConnectState();+ resetConnectedAppsState();+ setFlagOverride("spaces_ask_first_home", true);+});+afterEach(() => {+ cleanup();+ vi.unstubAllEnvs();+});++const q = (s: string) => document.querySelector<HTMLElement>(s);+const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];+const HOST = { failsCreates: false, listsGhost: false, demo: { accounts: true } };+const found = (s: string) =>+ waitFor(() => {+ const el = q(s);+ expect(el).not.toBeNull();+ return el!;+ });+const click = (el: Element) =>+ act(async () => {+ fireEvent.click(el);+ });+const openMenu = async () => {+ await click(await found('[data-picker="agent"]'));+ await found("[data-agent-menu]");+};+const groups = () => qa("[data-agent-group]").map((g) => g.dataset.agentGroup);+const sw = (app: string) => found(`[data-agent-menu-switch="${app}"]`);++describe.skipIf(!wasmBuilt)("the agent menu's apps", () => {+ it("ends with a Configure agents button that opens Settings, Connections", async () => {+ const { router } = await mountApp("/home", HOST);+ await screen.findByLabelText("What should it do?");+ await openMenu();+ const button = await found("[data-agent-configure]");+ expect(button.textContent).toBe("Configure agents");+ // It is the last thing in the menu.+ expect(q("[data-agent-menu] [role=listbox]")!.lastElementChild!.contains(button)).toBe(true);+ await click(button);+ await waitFor(() => expect(router.state.location.pathname).toBe("/settings/connections"));+ await found("[data-agent-menu-group]");+ });++ it("lists every coding app with a switch: the leading four on, the others on only while one of their accounts works", async () => {+ await mountApp("/settings/connections", HOST);+ await found("[data-agent-menu-group]");+ const rows = () => qa("[data-agent-menu-row]").map((r) => r.dataset.agentMenuRow);+ await waitFor(() => expect(rows().slice(0, 4)).toEqual(["codex", "hermes", "claude-code", "opencode"]));+ expect(rows()).toHaveLength(9);+ for (const app of ["codex", "hermes", "claude-code", "opencode"]) expect((await sw(app)).getAttribute("aria-checked")).toBe("true");+ for (const app of ["gemini-cli", "antigravity", "goose", "pi", "openclaw"]) expect((await sw(app)).getAttribute("aria-checked")).toBe("false");+ expect((await sw("codex")).getAttribute("aria-label")).toBe("Show in the agent menu: OpenAI Codex");+ expect(q("[data-agent-menu-group]")!.textContent).not.toContain("·");+ });++ it("a hidden app leaves Home's menu, keeps its sign-ins, and the pick falls back to the first app shown", async () => {+ const { router } = await mountApp("/settings/connections", HOST);+ await click(await sw("codex"));+ await waitFor(() => expect(q('[data-agent-menu-switch="codex"]')!.getAttribute("aria-checked")).toBe("false"));+ await act(async () => {+ await router.navigate({ to: "/home" });+ });+ await screen.findByLabelText("What should it do?");+ // Codex was the default pick; it is hidden, so the chip falls to the next connected app.+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toBe("Claude Code"));+ await openMenu();+ expect(groups()).toEqual(["hermes", "claude-code", "opencode"]);+ // Showing it again puts it back at its place.+ await act(async () => {+ await router.navigate({ to: "/settings/connections" });+ });+ await click(await sw("codex"));+ await act(async () => {+ await router.navigate({ to: "/home" });+ });+ await openMenu();+ await waitFor(() => expect(groups()).toEqual(["codex", "hermes", "claude-code", "opencode"]));+ });++ it("an app outside the leading four can be shown before it is signed in", async () => {+ const { router } = await mountApp("/settings/connections", HOST);+ await click(await sw("goose"));+ await waitFor(() => expect(q('[data-agent-menu-switch="goose"]')!.getAttribute("aria-checked")).toBe("true"));+ await act(async () => {+ await router.navigate({ to: "/home" });+ });+ await openMenu();+ await waitFor(() => expect(groups()).toContain("goose"));+ expect(q('[data-agent-sign-in="goose"]')!.textContent).toBe("Sign in");+ });++ it("never hides the last app: its switch is off limits and the page says why", async () => {+ await mountApp("/settings/connections", HOST);+ for (const app of ["codex", "hermes", "claude-code"]) {+ await click(await sw(app));+ await waitFor(() => expect(q(`[data-agent-menu-switch="${app}"]`)!.getAttribute("aria-checked")).toBe("false"));+ }+ const last = await sw("opencode");+ expect(last.getAttribute("aria-checked")).toBe("true");+ expect(last.hasAttribute("disabled") || last.getAttribute("aria-disabled") === "true" || last.dataset.disabled !== undefined).toBe(true);+ await click(last);+ expect(last.getAttribute("aria-checked")).toBe("true");+ await waitFor(() => expect(q("[data-agent-menu-note]")!.textContent).toContain("OpenCode stays in the menu: at least one coding app has to be shown."));+ // Another app on lets it go.+ await click(await sw("goose"));+ await waitFor(() => expect(q('[data-agent-menu-switch="opencode"]')!.hasAttribute("disabled")).toBe(false));+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/app-harness.tsx b/apps/cua-spaces-web/src/__tests__/app-harness.tsxindex 3175930dbd..db1bd26c6e 100644--- a/apps/cua-spaces-web/src/__tests__/app-harness.tsx+++ b/apps/cua-spaces-web/src/__tests__/app-harness.tsx@@ -92,6 +92,7 @@ export async function mountApp(path: string, host: TestHost = { failsCreates: trconst listeners = new Set<(event: HostEvent) => void>();const adapter: DataAdapter = {mode: demo.mode,+ ...(demo.children ? { children: demo.children } : {}),...(host.machinesView ? { machinesView: host.machinesView } : {}),...(host.listStatus ? { listStatus: host.listStatus } : {}),...(host.creatingElsewhere ? { creatingElsewhere: host.creatingElsewhere } : {}),diff --git a/apps/cua-spaces-web/src/__tests__/app-uses.test.tsx b/apps/cua-spaces-web/src/__tests__/app-uses.test.tsxindex d02cbd5261..619d2cc9f9 100644--- a/apps/cua-spaces-web/src/__tests__/app-uses.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/app-uses.test.tsx@@ -86,7 +86,7 @@ describe.skipIf(!wasmBuilt)("an app's Uses row", () => {const row = await found("[data-connector-uses=connected]");// The first connected one that works is in use until the person chooses.expect(row.querySelector("[data-uses-provider]")!.textContent).toBe("Anthropic");- expect(row.querySelector("[data-uses-line]")!.textContent).toContain("API key ending a91c");+ expect(row.querySelector("[data-uses-line]")!.textContent).toContain("API Key (*a91c)");expect(document.body.textContent).toContain("Takes effect the next time Hermes runs.");const popup = await openMenu();const options = qa("[data-uses-option]").map((o) => o.dataset.usesOption);@@ -100,7 +100,7 @@ describe.skipIf(!wasmBuilt)("an app's Uses row", () => {await waitFor(() => expect(q("[data-connector-uses-app=hermes] [data-uses-provider]")!.textContent).toBe("OpenRouter"));// Nothing was signed out or removed by choosing.expect(calls.filter((c) => c.op === "agentKeys.remove")).toEqual([]);- expect(q("[data-connector-uses-app=hermes] [data-uses-line]")!.textContent).toContain("API key ending cdef");+ expect(q("[data-connector-uses-app=hermes] [data-uses-line]")!.textContent).toContain("API Key (*cdef)");});it("Connect another provider opens the provider choice for this app", async () => {diff --git a/apps/cua-spaces-web/src/__tests__/ask-box.test.tsx b/apps/cua-spaces-web/src/__tests__/ask-box.test.tsxnew file mode 100644index 0000000000..90d732028e--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/ask-box.test.tsx@@ -0,0 +1,254 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The new prompt box on Home: pick a model, optionally a repo, type, Enter.++import { readFileSync } from "node:fs";+import { join } from "node:path";++import { act, 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 { resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { resetConnectState } from "@/hooks/use-connectors";+import { askTasks, resetAskTasks } from "@/lib/ask-first";+import { resetPickedAgent } from "@/lib/ask-first-model";+import { resetRepos } from "@/lib/ask-first-repo";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetAskTasks();+ resetPickedAgent();+ resetRepos();+ resetConnectState();+ resetConnectedAppsState();+ setFlagOverride("spaces_ask_first_home", true);+});+afterEach(() => {+ cleanup();+ vi.unstubAllEnvs();+});++const q = (s: string) => document.querySelector<HTMLElement>(s);+// Three Claude sign-ins and one ChatGPT sign-in; nothing for Hermes or OpenCode.+const ACCOUNTS = { demo: { accounts: true } };++async function openAgents() {+ await act(async () => {+ fireEvent.click(await waitFor(() => q('[data-picker="agent"]')!));+ });+ await waitFor(() => expect(q("[data-agent-menu]")).not.toBeNull());+}++describe.skipIf(!wasmBuilt)("the prompt box", () => {+ it("starts with the first connected app and its account (Codex, then Hermes, Claude Code, OpenCode) and only the agent and a repo to pick", async () => {+ await mountApp("/home", { failsCreates: false, listsGhost: false, ...ACCOUNTS });+ await screen.findByLabelText("What should it do?");+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toBe("OpenAI Codex"));+ expect(q('[data-picker="repo"]')!.textContent).toContain("Add a repo");+ // No model chip and no separate coding app picker.+ expect(q('[data-picker="model"]')).toBeNull();+ expect(q('[data-picker="who"]')).toBeNull();+ });++ it("groups by coding app: the top four first, their accounts as rows, Sign in where there is none", async () => {+ await mountApp("/home", { failsCreates: false, listsGhost: false, ...ACCOUNTS });+ await screen.findByLabelText("What should it do?");+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ await openAgents();+ const groups = [...document.querySelectorAll<HTMLElement>("[data-agent-group]")].map((g) => g.dataset.agentGroup);+ expect(groups).toEqual(["codex", "hermes", "claude-code", "opencode"]);+ const rows = (app: string) => [...document.querySelectorAll<HTMLElement>(`[data-agent-group="${app}"] [role="option"]`)].map((r) => r.textContent);+ expect(rows("claude-code")).toEqual(["[email protected] (Max)", "work Max", "side project Max"]);+ expect(rows("codex")).toEqual(["ChatGPT"]);+ expect(q('[data-agent-sign-in="hermes"]')!.textContent).toBe("Sign in");+ expect(q('[data-agent-sign-in="opencode"]')!.textContent).toBe("Sign in");+ expect(q('[data-agent-sign-in="claude-code"]')).toBeNull();+ // The model is not a group: it is one quiet line, and only for an account that offers a choice.+ expect(q("[data-model-group]")).toBeNull();+ // An account with one model shows no model line at all.+ expect(q("[data-agent-model-row]")).toBeNull();+ });++ it("picks an app and an account, shows both on the chip, and remembers them across a reload", async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ const host = { failsCreates: false, listsGhost: false, ...ACCOUNTS, intercept: (op: string, args: unknown) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) };+ await mountApp("/home", host);+ await screen.findByLabelText("What should it do?");+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ await openAgents();+ await act(async () => {+ fireEvent.click(q('[data-agent-group="claude-code"] [data-agent-account="kwork"]')!);+ });+ // The chip is the app alone; the account is the ticked row inside the menu.+ expect(q("[data-ask-agent]")!.textContent).toBe("Claude Code");+ await openAgents();+ expect(q('[data-agent-group="claude-code"] [aria-selected="true"]')!.textContent).toBe("work Max");+ await act(async () => {+ fireEvent.keyDown(q("[data-agent-menu]")!, { key: "Escape" });+ });+ // The host keeps which account the app runs with, so a run uses the one shown.+ await waitFor(() => expect(calls.some((c) => c.op === "agentKeys.use" && c.args.app === "claude-code" && c.args.env === "CLAUDE_CODE_OAUTH_TOKEN" && c.args.slot === "kwork")).toBe(true));+ cleanup();+ // A new launch: the choice is still there (the app and model here, the account from the host's store).+ await mountApp("/home", host);+ await screen.findByLabelText("What should it do?");+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toBe("Claude Code"));+ await openAgents();+ expect(q('[data-agent-group="claude-code"] [aria-selected="true"]')!.textContent).toBe("work Max");+ });++ it("opens an app's sign-ins from its chevron: the default, make default, rename and remove", async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ await mountApp("/home", { failsCreates: false, listsGhost: false, ...ACCOUNTS, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ await screen.findByLabelText("What should it do?");+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ await openAgents();+ await act(async () => {+ fireEvent.click(q('[data-agent-manage="claude-code"]')!);+ });+ const page = await waitFor(() => {+ const el = q('[data-agent-manage-page="claude-code"]');+ expect(el).not.toBeNull();+ return el!;+ });+ expect(page.textContent).toContain("Claude Code sign-ins");+ expect(q("[data-manage-default]")!.closest("[data-manage-account]")!.textContent).toContain("[email protected]");+ await act(async () => {+ fireEvent.click(q('[data-manage-account="kwork"] [data-manage-use]')!);+ });+ await waitFor(() => expect(calls.some((c) => c.op === "agentKeys.use" && c.args.slot === "kwork")).toBe(true));+ await act(async () => {+ fireEvent.click(q('[data-manage-account="kside"] [data-manage-rename]')!);+ });+ const name = screen.getByLabelText("Name") as HTMLInputElement;+ fireEvent.change(name, { target: { value: "client Max" } });+ await act(async () => {+ fireEvent.keyDown(name, { key: "Enter" });+ });+ await waitFor(() => expect(calls.some((c) => c.op === "agentKeys.rename" && c.args.slot === "kside" && c.args.label === "client Max")).toBe(true));+ await waitFor(() => expect(q('[data-manage-account="kside"]')!.textContent).toContain("client Max"));+ await act(async () => {+ fireEvent.click(q('[data-manage-account="kside"] [data-manage-remove]')!);+ });+ await act(async () => {+ fireEvent.click(q("[data-manage-confirm-remove]")!);+ });+ await waitFor(() => expect(calls.some((c) => c.op === "agentKeys.remove" && c.args.slot === "kside")).toBe(true));+ await waitFor(() => expect(q('[data-manage-account="kside"]')).toBeNull());+ });++ it("the model is a secondary line: it lists the account's models and keeps the pick", async () => {+ await mountApp("/home", { failsCreates: false, listsGhost: false, ...ACCOUNTS });+ await screen.findByLabelText("What should it do?");+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ await openAgents();+ await act(async () => {+ fireEvent.click(q('[data-agent-group="claude-code"] [data-agent-account="kwork"]')!);+ });+ await openAgents();+ await act(async () => {+ fireEvent.click(q("[data-agent-model-row]")!);+ });+ expect(q('[data-model-row="claude-haiku-4-5"]')!.textContent).toContain("Fast");+ await act(async () => {+ fireEvent.click(q('[data-model-row="claude-sonnet-5"]')!);+ });+ await openAgents();+ expect(q("[data-agent-model-row]")!.textContent).toContain("Claude Sonnet 5");+ });++ it("Enter sends the job with the picked app, account and model; Shift+Enter is a new line", async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ await mountApp("/home", {+ failsCreates: false,+ listsGhost: false,+ ...ACCOUNTS,+ intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined),+ });+ const box = (await screen.findByLabelText("What should it do?")) as HTMLTextAreaElement;+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ await openAgents();+ await act(async () => {+ fireEvent.click(q('[data-agent-group="claude-code"] [data-agent-account="kwork"]')!);+ });+ fireEvent.change(box, { target: { value: "fix the build" } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter", shiftKey: true });+ });+ expect(askTasks()).toHaveLength(0);+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ });+ await waitFor(() => expect(askTasks()[0]).toMatchObject({ prompt: "fix the build", agent: "claude-code", model: "claude-haiku-4-5" }));+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@claude fix the build")).toBe(true), { timeout: 15000 });+ });++ it("with nothing signed in the chip says to sign in, every app has a Sign in row and Start waits", async () => {+ await mountApp("/home", { failsCreates: false, listsGhost: false, demo: { keys: "none" } });+ await screen.findByLabelText("What should it do?");+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toBe("Sign in to an agent"));+ expect((screen.getByRole("button", { name: "Start" }) as HTMLButtonElement).disabled).toBe(true);+ await openAgents();+ expect(document.querySelectorAll("[data-agent-sign-in]")).toHaveLength(4);+ });++ it("adds a repo from a link, refuses what is not one, keeps it on the task, and removes it with the x", async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ const { router } = await mountApp("/home", { failsCreates: false, listsGhost: false, ...ACCOUNTS, intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined) });+ const box = (await screen.findByLabelText("What should it do?")) as HTMLTextAreaElement;+ await act(async () => {+ fireEvent.click(await waitFor(() => {+ const el = q('[data-picker="repo"]');+ expect(el).not.toBeNull();+ return el!;+ }));+ });+ const field = await screen.findByLabelText("Repo link or owner/name");+ fireEvent.change(field, { target: { value: "what is this" } });+ await act(async () => {+ fireEvent.keyDown(field, { key: "Enter" });+ });+ expect(field.getAttribute("aria-invalid")).toBe("true");+ fireEvent.change(field, { target: { value: "https://github.com/trycua/demo-failing-tests" } });+ await act(async () => {+ fireEvent.keyDown(field, { key: "Enter" });+ });+ await waitFor(() => expect(q("[data-ask-repo]")!.dataset.askRepo).toBe("trycua/demo-failing-tests"));+ fireEvent.change(box, { target: { value: "find out why the tests fail" } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ });+ await waitFor(() => expect(askTasks()[0]!.repo).toEqual({ url: "https://github.com/trycua/demo-failing-tests", label: "trycua/demo-failing-tests" }));+ // The agent is told the repo in the job's own message.+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && String(c.args.text).includes("find out why the tests fail\n\nRepo: https://github.com/trycua/demo-failing-tests"))).toBe(true), { timeout: 15000 });+ // It stays for the next job until removed (back on Home, the job's Space is open now).+ await act(async () => void router.navigate({ to: "/home" }));+ await act(async () => {+ fireEvent.click(+ await waitFor(() => {+ const el = q("[data-ask-repo-remove]");+ expect(el).not.toBeNull();+ return el!;+ }),+ );+ });+ expect(q("[data-ask-repo]")).toBeNull();+ expect(q('[data-picker="repo"]')).not.toBeNull();+ });+});++describe("the box's words", () => {+ it("never join two things with a middle dot, and never say devices", () => {+ const dir = join(__dirname, "..", "components", "ask-first");+ for (const f of ["ask-box.tsx", "agent-picker.tsx", "repo-chip.tsx", "home.tsx"]) {+ const text = readFileSync(join(dir, f), "utf8");+ expect(text, f).not.toContain("·");+ expect(text.toLowerCase(), f).not.toMatch(/\bdevices?\b/);+ }+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsxindex cdb891821a..a2e6604976 100644--- a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx@@ -36,7 +36,6 @@ afterEach(() => {});const q = (s: string) => document.querySelector<HTMLElement>(s);-const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];const found = (s: string, timeout = 8000) =>waitFor(() => {@@ -47,32 +46,82 @@ const found = (s: string, timeout = 8000) =>{ timeout },);+/** A Space the person's own job made (no agent in it yet): Home, a job, then its page. */+async function inAFreshSpace(host: Parameters<typeof mountApp>[1]) {+ const { router } = await mountApp("/home", host);+ fireEvent.change(await screen.findByLabelText("What should it do?"), { target: { value: "look around" } });+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Start" }));+ });+ await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\//));+ await waitFor(() => expect(askTasks()[0]?.inSpace).toBe(true), { timeout: 15000 });+ return router;+}++/** Types `text` in the Space's composer and sends it. */+async function compose(text: string) {+ const box = await waitFor(() => {+ const el = q("[data-composer]") as HTMLTextAreaElement | null;+ expect(el?.disabled).toBe(false);+ return el!;+ });+ fireEvent.change(box, { target: { value: text, selectionStart: text.length } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ await new Promise((r) => setTimeout(r, 20));+ });+}+describe.skipIf(!wasmBuilt)("Ask first in the Space (both flags)", () => {- it("lands on the Space being made, posts @claude <job>, and offers Connect, then sends again", { timeout: 40000 }, async () => {+ it("lands on the Space being made and posts the job to the agent the model runs on", { timeout: 40000 }, async () => {const calls: { op: string; args: Record<string, unknown> }[] = [];const { router } = await mountApp("/home", {failsCreates: false,listsGhost: false,intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined),});- fireEvent.change(await screen.findByLabelText("What do you want to do?"), { target: { value: "fix the build" } });+ fireEvent.change(await screen.findByLabelText("What should it do?"), { target: { value: "fix the build" } });await act(async () => {fireEvent.click(screen.getByRole("button", { name: "Start" }));});// Straight to the Space (not the task page), and its first message once made.await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\//));expect(router.state.location.pathname).not.toMatch(/^\/home/);+ // The demo has an OpenAI key saved, so the model is OpenAI's and Codex runs it.+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@codex fix the build")).toBe(true), { timeout: 15000 });+ expect(calls.some((c) => c.op === "thread.agentAdd" && c.args.harness === "openai-codex")).toBe(true);+ expect(calls.some((c) => c.op === "agents.start")).toBe(false);+ expect(askTasks()[0]).toMatchObject({ inSpace: true, agent: "openai-codex", model: "gpt-5.5" });+ expect(q("[data-wake-note]")).toBeNull();+ });+});++describe.skipIf(!wasmBuilt)("Ask first: nothing connected", () => {+ it("has no agent to start with: the box says to sign in and Start waits", { timeout: 40000 }, async () => {+ await mountApp("/home", { failsCreates: false, listsGhost: false, demo: { keys: "none" } });+ fireEvent.change(await screen.findByLabelText("What should it do?"), { target: { value: "fix the build" } });+ expect(q("[data-ask-agent]")!.textContent).toBe("Sign in to an agent");+ expect((screen.getByRole("button", { name: "Start" }) as HTMLButtonElement).disabled).toBe(true);+ });+});++describe.skipIf(!wasmBuilt)("Send again when the agent can't join", () => {+ it("offers Connect for an agent with no sign-in, and sends again once connected", { timeout: 40000 }, async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ await inAFreshSpace({+ failsCreates: false,+ listsGhost: false,+ intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined),+ });+ calls.length = 0;+ await compose("@claude fix the build");await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@claude fix the build")).toBe(true), { timeout: 15000 });// No Anthropic sign-in: Claude Code isn't added, and isn't started as a run either.expect(calls.some((c) => c.op === "thread.agentAdd")).toBe(false);expect(calls.some((c) => c.op === "agents.start")).toBe(false);- expect(askTasks()[0]!.inSpace).toBe(true);const note = await found("[data-wake-note=claude]", 15000);expect(note.textContent).toContain("Claude Code isn't connected yet");expect(q("[data-wake-connect]")!.textContent).toContain("Connect Claude Code");- // The message draws its mention as a chip.- expect(qa("[data-call-layout] .text-brand-strong").some((el) => el.textContent === "@claude")).toBe(true);-await act(async () => {fireEvent.click(q("[data-wake-connect]")!);});@@ -86,24 +135,22 @@ describe.skipIf(!wasmBuilt)("Ask first in the Space (both flags)", () => {await waitFor(() => expect(calls.some((c) => c.op === "thread.agentAdd" && c.args.harness === "claude-code")).toBe(true));await waitFor(() => expect(calls.filter((c) => c.op === "thread.post" && c.args.text === "@claude fix the build")).toHaveLength(2));});-});-describe.skipIf(!wasmBuilt)("Send again when the agent can't join", () => {it("says why and posts nothing more (a message no agent reads would look sent)", { timeout: 40000 }, async () => {const posts: string[] = [];- await mountApp("/home", {+ let armed = false;+ await inAFreshSpace({failsCreates: false,listsGhost: false,intercept: (op, args) => {+ if (!armed) return undefined;if (op === "thread.agentAdd") throw new Error("this Space is full: remove an agent first");if (op === "thread.post") posts.push((args as { text: string }).text);return undefined;},});- fireEvent.change(await screen.findByLabelText("What do you want to do?"), { target: { value: "fix the build" } });- await act(async () => {- fireEvent.click(screen.getByRole("button", { name: "Start" }));- });+ armed = true;+ await compose("@claude fix the build");await found("[data-wake-connect]", 15000);await act(async () => {fireEvent.click(q("[data-wake-connect]")!);@@ -118,13 +165,13 @@ describe.skipIf(!wasmBuilt)("Send again when the agent can't join", () => {});describe.skipIf(!wasmBuilt)("notes only you see", () => {- it("say so, can be dismissed, and never reach the thread or any other member", async () => {+ it("the queued line says so, and what a wake note says never reaches the thread or any other member", { timeout: 40000 }, async () => {const calls: { op: string; args: unknown }[] = [];// The create waits until the queued line has been looked at.let release!: () => void;const hold = new Promise<void>((r) => (release = r));await mountApp("/home", { failsCreates: false, listsGhost: false, hold, intercept: (op, args) => (calls.push({ op, args }), undefined) });- fireEvent.change(await screen.findByLabelText("What do you want to do?"), { target: { value: "fix the build" } });+ fireEvent.change(await screen.findByLabelText("What should it do?"), { target: { value: "fix the build" } });await act(async () => {fireEvent.click(screen.getByRole("button", { name: "Start" }));});@@ -134,14 +181,18 @@ describe.skipIf(!wasmBuilt)("notes only you see", () => {expect(queued.textContent).toContain("Only visible to you");expect(queued.textContent).toContain("Sends when the Space is ready");release();- // Once ready: the can't-wake note, marked the same, with Dismiss.+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && (c.args as { text: string }).text === "@codex fix the build")).toBe(true), { timeout: 15000 });+ const sent = JSON.stringify(calls.map((c) => c.args));+ for (const words of ["Only visible to you", "isn't connected yet", "Sends when the Space is ready", "Sent again"]) expect(sent).not.toContain(words);+ expect(calls.filter((c) => c.op === "thread.post").map((c) => (c.args as { text: string }).text)).toEqual(["@codex fix the build"]);+ });++ it("a wake note says so, can be dismissed, and is marked as only yours", { timeout: 40000 }, async () => {+ await inAFreshSpace({ failsCreates: false, listsGhost: false });+ await compose("@claude fix the build");const note = await found("[data-wake-note=claude]", 15000);expect(note.hasAttribute("data-only-you")).toBe(true);expect(note.querySelector("[data-only-you-label]")?.textContent).toContain("Only visible to you");- // Nothing a note says was ever sent anywhere: not posted, not in any call.- const sent = JSON.stringify(calls.map((c) => c.args));- for (const words of ["Only visible to you", "isn't connected yet", "Sends when the Space is ready", "Sent again"]) expect(sent).not.toContain(words);- expect(calls.filter((c) => c.op === "thread.post").map((c) => (c.args as { text: string }).text)).toEqual(["@claude fix the build"]);await act(async () => {fireEvent.click(note.querySelector("[data-wake-dismiss]")!);});diff --git a/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsx b/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsxindex 6c0d75e6c2..7fa9a5bce0 100644--- a/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/ask-first-start-failed.test.tsx@@ -42,7 +42,7 @@ async function pickThisMac() {}async function startJob(text: string) {- fireEvent.change(screen.getByLabelText("What do you want to do?"), { target: { value: text } });+ fireEvent.change(screen.getByLabelText("What should it do?"), { target: { value: text } });await act(async () => {fireEvent.click(screen.getByRole("button", { name: "Start" }));});@@ -55,7 +55,7 @@ describe.skipIf(!wasmBuilt)("This Mac as a task's computer (real routes, wasm coexpect(document.querySelector('[data-picker="where"]')!.textContent).toContain("New Space");await pickThisMac();await screen.findByText("Work on this Mac?");- expect(screen.getByText(/Claude Code will work directly on this Mac, with your files and apps\. It can't be undone by throwing the computer away\./)).toBeTruthy();+ expect(screen.getByText(/Codex will work directly on this Mac, with your files and apps\. It can't be undone by throwing the computer away\./)).toBeTruthy();await act(async () => {fireEvent.click(screen.getByRole("button", { name: "Use this Mac" }));});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.tsxdeleted file mode 100644index f9b13c05cd..0000000000--- a/apps/cua-spaces-web/src/__tests__/home-agent-picker.test.tsx+++ /dev/null@@ -1,66 +0,0 @@-// 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__/home-agents.test.tsx b/apps/cua-spaces-web/src/__tests__/home-agents.test.tsxindex 9cfd0006e7..bf0715b814 100644--- a/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx@@ -14,7 +14,7 @@ import { wasmBuilt } from "@/bridge/__tests__/testCore";import { resetWakeNotes } from "@/components/space-thread/summon";import { resetConnectedAppsState } from "@/hooks/use-connected-apps";import { resetConnectState } from "@/hooks/use-connectors";-import { addAskTask, resetAskTasks } from "@/lib/ask-first";+import { addAskTask, askTasks, resetAskTasks } from "@/lib/ask-first";import { mountApp, stubBrowserApis } from "./app-harness";stubBrowserApis();@@ -43,8 +43,22 @@ const found = (s: string, timeout = 8000) =>{ timeout },);+/** Types `text` in the Space's composer and sends it. */+async function compose(text: string) {+ const box = await waitFor(() => {+ const el = q("[data-composer]") as HTMLTextAreaElement | null;+ expect(el?.disabled).toBe(false);+ return el!;+ });+ fireEvent.change(box, { target: { value: text, selectionStart: text.length } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ await new Promise((r) => setTimeout(r, 20));+ });+}+async function start(job: string) {- fireEvent.change(await screen.findByLabelText("What do you want to do?"), { target: { value: job } });+ fireEvent.change(await screen.findByLabelText("What should it do?"), { target: { value: job } });await act(async () => {fireEvent.click(screen.getByRole("button", { name: "Start" }));});@@ -61,14 +75,32 @@ describe.skipIf(!wasmBuilt)("Your agents and the Agents page: one list", () => {const onAgents = await found("[data-chat-run][data-chat-tone='creating']");expect(onAgents.textContent).toContain("fix the build");expect(onAgents.querySelector("[data-chat-line]")?.textContent).toMatch(/^Waiting for .+ to be ready$/);- const total = qa("[data-agent-list] [data-chat]").length;- // …and Home counts the same list.+ // The list fills in as the host answers: wait for it to be whole (the demo's other agents and this run).+ await waitFor(() => expect(qa("[data-agent-list] [data-chat]").length).toBeGreaterThan(1));+ // …and Home counts the same list: its count is the Agents page's own, once both have settled.await act(async () => void router.navigate({ to: "/home" }));- expect((await found("[data-home-see-all='/agents']")).textContent?.trim()).toBe(`See all ${total}`);+ await waitFor(async () => {+ const shown = q("[data-home-see-all='/agents']")?.textContent?.trim();+ expect(shown).toMatch(/^See all \d+$/);+ await act(async () => void router.navigate({ to: "/agents" }));+ const total = await waitFor(() => {+ const n = qa("[data-agent-list] [data-chat]").length;+ expect(n).toBeGreaterThan(1);+ return n;+ });+ await act(async () => void router.navigate({ to: "/home" }));+ expect(shown).toBe(`See all ${total}`);+ }, { timeout: 15000 });await act(async () => void router.navigate({ to: "/agents" }));release();- // Ready, and Claude Code isn't connected: both say so, with Connect.+ // Ready. Claude Code isn't connected (the box could not pick it: no model of Anthropic's is connected),+ // so a message to it from the Space's composer says so: both lists say so, with Connect.+ await waitFor(() => expect(askTasks()[0]!.spaceId).toBeTruthy(), { timeout: 15000 });+ await act(async () => void router.navigate({ to: "/spaces/$spaceId", params: { spaceId: askTasks()[0]!.spaceId! } }));+ await compose("@claude fix the build");+ await found("[data-call-layout] [data-wake-note=claude]", 15000);+ await act(async () => void router.navigate({ to: "/agents" }));const nc = await found("[data-chat-run][data-chat-tone='not-connected']", 15000);expect(nc.querySelector("[data-chat-line]")?.textContent).toBe("Claude Code isn't connected yet");expect(nc.querySelector("[data-chat-action='connect']")).not.toBeNull();@@ -92,7 +124,7 @@ describe.skipIf(!wasmBuilt)("Your agents and the Agents page: one list", () => {fireEvent.click(await found("a[href='/home']"));await found("[data-home-agents]");await found("[data-home-spaces]");- const order = qa("[data-ask-first-home] section, [data-ask-first-home] [aria-label='What do you want to do?']").map((el) => el.getAttribute("data-home-agents") !== null ? "agents" : el.getAttribute("data-home-spaces") !== null ? "spaces" : "composer");+ const order = qa("[data-ask-first-home] section, [data-ask-first-home] [aria-label='What should it do?']").map((el) => el.getAttribute("data-home-agents") !== null ? "agents" : el.getAttribute("data-home-spaces") !== null ? "spaces" : "composer");expect(order.indexOf("composer")).toBeLessThan(order.indexOf("agents"));expect(order.indexOf("agents")).toBeLessThan(order.indexOf("spaces"));expect(q("[data-home-see-all='/agents']")?.textContent?.trim()).toMatch(/^See all \d+$/);@@ -100,8 +132,8 @@ describe.skipIf(!wasmBuilt)("Your agents and the Agents page: one list", () => {expect(q("[data-home-spaces] h2")?.textContent).not.toMatch(/\bon\b/);// The Spaces page's tiles.expect(qa("[data-home-spaces] [data-space-id]").length).toBeGreaterThan(0);- // The composer: the agent as the thread's mention, where as a Space.- expect(q("[data-ask-mention]")?.textContent).toBe("@claude");+ // The composer: the agent and its account (the demo has an OpenAI key saved), where as a Space.+ expect(q("[data-ask-agent]")?.textContent).toBe("OpenAI Codex");expect(q("[data-ask-where]")?.textContent).toBe("New SpaceLinux on This Mac");});diff --git a/apps/cua-spaces-web/src/__tests__/home-space-tag.test.tsx b/apps/cua-spaces-web/src/__tests__/home-space-tag.test.tsxnew file mode 100644index 0000000000..ce2bcbf44f--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/home-space-tag.test.tsx@@ -0,0 +1,42 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The agent's home is a Space like any other in the Spaces list; a plain "Home" tag+// (no middle dot, like the "Desktop" tag) says which one takes the requests from Home.++import { act, cleanup, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { setFlagOverride } from "@/bridge";+import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { forgetHome, rememberHome, resetHomes } from "@/lib/agent-home/home-space";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetHomes();+ setFlagOverride("spaces_ask_first_home", true);+});+afterEach(cleanup);++const spaceIds = () => [...document.querySelectorAll<HTMLElement>("[data-space-id]")].map((e) => e.getAttribute("data-space-id")!);++describe.skipIf(!wasmBuilt)("the Home tag in the Spaces list", () => {+ it("shows beside the agent's home Space and nowhere else, and goes when the home is forgotten", async () => {+ await mountApp("/spaces", { failsCreates: false, listsGhost: false });+ const ids = await waitFor(() => {+ const found = spaceIds().filter((id) => id !== "this-mac");+ expect(found.length).toBeGreaterThan(1);+ return found;+ });+ expect(document.querySelector("[data-home-tag]")).toBeNull();+ act(() => rememberHome("claude-code", ids[0]!));+ await waitFor(() => expect(document.querySelectorAll("[data-home-tag]")).toHaveLength(1));+ const tagged = document.querySelector("[data-home-tag]")!;+ expect(tagged.textContent).toBe("Home");+ expect(tagged.textContent).not.toContain("·");+ act(() => forgetHome("claude-code"));+ await waitFor(() => expect(document.querySelector("[data-home-tag]")).toBeNull());+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/keep-home-warm.test.tsx b/apps/cua-spaces-web/src/__tests__/keep-home-warm.test.tsxnew file mode 100644index 0000000000..ff3ed20fad--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/keep-home-warm.test.tsx@@ -0,0 +1,57 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Home turns a switched-off agent home back on in the background, once, and touches nothing else.++import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { useKeepHomeWarm } from "@/components/ask-first/use-keep-home-warm";+import { rememberHome, resetHomes } from "@/lib/agent-home/home-space";++const state = vi.hoisted(() => ({+ spaces: [] as { id: string; status: string }[],+ startSpace: vi.fn(async (_id: string) => {}),+ homes: [] as string[],+}));++vi.mock("@/bridge", () => ({ useSpaces: () => ({ data: state.spaces, startSpace: state.startSpace }) }));+vi.mock("@/components/children/use-children", () => ({ useChildren: () => ({ homesOf: () => state.homes }) }));++beforeEach(() => {+ localStorage.clear();+ resetHomes();+ state.startSpace.mockClear();+ state.homes = [];+ state.spaces = [];+});++describe("keeping the home warm", () => {+ it("starts a suspended home once, and not a running one", () => {+ rememberHome("claude-code", "local:home-a");+ state.spaces = [{ id: "local:home-a", status: "suspended" }];+ const { rerender } = renderHook(() => useKeepHomeWarm("claude-code", true));+ expect(state.startSpace).toHaveBeenCalledWith("local:home-a");+ rerender();+ expect(state.startSpace).toHaveBeenCalledTimes(1);+ state.startSpace.mockClear();+ state.spaces = [{ id: "local:home-a", status: "running" }];+ rerender();+ expect(state.startSpace).not.toHaveBeenCalled();+ });++ it("finds a home by its label when this device remembers none", () => {+ state.homes = ["local:home-z"];+ state.spaces = [{ id: "local:home-z", status: "suspended" }];+ renderHook(() => useKeepHomeWarm("claude-code", true));+ expect(state.startSpace).toHaveBeenCalledWith("local:home-z");+ });++ it("does nothing when there is no home, or the feature is off", () => {+ state.spaces = [{ id: "local:other", status: "suspended" }];+ renderHook(() => useKeepHomeWarm("claude-code", true));+ rememberHome("claude-code", "local:other");+ renderHook(() => useKeepHomeWarm("claude-code", false));+ expect(state.startSpace).not.toHaveBeenCalled();+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/onboarding-lands-on-home.test.tsx b/apps/cua-spaces-web/src/__tests__/onboarding-lands-on-home.test.tsxindex 069dd79c9b..83797fcde5 100644--- a/apps/cua-spaces-web/src/__tests__/onboarding-lands-on-home.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/onboarding-lands-on-home.test.tsx@@ -13,6 +13,7 @@ import { resetFirstRunCache } from "@/bridge/first-run";import { resetSavedOnboardingCache } from "@/bridge/onboarding";import { resetConnectedAppsState } from "@/hooks/use-connected-apps";import { resetAskTasks } from "@/lib/ask-first";+import { rememberAgent, resetPickedAgent } from "@/lib/ask-first-model";import { getDriver, resetPrepare } from "@/lib/prepare/store";import { mountApp, stubBrowserApis } from "./app-harness";@@ -24,6 +25,9 @@ beforeEach(() => {resetConnectedAppsState();resetPrepare();resetAskTasks();+ // The agent the first run prepares a home for is the one the person last used.+ resetPickedAgent();+ rememberAgent({ harness: "claude-code" });setFlagOverride("spaces_ask_first_home", true);setFlagOverride("spaces_new_onboarding", true);});@@ -68,7 +72,7 @@ describe.skipIf(!wasmBuilt)("where the first run ends", () => {const router = await throughOnboarding(new Promise<void>((r) => (release = r)));await waitFor(() => expect(router.state.location.pathname).toBe("/home"));// The prompt box and the suggestions are there, not a Space's page.- expect(await screen.findByLabelText("What do you want to do?")).not.toBeNull();+ expect(await screen.findByLabelText("What should it do?")).not.toBeNull();expectCards();expect(document.querySelector("[data-ask-first-home]")).not.toBeNull();// Warming is silent: no line, no steps, and the home is not in "Your Spaces".@@ -81,7 +85,7 @@ describe.skipIf(!wasmBuilt)("where the first run ends", () => {expect(document.body.textContent).not.toContain("Getting your agent ready");expect(document.querySelector("[data-home-spaces]")?.textContent ?? "").not.toContain("home-claude-code");// A prompt sent now is kept and goes once the agent is ready (the Space's thread says so).- fireEvent.change(screen.getByLabelText("What do you want to do?"), { target: { value: "fix the build" } });+ fireEvent.change(screen.getByLabelText("What should it do?"), { target: { value: "fix the build" } });fireEvent.click(screen.getByRole("button", { name: "Start" }));await waitFor(() => expect(getDriver()?.state?.messages.map((m) => m.text)).toEqual(["fix the build"]));release();@@ -92,7 +96,7 @@ describe.skipIf(!wasmBuilt)("where the first run ends", () => {await waitFor(() => expect(router.state.location.pathname).toBe("/home"));await waitFor(() => expect(getDriver()?.view()?.phase).toBe("ready"), { timeout: 30_000 });await waitFor(() => expect(document.querySelector("[data-prepare-line]")).toBeNull());- expect(screen.getByLabelText("What do you want to do?")).not.toBeNull();+ expect(screen.getByLabelText("What should it do?")).not.toBeNull();expect(document.querySelector("[data-home-spaces]")?.textContent ?? "").not.toContain("home-claude-code");expect(document.body.textContent).not.toContain("home-claude-code");// The home that was made meanwhile does not take the suggestions away: nothing was asked yet.diff --git a/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsxindex a0c763fa2c..bd7451ed0e 100644--- a/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx@@ -77,12 +77,12 @@ describe.skipIf(!wasmBuilt)("Settings tabs (real routes, wasm core)", () => {expect(text).not.toMatch(/Keyboard shortcuts|Shared links|Storage|Runtimes|Keyvault|AI agents|Welcome/);});- it("puts the Providers below Coding apps and On another machine, and Terminal is not on this tab", async () => {+ it("puts the Agent menu below Coding apps, then On another machine and the Providers, and Terminal is not on this tab", async () => {await mountApp("/settings/connections", { ...host, demo: { cli: "missing" } });await waitFor(() => expect(document.querySelector("[data-connectors-providers]")).not.toBeNull(), { timeout: 8000 });const t = tab("connections")!;const headings = [...t.querySelectorAll("h2")].map((h) => h.textContent);- expect(headings).toEqual(["Coding apps", "On another machine", "Providers"]);+ expect(headings).toEqual(["Coding apps", "Agent menu", "On another machine", "Providers"]);// The providers are the last section on the page.const sections = [...t.querySelectorAll("[data-connectors-apps], [data-connectors-other-machine-group], [data-connectors-providers]")].map((e) => e.getAttributeNames().find((n) => n.startsWith("data-connectors-")));expect(sections).toEqual(["data-connectors-apps", "data-connectors-other-machine-group", "data-connectors-providers"]);diff --git a/apps/cua-spaces-web/src/__tests__/warming-home-hidden.test.tsx b/apps/cua-spaces-web/src/__tests__/warming-home-hidden.test.tsxindex c83c0c0b8f..b33807a00b 100644--- a/apps/cua-spaces-web/src/__tests__/warming-home-hidden.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/warming-home-hidden.test.tsx@@ -14,6 +14,7 @@ import { resetFirstRunCache } from "@/bridge/first-run";import { resetSavedOnboardingCache } from "@/bridge/onboarding";import { resetConnectedAppsState } from "@/hooks/use-connected-apps";import { resetAskTasks } from "@/lib/ask-first";+import { rememberAgent, resetPickedAgent } from "@/lib/ask-first-model";import { getDriver, resetPrepare } from "@/lib/prepare/store";import { mountApp, stubBrowserApis } from "./app-harness";@@ -25,6 +26,9 @@ beforeEach(() => {resetConnectedAppsState();resetPrepare();resetAskTasks();+ // The agent the first run prepares a home for is the one the person last used.+ resetPickedAgent();+ rememberAgent({ harness: "claude-code" });setFlagOverride("spaces_ask_first_home", true);setFlagOverride("spaces_new_onboarding", true);});@@ -71,10 +75,10 @@ describe.skipIf(!wasmBuilt)("the warming home is not on any list until a personlet release!: () => void;const hold = new Promise<void>((r) => (release = r));const { router } = await mountApp("/home", { failsCreates: false, listsGhost: false, hold, demo });- await screen.findByLabelText("What do you want to do?");+ await screen.findByLabelText("What should it do?");await waitFor(() => expect(getDriver()?.state?.pendingId).toBeTruthy());expect(getDriver()?.state?.askedMs).toBeNull();- fireEvent.change(screen.getByLabelText("What do you want to do?"), { target: { value: "fix the build" } });+ fireEvent.change(screen.getByLabelText("What should it do?"), { target: { value: "fix the build" } });fireEvent.click(screen.getByRole("button", { name: "Start" }));await waitFor(() => expect(getDriver()?.state?.askedMs).not.toBeNull());await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\//));@@ -87,7 +91,7 @@ describe.skipIf(!wasmBuilt)("the warming home is not on any list until a personit("a home that cannot be made yet is not on a list and Home stays silent", { timeout: 60_000 }, async () => {await mountApp("/home", { failsCreates: true, listsGhost: false, demo });- await screen.findByLabelText("What do you want to do?");+ await screen.findByLabelText("What should it do?");// A dropped connection is retried by itself: Home stays silent and the home stays off every list.await waitFor(() => expect(getDriver()?.view()?.phase).toBe("waiting"), { timeout: 30_000 });expect(document.querySelector("[data-prepare-line]")).toBeNull();diff --git a/apps/cua-spaces-web/src/bridge/__tests__/agent-home-create.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/agent-home-create.test.tsnew file mode 100644index 0000000000..0376de97d2--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/__tests__/agent-home-create.test.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";+import type { DataAdapter } from "../adapter";+import { createDemoAdapter } from "../adapters/demo";+import type { Space } from "../contracts/spaces";+import { BridgeStore } from "../store";+import { testCore, until, wasmBuilt } from "./testCore";++// An agent home (CUA-2630) reaches the host as a plain `spaces.create` whose+// config carries children and the `cua.home.*` labels untouched:+// the hosts (Electron, SwiftUI, Tauri) forward them to the SDK.+describe.skipIf(!wasmBuilt)("an agent home's create", () => {+ it("passes children and labels to the host as they are", async () => {+ const demo = createDemoAdapter({ latencyMs: 0, stepMs: 4 });+ const configs: Record<string, unknown>[] = [];+ const adapter: DataAdapter = Object.assign(Object.create(demo), {+ call: ((method: string, args: unknown) => {+ if (method === "spaces.create") configs.push((args as { config: Record<string, unknown> }).config);+ return demo.call(method as never, args as never);+ }) as DataAdapter["call"],+ subscribe: demo.subscribe.bind(demo),+ });+ const store = new BridgeStore(adapter, await testCore(), { tickMs: 5 });+ store.ensure("spaces");+ await until(() => expect(store.get<Space[]>("spaces").data).toBeTruthy());+ const labels = { "cua.home": "1", "cua.home.agent": "claude-code", "cua.home.list": "all" };+ // A published image: the core refuses one the pipeline has not published yet+ // (the slim tag is published).+ const image = "ghcr.io/trycua/linux:24.04-slim";+ await store.createSpace({ image, name: "home-x", os: "linux", children: true, labels });+ expect(configs).toHaveLength(1);+ expect(configs[0]).toMatchObject({ image, children: true, labels });+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/children-homes.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/children-homes.test.tsnew file mode 100644index 0000000000..277b5267d2--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/__tests__/children-homes.test.ts@@ -0,0 +1,40 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The host says which Spaces are agent homes (from their labels), so the store can hand them out.++import { describe, expect, it } from "vitest";++import type { DataAdapter } from "../adapter";+import { createChildrenStore } from "../children";++const adapter = (tree: unknown[]) => ({ call: async (op: string) => (op === "spaces.tree" ? tree : null) }) as unknown as DataAdapter;+const settle = () => new Promise((r) => setTimeout(r, 0));++describe("agent homes in the children store", () => {+ it("lists the homes, the ones made for the agent first, and ignores Spaces that are not homes", async () => {+ const store = createChildrenStore(+ adapter([+ { id: "local:z-home", parent: null, depth: 0, children: true, home: "openai-codex" },+ { id: "local:a-home", parent: null, depth: 0, children: true, home: "claude-code" },+ { id: "local:b-home", parent: null, depth: 0, children: true, home: "claude-code" },+ { id: "local:plain", parent: null, depth: 0, children: false, home: null },+ { id: "local:old-host", parent: null, depth: 0, children: false },+ ]),+ );+ store.homesOf("claude-code"); // starts the read+ await settle();+ expect(store.homesOf("claude-code")).toEqual(["local:a-home", "local:b-home", "local:z-home"]);+ expect(store.homesOf("openai-codex")).toEqual(["local:z-home", "local:a-home", "local:b-home"]);+ expect(store.node("local:a-home")?.home).toBe("claude-code");+ expect(store.node("local:plain")?.home).toBeUndefined();+ expect(store.node("local:old-host")?.home).toBeUndefined();+ });++ it("offers no home from a host that does not answer the tree", async () => {+ const store = createChildrenStore({ call: async () => Promise.reject(Object.assign(new Error("unsupported"), { unsupported: true })) } as unknown as DataAdapter);+ store.homesOf("claude-code");+ await settle();+ expect(store.homesOf("claude-code")).toEqual([]);+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex ff36686476..6a68b21f73 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -25,6 +25,12 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"network.log": { spaceId: SPACE },"network.ackNotice": { spaceId: SPACE },"spaces.setAccess": { spaceId: SPACE, clipboard: "ask" },+ "spaces.tree": {},+ "children.set": { spaceId: SPACE, enabled: true },+ "budget.get": { spaceId: SPACE },+ "budget.set": { spaceId: SPACE, limits: { maxSpaces: 4 } },+ "services.list": { spaceId: SPACE },+ "services.control": { spaceId: SPACE, name: "web", action: "restart" },"spaces.open": { spaceId: SPACE },"machines.list": {},"host.status": {},@@ -106,6 +112,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"agentKeys.set": { provider: "anthropic", value: "sk-ant-test-0000" },"agentKeys.remove": { env: "ANTHROPIC_API_KEY" },"agentKeys.use": { app: "hermes", env: "OPENAI_API_KEY" },+ "agentKeys.rename": { env: "OPENAI_API_KEY", label: "Work key" },"agentKeys.shell": {},"agentKeys.fromShell": { env: "ANTHROPIC_API_KEY" },"github.status": {},diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 3f5adebf1c..6d2b2db11d 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -49,6 +49,12 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"network.log": { spaceId: "s1" },"network.ackNotice": { spaceId: "s1" },"spaces.setAccess": { spaceId: "s1", clipboard: "ask" },+ "spaces.tree": {},+ "children.set": { spaceId: "s1", enabled: true },+ "budget.get": { spaceId: "s1" },+ "budget.set": { spaceId: "s1", limits: { maxSpaces: 4 } },+ "services.list": { spaceId: "s1" },+ "services.control": { spaceId: "s1", name: "web", action: "restart" },"machines.list": {},"host.status": {},"settings.get": {},diff --git a/apps/cua-spaces-web/src/bridge/adapter.ts b/apps/cua-spaces-web/src/bridge/adapter.tsindex 544714d620..1a8164067f 100644--- a/apps/cua-spaces-web/src/bridge/adapter.ts+++ b/apps/cua-spaces-web/src/bridge/adapter.ts@@ -2,6 +2,7 @@// Copyright (c) 2026 Cua AI, Inc.import type { MachinesView } from "./contracts/host";+import type { ChildrenPreview } from "./contracts/children";import type { NetworkPreview } from "./contracts/network";import type { CreatingElsewhere, ListStatus } from "./contracts/spaces";import type { HostEvent, OpArgs, OpName, OpResult } from "./protocol";@@ -47,6 +48,10 @@ export interface DataAdapter {* (`bridge/network.ts`, over `network.*`) or the demo's (`?demo=network`).* Undefined: the host has none, and none of it shows. */readonly network?: NetworkPreview;+ /** Child Spaces: the tree, each tree's budget and the commands a Space+ * keeps running: the native hosts' (`bridge/children.ts`) or the demo's.+ * Undefined: the host has none, and none of it shows. */+ readonly children?: ChildrenPreview;/*** The Spaces your other computers are creating now, read with* `spaces.list` (CUA-2349). Undefined: the host does not read them.diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 38126ee39c..0c4a4f9219 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -41,7 +41,7 @@ import { demoNewSpaceState, newSpaceDemoHandlers, type DemoClouds, type DemoNewSimport { demoShareHandlers } from "./demo/share";import { DEMO_THREAD_SPACE, demoThreadHandlers, hangingSpace, seedLongDm } from "./demo/thread";import { demoAgentDetailHandlers } from "./demo/agent-detail";-import { demoAgentKeysHandlers, demoKeyStore, type DemoKeyStore } from "./demo/agent-keys";+import { demoAccountKeys, demoAgentKeysHandlers, demoKeyStore, type DemoKeyStore } from "./demo/agent-keys";import { demoKeyvaultManageHandlers, demoKeyvaultManageState, withDemoCopies, type DemoKeyvaultManageState } from "./demo/keyvault-manage";import { demoKeyvaultSetupHandlers, demoKeyvaultSetupState, demoNoVaultOverview, type DemoKeyvaultSetupState } from "./demo/keyvault-setup";import { unsupportedStreamOps } from "../ops/stream";@@ -63,7 +63,9 @@ import { demoLinksHandlers, demoLinksState, type DemoLinksState, type DemoSharesimport { demoResourcesHandlers, demoResourcesState, type DemoResourcesState } from "./demo/resources";import { demoRelayUsageHandlers, demoRelayUsageNamed, demoRelayUsageState, type DemoRelayUsageState } from "./demo/relay-usage";import { demoStartupHandlers, demoStartupState, type DemoStartupState } from "./demo/startup";-import { createDemoNetwork, demoNetworkSpaceRows } from "./demo/network";+import { createChildrenStore } from "../children";+import { createDemoChildren } from "./demo/children";+import { createDemoNetwork, demoAgentHomeRows, demoNetworkSpaceRows } from "./demo/network";import { demoMachine, MAC_DEMO_PLATFORM, type DemoPlatform } from "./demo/platform";export interface DemoOptions {@@ -95,6 +97,8 @@ export interface DemoOptions {claudeLogin?: "signed-in" | "expired" | "none";/** `?demo=chatgpt-signed-in`: a ChatGPT sign-in is saved for Codex (no OpenAI API key unless `no-keys` is left off). */chatgptLogin?: boolean;+ /** Three Claude sign-ins and one ChatGPT sign-in, nothing else (`?demo=accounts`). */+ accounts?: boolean;/** Which connections are saved: `none` (`?demo=no-keys`, an empty Connections list) or `several` (`?demo=connections`: Anthropic, OpenRouter, a custom endpoint and a DeepSeek key the provider refuses). Default: an OpenAI key. */keys?: "none" | "several";/** Start with no Spaces (the first-Space empty state). */@@ -185,6 +189,8 @@ export interface DemoOptions {* `net-exit-down`): research-swarm and its* workers, and each Space's network, Volume and clipboard settings. */network?: Set<string>;+ /** The agent's Home Space with two Spaces under it, and Child Spaces on (`?demo=agent-home`, CUA-2630). */+ agentHome?: boolean;/** Public TCP shares (Labs) on, with a scene: `?demo=shares-consent` (the first share through a share edge asks first), `shares-routes` (shares on three routes and an agent's ask), `shares-settings` (Settings, Sharing with a share edge) or `shares-cap` (the same, with today's data). */shares?: DemoSharesPreset;/** The home's create takes its time (`?demo=slow-home`), the rest of the demo does not: the first run to look at while it is preparing. */@@ -277,6 +283,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {...(flags.has("no-keys") ? { keys: "none" as const } : flags.has("connections") ? { keys: "several" as const, rejectedKeys: ["DEEPSEEK_API_KEY"] } : {}),...(flags.has("claude-expired") ? { claudeLogin: "expired" as const } : flags.has("claude-signed-in") ? { claudeLogin: "signed-in" as const } : flags.has("claude-none") ? { claudeLogin: "none" as const } : {}),...(flags.has("chatgpt-signed-in") ? { chatgptLogin: true } : {}),+ ...(flags.has("accounts") ? { accounts: true } : {}),noSpaces: flags.has("empty"),desktops: flags.has("desktops"),...(() => {@@ -330,6 +337,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {disk: flags.has("disk-full") ? "full" : flags.has("low-disk") ? "low" : undefined,cli: flags.has("cli-local") ? "local" : flags.has("cli-missing") ? "missing" : undefined,...(flags.has("network") ? { network: flags } : {}),+ ...(flags.has("agent-home") ? { agentHome: true } : {}),shares: (["consent", "routes", "settings", "cap"] as const).find((p) => flags.has(`shares-${p}`)),// Slow creates, to look at a state before it is gone (`?demo=slow-create`)....(flags.has("slow-create") ? { stepMs: 5000 } : {}),@@ -385,7 +393,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reconst timers = new Set<ReturnType<typeof setTimeout>>();const state: DemoState = {- rows: options.noSpaces ? [] : [...(options.network ? demoNetworkSpaceRows(now()) : []), ...demoSpaceRows(now()), ...(options.desktops ? demoDesktopRows(now()) : []), ...demoScaleRows(now(), options.extraSpaces ?? 0)],+ rows: options.noSpaces ? [] : [...(options.network ? demoNetworkSpaceRows(now()) : []), ...(options.agentHome ? demoAgentHomeRows(now()) : []), ...demoSpaceRows(now()), ...(options.desktops ? demoDesktopRows(now()) : []), ...demoScaleRows(now(), options.extraSpaces ?? 0)],items: demoKeyvaultItems(now()),keyvaultLocked: Boolean(options.keyvaultLocked),keyvaultDisabled: false,@@ -400,7 +408,10 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re// A named allowance is for showing the prompts, which wait for no agent run.runs: options.usage ? [] : demoRunRecords(now()),imported: [],- keyStore: demoKeyStore(now, options.rejectedKeys ?? [], options.claudeLogin, options.keys, options.chatgptLogin),+ keyStore: (() => {+ const store = demoKeyStore(now, options.rejectedKeys ?? [], options.claudeLogin, options.keys, options.chatgptLogin);+ return options.accounts ? { ...store, keys: demoAccountKeys(now) } : store;+ })(),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,@@ -411,8 +422,8 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reruntimes: demoRuntimesState(),volume: (() => {const v = demoVolumeState(now(), options.onboarded !== false, options.platform, Boolean(options.askFirst || options.github), options.ci !== undefined);- return options.shares || options.network- ? { ...v, experiments: { ...v.experiments, ...(options.shares ? { tcpShares: true } : {}), ...(options.network ? { secureSpaces: true } : {}) } }+ return options.shares || options.network || options.agentHome+ ? { ...v, experiments: { ...v.experiments, ...(options.shares ? { tcpShares: true } : {}), ...(options.network ? { secureSpaces: true } : {}), ...(options.agentHome ? { childSpaces: true, askFirst: true } : {}) } }: v;})(),...demoTelemetryState(),@@ -461,6 +472,8 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reif (!row) throw new HostError(`no Space ${id}`, "not_found");return row;};+ // Child Spaces: research-swarm's tree with `?demo=network`, the agent's Home with `?demo=agent-home`, else none.+ const children = createDemoChildren({ rows: () => state.rows, findRow: (id) => findRow(id), network: Boolean(options.network), agentHome: Boolean(options.agentHome) });const replaceRow = (id: string, patch: Partial<SpaceRow>) => {state.rows = state.rows.map((r) => (r.id === id ? { ...r, ...patch } : r));};@@ -699,6 +712,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { refindRow(spaceId);return null;},+ ...children,"spaces.rename": async ({ spaceId, name }) => {findRow(spaceId);const next = name.trim();@@ -1077,8 +1091,8 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re},};- return {- mode: "demo",+ const self = {+ mode: "demo" as const,state,async call<K extends OpName>(op: K, args: OpArgs<K>): Promise<OpResult<K>> {const handler = handlers[op] as Handler<K> | undefined;@@ -1086,7 +1100,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reawait wait(latency);return handler(args);},- subscribe: (l) => events.subscribe(l),+ subscribe: (l: Parameters<DataAdapter["subscribe"]>[0]) => events.subscribe(l),...(options.network ? { network: createDemoNetwork({ now, flags: options.network }) } : {}),...(options.creatingElsewhere ? { creatingElsewhere: () => DEMO_CREATING_ELSEWHERE } : {}),dispose() {@@ -1095,6 +1109,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reevents.clear();},};+ return Object.assign(self, { children: createChildrenStore(self, now) });}interface DemoLinksStateField {diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.tsindex 0d978ef267..f55c968cc6 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts@@ -35,6 +35,14 @@ const SEVERAL = (now: () => number): AgentKeyInfo[] => [{ provider: "custom", env: "CUSTOM_ENDPOINT_API_KEY", last4: "", addedMs: now() - DAY, fields: { base_url: "http://192.168.1.20:1234/v1", model: "qwen3-coder", wire: "openai-chat" } },];+/** `?demo=accounts`: three Claude sign-ins and one ChatGPT sign-in, and nothing for Hermes or OpenCode. */+export const demoAccountKeys = (now: () => number): AgentKeyInfo[] => [+ { provider: "other", env: "CLAUDE_CODE_OAUTH_TOKEN", last4: "", addedMs: now() - 9 * DAY, label: "Signed in as [email protected] (Claude Max)" },+ { provider: "other", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: "kwork", last4: "", addedMs: now() - 5 * DAY, label: "work Max" },+ { provider: "other", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: "kside", last4: "", addedMs: now() - 2 * DAY, label: "side project Max" },+ { provider: "other", env: "CODEX_AUTH_JSON", last4: "", addedMs: now() - 3 * DAY, label: "Signed in with ChatGPT" },+];+export const demoKeyStore = (now: () => number, rejected: string[] = [], claude?: "signed-in" | "expired" | "none", keys?: "none" | "several", chatgpt?: boolean): DemoKeyStore => ({keys: [...(keys === "none" ? [] : keys === "several" ? SEVERAL(now) : [{ provider: "openai", env: "OPENAI_API_KEY", last4: "3f9a", addedMs: now() - 6 * DAY }]),@@ -59,7 +67,7 @@ export function demoAgentKeysHandlers({stepMs: number;now: () => number;store?: DemoKeyStore;-}): DemoHandlers<"agentKeys.list" | "agentKeys.check" | "agentKeys.set" | "agentKeys.remove" | "agentKeys.use" | "agentKeys.shell" | "agentKeys.fromShell"> {+}): DemoHandlers<"agentKeys.list" | "agentKeys.check" | "agentKeys.set" | "agentKeys.remove" | "agentKeys.use" | "agentKeys.rename" | "agentKeys.shell" | "agentKeys.fromShell"> {const keys = () => store.keys;const report = (): AgentKeysReport => ({ keys: keys().map((k) => ({ ...k })), ...(Object.keys(store.uses).length ? { uses: { ...store.uses } } : {}), providers: PROVIDERS, available: true, unavailable: null });return {@@ -91,6 +99,15 @@ export function demoAgentKeysHandlers({].sort((a, b) => a.env.localeCompare(b.env) || (a.slot ?? "").localeCompare(b.slot ?? ""));return report();},+ "agentKeys.rename": async ({ env, slot, label }) => {+ await wait(stepMs / 2);+ const name = label.trim();+ if (!name || name.length > 40 || /[\u0000-\u001f]/.test(name)) throw new HostError("a key's name must be one line of at most 40 characters");+ const k = keys().find((x) => x.env === env && (x.slot ?? undefined) === (slot ?? undefined));+ if (!k) throw new HostError("that key isn't saved");+ store.keys = keys().map((x) => (x === k ? { ...x, label: name } : x));+ return report();+ },// The demo's shell exports an Anthropic key (`?demo=…` none needed): Use it saves a copy."agentKeys.shell": async () => {await wait(stepMs);@@ -117,14 +134,16 @@ export function demoAgentKeysHandlers({// Which credential an app uses: one that is saved and that the app can read (the demo knows the apps that take any provider)."agentKeys.use": async ({ app, env, slot }) => {await wait(stepMs / 2);- if (!["hermes", "opencode", "goose", "pi", "openclaw"].includes(app)) throw new HostError(`${app} reads one fixed sign-in; there is nothing to choose`);+ const anyProvider = ["hermes", "opencode", "goose", "pi", "openclaw"].includes(app);+ if (!anyProvider && !["claude-code", "codex", "openai-codex"].includes(app)) throw new HostError(`${app} reads one fixed sign-in; there is nothing to choose`);if (!env) {delete store.uses[app];return report();}const k = keys().find((x) => x.env === env && (x.slot ?? undefined) === (slot ?? undefined) && !x.expired);- if (!k || env === "CLAUDE_CODE_OAUTH_TOKEN" || env === "CODEX_AUTH_JSON") throw new HostError("that key isn't saved, or has stopped working");- store.uses[app] = { provider: k.provider, env: k.env, ...(k.slot ? { slot: k.slot } : {}) };+ const reads: Record<string, string[]> = { "claude-code": ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY"], codex: ["CODEX_AUTH_JSON", "OPENAI_API_KEY"], "openai-codex": ["CODEX_AUTH_JSON", "OPENAI_API_KEY"] };+ if (!k || (anyProvider ? env === "CLAUDE_CODE_OAUTH_TOKEN" || env === "CODEX_AUTH_JSON" : !reads[app]!.includes(env))) throw new HostError("that key isn't saved, or has stopped working");+ store.uses[app === "openai-codex" ? "codex" : app] = { provider: k.provider, env: k.env, ...(k.slot ? { slot: k.slot } : {}) };return report();},};diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/children.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/children.tsnew file mode 100644index 0000000000..1f6265ee01--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/children.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Child Spaces on demo data: every demo Space is top-level, except with+ * `?demo=network`, where research-swarm may make children, has two+ * workers, a budget with some of it used, and swarm-worker-1 keeps a web+ * server and a worker running; and `?demo=agent-home`, where the agent's+ * Home Space has made two children for its task (CUA-2630).+ */++import type { OpArgs, OpName, OpResult, ServiceWire, TreeBudgetLimitsWire, TreeBudgetWire, TreeNodeWire } from "../../protocol";+import type { SpaceRow } from "../../contracts/spaces";++type Handler<K extends OpName> = (args: OpArgs<K>) => Promise<OpResult<K>> | OpResult<K>;+type ChildOps = "spaces.tree" | "children.set" | "budget.get" | "budget.set" | "services.list" | "services.control";++const ROOT = "local:research-swarm";+export const AGENT_HOME_ID = "local:agent-home-demo";+const DEFAULTS = { maxSpaces: 16, maxVcpus: 16, maxMemoryMb: 32_768, usdPerHour: 2 };++export function createDemoChildren({+ rows,+ findRow,+ network,+ agentHome = false,+}: {+ rows: () => SpaceRow[];+ findRow: (id: string) => SpaceRow;+ /** `?demo=network`: research-swarm's tree. */+ network: boolean;+ /** `?demo=agent-home`: the agent's Home Space and the two Spaces it made. */+ agentHome?: boolean;+}): { [K in ChildOps]: Handler<K> } {+ const parents = new Map<string, string>([+ ...(network+ ? ([+ ["local:swarm-worker-1", ROOT],+ ["local:swarm-worker-2", ROOT],+ ] as [string, string][])+ : []),+ ...(agentHome+ ? ([+ ["local:acme-app-db", AGENT_HOME_ID],+ ["local:acme-app-build", AGENT_HOME_ID],+ ] as [string, string][])+ : []),+ ]);+ const on = new Set<string>([...(network ? [ROOT] : []), ...(agentHome ? [AGENT_HOME_ID] : [])]);+ let limits: TreeBudgetLimitsWire = network ? { usdPerHour: 1 } : {};+ const services = new Map<string, ServiceWire[]>(+ network+ ? [+ [+ "local:swarm-worker-1",+ [+ { name: "web", command: "python3 -m http.server 8080", state: "running", restarts: 0, lastEnd: "", probeError: "" },+ { name: "crawler", command: "./crawl.sh", state: "backoff", restarts: 3, lastEnd: "exited with code 1", probeError: "" },+ ],+ ],+ ]+ : [],+ );+ const rootOf = (id: string) => {+ let at = id;+ for (let i = 0; i < 8 && parents.has(at); i += 1) at = parents.get(at) as string;+ return at;+ };+ const budget = (id: string): TreeBudgetWire => {+ const root = rootOf(id);+ const kids = [...parents.entries()].filter(([, p]) => rootOf(p) === root).map(([c]) => c);+ const n = kids.length;+ return {+ root,+ set: limits,+ maxSpaces: limits.maxSpaces ?? DEFAULTS.maxSpaces,+ maxVcpus: limits.maxVcpus ?? DEFAULTS.maxVcpus,+ maxMemoryMb: limits.maxMemoryMb ?? DEFAULTS.maxMemoryMb,+ usdPerHour: limits.usdPerHour ?? DEFAULTS.usdPerHour,+ usdTotal: limits.usdTotal ?? null,+ spaces: n,+ vcpus: n * 2,+ memoryMb: n * 4096,+ usdPerHourUsed: 0,+ usdSpent: 0,+ };+ };+ const depth = (id: string) => {+ let d = 0;+ for (let at = id; parents.has(at) && d < 8; at = parents.get(at) as string) d += 1;+ return d;+ };+ return {+ "spaces.tree": (): TreeNodeWire[] => rows().map((r) => ({ id: r.id, parent: parents.get(r.id) ?? null, depth: depth(r.id), children: on.has(r.id), home: agentHome && r.id === AGENT_HOME_ID ? "claude-code" : null })),+ "children.set": ({ spaceId, enabled }) => {+ findRow(spaceId);+ if (enabled) on.add(spaceId);+ else on.delete(spaceId);+ return null;+ },+ "budget.get": ({ spaceId }) => {+ findRow(spaceId);+ return budget(spaceId);+ },+ "budget.set": ({ spaceId, limits: next }) => {+ findRow(spaceId);+ limits = { ...next };+ return budget(spaceId);+ },+ "services.list": ({ spaceId }) => {+ findRow(spaceId);+ return services.get(spaceId) ?? [];+ },+ "services.control": ({ spaceId, name, action }) => {+ findRow(spaceId);+ const list = services.get(spaceId) ?? [];+ services.set(+ spaceId,+ action === "remove"+ ? list.filter((s) => s.name !== name)+ : list.map((s) => (s.name === name ? { ...s, state: action === "stop" ? "stopped" : "running", restarts: action === "restart" ? s.restarts + 1 : s.restarts } : s)),+ );+ return null;+ },+ };+}diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/network.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/network.tsindex 6129177975..d054afb13b 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/network.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/network.ts@@ -46,6 +46,20 @@ export function demoNetworkSpaceRows(now: number): SpaceRow[] {];}+/** The agent's Home Space and the two Spaces it made for "test acme/app" (`?demo=agent-home`, CUA-2630). */+export function demoAgentHomeRows(now: number): SpaceRow[] {+ const mac: SpaceRow = {+ ...linux("local:acme-app-build", "acme-app-build", now, 2),+ os: "macos",+ osName: "macOS",+ osPrettyName: "macOS Tahoe 26.0",+ image: "macos-tahoe",+ kind: "vm",+ power: "suspend",+ };+ return [{ ...linux("local:agent-home-demo", "Home", now, 6), image: "linux-slim" }, linux("local:acme-app-db", "acme-app-db", now, 3), mac];+}+const internet = (extra: Partial<SpaceNetwork> = {}): SpaceNetwork => ({ preset: "internet", allow: [], deny: [], enforced: true, ...extra });const MEMBERS = ["research-swarm", "swarm-worker-1", "swarm-worker-2"];diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.tsindex 386c66fb9e..3683b1801e 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts@@ -882,14 +882,17 @@ export function demoThreadHandlers({}return agentMemberFromTool(memberJson(m));},- "thread.agentAdd": async ({ spaceId, name, harness }) => {+ "thread.agentAdd": async ({ spaceId, name, harness, standby }) => {if (role === "guest") throw denied(GUEST);const t = thread(spaceId);const handle = name.trim().toLowerCase();if (!/^[a-z0-9][a-z0-9._-]{0,62}$/.test(handle)) throw new HostError("Use 1 to 63 lowercase letters, digits, dots, dashes or underscores.", "invalid_argument");- if (t.members.some((m) => m.name === handle)) throw new HostError(`@${handle} is taken here. Pick another name.`, "invalid_argument");+ // Adding the member of the same harness again is the same member (the daemon does the same).+ const existing = t.members.find((m) => m.name === handle);+ if (existing && existing.harness === harness) return agentMemberFromTool(memberJson(existing));+ if (existing) throw new HostError(`@${handle} is taken here. Pick another name.`, "invalid_argument");await wait(stepMs);- const member: DemoMember = { name: handle, harness, status: "asleep", activity: null, sessions: 1, rights: { ...DEFAULT_AGENT_RIGHTS }, identity: startedIdentity(handle, harness) };+ const member: DemoMember = { name: handle, harness, status: standby ? "idle" : "asleep", activity: null, sessions: 1, rights: { ...DEFAULT_AGENT_RIGHTS }, identity: startedIdentity(handle, harness) };join(spaceId, member);return agentMemberFromTool(memberJson(member));},diff --git a/apps/cua-spaces-web/src/bridge/adapters/index.ts b/apps/cua-spaces-web/src/bridge/adapters/index.tsindex 90efe2fdd2..83bcf19fca 100644--- a/apps/cua-spaces-web/src/bridge/adapters/index.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/index.ts@@ -2,6 +2,7 @@// Copyright (c) 2026 Cua AI, Inc.import type { BridgeMode, DataAdapter } from "../adapter";+import { createChildrenStore } from "../children";import { createNetworkStore } from "../network";import { detectMode, type HostWindow } from "../detect";import { createDemoAdapter, demoOptionsFromSearch } from "./demo";@@ -23,9 +24,9 @@ export function createAdapter(case "tauri":return createTauriAdapter(win);case "electron":- return withNetwork(createElectronAdapter(win));+ return withChildren(withNetwork(createElectronAdapter(win)));case "webkit":- return withNetwork(createWebkitAdapter(win));+ return withChildren(withNetwork(createWebkitAdapter(win)));case "demo":return createDemoAdapter(demoOptionsFromSearch(win?.location?.search ?? ""));}@@ -36,3 +37,9 @@ export function createAdapter(function withNetwork(a: DataAdapter): DataAdapter {return a.network ? a : Object.assign(a, { network: createNetworkStore(a) });}++/** `a` with the child Spaces store over its `spaces.tree`, `children.*`,+ * `budget.*` and `services.*` operations. */+function withChildren(a: DataAdapter): DataAdapter {+ return a.children ? a : Object.assign(a, { children: createChildrenStore(a) });+}diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex 30994f33f0..da0e4c8450 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -98,6 +98,12 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = ["network.log","network.ackNotice","spaces.setAccess",+ "spaces.tree",+ "children.set",+ "budget.get",+ "budget.set",+ "services.list",+ "services.control","spaces.deleteMany","spaces.leave","spaces.rename",@@ -257,6 +263,7 @@ export function createTauriAdapter(win: HostWindow = globalThis.window as HostWi// The app core's own settings file is the Mac and Electron apps'; the page keeps this for the session.case "tips":case "notchPinned":+ case "agentMenu":throw new UnsupportedOperationError("tauri", `settings.set ${key}`);}return readSettings();diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex 507ef68020..e91081a492 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -43,6 +43,9 @@ import {type SettingsSnapshot,type SettingsValues,type NetworkEventWire,+ type ServiceWire,+ type TreeBudgetWire,+ type TreeNodeWire,type SpaceNetworkWire,} from "../protocol";import type { KeyvaultOverview, KvGrant, KvPending } from "../contracts/keyvault";@@ -294,6 +297,7 @@ function fromPageRows(spaces: WkSpaces, machines: WkMachines, rows: MachinePageR}const rowsById = (s: WkSettings) => new Map(s.page.sections.flatMap((sec) => sec.rows).map((r) => [r.id, r] as const));+const only = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []);const active = (r: WkSettingsRow | undefined) => r?.options.find((o) => o.active)?.id;const lockedBy = (r: WkSettingsRow | undefined) => (r && !r.enabled && r.help?.startsWith("Set by ") ? r.help.slice(7) : undefined);@@ -323,6 +327,7 @@ export function toSettingsSnapshot(s: WkSettings, page: Pick<SettingsValues, "th...(rows.has("auto-connect") ? { autoConnect: active(rows.get("auto-connect")) === "on" } : {}),// The core's own settings the page changes (`settings.update`); an older host has none....(s.tips ? { tips: { off: s.tips.off === true, done: Array.isArray(s.tips.done) ? s.tips.done : [] } } : {}),+ ...(s.agentMenu ? { agentMenu: { shown: only(s.agentMenu.shown), hidden: only(s.agentMenu.hidden), seen: only(s.agentMenu.seen) } } : {}),...(Array.isArray(s.notchPinned) ? { notchPinned: s.notchPinned.filter((id): id is string => typeof id === "string") } : {}),},defaultLocation: null,@@ -625,6 +630,19 @@ export function createWebkitAdapter(await request("spaces.setAccess", args);return null;},+ // Child Spaces (the Child Spaces experiment), as the host's SDK says them.+ "spaces.tree": () => request<TreeNodeWire[]>("spaces.tree", {}),+ "children.set": async (args) => {+ await request("children.set", args);+ return null;+ },+ "budget.get": ({ spaceId }) => request<TreeBudgetWire>("budget.get", { spaceId }),+ "budget.set": (args) => request<TreeBudgetWire>("budget.set", args),+ "services.list": ({ spaceId }) => request<ServiceWire[]>("services.list", { spaceId }),+ "services.control": async (args) => {+ await request("services.control", args);+ return null;+ },"spaces.open": async ({ spaceId }) => {await request("spaces.open", { id: spaceId });return null;@@ -670,6 +688,7 @@ export function createWebkitAdapter(// The app core's own settings (`AppSettings`), saved as given.case "tips":case "notchPinned":+ case "agentMenu":return toSettingsSnapshot(await request<WkSettings>("settings.update", { [key]: value ?? null }), page);}return settingsSnapshot();diff --git a/apps/cua-spaces-web/src/bridge/agent-keys.ts b/apps/cua-spaces-web/src/bridge/agent-keys.tsindex debe37f7d3..6e467fb2ff 100644--- a/apps/cua-spaces-web/src/bridge/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/agent-keys.ts@@ -262,6 +262,15 @@ export class AgentKeysStore {this.set({ report, error: null });}+ /** Gives a saved key or sign-in a name (`slot` null: the first saved for `env`). Throws the host's words. */+ async rename(env: string, slot: string | null, label: string): Promise<void> {+ this.epoch++;+ const report = await this.adapter.call("agentKeys.rename", { env, label, ...(slot ? { slot } : {}) });+ this.epoch++;+ this.pinned = false;+ this.set({ report, error: null });+ }+openSheet(provider: AgentKeyProvider, env: string | null = null): void {this.set({ sheet: { provider, env }, removing: null });}@@ -312,6 +321,8 @@ export interface AgentKeysHook extends AgentKeysState {remove(env: string, which?: { slot?: string; keepOthers?: boolean }): Promise<void>;/** Tells `app` which saved credential to use (null: the first that works). */use(app: string, choice: { env: string; slot?: string } | null): Promise<void>;+ /** Gives a saved key or sign-in a name. */+ rename(env: string, slot: string | null, label: string): Promise<void>;openSheet(provider: AgentKeyProvider, env?: string | null): void;closeSheet(): void;askRemove(env: string | null): void;@@ -355,6 +366,7 @@ export function useAgentKeys({ watch = false }: { watch?: boolean } = {}): Agentsave: (provider, value, env, choices, more) => need().save(provider, value, env, choices, more),remove: (env, which) => need().remove(env, which),use: (app, choice) => need().use(app, choice),+ rename: (env, slot, label) => need().rename(env, slot, label),openSheet: (provider, env = null) => store?.openSheet(provider, env),closeSheet: () => store?.closeSheet(),askRemove: (env) => store?.askRemove(env),diff --git a/apps/cua-spaces-web/src/bridge/children.ts b/apps/cua-spaces-web/src/bridge/children.tsnew file mode 100644index 0000000000..8df8196609--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/children.ts@@ -0,0 +1,175 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Child Spaces from the host (`spaces.tree`, `children.set`, `budget.get`,+ * `budget.set`, `services.list`, `services.control`), behind the store the+ * Spaces page and the Space page read ([`ChildrenPreview`]). A host that+ * does not answer them leaves every read empty, and none of it shows.+ *+ * Reads are cached and refreshed when asked again after a while; a change+ * reads again at once.+ */++import { isUnsupported, type DataAdapter } from "./adapter";+import type { ChildrenPreview, KeptService, TreeBudget, TreeBudgetLimits, TreeNode } from "./contracts/children";+import type { ServiceWire, TreeBudgetLimitsWire, TreeBudgetWire, TreeNodeWire } from "./protocol";++/** How long a read stays fresh. */+const FRESH_MS = 10_000;++const num = (v: number | null | undefined) => (v === null || v === undefined ? undefined : v);++export function nodeFromWire(w: TreeNodeWire): TreeNode {+ return { id: w.id, parent: w.parent ?? undefined, depth: w.depth, childrenOn: w.children, ...(w.home ? { home: w.home } : {}) };+}++export function limitsFromWire(w: TreeBudgetLimitsWire | null | undefined): TreeBudgetLimits {+ return {+ maxSpaces: num(w?.maxSpaces),+ maxVcpus: num(w?.maxVcpus),+ maxMemoryMb: num(w?.maxMemoryMb),+ usdPerHour: num(w?.usdPerHour),+ usdTotal: num(w?.usdTotal),+ };+}++export function budgetFromWire(w: TreeBudgetWire): TreeBudget {+ return { ...w, set: limitsFromWire(w.set), usdTotal: num(w.usdTotal) };+}++export function serviceFromWire(w: ServiceWire): KeptService {+ return { name: w.name, command: w.command, state: w.state, restarts: w.restarts, lastEnd: w.lastEnd, probeError: w.probeError };+}++/** The store over `adapter`'s operations. */+export function createChildrenStore(adapter: DataAdapter, now: () => number = Date.now): ChildrenPreview {+ const listeners = new Set<() => void>();+ let version = 0;+ let unsupported = false;+ const changed = () => {+ version += 1;+ for (const l of listeners) l();+ };+ const failed = (e: unknown) => {+ if (isUnsupported(e)) unsupported = true;+ };+ const errors = new Map<string, string>();+ const refused = (spaceId: string) => (e: unknown) => {+ failed(e);+ errors.set(spaceId, e instanceof Error ? e.message : String(e));+ changed();+ };++ // The tree, for every Space at once.+ let nodes = new Map<string, TreeNode>();+ let treeAt = 0;+ let treeLoading = false;+ const readTree = () => {+ if (unsupported || treeLoading) return;+ treeLoading = true;+ void adapter+ .call("spaces.tree", {})+ .then((list) => {+ nodes = new Map(list.map((w) => [w.id, nodeFromWire(w)]));+ })+ .catch(failed)+ .finally(() => {+ treeAt = now();+ treeLoading = false;+ changed();+ });+ };+ const tree = () => {+ if (now() - treeAt > FRESH_MS) readTree();+ return nodes;+ };++ // Budgets by Space asked about, services by Space.+ const cached = <T,>(load: (id: string) => Promise<T>, empty: T) => {+ const values = new Map<string, { value: T; at: number; loading: boolean }>();+ const read = (id: string) => {+ const e = values.get(id) ?? { value: empty, at: 0, loading: false };+ values.set(id, e);+ if (unsupported || e.loading) return;+ e.loading = true;+ void load(id)+ .then((v) => {+ e.value = v;+ })+ .catch(failed)+ .finally(() => {+ e.at = now();+ e.loading = false;+ changed();+ });+ };+ return {+ get(id: string): T {+ const e = values.get(id);+ if (!e || now() - e.at > FRESH_MS) read(id);+ return values.get(id)?.value ?? empty;+ },+ reread(id: string) {+ const e = values.get(id);+ if (e) e.at = 0;+ read(id);+ },+ };+ };+ const budgets = cached<TreeBudget | null>(async (id) => budgetFromWire(await adapter.call("budget.get", { spaceId: id })), null);+ const services = cached<KeptService[]>(async (id) => (await adapter.call("services.list", { spaceId: id })).map(serviceFromWire), []);++ return {+ node: (spaceId) => (unsupported ? null : (tree().get(spaceId) ?? null)),+ childrenOf: (spaceId) =>+ unsupported+ ? []+ : [...tree().values()]+ .filter((n) => n.parent === spaceId)+ .map((n) => n.id)+ .sort(),+ homesOf: (agent) =>+ unsupported+ ? []+ : [...tree().values()]+ .filter((n) => n.home !== undefined)+ .sort((a, b) => Number(b.home === agent) - Number(a.home === agent) || a.id.localeCompare(b.id))+ .map((n) => n.id),+ setChildrenOn(spaceId, on) {+ const n = nodes.get(spaceId);+ if (n) nodes.set(spaceId, { ...n, childrenOn: on });+ changed();+ void adapter+ .call("children.set", { spaceId, enabled: on })+ .then(() => errors.delete(spaceId))+ .catch(refused(spaceId))+ .finally(() => {+ treeAt = 0;+ readTree();+ });+ },+ budget: (spaceId) => (unsupported ? null : budgets.get(spaceId)),+ setBudget(spaceId, limits) {+ void adapter+ .call("budget.set", { spaceId, limits })+ .then(() => errors.delete(spaceId))+ .catch(refused(spaceId))+ .finally(() => budgets.reread(spaceId));+ },+ services: (spaceId) => (unsupported ? [] : services.get(spaceId)),+ controlService(spaceId, name, action) {+ void adapter+ .call("services.control", { spaceId, name, action })+ .then(() => errors.delete(spaceId))+ .catch(refused(spaceId))+ .finally(() => services.reread(spaceId));+ },+ error: (spaceId) => errors.get(spaceId) ?? null,+ subscribe(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ version: () => version,+ };+}diff --git a/apps/cua-spaces-web/src/bridge/connectors.ts b/apps/cua-spaces-web/src/bridge/connectors.tsindex 1ba998fa3a..e50ede0237 100644--- a/apps/cua-spaces-web/src/bridge/connectors.ts+++ b/apps/cua-spaces-web/src/bridge/connectors.ts@@ -10,6 +10,7 @@*/import type { CoreClient } from "./core";+import type { AgentMenuPrefs } from "./protocol";import type { AgentSetupRow } from "./contracts/agents";import { hostOs, type HostOs } from "./host-os";import type { AgentKeysInput, AgentKeyRowView } from "./agent-keys";@@ -353,6 +354,96 @@ export interface ModelsView {export const modelsView = (core: CoreClient, input: ConnectorsInput): ModelsView | null =>core.tryCall<ModelsView>("connectors.models", { input: input as unknown as Json }) ?? null;+/* ---- The agent menu of the prompt box ------------------------------------------------ */++/** One sign-in or key a coding app can run with. */+export interface AgentAccount {+ provider: string;+ providerLabel: string;+ icon: string;+ env: string;+ slot: string | null;+ /** What the person sees: the sign-in's own name, "Signed in with ChatGPT", a key's name or "API key ending 4f2a". */+ line: string;+ via: "sign-in" | "key";+ /** The account runs use now. */+ selected: boolean;+ models: ModelChoice[];+ defaultModel: string | null;+}++/** One coding app of the menu and the accounts the person has for it. */+export interface AgentGroup {+ /** The harness id a run uses (`openai-codex`). */+ harness: string;+ /** The app's Connections id (`codex`), where its sign-ins are managed. */+ app: string;+ label: string;+ state: "connected" | "needs-reconnect" | "not-connected";+ accounts: AgentAccount[];+ signInLabel: string;+}++/** A coding app, an account and a model picked together. */+export interface AgentRef {+ harness: string;+ provider: string;+ env: string;+ slot: string | null;+ model: string;+}++/** The agent menu (`connectors.agents`). */+export interface AgentsView {+ groups: AgentGroup[];+ default: AgentRef | null;+ empty: string | null;+}++export const agentsView = (core: CoreClient, input: ConnectorsInput, menu?: AgentMenuPrefs): AgentsView | null =>+ core.tryCall<AgentsView>("connectors.agents", { input: input as unknown as Json, ...(menu ? { menu: menu as unknown as Json } : {}) }) ?? null;++/** One coding app in Settings, Connections, Agent menu (`agentMenu.view`). */+export interface AgentMenuRow {+ app: string;+ label: string;+ /** The app is in the agent menu. */+ shown: boolean;+ /** "Signed in", "Sign in again" or "Not signed in". */+ status: string;+ /** The last app shown: its switch cannot be turned off. */+ locked: boolean;+}++export interface AgentMenuSettings {+ title: string;+ switchLabel: string;+ help: string;+ rows: AgentMenuRow[];+ /** Said while one app is left: why it stays. */+ lastNote: string | null;+}++export interface AgentMenuChange {+ prefs: AgentMenuPrefs;+ /** Said when the switch was refused (the last app cannot be hidden). */+ refused: string | null;+}++const menuArgs = (input: ConnectorsInput, menu: AgentMenuPrefs) => ({ input: input as unknown as Json, menu: menu as unknown as Json });++/** The rows of the agent menu switches (`agentMenu.view`). */+export const agentMenuView = (core: CoreClient, input: ConnectorsInput, menu: AgentMenuPrefs): AgentMenuSettings | null =>+ core.tryCall<AgentMenuSettings>("agentMenu.view", menuArgs(input, menu)) ?? null;++/** The choice after switching `app` on or off (`agentMenu.choose`). */+export const agentMenuChoose = (core: CoreClient, input: ConnectorsInput, menu: AgentMenuPrefs, app: string, on: boolean): AgentMenuChange | null =>+ core.tryCall<AgentMenuChange>("agentMenu.choose", { ...menuArgs(input, menu), app, on }) ?? null;++/** The choice after the accounts changed: an app that gained an account is shown again (`agentMenu.sync`). */+export const agentMenuSync = (core: CoreClient, input: ConnectorsInput, menu: AgentMenuPrefs): AgentMenuPrefs | null =>+ core.tryCall<AgentMenuPrefs>("agentMenu.sync", menuArgs(input, menu)) ?? null;+export const appDetail = (core: CoreClient, input: ConnectorsInput, agent: string): AppDetailView | null =>core.tryCall<AppDetailView | null>("connectors.appDetail", { input: input as unknown as Json, agent }) ?? null;diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex cf3b3d1c14..4ac1d8da9b 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -5016,6 +5016,34 @@"items": {"type": "string"}+ },+ "agentMenu": {+ "type": "object",+ "properties": {+ "shown": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "hidden": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "seen": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "shown",+ "hidden",+ "seen"+ ]}},"required": [@@ -5720,6 +5748,37 @@"reachable"]},+ "SpaceService": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "command": {+ "type": "string"+ },+ "state": {+ "type": "string"+ },+ "restarts": {+ "type": "number"+ },+ "lastEnd": {+ "type": "string"+ },+ "probeError": {+ "type": "string"+ }+ },+ "required": [+ "name",+ "command",+ "state",+ "restarts",+ "lastEnd",+ "probeError"+ ]+ },"SpaceSharingFacts": {"type": "object","properties": {@@ -6402,6 +6461,129 @@"event"]},+ "TreeBudget": {+ "type": "object",+ "properties": {+ "root": {+ "type": "string"+ },+ "set": {+ "$ref": "#/$defs/TreeBudgetLimits"+ },+ "maxSpaces": {+ "type": "number"+ },+ "maxVcpus": {+ "type": "number"+ },+ "maxMemoryMb": {+ "type": "number"+ },+ "usdPerHour": {+ "type": "number"+ },+ "usdTotal": {+ "type": [+ "number",+ "null"+ ]+ },+ "spaces": {+ "type": "number"+ },+ "vcpus": {+ "type": "number"+ },+ "memoryMb": {+ "type": "number"+ },+ "usdPerHourUsed": {+ "type": "number"+ },+ "usdSpent": {+ "type": "number"+ }+ },+ "required": [+ "root",+ "set",+ "maxSpaces",+ "maxVcpus",+ "maxMemoryMb",+ "usdPerHour",+ "spaces",+ "vcpus",+ "memoryMb",+ "usdPerHourUsed",+ "usdSpent"+ ]+ },+ "TreeBudgetLimits": {+ "type": "object",+ "properties": {+ "maxSpaces": {+ "type": [+ "number",+ "null"+ ]+ },+ "maxVcpus": {+ "type": [+ "number",+ "null"+ ]+ },+ "maxMemoryMb": {+ "type": [+ "number",+ "null"+ ]+ },+ "usdPerHour": {+ "type": [+ "number",+ "null"+ ]+ },+ "usdTotal": {+ "type": [+ "number",+ "null"+ ]+ }+ }+ },+ "TreeNode": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "parent": {+ "type": [+ "string",+ "null"+ ]+ },+ "depth": {+ "type": "number"+ },+ "children": {+ "type": "boolean"+ },+ "home": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "id",+ "depth",+ "children"+ ]+ },"UpdateState": {"type": "object","properties": {@@ -7692,6 +7874,34 @@"type": "string"}},+ "agentMenu": {+ "type": "object",+ "properties": {+ "shown": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "hidden": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "seen": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "shown",+ "hidden",+ "seen"+ ]+ },"runtimes": {"anyOf": [{@@ -8005,6 +8215,9 @@"agentKeys.remove": {"$ref": "#/$defs/AgentKeysReport"},+ "agentKeys.rename": {+ "$ref": "#/$defs/AgentKeysReport"+ },"agentKeys.set": {"$ref": "#/$defs/AgentKeysReport"},@@ -8447,6 +8660,12 @@"earlierOmitted"]},+ "budget.get": {+ "$ref": "#/$defs/TreeBudget"+ },+ "budget.set": {+ "$ref": "#/$defs/TreeBudget"+ },"checklist.get": {"type": "object","properties": {@@ -8521,6 +8740,9 @@"state"]},+ "children.set": {+ "type": "null"+ },"ci.connect": {"$ref": "#/$defs/CiConnectAnswer"},@@ -9481,6 +9703,15 @@"runtimes.check": {"$ref": "#/$defs/RuntimePathCheck"},+ "services.control": {+ "type": "null"+ },+ "services.list": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/SpaceService"+ }+ },"session.completeOnboarding": {"type": "null"},@@ -9864,6 +10095,12 @@"capturedAtMs"]},+ "spaces.tree": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/TreeNode"+ }+ },"spaces.usage": {"type": ["object",@@ -11104,6 +11341,111 @@"available"]},+ "agentKeys.rename": {+ "type": "object",+ "properties": {+ "keys": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string"+ },+ "env": {+ "type": "string"+ },+ "slot": {+ "type": "string"+ },+ "last4": {+ "type": "string"+ },+ "added_ms": {+ "type": "number"+ },+ "expired": {+ "type": "boolean"+ },+ "label": {+ "type": "string"+ },+ "region": {+ "type": "string"+ },+ "fields": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "required": [+ "provider",+ "env",+ "last4",+ "added_ms"+ ]+ }+ },+ "uses": {+ "type": "object",+ "additionalProperties": {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string"+ },+ "env": {+ "type": "string"+ },+ "slot": {+ "type": "string"+ }+ },+ "required": [+ "provider",+ "env"+ ]+ }+ },+ "providers": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "env": {+ "type": "string"+ },+ "label": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "env"+ ]+ }+ },+ "available": {+ "type": "boolean"+ },+ "unavailable": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "keys",+ "providers",+ "available"+ ]+ },"agentKeys.set": {"type": "object","properties": {@@ -11718,6 +12060,12 @@"methods"]},+ "budget.get": {+ "$ref": "#/$defs/TreeBudget"+ },+ "budget.set": {+ "$ref": "#/$defs/TreeBudget"+ },"checklist.get": {"type": "object","properties": {@@ -11792,6 +12140,10 @@"state"]},+ "children.set": {+ "type": "object",+ "properties": {}+ },"ci.connect": {"$ref": "#/$defs/CiConnectAnswer"},@@ -13389,6 +13741,16 @@"runtimes.check": {"$ref": "#/$defs/RuntimePathCheck"},+ "services.control": {+ "type": "object",+ "properties": {}+ },+ "services.list": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/SpaceService"+ }+ },"session.get": {"$ref": "#/$defs/WkSession"},@@ -13704,6 +14066,12 @@"capturedAtMs"]},+ "spaces.tree": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/TreeNode"+ }+ },"spaces.usage": {"type": ["object",diff --git a/apps/cua-spaces-web/src/bridge/contracts/children.ts b/apps/cua-spaces-web/src/bridge/contracts/children.tsnew file mode 100644index 0000000000..c0db74c06d--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/contracts/children.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Child Spaces as the Spaces page and the Space page read them: which+ * Spaces belong to which, whether a Space may make children, its tree's+ * budget and the commands it keeps running. From the host+ * (`bridge/children.ts`, over `spaces.tree`, `children.*`, `budget.*` and+ * `services.*`) or the demo's memory (`?demo=network`). All of it is the+ * Child Spaces experiment's (Settings, Experiments).+ */++/** One Space's place in its tree. */+export interface TreeNode {+ id: string;+ /** Its parent's id; absent for a top-level Space. */+ parent?: string;+ /** 0 for a top-level Space, 1 for its children, ... */+ depth: number;+ /** It may make child Spaces of its own. */+ childrenOn: boolean;+ /** It is an agent's home: the agent (harness id) it was made for. */+ home?: string;+}++/** What a tree's children may hold and cost. Unset: the default. */+export interface TreeBudgetLimits {+ maxSpaces?: number;+ maxVcpus?: number;+ maxMemoryMb?: number;+ usdPerHour?: number;+ usdTotal?: number;+}++/** A tree's budget and what its children use now. */+export interface TreeBudget {+ root: string;+ /** What the owner set (unset fields take the default). */+ set: TreeBudgetLimits;+ maxSpaces: number;+ maxVcpus: number;+ maxMemoryMb: number;+ usdPerHour: number;+ usdTotal?: number;+ spaces: number;+ vcpus: number;+ memoryMb: number;+ usdPerHourUsed: number;+ usdSpent: number;+}++/** A command a Space keeps running. */+export interface KeptService {+ name: string;+ command: string;+ /** `starting`, `running`, `unhealthy`, `backoff`, `stopped`, `exited`, `failed`. */+ state: string;+ restarts: number;+ /** How the last process ended, when one did. */+ lastEnd: string;+ /** The last failed health check. */+ probeError: string;+}++export type ServiceAction = "start" | "stop" | "restart" | "remove";++/** The host's store (`DataAdapter.children`). */+export interface ChildrenPreview {+ /** A Space's place in its tree; null before the first read. */+ node(spaceId: string): TreeNode | null;+ /** A Space's direct children, by id. */+ childrenOf(spaceId: string): string[];+ /** The agent homes the host knows (from their labels), by id: the ones made for `agent` first. */+ homesOf(agent: string): string[];+ /** Lets a Space make children, or stops it. */+ setChildrenOn(spaceId: string, on: boolean): void;+ /** The budget of `spaceId`'s tree; null before the first read. */+ budget(spaceId: string): TreeBudget | null;+ setBudget(spaceId: string, limits: TreeBudgetLimits): void;+ /** The commands a Space keeps running. */+ services(spaceId: string): KeptService[];+ controlService(spaceId: string, name: string, action: ServiceAction): void;+ /** The last change the host refused, in its words. */+ error(spaceId: string): string | null;+ subscribe(listener: () => void): () => void;+ /** Bumps on every change (for `useSyncExternalStore`). */+ version(): number;+}diff --git a/apps/cua-spaces-web/src/bridge/contracts/host.ts b/apps/cua-spaces-web/src/bridge/contracts/host.tsindex 3286bf5cf2..d01521863f 100644--- a/apps/cua-spaces-web/src/bridge/contracts/host.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/host.ts@@ -59,6 +59,10 @@ export interface SpaceCreateConfig {spacesd?: boolean;reuse?: boolean;gpu?: string;+ /** Lets the Space make child Spaces of its own (the SDK's `children`). */+ children?: boolean;+ /** Labels kept with the Space (the SDK's `labels`). The agent home's grants ride on `cua.home.*`. */+ labels?: Record<string, string>;}/** Where new Spaces go by default (`default.on`), and where that came from. */diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 4624bd0dfd..b19a7e59fb 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -80,7 +80,7 @@ import type { AgentMember, JoinCode, JoinCodeRow, LiveAgent, MemberIdentity, Thrimport type { PresenceCursorWire, PresenceJoinInfo, PresenceParticipantWire } from "../ops/presence";import type { StartupState } from "../ops/startup";import type { StreamTicket } from "../ops/stream";-import type { CliInfo, GlobalShortcut, HostSettings, HostSignIn, HostSignInFailure, NetworkEventWire, OpName, SessionSnapshot, SettingsSnapshot, SettingsValues, SpaceNetworkWire } from "../protocol";+import type { AgentMenuPrefs, CliInfo, GlobalShortcut, HostSettings, HostSignIn, HostSignInFailure, NetworkEventWire, OpName, ServiceWire, SessionSnapshot, SettingsSnapshot, SettingsValues, SpaceNetworkWire, TreeBudgetLimitsWire, TreeBudgetWire, TreeNodeWire } from "../protocol";import type { WebkitMethod, WkHostState, WkMachines, WkOnboarding, WkSession, WkSettings, WkSettingsRow, WkSpace, WkSpaces } from "../webkit-protocol";import { Defs, any, bool, dict, list, nul, nullable, num, obj, object, oneOf, opt, optNull, str, union, type Schema } from "./schema";@@ -391,6 +391,9 @@ const SessionShape = ref(/** `AppSettings.tips` (`tips::TipsState`). */const TipsStateShape = obj<TipsState>()({ off: bool, done: strings });+/** `AppSettings.agentMenu*` (`agent_menu::AgentMenuPrefs`). */+const AgentMenuPrefsShape = obj<AgentMenuPrefs>()({ shown: strings, hidden: strings, seen: strings });+const RuntimePathCheckShape = ref("RuntimePathCheck",obj<RuntimePathCheck>()({@@ -444,6 +447,7 @@ const SettingsShape = ref(autoConnect: opt(bool),tips: opt(TipsStateShape),notchPinned: opt(strings),+ agentMenu: opt(AgentMenuPrefsShape),}),defaultLocation: nullable(obj<DefaultLocation>()({ value: str, source: oneOf("env", "config", "default"), env: opt(str), path: str })),telemetry: nullable(@@ -1329,6 +1333,39 @@ const NetworkEventShape = ref(obj<NetworkEventWire>()({ reason: str, dst: str, proto: optNull(str), count: num, lastUnix: optNull(num) }),);+const TreeNodeShape = ref("TreeNode", obj<TreeNodeWire>()({ id: str, parent: optNull(str), depth: num, children: bool, home: optNull(str) }));+const TreeBudgetLimitsShape = ref(+ "TreeBudgetLimits",+ obj<TreeBudgetLimitsWire>()({+ maxSpaces: optNull(num),+ maxVcpus: optNull(num),+ maxMemoryMb: optNull(num),+ usdPerHour: optNull(num),+ usdTotal: optNull(num),+ }),+);+const TreeBudgetShape = ref(+ "TreeBudget",+ obj<TreeBudgetWire>()({+ root: str,+ set: TreeBudgetLimitsShape,+ maxSpaces: num,+ maxVcpus: num,+ maxMemoryMb: num,+ usdPerHour: num,+ usdTotal: optNull(num),+ spaces: num,+ vcpus: num,+ memoryMb: num,+ usdPerHourUsed: num,+ usdSpent: num,+ }),+);+const ServiceShape = ref(+ "SpaceService",+ obj<ServiceWire>()({ name: str, command: str, state: str, restarts: num, lastEnd: str, probeError: str }),+);+export const OP_SHAPES: Record<OpName, Schema> = {"spaces.list": list(SpaceRowShape),"spaces.create": SpaceRowShape,@@ -1343,6 +1380,12 @@ export const OP_SHAPES: Record<OpName, Schema> = {"network.log": list(NetworkEventShape),"network.ackNotice": nul,"spaces.setAccess": nul,+ "spaces.tree": list(TreeNodeShape),+ "children.set": nul,+ "budget.get": TreeBudgetShape,+ "budget.set": TreeBudgetShape,+ "services.list": list(ServiceShape),+ "services.control": nul,"spaces.open": nul,"machines.list": list(MachineRowShape),"host.status": hostStatusOrNull,@@ -1507,6 +1550,7 @@ export const OP_SHAPES: Record<OpName, Schema> = {"agentKeys.set": AgentKeysShape,"agentKeys.remove": AgentKeysShape,"agentKeys.use": AgentKeysShape,+ "agentKeys.rename": AgentKeysShape,"agentKeys.shell": object({ names: list(str) }),"agentKeys.fromShell": AgentKeysShape,"github.status": GithubShape,@@ -1810,6 +1854,7 @@ const WkSettingsShape = ref(cli: optNull(object({ name: str, installed: bool })),tips: opt(TipsStateShape),notchPinned: opt(strings),+ agentMenu: opt(AgentMenuPrefsShape),runtimes: optNull(RuntimesInputShape),}),);@@ -1970,6 +2015,12 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"network.log": list(NetworkEventShape),"network.ackNotice": object({}),"spaces.setAccess": object({}),+ "spaces.tree": list(TreeNodeShape),+ "children.set": object({}),+ "budget.get": TreeBudgetShape,+ "budget.set": TreeBudgetShape,+ "services.list": list(ServiceShape),+ "services.control": object({}),// The page's wizard runs on `env`, and reads `local`."spaces.createOptions": ref("WkCreateOptions", createOptions(true)),"spaces.create": WkSpaceShape,@@ -2010,6 +2061,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"agentKeys.set": AgentKeysWire,"agentKeys.remove": AgentKeysWire,"agentKeys.use": AgentKeysWire,+ "agentKeys.rename": AgentKeysWire,"agentKeys.shell": object({ names: list(str) }),"agentKeys.fromShell": AgentKeysWire,"github.status": GithubWire,diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 37e1547e8c..3a1464e1f7 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -93,6 +93,12 @@ export const HOST_COVERAGE = {"network.log": { webkit: { methods: ["network.log"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no network settings" } },"network.ackNotice": { webkit: { methods: ["network.ackNotice"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no network settings" } },"spaces.setAccess": { webkit: { methods: ["spaces.setAccess"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no network settings" } },+ "spaces.tree": { webkit: { methods: ["spaces.tree"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no child Spaces" } },+ "children.set": { webkit: { methods: ["children.set"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no child Spaces" } },+ "budget.get": { webkit: { methods: ["budget.get"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no child Spaces" } },+ "budget.set": { webkit: { methods: ["budget.set"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no child Spaces" } },+ "services.list": { webkit: { methods: ["services.list"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no child Spaces" } },+ "services.control": { webkit: { methods: ["services.control"] }, tauri: [], unsupported: { tauri: "the Tauri shell is not the shipped app (SwiftUI and Electron are); it has no child Spaces" } },"machines.list": {webkit: { methods: ["spaces.list", "machines.list"] },tauri: ["host_status", "list_hosts", "get_environment"],diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex cc2e9eda06..ded8ecb0e3 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -98,6 +98,7 @@ export {type OpName,type SettingKey,type SettingsValues,+ type AgentMenuPrefs,type UpdateChannel,} from "./protocol";diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts b/apps/cua-spaces-web/src/bridge/ops/agent-keys.tsindex e4034e8f6e..035cd18535 100644--- a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts@@ -20,6 +20,7 @@* | `agentKeys.set {provider, env?, value}` | `agent_keys.set` | `agentKeys.set` |* | `agentKeys.remove {env, slot?, keepOthers?}` | `agent_keys.remove` | `agentKeys.remove` |* | `agentKeys.use {app, env?, slot?}` | `agent_keys.use` | `agentKeys.use` |+ * | `agentKeys.rename {env, slot?, label}` | `agent_keys.rename` | `agentKeys.rename` |** The Electron shell answers the SwiftUI host's methods.*/@@ -112,6 +113,8 @@ declare module "../protocol" {* nothing. Answers the list after.*/"agentKeys.use": { args: { app: string; env?: string; slot?: string }; result: AgentKeysReport };+ /** Gives a saved key or sign-in a name (`slot` absent: the first saved for `env`). Answers the list after. */+ "agentKeys.rename": { args: { env: string; slot?: string; label: string }; result: AgentKeysReport };/** Which provider keys your login shell has set (names only; never a value). */"agentKeys.shell": { args: Record<string, never>; result: { names: string[] } };/** Saves the key `env` from your login shell (the value goes straight to the store). Answers the list after. */@@ -119,7 +122,7 @@ declare module "../protocol" {}}-export const AGENT_KEYS_OPERATIONS = ["agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.shell", "agentKeys.fromShell"] as const;+export const AGENT_KEYS_OPERATIONS = ["agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.rename", "agentKeys.shell", "agentKeys.fromShell"] as const;export type AgentKeysOp = (typeof AGENT_KEYS_OPERATIONS)[number];/** The SwiftUI host routes each under its own name. */@@ -132,6 +135,7 @@ export const AGENT_KEYS_METHODS = {"agentKeys.set": "agent_keys.set","agentKeys.remove": "agent_keys.remove","agentKeys.use": "agent_keys.use",+ "agentKeys.rename": "agent_keys.rename","agentKeys.shell": "agent_keys.shell","agentKeys.fromShell": "agent_keys.from_shell",} as const satisfies { [K in AgentKeysOp]: string };@@ -142,6 +146,7 @@ export const AGENT_KEYS_COVERAGE = {"agentKeys.set": { webkit: { methods: ["agentKeys.set"] }, tauri: ["agents_tool"] },"agentKeys.remove": { webkit: { methods: ["agentKeys.remove"] }, tauri: ["agents_tool"] },"agentKeys.use": { webkit: { methods: ["agentKeys.use"] }, tauri: ["agents_tool"] },+ "agentKeys.rename": { webkit: { methods: ["agentKeys.rename"] }, tauri: ["agents_tool"] },"agentKeys.shell": { webkit: { methods: ["agentKeys.shell"] }, tauri: ["agents_tool"] },"agentKeys.fromShell": { webkit: { methods: ["agentKeys.fromShell"] }, tauri: ["agents_tool"] },} as const satisfies Record<AgentKeysOp, OpCoverage>;@@ -153,6 +158,7 @@ export const AGENT_KEYS_ARGS: { [K in AgentKeysOp]: OpArgs<K> } = {"agentKeys.set": { provider: "anthropic", value: "sk-ant-test-0000" },"agentKeys.remove": { env: "ANTHROPIC_API_KEY" },"agentKeys.use": { app: "hermes", env: "OPENAI_API_KEY" },+ "agentKeys.rename": { env: "OPENAI_API_KEY", label: "Work key" },"agentKeys.shell": {},"agentKeys.fromShell": { env: "ANTHROPIC_API_KEY" },};@@ -241,6 +247,7 @@ export function tauriAgentKeysOps(invoke: Invoke): Handlers {"agentKeys.set": (args) => tool("agentKeys.set", setArgs(args)),"agentKeys.remove": (args) => tool("agentKeys.remove", removeArgs(args)),"agentKeys.use": ({ app, env, slot }) => tool("agentKeys.use", { app, ...(env ? { env } : {}), ...(slot ? { slot } : {}) }),+ "agentKeys.rename": ({ env, slot, label }) => tool("agentKeys.rename", { env, label, ...(slot ? { slot } : {}) }),"agentKeys.shell": async () => shellNamesFromWire(await invoke<unknown>("agents_tool", { tool: AGENT_KEYS_METHODS["agentKeys.shell"], args: {} })),"agentKeys.fromShell": ({ env, region, fields }) => tool("agentKeys.fromShell", { env, ...choicesOf({ region, fields }) }),};@@ -255,6 +262,7 @@ export function webkitAgentKeysOps(request: Request): Handlers {"agentKeys.set": (args) => call("agentKeys.set", setArgs(args)),"agentKeys.remove": (args) => call("agentKeys.remove", removeArgs(args)),"agentKeys.use": ({ app, env, slot }) => call("agentKeys.use", { app, ...(env ? { env } : {}), ...(slot ? { slot } : {}) }),+ "agentKeys.rename": ({ env, slot, label }) => call("agentKeys.rename", { env, label, ...(slot ? { slot } : {}) }),"agentKeys.shell": async () => shellNamesFromWire(await request<unknown>("agentKeys.shell", {})),"agentKeys.fromShell": ({ env, region, fields }) => call("agentKeys.fromShell", { env, ...choicesOf({ region, fields }) }),};diff --git a/apps/cua-spaces-web/src/bridge/ops/thread.ts b/apps/cua-spaces-web/src/bridge/ops/thread.tsindex 9f6b9cf92b..3d9fa9d241 100644--- a/apps/cua-spaces-web/src/bridge/ops/thread.ts+++ b/apps/cua-spaces-web/src/bridge/ops/thread.ts@@ -14,7 +14,7 @@* | `thread.post {spaceId, text, replyTo?, answer?, toSession?, view?}` | `thread_post` | the tool's JSON as-is | unsupported |* | `thread.members {spaceId}` | `agent_members` | the tool's JSON as-is | unsupported |* | `thread.setRights {spaceId, name, task?, control?, approve?}` | `agent_set_rights` | the tool's JSON as-is | unsupported |- * | `thread.agentAdd {spaceId, name, harness}` | `agent_add` | the tool's JSON as-is | unsupported |+ * | `thread.agentAdd {spaceId, name, harness, model?, standby?, brief?}` | `agent_add` | the tool's JSON as-is | unsupported |* | `thread.agentRemove {spaceId, name}` | `agent_remove` | the tool's JSON as-is | unsupported |* | `thread.joinCodeCreate {spaceId, ttlS?, canTask?, askBeforeJoin?}` | `thread_join_code_create` | the tool's JSON as-is | unsupported |* | `thread.joinCodeList {spaceId}` | `thread_join_code_list` | the tool's JSON as-is | unsupported |@@ -320,6 +320,12 @@ export interface ThreadAgentAddArgs {name: string;/** The harness id (`hermes`, `claude-code`, `openai-codex`, ...). */harness: string;+ /** The model its next message uses (an open session switches to it before the turn). On a member that exists, it is updated. */+ model?: string;+ /** Keep its run open with the session ready, so a message starts its turn at once. */+ standby?: boolean;+ /** Standing instructions: the first message each run takes carries them in front of its text. */+ brief?: string;}export interface ThreadJoinCodeCreateArgs {@@ -496,7 +502,14 @@ export function threadSetRightsArgs(a: ThreadSetRightsArgs): Json {export const threadAgentRemoveArgs = (a: ThreadAgentRemoveArgs): Json => ({ name: a.name });/** `agent_add`: a started member of the Space (`agent` is the harness id). */-export const threadAgentAddArgs = (a: ThreadAgentAddArgs): Json => ({ space: a.spaceId, name: a.name, agent: a.harness });+export const threadAgentAddArgs = (a: ThreadAgentAddArgs): Json => ({+ space: a.spaceId,+ name: a.name,+ agent: a.harness,+ ...(a.model ? { model: a.model } : {}),+ ...(a.standby !== undefined ? { standby: a.standby } : {}),+ ...(a.brief ? { brief: a.brief } : {}),+});export function threadJoinCodeCreateArgs(a: ThreadJoinCodeCreateArgs): Json {const out: Json = { space: a.spaceId };diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex fa4bb05754..3ac6dc5151 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -97,6 +97,17 @@ export interface SettingsValues {* in pin order. Absent where the host keeps no core settings (the page keeps them* for this session). */notchPinned?: string[];+ /** Which coding apps Home's agent menu shows (`AppSettings.agentMenu*`, the core's+ * `agent_menu`). Absent where the host keeps no core settings (the page keeps it+ * for this session). */+ agentMenu?: AgentMenuPrefs;+}++/** The apps whose default the person changed (`agent_menu::AgentMenuPrefs`). */+export interface AgentMenuPrefs {+ shown: string[];+ hidden: string[];+ seen: string[];}export type UpdateChannel = "stable" | "beta";@@ -245,7 +256,10 @@ export interface HostOperationsAgentThreadsOps,RuntimeFixOps {"spaces.list": { args: Record<string, never>; result: SpaceRow[] };- /** `os`: the plan's OS, for a host that draws its own pending row (the SwiftUI app's notch). */+ /** `os`: the plan's OS, for a host that draws its own pending row (the SwiftUI app's notch).+ * `config.children` and `config.labels` (an agent home, CUA-2630) are forwarded to+ * the SDK's create as they are by every host: Electron (`createExtras`), SwiftUI (`CreateExtras`)+ * and Tauri (`SpaceCreateConfig`). */"spaces.create": { args: { config: SpaceCreateConfig; pendingId: string; os?: SpaceOs; notifyWhenReady?: boolean }; result: SpaceRow };"spaces.cancelCreate": { args: { pendingId: string }; result: CancelOutcome };"spaces.setPower": { args: { spaceId: string; on: boolean }; result: SpacePowerReport };@@ -288,8 +302,25 @@ export interface HostOperations/** The one-time notice about the new network default was shown. */"network.ackNotice": { args: { spaceId: string }; result: null };/** Sets a Space's clipboard (`viewing`, `ask`, `off`) and/or Volume- * (`own`, `off`) setting. */- "spaces.setAccess": { args: { spaceId: string; clipboard?: string; volume?: string }; result: null };+ * (`own`, `off`) setting. `home` (CUA-2630): what the person approved for an agent home while it+ * runs, written to the cua home's `agent-home/grants.json` where this machine's daemon reads it (`mentions`: Spaces and machines @mentioned in a later request, which count as the grant)+ * (SwiftUI and Electron; the Tauri shell does not answer this operation). */+ "spaces.setAccess": { args: { spaceId: string; clipboard?: string; volume?: string; home?: { listAll?: boolean; machines?: string[]; mentions?: string[] } }; result: null };+ /** Every Space's place in its tree, and whether it may make children+ * (the SDK's `Spaces.list`: `parent`, `depth`, `children`). */+ "spaces.tree": { args: Record<string, never>; result: TreeNodeWire[] };+ /** Lets a Space make child Spaces of its own, or stops it+ * (`cua spaces children <space> on|off`). */+ "children.set": { args: { spaceId: string; enabled: boolean }; result: null };+ /** The budget of a Space's tree and what its children use+ * (`cua spaces budget <space>`). */+ "budget.get": { args: { spaceId: string }; result: TreeBudgetWire };+ /** Sets the budget of a Space's tree; unset limits take the defaults. */+ "budget.set": { args: { spaceId: string; limits: TreeBudgetLimitsWire }; result: TreeBudgetWire };+ /** The commands a Space keeps running (`cua spaces service ls`). */+ "services.list": { args: { spaceId: string }; result: ServiceWire[] };+ /** Starts, stops, restarts or removes one (`cua spaces service ...`). */+ "services.control": { args: { spaceId: string; name: string; action: "start" | "stop" | "restart" | "remove" }; result: null };/** Opens (or focuses) the Space's own desktop window, natively. `name`* and `os` title the window where the host wants them (Tauri). */"spaces.open": { args: { spaceId: string; name?: string; os?: SpaceOs }; result: null };@@ -392,6 +423,54 @@ export interface SpaceNetworkWire {volume: string;}+/** A Space's place in its tree (the SDK's `SpaceInfo`, camelCase). */+export interface TreeNodeWire {+ id: string;+ parent?: string | null;+ depth: number;+ /** It may make child Spaces of its own. */+ children: boolean;+ /** It is an agent's home (the Space made for ask-first, labelled `cua.home`): the agent it was made for.+ * Absent or null: it is not one. The host reads it from the Space's labels, so a home is found again on+ * a new device or after the app's storage is cleared. */+ home?: string | null;+}++/** A tree's limits (the SDK's `TreeBudgetLimits`, camelCase); unset: the default. */+export interface TreeBudgetLimitsWire {+ maxSpaces?: number | null;+ maxVcpus?: number | null;+ maxMemoryMb?: number | null;+ usdPerHour?: number | null;+ usdTotal?: number | null;+}++/** A tree's budget and use (the SDK's `TreeBudget`, camelCase). */+export interface TreeBudgetWire {+ root: string;+ set: TreeBudgetLimitsWire;+ maxSpaces: number;+ maxVcpus: number;+ maxMemoryMb: number;+ usdPerHour: number;+ usdTotal?: number | null;+ spaces: number;+ vcpus: number;+ memoryMb: number;+ usdPerHourUsed: number;+ usdSpent: number;+}++/** A kept command (the SDK's `SpaceServiceInfo`, camelCase). */+export interface ServiceWire {+ name: string;+ command: string;+ state: string;+ restarts: number;+ lastEnd: string;+ probeError: string;+}+/** One kind of blocked connection (the SDK's `NetworkEvent`, camelCase). */export interface NetworkEventWire {reason: string;@@ -417,6 +496,12 @@ export const OPERATIONS = ["network.log","network.ackNotice","spaces.setAccess",+ "spaces.tree",+ "children.set",+ "budget.get",+ "budget.set",+ "services.list",+ "services.control","spaces.open","machines.list","host.status",diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 72c7d2cb3c..8f1a984c31 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -71,6 +71,12 @@ export const WEBKIT_METHODS = ["network.log","network.ackNotice","spaces.setAccess",+ "spaces.tree",+ "children.set",+ "budget.get",+ "budget.set",+ "services.list",+ "services.control","spaces.cancelCreate","machines.list","host.status",@@ -400,6 +406,8 @@ export interface WkSettings {tips?: { off: boolean; done: string[] };/** `AppSettings.notchPinned`: the Spaces and desktops pinned to the notch, in pin order; absent: an older host. Saved with `settings.update`. */notchPinned?: string[];+ /** `AppSettings.agentMenu*`: which coding apps the agent menu shows; absent: an older host. Saved with `settings.update`. */+ agentMenu?: { shown: string[]; hidden: string[]; seen: string[] };/** Settings, Advanced's runtimes as the host read them (`runtimes::RuntimesInput`); absent: not read. */runtimes?: RuntimesInput | null;}diff --git a/apps/cua-spaces-web/src/components/ask-first/agent-picker.tsx b/apps/cua-spaces-web/src/components/ask-first/agent-picker.tsxnew file mode 100644index 0000000000..960f4968f3--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/agent-picker.tsx@@ -0,0 +1,376 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { CheckIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, PlusIcon } from "lucide-react";+import { useEffect, useRef, useState } from "react";++import type { AgentAccount, AgentGroup, AgentsView } from "@/bridge";+import { HarnessMark } from "@/components/agents/harness-mark";+import { Popover, PopoverDivider } from "@/components/ui/popover";+import { agentLine, type AgentSelection } from "@/lib/ask-first-model";+import { cn } from "@/lib/utils";++/** What the menu can do with the accounts of an app: the calls Home makes against the host. */+export interface AccountActions {+ /** Makes `account` the one the app runs with. */+ onUse(group: AgentGroup, account: AgentAccount): void;+ /** Takes `account` off the app. */+ onRemove(group: AgentGroup, account: AgentAccount): void;+ /** Gives `account` a name. */+ onRename(group: AgentGroup, account: AgentAccount, name: string): void;+ /** Adds another sign-in (a token or key, named) to the app; rejects with the host's words. */+ onAdd(group: AgentGroup, name: string, value: string): Promise<void>;+}++const same = (a: AgentAccount, b: AgentAccount) => a.env === b.env && (a.slot ?? null) === (b.slot ?? null);++/**+ * The agent menu of the ask box: the coding apps the person has connected+ * (Codex, Hermes, Claude Code and OpenCode first), each with its accounts as+ * rows to pick from. An app with no account has a Sign in row. The chevron on+ * an app's header opens that app's sign-ins in place: which is the default,+ * rename, remove and add. The model is a quiet line at the bottom, only for an+ * account that offers a choice. The chip shows the app and the account.+ */+export function AgentPicker({+ view,+ selected,+ onPick,+ onModel,+ onSignIn,+ onConfigure,+ accounts,+}: {+ view: AgentsView | null;+ selected: AgentSelection | null;+ onPick: (group: AgentGroup, account: AgentAccount) => void;+ onModel: (model: string) => void;+ /** Starts the sign-in of an app that has no account. */+ onSignIn: (group: AgentGroup) => void;+ /** Opens where the menu's apps are chosen (Settings, Connections). */+ onConfigure?: () => void;+ accounts: AccountActions;+}) {+ const [open, setOpen] = useState(false);+ const [page, setPage] = useState<{ kind: "manage"; app: string } | { kind: "model" } | null>(null);+ const focus = useRef<HTMLButtonElement>(null);+ const groups = view?.groups ?? [];+ useEffect(() => {+ if (!open) setPage(null);+ }, [open]);+ const manageGroup = page?.kind === "manage" ? groups.find((g) => g.app === page.app) : undefined;+ return (+ <Popover+ open={open}+ onOpenChange={setOpen}+ width={340}+ initialFocus={focus}+ popupProps={{ "data-agent-menu": "" } as never}+ trigger={+ <button+ type="button"+ data-picker="agent"+ className={cn(+ "flex h-9 max-w-[22rem] items-center gap-2 rounded-lg px-2.5 text-[13px] outline-none hover:bg-foreground/5 focus-visible:ring-2 focus-visible:ring-ring/60 data-popup-open:bg-foreground/[0.07]",+ !selected && "text-brand-strong",+ )}+ aria-label={selected ? `Agent: ${agentLine(selected)}, ${selected.account.line}` : "Sign in to an agent"}+ >+ {selected ? (+ <>+ <HarnessMark agent={selected.group.app} name={selected.group.label} plain />+ <span data-ask-agent="" className="truncate font-medium">+ {agentLine(selected)}+ </span>+ </>+ ) : (+ <span data-ask-agent="">Sign in to an agent</span>+ )}+ <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />+ </button>+ }+ >+ <button ref={focus} aria-hidden tabIndex={-1} className="sr-only" />+ {manageGroup ? (+ <ManagePage group={manageGroup} actions={accounts} onBack={() => setPage(null)} />+ ) : page?.kind === "model" && selected ? (+ <ModelPage+ selected={selected}+ onBack={() => setPage(null)}+ onPick={(m) => {+ onModel(m);+ setOpen(false);+ }}+ />+ ) : (+ <div role="listbox" aria-label="Agents" className="max-h-[420px] overflow-y-auto">+ {groups.map((g) => (+ <div key={g.app} data-agent-group={g.app} data-state={g.state} className="py-0.5">+ <div className="flex items-center gap-2 pr-1 pl-2.5">+ <HarnessMark agent={g.app} name={g.label} plain />+ <span className="min-w-0 flex-1 truncate py-1.5 text-[12px] font-medium text-muted-foreground">{g.label}</span>+ <button+ type="button"+ data-agent-manage={g.app}+ aria-label={`${g.label}: manage sign-ins`}+ onClick={() => setPage({ kind: "manage", app: g.app })}+ className="flex size-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <ChevronRightIcon className="size-3.5" />+ </button>+ </div>+ {g.accounts.length ? (+ g.accounts.map((a) => {+ const on = selected?.harness === g.harness && same(selected.account, a);+ return (+ <button+ type="button"+ role="option"+ aria-selected={on}+ key={`${a.env}/${a.slot ?? ""}`}+ data-agent-account={a.slot ?? a.env}+ onClick={() => {+ onPick(g, a);+ setOpen(false);+ }}+ className="flex w-full items-center gap-2 rounded-lg py-1.5 pr-2.5 pl-9 text-left text-[13px] outline-none hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <span className="min-w-0 flex-1 truncate">{a.line}</span>+ {on ? <CheckIcon className="size-3.5 shrink-0" /> : null}+ </button>+ );+ })+ ) : (+ <button+ type="button"+ data-agent-sign-in={g.app}+ onClick={() => {+ setOpen(false);+ onSignIn(g);+ }}+ className="flex w-full items-center rounded-lg py-1.5 pr-2.5 pl-9 text-left text-[13px] text-brand-strong outline-none hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ {g.signInLabel}+ </button>+ )}+ </div>+ ))}+ {selected && selected.account.models.length > 1 ? (+ <>+ <PopoverDivider />+ <button+ type="button"+ data-agent-model-row=""+ onClick={() => setPage({ kind: "model" })}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <span className="text-muted-foreground">Model</span>+ <span data-ask-model="" className="min-w-0 flex-1 truncate text-right">+ {selected.model.label}+ </span>+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />+ </button>+ </>+ ) : null}+ {onConfigure ? (+ <>+ {selected && selected.account.models.length > 1 ? null : <PopoverDivider />}+ <button+ type="button"+ data-agent-configure=""+ onClick={() => {+ setOpen(false);+ onConfigure();+ }}+ className="flex w-full items-center rounded-lg px-2.5 py-1.5 text-left text-[13px] text-muted-foreground outline-none hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ Configure agents+ </button>+ </>+ ) : null}+ </div>+ )}+ </Popover>+ );+}++function Back({ onBack, title }: { onBack: () => void; title: string }) {+ return (+ <div className="flex items-center gap-1 pb-1">+ <button type="button" data-agent-back="" aria-label="Back" onClick={onBack} className="flex size-7 items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60">+ <ChevronLeftIcon className="size-3.5" />+ </button>+ <span className="text-[13px] font-medium">{title}</span>+ </div>+ );+}++const small = "rounded-lg px-1.5 py-0.5 text-[12px] text-muted-foreground outline-none hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60";++/** An app's sign-ins: the default, rename, remove and add. */+function ManagePage({ group, actions, onBack }: { group: AgentGroup; actions: AccountActions; onBack: () => void }) {+ const [renaming, setRenaming] = useState<AgentAccount | null>(null);+ const [name, setName] = useState("");+ const [removing, setRemoving] = useState<AgentAccount | null>(null);+ const [adding, setAdding] = useState(false);+ const [newName, setNewName] = useState("");+ const [value, setValue] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const add = async () => {+ setBusy(true);+ setError(null);+ try {+ await actions.onAdd(group, newName.trim(), value.trim());+ setAdding(false);+ setNewName("");+ setValue("");+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(false);+ }+ };+ return (+ <div data-agent-manage-page={group.app}>+ <Back onBack={onBack} title={`${group.label} sign-ins`} />+ {group.accounts.length === 0 ? <p className="px-2.5 py-2 text-[13px] text-muted-foreground">No sign-in yet.</p> : null}+ {group.accounts.map((a) => (+ <div key={`${a.env}/${a.slot ?? ""}`} data-manage-account={a.slot ?? a.env} className="rounded-lg px-2.5 py-1.5">+ {renaming && same(renaming, a) ? (+ <input+ autoFocus+ value={name}+ aria-label="Name"+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && name.trim()) {+ actions.onRename(group, a, name.trim());+ setRenaming(null);+ } else if (e.key === "Escape") {+ e.stopPropagation();+ setRenaming(null);+ }+ }}+ className="w-full rounded-lg bg-foreground/[0.05] px-2.5 py-1.5 text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring/60"+ />+ ) : (+ <div className="flex items-center gap-2 text-[13px]">+ <span className="min-w-0 flex-1 truncate">{a.line}</span>+ {a.selected ? (+ <span data-manage-default="" className="text-[12px] text-muted-foreground">+ Default+ </span>+ ) : null}+ </div>+ )}+ {removing && same(removing, a) ? (+ <div className="mt-1 flex items-center gap-1 text-[12px]">+ <span className="text-muted-foreground">Remove this sign-in?</span>+ <button+ type="button"+ data-manage-confirm-remove=""+ onClick={() => {+ actions.onRemove(group, a);+ setRemoving(null);+ }}+ className={cn(small, "text-destructive hover:text-destructive")}+ >+ Remove+ </button>+ <button type="button" onClick={() => setRemoving(null)} className={small}>+ Cancel+ </button>+ </div>+ ) : (+ <div className="mt-0.5 flex items-center gap-1">+ {a.selected ? null : (+ <button type="button" data-manage-use="" onClick={() => actions.onUse(group, a)} className={small}>+ Make default+ </button>+ )}+ <button+ type="button"+ data-manage-rename=""+ onClick={() => {+ setRenaming(a);+ setName(a.line);+ }}+ className={small}+ >+ Rename+ </button>+ <button type="button" data-manage-remove="" onClick={() => setRemoving(a)} className={small}>+ Remove+ </button>+ </div>+ )}+ </div>+ ))}+ <PopoverDivider />+ {adding ? (+ <div data-manage-add-form="" className="flex flex-col gap-1.5 px-2.5 py-1.5">+ <input value={newName} maxLength={40} placeholder="Name (optional)" aria-label="Name" autoComplete="off" onChange={(e) => setNewName(e.target.value)} className="w-full rounded-lg bg-foreground/[0.05] px-2.5 py-1.5 text-[13px] outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60" />+ <input+ type="password"+ value={value}+ placeholder="Token or key"+ aria-label="Token or key"+ autoComplete="off"+ spellCheck={false}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && value.trim() && !busy) void add();+ }}+ className="w-full rounded-lg bg-foreground/[0.05] px-2.5 py-1.5 font-mono text-[13px] outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ />+ {error ? <p className="text-[12px] text-destructive">{error}</p> : null}+ <div className="flex items-center justify-end gap-1">+ <button type="button" onClick={() => setAdding(false)} className={small}>+ Cancel+ </button>+ <button type="button" data-manage-add-save="" disabled={busy || !value.trim()} onClick={() => void add()} className={cn(small, "text-foreground disabled:opacity-50")}>+ Add+ </button>+ </div>+ </div>+ ) : (+ <button+ type="button"+ data-manage-add=""+ onClick={() => setAdding(true)}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] text-muted-foreground outline-none hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <PlusIcon className="size-3.5" />+ Add a sign-in+ </button>+ )}+ </div>+ );+}++/** The models of the account in use. */+function ModelPage({ selected, onBack, onPick }: { selected: AgentSelection; onBack: () => void; onPick: (model: string) => void }) {+ return (+ <div data-agent-model-page="">+ <Back onBack={onBack} title="Model" />+ <div role="listbox" aria-label="Models" className="max-h-[320px] overflow-y-auto">+ {selected.account.models.map((m) => (+ <button+ type="button"+ role="option"+ aria-selected={m.id === selected.model.id}+ key={m.id}+ data-model-row={m.id}+ onClick={() => onPick(m.id)}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <span className="min-w-0 flex-1 truncate">{m.label}</span>+ {m.fast ? <span className="text-[11px] text-muted-foreground">Fast</span> : null}+ {m.id === selected.model.id ? <CheckIcon className="size-3.5 shrink-0" /> : null}+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/components/ask-first/agent-status.tsx b/apps/cua-spaces-web/src/components/ask-first/agent-status.tsxnew file mode 100644index 0000000000..f05f559712--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/agent-status.tsx@@ -0,0 +1,33 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { cn } from "@/lib/utils";++/** What the agent behind the box is doing: ready with its session open, starting, or needing a reconnect. */+export type AgentReadiness = "ready" | "starting" | "reconnect" | "none";++const WORDS: Record<Exclude<AgentReadiness, "none">, string> = {+ ready: "Agent ready",+ starting: "Starting agent",+ reconnect: "Reconnect needed",+};++/**+ * One quiet line under the box: "Agent ready" when the standby agent is up,+ * "Starting agent" while it starts, "Reconnect needed" with the way to fix it.+ * No badge and no animation: only the dot's colour changes.+ */+export function AgentStatus({ state, onReconnect }: { state: AgentReadiness; onReconnect?: () => void }) {+ if (state === "none") return null;+ return (+ <p data-agent-status={state} className="flex items-center gap-2 px-2 text-[12px] text-muted-foreground" role="status">+ <span className={cn("size-1.5 rounded-full", state === "ready" ? "bg-success" : state === "reconnect" ? "bg-warning" : "bg-muted-foreground/40")} aria-hidden />+ {WORDS[state]}+ {state === "reconnect" && onReconnect ? (+ <button type="button" onClick={onReconnect} className="text-foreground underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring/60">+ Reconnect+ </button>+ ) : null}+ </p>+ );+}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 dedfe9efea..b43c958c48 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@@ -2,16 +2,19 @@// Copyright (c) 2026 Cua AI, Inc.import { Menu as MenuPrimitive } from "@base-ui/react/menu";-import { ArrowUpIcon, CheckIcon, ChevronDownIcon, LaptopIcon, MonitorIcon } from "lucide-react";+import { ArrowUpIcon, CheckIcon, ChevronDownIcon, EllipsisIcon, LaptopIcon, MonitorIcon, SparklesIcon } from "lucide-react";import { useEffect, useRef, type ReactElement, type ReactNode } from "react";-import { firstMessage, useBridge, useSession, type Space, type SpaceOs } from "@/bridge";+import type { AgentAccount, AgentGroup, AgentsView, Space, 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 type { AgentSelection } from "@/lib/ask-first-model";+import type { AskRepo } from "@/lib/ask-first-repo";import { cn } from "@/lib/utils";-import { agentName, CLAUDE_CODE_URL, offeredAgents } from "./task-agents";+import { AgentPicker, type AccountActions } from "./agent-picker";+import { RepoChip } from "./repo-chip";export type { TaskWhere } from "@/lib/ask-first";@@ -21,6 +24,8 @@ const OS_WORD: Record<SpaceOs, string> = { linux: "Linux", macos: "Mac", windows/** Where it runs is a Space: "New Space", then quieter "Linux on This Mac". */export function whereSpaceLabel(where: TaskWhere): { title: string; detail: string | null } {+ if (where.kind === "agent") return { title: where.fresh ? "Agent decides, new Home" : "Agent decides", detail: null };+ if (where.kind === "machine") return { title: where.machine.name, detail: null };if (where.kind === "new") return { title: "New Space", detail: `${OS_WORD[where.os]} on This Mac` };return { title: where.kind === "this-mac" ? "This Mac" : where.space.name, detail: null };}@@ -36,6 +41,17 @@ export function AppMark({ agent, size = 32 }: { agent: string; size?: number })/** The trade-off, under the list. */export const WHERE_FOOTER = "A new computer keeps yours untouched. This Mac works on your own files and apps.";+/** With agent homes: what the footer adds (the agent can also be told in the text with @). */+export const WHERE_FOOTER_HOME = "You can also name a Space or computer in the text with @.";++/** A computer the person can name for the agent to use (agent homes). */+export interface NameableMachine {+ id: string;+ name: string;+ current: boolean;+ online: boolean;+}+function Picker({trigger,title,@@ -83,25 +99,34 @@ function PickerRow({ icon, title, note, selected, onSelect }: { icon: ReactNode;);}-const pickerButton = "flex h-12 items-center gap-2.5 rounded-lg px-3 text-[14px] outline-none hover:bg-foreground/5 data-popup-open:bg-foreground/[0.07]";+const whereButton = "flex h-9 items-center gap-2 rounded-lg px-2.5 text-[13px] outline-none hover:bg-foreground/5 focus-visible:ring-2 focus-visible:ring-ring/60 data-popup-open:bg-foreground/[0.07]";/**- * Home's box: the job in your own words, who does it and where it runs.- * Enter starts it (Shift+Enter for a new line).+ * Home's box, like the first prompt of a chat app: the job in your own words,+ * then one row under it with the agent (the app and its account), an optional repo and, without an agent home, where it runs.+ * Enter starts it (Shift+Enter for a new line). The model is a line in the agent menu.*/export function AskBox({text,onText,- agent,- onAgent,- installed,- mostUsed,+ view,+ selected,+ onPickAccount,+ onModel,+ onSignIn,+ onConfigure,+ accounts,+ repo,+ onRepo,where,onWhere,whereOpen,onWhereOpen,kinds,spaces,+ machines,+ agentHome,+ hasHome,busy,onSubmit,compact,@@ -109,12 +134,20 @@ export function AskBox({}: {text: string;onText: (t: string) => void;- /** 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: the only ones offered. */- installed: ReadonlySet<string>;- mostUsed: string | null;+ /** The coding apps and the accounts for each (`connectors.agents`); null before they are read. */+ view: AgentsView | null;+ /** The app, account and model it will use. */+ selected: AgentSelection | null;+ onPickAccount: (group: AgentGroup, account: AgentAccount) => void;+ onModel: (model: string) => void;+ /** Starts the sign-in of an app that has no account. */+ onSignIn: (group: AgentGroup) => void;+ /** Opens Settings, Connections, where the menu's apps are chosen. */+ onConfigure?: () => void;+ /** What the menu does with an app's accounts (default, rename, remove, add). */+ accounts: AccountActions;+ repo: AskRepo | null;+ onRepo?: (r: AskRepo | null) => void;where: TaskWhere;onWhere: (w: TaskWhere) => void;/** The Where picker held open (it reopens when "Use this Mac?" is declined). */@@ -124,6 +157,12 @@ export function AskBox({kinds: NewKind[];/** Running Spaces to use instead (never this Mac's own desktop: `pickableSpaces`). */spaces: Space[];+ /** With agent homes (Child Spaces on): the computers the person can name, this one first. */+ machines?: NameableMachine[];+ /** The job goes to the agent's Home Space, which makes the Spaces it needs: no where picker until a place is named. */+ agentHome?: boolean;+ /** The person already has a Home Space: the picker offers a fresh one. */+ hasHome?: boolean;busy: boolean;onSubmit: () => void;compact?: boolean;@@ -133,13 +172,12 @@ export function AskBox({useEffect(() => {if (autoFocus) ref.current?.focus();}, [autoFocus]);- 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 = 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);+ const ready = text.trim().length > 0 && !busy && selected !== null;+ const label = whereSpaceLabel(where);+ // With agent homes the agent decides where, so nothing about it shows until the person names a place: with @ in the+ // text, or by picking one (the "..." button then shows).+ const placed = where.kind !== "agent" || Boolean(where.fresh);+ const naming = placed || /(^|\s)@/.test(text);return (<div data-ask-box="" className="rounded-2xl border bg-card shadow-xs dark:bg-white/[0.03]"><textarea@@ -153,74 +191,74 @@ export function AskBox({}}}rows={compact ? 1 : 3}- aria-label="What do you want to do?"- placeholder="Describe the job in your own words, or paste a link to an issue or pull request"+ aria-label="What should it do?"+ placeholder="What should it do?"className={cn("block w-full resize-none bg-transparent px-5 pt-4 text-[16px] leading-relaxed outline-none placeholder:text-muted-foreground", compact ? "min-h-14" : "min-h-24")}/><div className="flex items-center gap-1 px-2 pt-1 pb-2">- <Picker- title="Who does it"- trigger={- <button type="button" className={pickerButton} data-picker="who">- <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}+ <AgentPicker view={view} selected={selected} onPick={onPickAccount} onModel={onModel} onSignIn={onSignIn} onConfigure={onConfigure} accounts={accounts} />+ <RepoChip repo={repo} onRepo={onRepo} />+ {placed && agentHome ? (+ <span data-ask-where="" className="max-w-64 truncate px-1.5 text-[13px] text-muted-foreground">+ in {label.title}+ </span>+ ) : null}+ {agentHome ? null : (+ <WherePicker+ where={where}+ onWhere={onWhere}+ open={whereOpen}+ onOpenChange={onWhereOpen}+ kinds={kinds}+ spaces={spaces}+ trigger={+ <button type="button" className={whereButton} data-picker="where">+ {where.kind === "new" ? (+ <OsIcon os={where.os} className="size-3.5" />+ ) : where.kind === "this-mac" ? (+ <LaptopIcon className="size-3.5" />+ ) : (+ <MonitorIcon className="size-3.5" />+ )}+ <span className="max-w-64 truncate" data-ask-where="">+ {label.title}+ {label.detail ? <span className="ml-1.5 text-muted-foreground">{label.detail}</span> : null}</span>- ) : (- <span>{agentName(agent)}</span>- )}- <ChevronDownIcon className="size-4 text-muted-foreground" />- </button>- }- 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."}- >- {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>- <WherePicker- where={where}- onWhere={onWhere}- open={whereOpen}- onOpenChange={onWhereOpen}- kinds={kinds}- spaces={spaces}- trigger={- <button type="button" className={pickerButton} data-picker="where">- {where.kind === "new" ? (- <OsIcon os={where.os} className="size-4 text-muted-foreground" />- ) : where.kind === "this-mac" ? (- <LaptopIcon className="size-4 text-muted-foreground" />- ) : (- <MonitorIcon className="size-4 text-muted-foreground" />- )}- <span className="max-w-80 truncate" data-ask-where="">- {whereSpaceLabel(where).title}- {whereSpaceLabel(where).detail ? <span className="ml-1.5 text-muted-foreground">{whereSpaceLabel(where).detail}</span> : null}- </span>- <ChevronDownIcon className="size-4 text-muted-foreground" />- </button>- }- />+ <ChevronDownIcon className="size-3.5 text-muted-foreground" />+ </button>+ }+ />+ )}<div className="flex-1" />+ {agentHome && naming ? (+ <WherePicker+ where={where}+ onWhere={onWhere}+ open={whereOpen}+ onOpenChange={onWhereOpen}+ kinds={kinds}+ spaces={spaces}+ machines={machines}+ agentHome+ hasHome={hasHome}+ trigger={+ <button+ type="button"+ data-picker="where"+ aria-label="Where it runs"+ className="flex size-9 items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 data-popup-open:bg-foreground/[0.07]"+ >+ <EllipsisIcon className="size-4" />+ </button>+ }+ />+ ) : null}<buttontype="button"disabled={!ready}onClick={onSubmit}aria-label="Start"- className={cn("flex size-12 items-center justify-center rounded-full transition-colors", ready ? "bg-primary text-primary-foreground hover:bg-primary/90" : "bg-foreground/10 text-muted-foreground")}+ className={cn("flex size-10 items-center justify-center rounded-full transition-colors", ready ? "bg-primary text-primary-foreground hover:bg-primary/90" : "bg-foreground/10 text-muted-foreground")}><ArrowUpIcon className="size-5" /></button>@@ -239,6 +277,9 @@ export function WherePicker({onWhere,kinds,spaces,+ machines,+ agentHome,+ hasHome,trigger,open,onOpenChange,@@ -247,12 +288,44 @@ export function WherePicker({onWhere: (w: TaskWhere) => void;kinds: NewKind[];spaces: Space[];+ /** With agent homes: the computers the person can name (other than this one, which has its own row). */+ machines?: NameableMachine[];+ /** Leads with "Let the agent decide". */+ agentHome?: boolean;+ /** The person already has a Home Space (the next request reuses it): offers a fresh one. */+ hasHome?: boolean;trigger: ReactElement;open?: boolean;onOpenChange?: (open: boolean) => void;}) {return (- <Picker title="Where it runs" trigger={trigger} footer={WHERE_FOOTER} open={open} onOpenChange={onOpenChange}>+ <Picker title="Where it runs" trigger={trigger} footer={agentHome ? `${WHERE_FOOTER} ${WHERE_FOOTER_HOME}` : WHERE_FOOTER} open={open} onOpenChange={onOpenChange}>+ {agentHome ? (+ <PickerRow+ icon={+ <span className="flex size-7 items-center justify-center rounded-lg bg-muted text-muted-foreground">+ <SparklesIcon className="size-4" />+ </span>+ }+ title="Let the agent decide"+ note="It picks what the job needs, within your budget"+ selected={where?.kind === "agent" && !where.fresh}+ onSelect={() => onWhere({ kind: "agent" })}+ />+ ) : null}+ {agentHome && hasHome ? (+ <PickerRow+ icon={+ <span className="flex size-7 items-center justify-center rounded-lg bg-muted text-muted-foreground">+ <SparklesIcon className="size-4" />+ </span>+ }+ title="Let the agent decide, in a new Home"+ note="Starts a fresh Home Space instead of reusing yours"+ selected={where?.kind === "agent" && Boolean(where.fresh)}+ onSelect={() => onWhere({ kind: "agent", fresh: true })}+ />+ ) : null}{kinds.map((k) => (<PickerRowkey={k.os}@@ -279,6 +352,26 @@ export function WherePicker({selected={where?.kind === "this-mac"}onSelect={() => onWhere({ kind: "this-mac" })}/>+ {agentHome && machines?.some((m) => !m.current) ? <p className="px-3 pt-3 pb-1 text-[12px] font-medium text-muted-foreground">Your computers</p> : null}+ {agentHome+ ? machines+ ?.filter((m) => !m.current)+ .slice(0, 5)+ .map((m) => (+ <PickerRow+ key={m.id}+ icon={+ <span className="flex size-7 items-center justify-center rounded-lg bg-muted text-muted-foreground">+ <LaptopIcon className="size-4" />+ </span>+ }+ title={m.name}+ note={m.online ? "Online" : "Off"}+ selected={where?.kind === "machine" && where.machine.id === m.id}+ onSelect={() => onWhere({ kind: "machine", machine: { id: m.id, name: m.name } })}+ />+ ))+ : null}{spaces.slice(0, 5).map((s) => (<PickerRowkey={s.id}diff --git a/apps/cua-spaces-web/src/components/ask-first/home.tsx b/apps/cua-spaces-web/src/components/ask-first/home.tsxindex 7f67c70335..676518e832 100644--- a/apps/cua-spaces-web/src/components/ask-first/home.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/home.tsx@@ -1,19 +1,29 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { useState } from "react";+import { useNavigate } from "@tanstack/react-router";+import { useMemo, useState } from "react";-import { useAgentChats, useSpaces, type AgentRunSummary } from "@/bridge";+import { agentsView, useAgentChats, useAgentKeys, useBridge, useMachines, useSpaces, type AgentAccount, type AgentGroup, type AgentRunSummary } from "@/bridge";+import { useChildren } from "@/components/children/use-children";import { CuaKey } from "@/components/cua-key";import { useAgentAttempts } from "@/hooks/use-agent-attempts";+import { useAgentMenu } from "@/hooks/use-agent-menu";+import { useConnectors } from "@/hooks/use-connectors";import { OsIcon } from "@/components/os-icon";-import { currentWhere, mostUsedAgent, SUGGESTIONS, useAskTasks, type AskTask, type TaskState } from "@/lib/ask-first";+import { currentWhere, SUGGESTIONS, useAskTasks, type AskTask, type TaskState } from "@/lib/ask-first";+import { pickAccount, pickOf, rememberAgent, resolveAgent, usePickedAgent } from "@/lib/ask-first-model";+import { reusableHome } from "@/lib/agent-home/home-space";+import { useRepos } from "@/lib/ask-first-repo";import { useListedSpaces } from "@/components/spaces/listed";import { cn } from "@/lib/utils";import { AskBox, type TaskWhere } from "./ask-box";-import { agentName, chooseAgent } from "./task-agents";-import { useInstalledAgents } from "./use-installed-agents";+import { agentName } from "./task-agents";+import { AgentStatus } from "./agent-status";+import type { AccountActions } from "./agent-picker";+import { useAgentReadiness } from "./use-agent-readiness";+import { useKeepHomeWarm } from "./use-keep-home-warm";import { YourAgents, YourSpaces as YourSpacesRow } from "./home-sections";import { useWherePick } from "./this-mac-confirm";import { useStartTask } from "./use-start-task";@@ -22,8 +32,6 @@ 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;@@ -50,25 +58,54 @@ export function AskFirstHome() {const listed = useListedSpaces(spaces);const { kinds, spaces: pickable } = useWhereOptions();const { start } = useStartTask();- // 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 { core } = useBridge();+ // The agent: the last app, account and model picked while they are still there, else the first connected app. The+ // account is the app's own choice (kept by the host), so a run uses the one shown.+ const connectors = useConnectors();+ const keys = useAgentKeys();+ // Which apps the menu lists is the person's choice (Settings, Connections); an app they connect shows again.+ const menu = useAgentMenu(connectors);+ const navigate = useNavigate();+ const agents = useMemo(() => (core ? agentsView(core, connectors.input, menu.prefs) : null), [core, connectors.input, menu.prefs]);+ const picked = usePickedAgent();+ const selected = resolveAgent(agents, picked);+ const { current: repo } = useRepos();const [text, setText] = useState("");- const [agent, setAgent] = useState<string | null>(null);- const chosenAgent = chooseAgent(agent, mostUsed, installed);+ // With Child Spaces on (and this Home, the Ask first experiment), the job goes to the agent's Home Space, which+ // makes the Spaces it needs on your computers when asked in plain words.+ const children = useChildren();+ const agentHome = Boolean(children);+ const chosenAgent = selected?.harness ?? "claude-code";+ const { data: machineRows } = useMachines();+ const machines = useMemo(() => (machineRows ?? []).map((m) => ({ id: m.id, name: m.name, current: m.current, online: m.online })), [machineRows]);+ useKeepHomeWarm(chosenAgent, agentHome);+ const readiness = useAgentReadiness(chosenAgent, agentHome, agents, selected);// 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);+ const [pickedWhere, 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(chosenAgent ? agentName(chosenAgent) : "Your agent");- const where = currentWhere(picked, kinds, pickable);+ const pick = useWherePick(agentName(chosenAgent));+ const where = currentWhere(pickedWhere ?? (agentHome ? { kind: "agent" } : null), kinds, pickable);const submit = (prompt = text, w = where) => {- if (!prompt.trim() || !chosenAgent) return;- start({ prompt, agent: chosenAgent, where: w });+ if (!prompt.trim() || !selected) return;+ // The run uses the app's own choice of account: make it the one shown.+ if (!selected.account.selected) void connectors.useCredential(selected.group.app, { env: selected.account.env, slot: selected.account.slot });+ start({ prompt, agent: chosenAgent, where: w, model: selected.model.id, repo });setText("");};+ const useAccount = (group: AgentGroup, account: AgentAccount) => {+ rememberAgent(pickAccount(group, account, picked));+ if (!account.selected) void connectors.useCredential(group.app, { env: account.env, slot: account.slot });+ };+ const accountActions: AccountActions = {+ onUse: useAccount,+ onRemove: (_g, a) => void (a.slot ? keys.remove(a.env, { slot: a.slot }) : keys.remove(a.env, { keepOthers: true })).catch(() => {}),+ onRename: (_g, a, name) => void keys.rename(a.env, a.slot, name).catch(() => {}),+ // Another sign-in or key beside the others: Claude Code's takes a token, the others the key of their provider.+ onAdd: (g, name, value) => keys.save(g.accounts[0]?.provider ?? (g.app === "claude-code" ? "anthropic" : g.app === "codex" ? "openai" : "anthropic"), value, null, {}, { add: true, ...(name ? { label: name } : {}) }),+ };// Home lists agents and Spaces, not tasks: with neither (a first run,// or tasks whose Spaces are gone), Home is the welcome again.@@ -86,34 +123,43 @@ export function AskFirstHome() {<AskBoxtext={text}onText={setText}- agent={chosenAgent}- onAgent={setAgent}- installed={installed}- mostUsed={mostUsed}+ view={agents}+ selected={selected}+ onPickAccount={useAccount}+ onModel={(model) => selected && rememberAgent({ ...pickOf(selected), model })}+ onSignIn={(g) => void connectors.connectApp(g.app)}+ onConfigure={() => void navigate({ to: "/settings/connections" })}+ accounts={accountActions}+ repo={repo}where={where}onWhere={(w) => pick.choose(w, setWhere, () => setWhereOpen(true))}whereOpen={whereOpen}onWhereOpen={setWhereOpen}kinds={kinds}spaces={pickable}+ machines={machines}+ agentHome={agentHome}+ hasHome={agentHome && reusableHome(chosenAgent, spaces, false, children?.homesOf(chosenAgent)) !== null}busy={false}onSubmit={() => submit()}compact={!first}autoFocus/>+ <AgentStatus state={agentHome ? readiness : "none"} onReconnect={() => selected && void connectors.connectApp(selected.group.app)} />{/* Preparing is silent: only a failed prepare says so, with Try again. */}<PrepareLine view={prep.view} onRetry={onPrepareAction} />{first ? (<><div className="grid gap-4 sm:grid-cols-3">- {SUGGESTIONS.filter((s) => kinds.some((k) => k.os === s.os) || s.os === "linux").map((s) => (+ {SUGGESTIONS.filter((s) => agentHome || kinds.some((k) => k.os === s.os) || s.os === "linux").map((s) => (<buttontype="button"key={s.title}data-home-card=""onClick={() => {setText(s.prompt);- setWhere({ kind: "new", os: kinds.some((k) => k.os === s.os) ? s.os : "linux" });+ // Without an agent home the suggestion's kind of computer is made for it.+ if (!agentHome) setWhere({ kind: "new", os: kinds.some((k) => k.os === s.os) ? s.os : "linux" });}}className="flex flex-col gap-2 rounded-xl border bg-card/60 px-5 py-4 text-left transition-colors hover:bg-accent dark:bg-white/[0.02]">@@ -124,7 +170,10 @@ export function AskFirstHome() {))}</div><p className="flex items-center gap-3 text-[13px] text-muted-foreground">- <CuaKey size={24} />A fresh computer does the work, so yours stays untouched. Watch it live, step in any time, and throw it away when you're done.+ <CuaKey size={24} />+ {agentHome+ ? "The agent works in Spaces of its own, so your computer stays untouched. Watch it live, step in any time, and throw them away when you're done."+ : "A fresh computer does the work, so yours stays untouched. Watch it live, step in any time, and throw it away when you're done."}</p></>) : null}diff --git a/apps/cua-spaces-web/src/components/ask-first/repo-chip.tsx b/apps/cua-spaces-web/src/components/ask-first/repo-chip.tsxnew file mode 100644index 0000000000..f8e8050739--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/repo-chip.tsx@@ -0,0 +1,112 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { GitBranchIcon, XIcon } from "lucide-react";+import { useRef, useState } from "react";++import { Popover } from "@/components/ui/popover";+import { chooseRepo, clearRepo, parseRepo, useRepos, type AskRepo } from "@/lib/ask-first-repo";+import { cn } from "@/lib/utils";++/**+ * The optional repo of the task: an empty "Add a repo" that opens a field+ * for a link or `owner/name` and the repos used lately, then the repo as a+ * chip with a way to take it off.+ */+export function RepoChip({ repo, onRepo }: { repo: AskRepo | null; onRepo?: (r: AskRepo | null) => void }) {+ const { recent } = useRepos();+ const [open, setOpen] = useState(false);+ const [text, setText] = useState("");+ const [bad, setBad] = useState(false);+ const field = useRef<HTMLInputElement>(null);+ const take = (r: AskRepo) => {+ chooseRepo(r);+ onRepo?.(r);+ setOpen(false);+ setText("");+ setBad(false);+ };+ const submit = () => {+ const r = parseRepo(text);+ if (!r) {+ setBad(true);+ return;+ }+ take(r);+ };+ if (repo) {+ return (+ <span data-ask-repo={repo.label} className="flex h-9 items-center gap-1.5 rounded-lg bg-foreground/[0.06] pr-1 pl-2.5 text-[13px]">+ <GitBranchIcon className="size-3.5 text-muted-foreground" />+ <span className="max-w-56 truncate font-medium">{repo.label}</span>+ <button+ type="button"+ aria-label={`Remove ${repo.label}`}+ data-ask-repo-remove=""+ onClick={() => {+ clearRepo();+ onRepo?.(null);+ }}+ className="flex size-6 items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <XIcon className="size-3.5" />+ </button>+ </span>+ );+ }+ return (+ <Popover+ open={open}+ onOpenChange={setOpen}+ width={340}+ initialFocus={field}+ trigger={+ <button+ type="button"+ data-picker="repo"+ className="flex h-9 items-center gap-2 rounded-lg px-2.5 text-[13px] text-muted-foreground outline-none hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 data-popup-open:bg-foreground/[0.07]"+ >+ <GitBranchIcon className="size-3.5" />+ Add a repo+ </button>+ }+ >+ <input+ ref={field}+ value={text}+ onChange={(e) => {+ setText(e.target.value);+ setBad(false);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ submit();+ }+ }}+ placeholder="Paste a link, or owner/name"+ aria-label="Repo link or owner/name"+ aria-invalid={bad}+ className={cn("w-full rounded-lg bg-foreground/[0.05] px-2.5 py-2 text-[13px] outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60", bad && "ring-2 ring-destructive/50")}+ />+ {bad ? <p className="px-2.5 pt-1.5 text-[12px] text-destructive">That is not a repo link. Try https://github.com/owner/name or owner/name.</p> : null}+ {recent.length ? (+ <div className="mt-1 pt-1">+ <p className="px-2.5 pt-1 pb-0.5 text-[12px] font-medium text-muted-foreground">Recent</p>+ {recent.map((r) => (+ <button+ type="button"+ key={r.url}+ data-repo-recent={r.label}+ onClick={() => take(r)}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <GitBranchIcon className="size-3.5 text-muted-foreground" />+ <span className="truncate">{r.label}</span>+ </button>+ ))}+ </div>+ ) : null}+ </Popover>+ );+}diff --git a/apps/cua-spaces-web/src/components/ask-first/use-agent-readiness.ts b/apps/cua-spaces-web/src/components/ask-first/use-agent-readiness.tsnew file mode 100644index 0000000000..750df118c1--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/use-agent-readiness.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useEffect, useState } from "react";++import { threadOpAvailable, useBridge, useSpaces, type AgentMember, type AgentsView } from "@/bridge";+import { useChildren } from "@/components/children/use-children";+import { reusableHome } from "@/lib/agent-home/home-space";+import type { AgentSelection } from "@/lib/ask-first-model";++import type { AgentReadiness } from "./agent-status";++/** How often the member's state is read while Home is open. */+export const READINESS_POLL_MS = 2_500;++/**+ * Whether the agent behind the box is ready: its home has the member for the+ * app the model runs on, kept on standby with its session open (`idle`),+ * still starting (`asleep` or `working` before it has been ready), or a+ * provider's sign-in ran out and nothing connected is left to pick.+ */+export function readinessOf(member: Pick<AgentMember, "status"> | undefined, view: AgentsView | null, selected: AgentSelection | null): AgentReadiness {+ if (!selected) return view?.groups.some((g) => g.state === "needs-reconnect") ? "reconnect" : "none";+ if (!member) return "none";+ if (member.status === "failed") return "reconnect";+ return member.status === "idle" || member.status === "working" || member.status === "waiting" ? "ready" : "starting";+}++export function useAgentReadiness(agent: string, enabled: boolean, view: AgentsView | null, selected: AgentSelection | null): AgentReadiness {+ const { data } = useBridge();+ const { data: spaces } = useSpaces();+ const children = useChildren();+ const home = enabled ? reusableHome(agent, spaces, false, children?.homesOf(agent)) : null;+ const [member, setMember] = useState<Pick<AgentMember, "status"> | undefined>(undefined);+ useEffect(() => {+ setMember(undefined);+ if (!home || !data || !threadOpAvailable(data.mode, "thread.members")) return;+ let live = true;+ const read = () =>+ void data+ .call("thread.members", { spaceId: home })+ .then((r) => {+ if (live) setMember(r.members.find((m) => m.harness === agent));+ })+ .catch(() => {});+ read();+ const t = setInterval(read, READINESS_POLL_MS);+ return () => {+ live = false;+ clearInterval(t);+ };+ }, [home, data, agent]);+ return readinessOf(member, view, selected);+}diff --git a/apps/cua-spaces-web/src/components/ask-first/use-keep-home-warm.ts b/apps/cua-spaces-web/src/components/ask-first/use-keep-home-warm.tsnew file mode 100644index 0000000000..a6e473e69a--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/use-keep-home-warm.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useEffect, useRef } from "react";++import { useSpaces } from "@/bridge";+import { useChildren } from "@/components/children/use-children";+import { reusableHome } from "@/lib/agent-home/home-space";++/**+ * Keeps the agent's home warm while Home is open: a home that was turned off+ * (suspended or stopped) is turned back on in the background, so the first+ * request after opening the app finds a running Space and does not wait for a+ * boot. Once per Space per page load; a home that is not there is not made+ * (that is the first request's job), and nothing is stopped by this: a home+ * stays on until the person turns it off.+ */+export function useKeepHomeWarm(agent: string, enabled: boolean): void {+ const { data: spaces, startSpace } = useSpaces();+ const children = useChildren();+ const asked = useRef(new Set<string>());+ const labelled = children?.homesOf(agent);+ useEffect(() => {+ if (!enabled) return;+ const id = reusableHome(agent, spaces, false, labelled);+ const row = id ? spaces?.find((s) => s.id === id) : undefined;+ if (!id || !row || row.status !== "suspended" || asked.current.has(id)) return;+ asked.current.add(id);+ Promise.resolve(startSpace(id)).catch(() => asked.current.delete(id));+ }, [agent, enabled, spaces, labelled, startSpace]);+}diff --git a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts b/apps/cua-spaces-web/src/components/ask-first/use-start-task.tsindex 9f4e2cc21a..2048d9e731 100644--- a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts+++ b/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts@@ -3,13 +3,36 @@import { useNavigate, useRouter } from "@tanstack/react-router";-import { firstMessage, newPendingId, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useSpaces, type HostStatus } from "@/bridge";+import { firstMessage, newPendingId, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useMachines, useSpaces, type HostStatus } from "@/bridge";+import type { SpaceCreateConfig } from "@/bridge/contracts/host";+import { useChildren } from "@/components/children/use-children";import { useSummonIn } from "@/components/ask-first/use-summon-in";import { enqueue, flushQueue, resolveQueue } from "@/components/space-thread/queued";import { useConnectors } from "@/hooks/use-connectors";+import { containerHome } from "@/lib/agent-home/container";+import { grantsFor, homeGrantsArg, homeMentionsArg } from "@/lib/agent-home/grants";+import { rememberHome, reusableHome } from "@/lib/agent-home/home-space";+import { parseMentions } from "@/lib/agent-home/mentions";+import { homeBrief, homePrompt } from "@/lib/agent-home/prompt";+import type { AskRepo } from "@/lib/ask-first-repo";import { getDriver } from "@/lib/prepare/store";import { addAskTask, askTask, HOST_NOT_SHARED, hostSpaceId, postToSpaceThread, retryTarget, taskTarget, updateAskTask, whereOs, type AskTask, type TaskTarget, type TaskWhere } from "@/lib/ask-first";+/** The home's name: short, and readable in the Spaces list. */+export const homeName = (prompt: string, now = Date.now()) => {+ const slug = prompt+ .toLowerCase()+ .replace(/https?:\/\/\S+/g, " ")+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 24)+ .replace(/-+$/g, "");+ return `home-${slug || "task"}-${now.toString(36).slice(-3)}`;+};++/** The job as the agent is told it: the repo the person picked is a line of it, said once in plain words. */+export const withRepo = (prompt: string, repo?: { url: string } | null) => (repo ? `${prompt.trim()}\n\nRepo: ${repo.url}` : prompt);+/** Task and Space pairs whose thread already has the task's job. */const posted = new Set<string>();@@ -20,14 +43,22 @@ const posted = new Set<string>();* host service shares it as (`hostSpaceId`). A failure is kept on the task and shown in its* thread, which offers Try again (`retry`) and Change computer* (`retry(task, where)`).+ *+ * With Child Spaces on and the agent left to decide (or a computer named), the+ * Space is the agent's home (CUA-2630): the slim Linux image, made on the first+ * request and reused by the next ones (one per agent unless the person asks for+ * a fresh one), its spawn capability on. The agent decides where the work runs,+ * unless the person said where, and the Spaces it makes appear under the home.*/export function useStartTask(): {- start: (job: { prompt: string; agent: string; where: TaskWhere }) => void;+ start: (job: { prompt: string; agent: string; where: TaskWhere; model?: string; repo?: AskRepo | null }) => void;retry: (task: AskTask, where?: TaskWhere) => void;} {const navigate = useNavigate();const router = useRouter();- const { createSpace } = useSpaces();+ const { data: spaces, createSpace } = useSpaces();+ const { data: machines } = useMachines();+ const children = useChildren();const { data: host } = useBridge();const { startRun } = useAgents();const { offers } = useFirstSpaceOffers();@@ -39,35 +70,101 @@ export function useStartTask(): {const { summonInput, send, summonIn, canSummon } = useSummonIn();- const run = (id: string, target: TaskTarget, place?: { pendingId?: string; queued?: boolean; onCreated?: (spaceId: string) => void }) =>+ /** What the person named in the job: @mentions, "on my Mac", and the picked place (agent homes). */+ const named = (prompt: string, where?: TaskWhere) => {+ const mentions = parseMentions(prompt, {+ spaces: (spaces ?? []).map((s) => ({ id: s.id, name: s.name })),+ machines: (machines ?? []).map((m) => ({ id: m.id, name: m.name, current: m.current })),+ });+ if (where?.kind === "space" && !mentions.spaces.some((s) => s.id === where.space.id)) mentions.spaces.push({ id: where.space.id, name: where.space.name });+ if (where?.kind === "machine" && !mentions.machines.some((m) => m.id === where.machine.id)) mentions.machines.push({ id: where.machine.id, name: where.machine.name });+ return mentions;+ };++ /** What a home is made with and briefed with: the agent, what it already holds and what the person named. */+ const setupFor = (agent: string, prompt: string, where?: TaskWhere) => ({ agent, grants: grantsFor(agent), mentions: named(prompt, where) });++ /** Posts the job to the agent's home: what the person named now is the grant, then the message goes to the agent through the thread. */+ const reuseHome = async (spaceId: string, agent: string, prompt: string, model?: string, brief?: string): Promise<"posted" | "needs-run"> => {+ // An @mention of a Space or a computer, or "on my Mac", is the approval, so no card asks. It goes to the grants+ // file the daemon reads each time the home asks (no restart).+ const mentions = named(prompt);+ const g = grantsFor(agent);+ if ((mentions.machines.length || mentions.spaces.length) && host) {+ const names = new Map((machines ?? []).map((m) => [m.id, m.name] as const));+ const merged = { listAll: g.listAll, machines: [...new Set([...g.machines, ...mentions.machines.map((m) => m.id)])] };+ await host.call("spaces.setAccess", { spaceId, home: { ...homeGrantsArg(merged, names), mentions: homeMentionsArg(mentions) } }).catch(() => null);+ }+ // The home's agent is a member of the Space, kept on standby with the picked model.+ if (await summonIn(spaceId, agent, prompt, model, true, brief)) return "posted";+ return "needs-run";+ };++ const run = (id: string, target: TaskTarget, place?: { pendingId?: string; queued?: boolean; reuse?: string; onCreated?: (spaceId: string) => void }) =>void (async () => {try {let spaceId = target.kind === "space" ? target.spaceId : null;+ const task0 = askTask(id);+ const isHome = Boolean(task0?.home && children);if (target.kind === "host") {const status = (await host?.call("host.status", {} as never).catch(() => null)) as HostStatus | null;spaceId = hostSpaceId(status);if (!spaceId) throw new Error(HOST_NOT_SHARED);updateAskTask(id, { spaceId, onHost: true });}+ // The agent's home is made on the first request and reused by the next ones.+ if (!spaceId && isHome && place?.reuse) {+ spaceId = place.reuse;+ updateAskTask(id, { spaceId, pendingId: null });+ }if (!spaceId) {const os = target.kind === "create" ? target.os : "linux";const pendingId = place?.pendingId ?? newPendingId();updateAskTask(id, { pendingId });- const offer = offers.find((o) => o.os === os);- const space = await createSpace(offer ? { ...offer.args, os } : { os }, pendingId);+ let space;+ if (isHome && children) {+ // The agent home: a slim Linux Space, the root of this person's tree (the agent decides where the work runs).+ const agent = task0?.agent ?? "";+ const config: SpaceCreateConfig = containerHome.create(setupFor(agent, task0?.prompt ?? ""), homeName(task0?.prompt ?? ""));+ space = await createSpace({ ...config, os: "linux" }, pendingId);+ // The spawn capability, whatever the host did with `children` in the config.+ children.setChildrenOn(space.id, true);+ rememberHome(agent, space.id);+ } else {+ const offer = offers.find((o) => o.os === os);+ space = await createSpace(offer ? { ...offer.args, os } : { os }, pendingId);+ }spaceId = space.id;updateAskTask(id, { spaceId, pendingId: null });place?.onCreated?.(spaceId);if (place?.queued) {// The job (and anything typed meanwhile) waited in the Space's thread: send it now.resolveQueue(pendingId, spaceId);+ // The picked model goes with the agent when it joins (adding it before the first message names it).+ const t = askTask(id);+ if (t?.model && host && canSummon()) {+ const first = firstMessage(core, await summonInput(spaceId), t.agent, "");+ if (first?.handle) await host.call("thread.agentAdd", { spaceId, name: first.handle, harness: first.harness || t.agent, model: t.model }).catch(() => null);+ }await flushQueue(pendingId, send(spaceId, await summonInput(spaceId)));updateAskTask(id, { inSpace: true });return;}}- const prompt = askTask(id)?.prompt ?? "";- if (place && (await summonIn(spaceId, askTask(id)?.agent ?? "", prompt))) {+ const task = askTask(id);+ const prompt = withRepo(task?.prompt ?? "", task?.repo);+ const agent = task?.agent ?? "";+ let homeText: string | null = null;+ if (isHome) {+ homeText = homePrompt(task?.prompt ?? "", setupFor(agent, task?.prompt ?? ""), containerHome.abilities(), task?.repo ?? undefined);+ // A home takes the job through its member (a new one too): the chosen repo is a line of the message.+ const brief = homeBrief(setupFor(agent, task?.prompt ?? ""), containerHome.abilities());+ if ((await reuseHome(spaceId, agent, prompt, task?.model, brief)) === "posted") {+ updateAskTask(id, { inSpace: true });+ return;+ }+ }+ if (!isHome && place && (await summonIn(spaceId, agent, prompt, task?.model))) {updateAskTask(id, { inSpace: true });return;}@@ -77,29 +174,43 @@ export function useStartTask(): {posted.add(`${id}\u0000${spaceId}`);await postToSpaceThread(host, spaceId, prompt);}- const started = await startRun({ spaceId, agent: askTask(id)?.agent ?? "", prompt });- updateAskTask(id, { runId: started.run_id });+ const started = await startRun({ spaceId, agent, prompt: homeText ?? prompt, ...(task?.model ? { model: task.model } : {}) });+ updateAskTask(id, { runId: started.run_id, inSpace: true });} catch (e) {updateAskTask(id, { error: e instanceof Error ? e.message : String(e), pendingId: null });}})();return {- start: ({ prompt, agent, where }) => {+ start: ({ prompt, agent, where, model, repo }) => {const target = taskTarget(where);+ // With Child Spaces on, the agent decides (or is told a computer): its home Space takes the request.+ const home = Boolean(children) && (where.kind === "agent" || where.kind === "machine");+ const fresh = where.kind === "agent" && Boolean(where.fresh);+ const mentions = named(prompt, where);+ const reuse = home ? reusableHome(agent, spaces, fresh, children?.homesOf(agent)) : null;// The new setup (Labs) made a Linux Space for this agent while the person was in the first run: the job is// kept by the preparing driver, which sends it exactly once when the agent is ready, even across a quit.const preparing = getDriver();const prep = preparing?.state;- if (preparing && prep?.wanted && prep.harness === agent && target.kind === "create" && target.os === "linux") {+ if (!home && preparing && prep?.wanted && prep.harness === agent && target.kind === "create" && target.os === "linux") {const spaceId = prep.homeSpaceId;- const task = addAskTask({ prompt: prompt.trim(), agent, os: "linux", spaceId, pendingId: spaceId ? null : prep.pendingId, onHost: false });+ const task = addAskTask({ prompt: prompt.trim(), agent, os: "linux", spaceId, pendingId: spaceId ? null : prep.pendingId, onHost: false, ...(model ? { model } : {}), ...(repo ? { repo } : {}) });record("ask_first_task_started");- preparing.send({ id: task.id, text: prompt.trim(), agent });+ preparing.send({ id: task.id, text: withRepo(prompt, repo), agent, model: model ?? null, repo: repo?.url ?? null });void navigate({ to: "/spaces/$spaceId", params: { spaceId: spaceId ?? prep.pendingId! } });return;}- const task = addAskTask({ prompt: prompt.trim(), agent, os: whereOs(where), spaceId: target.kind === "space" ? target.spaceId : null, onHost: target.kind === "host" });+ const task = addAskTask({+ prompt: prompt.trim(),+ agent,+ os: whereOs(where),+ spaceId: target.kind === "space" ? target.spaceId : null,+ onHost: target.kind === "host",+ ...(home ? { home, named: [...mentions.spaces.map((s) => s.name), ...mentions.machines.map((m) => m.name)] } : {}),+ ...(model ? { model } : {}),+ ...(repo ? { repo } : {}),+ });record("ask_first_task_started");// Straight to the Space: the one picked or the one being made (its page follows the create); this Mac opens the task's page.const go = (spaceId: string) => void navigate({ to: "/spaces/$spaceId", params: { spaceId } });@@ -107,13 +218,18 @@ export function useStartTask(): {run(task.id, target, {});go(target.spaceId);} else if (target.kind === "create") {+ if (reuse) {+ run(task.id, target, { reuse });+ go(reuse);+ return;+ }const pendingId = newPendingId();// Still on the row being made when it's done (a create quicker than the page): its Space's own page.const onCreated = (spaceId: string) => {if (decodeURIComponent(router.state.location.pathname) === `/spaces/${pendingId}`) void navigate({ to: "/spaces/$spaceId", params: { spaceId }, replace: true });};- // The job shows in the Space's thread at once, queued until the Space is ready.- const first = canSummon() ? firstMessage(core, { members: [], people: [], canAdd: true, connectors }, agent, prompt) : null;+ // The job shows in the Space's thread at once, queued until the Space is ready (a home gets it with its briefing instead).+ const first = !home && canSummon() ? firstMessage(core, { members: [], people: [], canAdd: true, connectors }, agent, withRepo(prompt, repo)) : null;if (first?.handle) enqueue(pendingId, first.text);run(task.id, target, { pendingId, onCreated, queued: Boolean(first?.handle) });go(pendingId);diff --git a/apps/cua-spaces-web/src/components/children/use-children.ts b/apps/cua-spaces-web/src/components/children/use-children.tsnew file mode 100644index 0000000000..c9035f9223--- /dev/null+++ b/apps/cua-spaces-web/src/components/children/use-children.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Child Spaces from the host's store, whether the experiment is on, and+// which Space's Children sheet is open.++import { useSyncExternalStore } from "react";++import { useBridge } from "@/bridge";+import type { ChildrenPreview } from "@/bridge/contracts/children";+import { useExperiments } from "@/bridge/settings-hooks";++const noop = () => () => {};++/** The host's store while the Child Spaces experiment is on, re-rendering+ * on every change; null otherwise (and on a host without it). */+export function useChildren(): ChildrenPreview | null {+ const { data } = useBridge();+ const on = useExperiments().data?.experiments.childSpaces === true;+ const store = on ? (data?.children ?? null) : null;+ useSyncExternalStore(store ? store.subscribe : noop, () => store?.version() ?? 0, () => 0);+ return store;+}++let openFor: string | null = null;+const listeners = new Set<() => void>();+const set = (id: string | null) => {+ openFor = id;+ for (const l of listeners) l();+};++/** Opens a Space's Children sheet (from its Children row). */+export const openChildrenSheet = (spaceId: string) => set(spaceId);+export const closeChildrenSheet = () => set(null);++export function useChildrenSheetFor(): string | null {+ return useSyncExternalStore(+ (l) => {+ listeners.add(l);+ return () => listeners.delete(l);+ },+ () => openFor,+ () => null,+ );+}diff --git a/apps/cua-spaces-web/src/components/settings/connections/agent-menu-group.tsx b/apps/cua-spaces-web/src/components/settings/connections/agent-menu-group.tsxnew file mode 100644index 0000000000..a135f2c5d0--- /dev/null+++ b/apps/cua-spaces-web/src/components/settings/connections/agent-menu-group.tsx@@ -0,0 +1,54 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useState } from "react";++import { HarnessMark } from "@/components/agents/harness-mark";+import { SettingsGroup } from "@/components/settings-group";+import { GroupedRow } from "@/components/ui/grouped";+import { Switch } from "@/components/ui/switch";+import { toastError } from "@/components/ui/toast";+import { useAgentMenu } from "@/hooks/use-agent-menu";+import type { Connectors } from "@/hooks/use-connectors";++/**+ * Settings, Connections, Agent menu: one switch per coding app for whether+ * Home's agent menu lists it. A hidden app keeps its sign-ins and stays on the+ * Agents page and available by name. The last app shown cannot be hidden, and+ * the group says so. Every word and rule is the core's (`agentMenu.view`).+ */+export function AgentMenuGroup({ c }: { c: Connectors }) {+ const { view, choose } = useAgentMenu(c);+ const [refused, setRefused] = useState<string | null>(null);+ if (!view) return null;+ const note = refused ?? view.lastNote;+ const flip = (app: string, on: boolean) => {+ setRefused(null);+ void choose(app, on)+ .then((no) => setRefused(no))+ .catch(toastError("Couldn't change the agent menu"));+ };+ return (+ <SettingsGroup+ title={view.title}+ data-agent-menu-group=""+ footer={+ <span data-agent-menu-note={note ? "" : undefined}>+ {view.help}+ {note ? <> {note}</> : null}+ </span>+ }+ >+ {view.rows.map((r) => (+ <GroupedRow key={r.app} data-agent-menu-row={r.app} data-shown={r.shown}>+ <HarnessMark agent={r.app} name={r.label} />+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13px]">{r.label}</div>+ <p className="mt-px truncate text-xs text-muted-foreground">{r.status}</p>+ </div>+ <Switch aria-label={`${view.switchLabel}: ${r.label}`} data-agent-menu-switch={r.app} checked={r.shown} disabled={r.locked} onCheckedChange={(on) => flip(r.app, on)} />+ </GroupedRow>+ ))}+ </SettingsGroup>+ );+}diff --git a/apps/cua-spaces-web/src/components/settings/connections/connectors-page.tsx b/apps/cua-spaces-web/src/components/settings/connections/connectors-page.tsxindex 385ac4a000..51ee06126e 100644--- a/apps/cua-spaces-web/src/components/settings/connections/connectors-page.tsx+++ b/apps/cua-spaces-web/src/components/settings/connections/connectors-page.tsx@@ -10,6 +10,7 @@ import { OtherMachineBlock, useThisAndOthers } from "@/components/agents/other-mimport { HarnessMark } from "@/components/agents/harness-mark";import { KeySheet } from "@/components/agents/key-sheet";import { SettingsGroup, SettingsRow } from "@/components/settings-group";+import { AgentMenuGroup } from "@/components/settings/connections/agent-menu-group";import { ConfirmDialog } from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";@@ -116,6 +117,7 @@ export function ConnectorsRedesign({ focusApp }: { focusApp?: string }) {{all ? "Show fewer" : "Show all"} {all ? <ChevronUpIcon className="size-3.5" /> : <ChevronDownIcon className="size-3.5" />}</GroupedAction></SettingsGroup>+ <AgentMenuGroup c={c} />{all ? (<SettingsGroup title="Background computer use"><Suspense fallback={<div className="h-48" />}>diff --git a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx b/apps/cua-spaces-web/src/components/space-thread/space-call.tsxindex 810694ddeb..181c8ada8d 100644--- a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/space-call.tsx@@ -18,6 +18,8 @@ import { toast } from "@/components/ui/toast";import { AddAgentSheet } from "@/components/add-agent/add-agent-sheet";import { registerAddAgent } from "@/components/add-agent/add-agent-launcher";+import { useAbilityAnswer } from "@/lib/agent-home/answer";+import { CallSplit } from "./call-split";import { defaultAddressee, EMPTY_ADDRESS, resolveAddressing, setAddress, unpinAgent, useAddressing } from "@/lib/addressing";import { EVERYONE, type MentionCandidate } from "@/lib/mentions";@@ -172,6 +174,8 @@ export function SpaceCall({const preparedQueue = usePreparedQueue(spaceId);const preparedWords = preparedQueue.length ? prepared.view?.queued[0]?.note : undefined;const items = useMemo(() => [...thread.items, ...queuedItems(queued, thread.me ?? "me", myName)], [thread.items, thread.me, queued, myName]);+ // An agent's request for an ability (list Spaces, use a machine) is a standard approval card; allowing it is remembered for that agent.+ const answerApproval = useAbilityAnswer(spaceId, thread.items, roster, thread.answer);const after = (seq: number) =>seq < 0 ? (<div data-queued-note="" data-only-you="" className="-mt-0.5 mb-1 ml-11 w-fit rounded-lg bg-brand-surface px-2.5 py-1.5">@@ -277,7 +281,7 @@ export function SpaceCall({<LiveRows live={thread.live} roster={shown} /></>}- onAnswer={thread.answer}+ onAnswer={answerApproval}onOpenAttachment={openAttachment}onRemoveAgent={thread.removeAgent ?? undefined}onRetry={(text) => summon.send(text, view ?? null)}diff --git a/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx b/apps/cua-spaces-web/src/components/space-thread/thread-view.tsxindex 3d5983e071..c63f704b33 100644--- a/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx@@ -12,6 +12,8 @@ import { Inlines } from "@/components/markdown";import { Button } from "@/components/ui/button";import { parseInline } from "@/lib/markdown";import { mentionSegments } from "@/lib/mentions";+import { abilityOfAction } from "@/lib/agent-home/prompt";+import { askText } from "@/lib/agent-home/requests";import { cn, isMacPlatform } from "@/lib/utils";import { AgentTile, MemberAvatar } from "./avatar";@@ -470,7 +472,10 @@ function Approval({const { core } = useBridge();const card = useMemo(() => (entry.approval?.card ? exportCardView(core, entry.approval.card) : null), [core, entry.approval?.card]);const exportAsk = !card && entry.approval ? exportAskText(entry.approval.action, entry.approval.details) : null;- const ask = card ? { title: card.repo, detail: "", allow: card.allow } : exportAsk;+ // An agent asking for an ability (see Spaces, use a machine) says it in plain words, on this same card.+ const ability = !card && !exportAsk && entry.approval ? abilityOfAction(entry.approval.action) : null;+ const abilityAsk = ability ? askText({ seq: entry.seq, ability, detail: (entry.approval?.details ?? "").trim(), tsMs: entry.tsMs }, null) : null;+ const ask = card ? { title: card.repo, detail: "", allow: card.allow } : (exportAsk ?? abilityAsk);const press = (approve: boolean) => {setBusy(approve);setError(null);diff --git a/apps/cua-spaces-web/src/components/spaces/space-list.tsx b/apps/cua-spaces-web/src/components/spaces/space-list.tsxindex cac4c95cee..a07b3f6704 100644--- a/apps/cua-spaces-web/src/components/spaces/space-list.tsx+++ b/apps/cua-spaces-web/src/components/spaces/space-list.tsx@@ -6,15 +6,20 @@* computer, size on disk ("—" when it isn't yours or isn't known), last* used. Name, Size and Last used sort from their headers. No row lines: a* fill on hover and on selection.+ *+ * With the Child Spaces experiment on, a Space's children follow it,+ * indented and collapsed under a disclosure on its row.*/import { Link, useNavigate } from "@tanstack/react-router";-import { ArrowDownIcon, ArrowUpIcon, EyeOffIcon, LoaderCircleIcon } from "lucide-react";-import type { MouseEvent, ReactNode, RefObject } from "react";+import { ArrowDownIcon, ArrowUpIcon, ChevronRightIcon, EyeOffIcon, LoaderCircleIcon } from "lucide-react";+import { useState, type MouseEvent, type ReactNode, type RefObject } from "react";+import type { ChildrenPreview } from "@/bridge/contracts/children";+import { useChildren } from "@/components/children/use-children";import { OsIcon } from "@/components/os-icon";import { StateLabel } from "@/components/state-dot";-import { DesktopTag, PinnedMark } from "@/components/spaces/space-tile";+import { DesktopTag, HomeTag, PinnedMark } from "@/components/spaces/space-tile";import { useWindowedRows } from "@/hooks/use-windowed-rows";import { lastUsedText, sizeCell, type SpacesSort } from "@/lib/spaces-page";import { WINDOW_FROM } from "@/lib/windowing";@@ -47,9 +52,51 @@ export interface SpaceListProps {/** A list row's height (`h-10`), and nothing between rows. */const ROW_PITCH = 40;+/** One row to draw: its depth under a listed parent, and its disclosure. */+interface Shown {+ item: SpaceItem;+ depth: number;+ /** Children listed under it (0: no disclosure). */+ kids: number;+}++/** `items` with each Space's listed children after it (in `items`' order),+ * only under the expanded ones. */+export function nestChildren(items: SpaceItem[], tree: ChildrenPreview | null, open: ReadonlySet<string>): Shown[] {+ if (!tree) return items.map((item) => ({ item, depth: 0, kids: 0 }));+ const listed = new Set(items.map((i) => i.space.id));+ const parentOf = (id: string) => {+ const p = tree.node(id)?.parent;+ return p && listed.has(p) ? p : undefined;+ };+ const under = new Map<string, SpaceItem[]>();+ for (const i of items) {+ const p = parentOf(i.space.id);+ if (p) under.set(p, [...(under.get(p) ?? []), i]);+ }+ const out: Shown[] = [];+ const walk = (i: SpaceItem, depth: number) => {+ const kids = under.get(i.space.id) ?? [];+ out.push({ item: i, depth, kids: kids.length });+ if (open.has(i.space.id) && depth < 8) for (const k of kids) walk(k, depth + 1);+ };+ for (const i of items) if (!parentOf(i.space.id)) walk(i, 0);+ return out;+}+export function SpaceList({ items, sort, onSort, now, selection, menu, more, hide }: SpaceListProps) {+ const tree = useChildren();+ const [open, setOpen] = useState<ReadonlySet<string>>(() => new Set());+ const toggle = (id: string) =>+ setOpen((o) => {+ const next = new Set(o);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ const rows = nestChildren(items, tree, open);// A long list draws only the rows on screen (`lib/windowing.ts`).- const windowed = useWindowedRows({ enabled: items.length >= WINDOW_FROM, rows: items.length, perRow: 1, gap: 0, estimatePitch: () => ROW_PITCH });+ const windowed = useWindowedRows({ enabled: rows.length >= WINDOW_FROM, rows: rows.length, perRow: 1, gap: 0, estimatePitch: () => ROW_PITCH });const { start: from, end: to } = windowed.window;const cols = cn("grid items-center gap-x-3", selection ? "grid-cols-[20px_minmax(0,1fr)_100px_140px_72px_100px_28px]" : "grid-cols-[minmax(0,1fr)_100px_140px_72px_100px_28px]");const head = (key: SpacesSort | null, label: string, right = false) =>@@ -78,8 +125,9 @@ export function SpaceList({ items, sort, onSort, now, selection, menu, more, hid<span /></div><div role="rowgroup" ref={windowed.ref as RefObject<HTMLDivElement>} style={windowed.style}>- {items.slice(from, to).map((item) => {- const row = <ListRow key={item.space.id} item={item} cols={cols} now={now} selection={selection} more={hasMenu(item) ? more?.(item) : undefined} hide={hasHideButton(item) ? () => hide?.(item) : undefined} />;+ {rows.slice(from, to).map(({ item, depth, kids }) => {+ const nest = { depth, kids, open: open.has(item.space.id), toggle: () => toggle(item.space.id) };+ const row = <ListRow key={item.space.id} item={item} cols={cols} now={now} selection={selection} more={hasMenu(item) ? more?.(item) : undefined} hide={hasHideButton(item) ? () => hide?.(item) : undefined} nest={nest} />;return menu ? <div key={item.space.id}>{menu(item, row)}</div> : row;})}</div>@@ -87,7 +135,23 @@ export function SpaceList({ items, sort, onSort, now, selection, menu, more, hid);}-function ListRow({ item, cols, now, selection, more, hide }: { item: SpaceItem; cols: string; now: number; selection: SpaceListProps["selection"]; more?: ReactNode; hide?: () => void }) {+function ListRow({+ item,+ cols,+ now,+ selection,+ more,+ hide,+ nest,+}: {+ item: SpaceItem;+ cols: string;+ now: number;+ selection: SpaceListProps["selection"];+ more?: ReactNode;+ hide?: () => void;+ nest?: { depth: number; kids: number; open: boolean; toggle: () => void };+}) {const { space, state, access } = item;const navigate = useNavigate();const selected = selection?.selected(item) ?? false;@@ -111,7 +175,22 @@ function ListRow({ item, cols, now, selection, more, hide }: { item: SpaceItem;)}>{selection ? <span role="cell">{selection.row(item)}</span> : null}- <span role="cell" className="flex min-w-0 items-center gap-2.5">+ <span role="cell" className="flex min-w-0 items-center gap-2.5" style={nest?.depth ? { paddingLeft: nest.depth * 20 } : undefined}>+ {nest && nest.kids > 0 ? (+ <button+ type="button"+ aria-label={nest.open ? "Hide its Spaces" : `Show its ${nest.kids} Space${nest.kids === 1 ? "" : "s"}`}+ aria-expanded={nest.open}+ data-children-toggle={space.id}+ onClick={(e) => {+ e.stopPropagation();+ nest.toggle();+ }}+ className="-mx-1 inline-flex size-5 shrink-0 cursor-default items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <ChevronRightIcon className={cn("size-3.5 transition-transform", nest.open && "rotate-90")} />+ </button>+ ) : null}{access.kind === "mine" ? (<OsIcon os={space.os} className="size-3.5 shrink-0 text-muted-foreground" />) : (@@ -128,6 +207,7 @@ function ListRow({ item, cols, now, selection, more, hide }: { item: SpaceItem;</Link><PinnedMark id={space.id} />{item.desktop ? <DesktopTag /> : null}+ <HomeTag spaceId={item.space.id} /><PeopleStack access={access} /></span><span role="cell" className="flex min-w-0 items-center">diff --git a/apps/cua-spaces-web/src/components/spaces/space-tile.tsx b/apps/cua-spaces-web/src/components/spaces/space-tile.tsxindex f246a4c39d..394eb5e9d8 100644--- a/apps/cua-spaces-web/src/components/spaces/space-tile.tsx+++ b/apps/cua-spaces-web/src/components/spaces/space-tile.tsx@@ -24,6 +24,8 @@ import { StateLabel } from "@/components/state-dot";import { toast, toastError } from "@/components/ui/toast";import { useTileVideo } from "@/components/video/tile-video";import { useInView } from "@/hooks/use-in-view";+import { useChildren } from "@/components/children/use-children";+import { useIsHomeSpace } from "@/lib/agent-home/home-space";import { creatingLine } from "@/lib/host-labels";import { createError, createProgress, osLabel, powerButton, powerError, type PowerButton } from "@/lib/spaces";import { cn } from "@/lib/utils";@@ -98,6 +100,7 @@ export function SpaceTile({ item, accessKey, selected = false, busy = false, top</p><PinnedMark id={space.id} />{item.desktop ? <DesktopTag /> : null}+ <HomeTag spaceId={space.id} />{/* The state, in the core's words ("Running", "Suspended", "Turning off…"), flush right; the hover "⋯" takes its place. */}<StateLabelstate={item.desktop === "off" ? "stopped" : state}@@ -188,6 +191,19 @@ export function DesktopTag() {);}+/** The "Home" tag beside an agent's home Space (the Space its requests from Home go to). */+export function HomeTag({ spaceId }: { spaceId: string }) {+ const remembered = useIsHomeSpace(spaceId);+ // The host knows a home by its label, so the tag shows on a new device too.+ const labelled = Boolean(useChildren()?.node(spaceId)?.home);+ if (!remembered && !labelled) return null;+ return (+ <span data-home-tag="" className="shrink-0 text-xs text-muted-foreground">+ Home+ </span>+ );+}+/** Hide, on a desktop's hover where a Space has its power button: the row leaves the list until "Show hidden". */function TileHide({ name, onHide }: { name: string; onHide: () => void }) {return (diff --git a/apps/cua-spaces-web/src/components/ui/popover.tsx b/apps/cua-spaces-web/src/components/ui/popover.tsxnew file mode 100644index 0000000000..658c14e4c2--- /dev/null+++ b/apps/cua-spaces-web/src/components/ui/popover.tsx@@ -0,0 +1,57 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { Popover as PopoverPrimitive } from "@base-ui/react/popover";+import type { ComponentProps, ReactElement, ReactNode, RefObject } from "react";++import { cn } from "@/lib/utils";++/**+ * A panel on a trigger that holds its own controls (a field, a list with+ * arrow keys), where a menu would take the keys itself: the model menu and+ * the repo field of the ask box. The same glass and shadow as the menus.+ */+export function Popover({+ trigger,+ children,+ open,+ onOpenChange,+ width = 340,+ initialFocus,+ align = "start",+ popupProps,+}: {+ trigger: ReactElement;+ children: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ /** Width in px. */+ width?: number;+ /** The element that takes focus when it opens. */+ initialFocus?: RefObject<HTMLElement | null>;+ align?: "start" | "center" | "end";+ popupProps?: Omit<ComponentProps<typeof PopoverPrimitive.Popup>, "className" | "children" | "initialFocus">;+}) {+ return (+ <PopoverPrimitive.Root {...(open === undefined ? {} : { open })} onOpenChange={(o) => onOpenChange?.(o)}>+ <PopoverPrimitive.Trigger render={trigger} />+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Positioner sideOffset={6} align={align} className="z-50 outline-none">+ <PopoverPrimitive.Popup+ {...popupProps}+ initialFocus={initialFocus}+ style={{ width }}+ className={cn("glass max-w-[calc(100vw-2rem)] origin-(--transform-origin) rounded-lg border p-1.5 text-popover-foreground shadow-float outline-none transition-[opacity,scale] data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0")}+ >+ {children}+ </PopoverPrimitive.Popup>+ </PopoverPrimitive.Positioner>+ </PopoverPrimitive.Portal>+ </PopoverPrimitive.Root>+ );+}++/** A short rule between a panel's groups. */+export function PopoverDivider() {+ return <div role="separator" className="my-1 h-px bg-border" />;+}diff --git a/apps/cua-spaces-web/src/hooks/use-agent-menu.ts b/apps/cua-spaces-web/src/hooks/use-agent-menu.tsnew file mode 100644index 0000000000..2a2e95f754--- /dev/null+++ b/apps/cua-spaces-web/src/hooks/use-agent-menu.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Which coding apps Home's agent menu shows. The rule (the defaults, the last+ * app that cannot be hidden, a connect that shows an app again) is the app+ * core's `agent_menu`; the choice is kept by the host with the rest of the+ * app's settings (`settings.get` answers `values.agentMenu`, `settings.set`+ * with key `agentMenu` saves it), so the web, SwiftUI and Electron apps+ * agree and it survives a restart. A host that keeps no core settings+ * refuses the save: the page then keeps the choice for this session.+ */++import { useCallback, useEffect, useMemo, useState } from "react";++import { agentMenuChoose, agentMenuSync, agentMenuView, useBridge, useSettings, type AgentMenuChange, type AgentMenuPrefs, type AgentMenuSettings } from "@/bridge";+import type { Connectors } from "@/hooks/use-connectors";++const NONE: AgentMenuPrefs = { shown: [], hidden: [], seen: [] };++const same = (a: AgentMenuPrefs, b: AgentMenuPrefs) => JSON.stringify(a) === JSON.stringify(b);++export interface AgentMenu {+ /** The choice now, with a connect since the last look already counted (null before the sign-ins are read: use `prefs`). */+ prefs: AgentMenuPrefs;+ /** The rows of the switches (the core's). */+ view: AgentMenuSettings | null;+ /** Switches an app on or off; answers the core's words when it was refused (the last app). */+ choose(app: string, on: boolean): Promise<string | null>;+}++/** The agent menu's choice and what changes it. */+export function useAgentMenu(c: Pick<Connectors, "input" | "keysReady">): AgentMenu {+ const { core } = useBridge();+ const settings = useSettings();+ const [session, setSession] = useState<AgentMenuPrefs | null>(null);+ const stored = session ?? settings.data?.values.agentMenu ?? NONE;+ const ready = c.keysReady && Boolean(settings.data);+ // A hidden app that gained an account since the last look is shown again (not on every refresh).+ const prefs = useMemo(() => (ready ? (agentMenuSync(core, c.input, stored) ?? stored) : stored), [ready, core, c.input, stored]);+ const save = useCallback(+ async (next: AgentMenuPrefs) => {+ if (session) return void setSession(next);+ try {+ await settings.updateSetting("agentMenu", next);+ } catch {+ setSession(next);+ }+ },+ [session, settings],+ );+ useEffect(() => {+ if (ready && !same(prefs, stored)) void save(prefs);+ }, [ready, prefs, stored, save]);+ const view = useMemo(() => agentMenuView(core, c.input, prefs), [core, c.input, prefs]);+ const choose = useCallback(+ async (app: string, on: boolean): Promise<string | null> => {+ const r: AgentMenuChange | null = agentMenuChoose(core, c.input, prefs, app, on);+ if (!r) return null;+ if (r.refused) return r.refused;+ await save(r.prefs);+ return null;+ },+ [core, c.input, prefs, save],+ );+ return { prefs, view, choose };+}diff --git a/apps/cua-spaces-web/src/hooks/use-connectors.ts b/apps/cua-spaces-web/src/hooks/use-connectors.tsindex 1d470c73d1..ac1d679705 100644--- a/apps/cua-spaces-web/src/hooks/use-connectors.ts+++ b/apps/cua-spaces-web/src/hooks/use-connectors.ts@@ -108,6 +108,8 @@ export type ConnectOutcome = "connected" | "sheet" | "failed";export interface Connectors {apps: ConnectedApps;input: ConnectorsInput;+ /** The saved sign-ins and keys were read (a sync of the agent menu waits for it). */+ keysReady: boolean;view: ConnectorsView | null;detail(agent: string): AppDetailView | null;/** The provider sheet open now. */@@ -401,6 +403,7 @@ export function useConnectors(): Connectors {return {apps,input,+ keysReady: !keys.isLoading && !keys.input.error && !keys.input.unavailable && apps.rows !== null,view,detail: (agent) => appDetail(core, input, agent),sheet,diff --git a/apps/cua-spaces-web/src/lib/agent-home/abilities.ts b/apps/cua-spaces-web/src/lib/agent-home/abilities.tsnew file mode 100644index 0000000000..fb28d68cd2--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/abilities.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * What an agent can ask for in its home (CUA-2630), as one small interface.+ *+ * The agent home is where an ask-first request starts: the root of that+ * request's tree. The container version (`containerHome`) is the+ * slim Linux image (`linux:24.04-slim`); a wasm version can replace it later by implementing+ * `AgentHomeRuntime` and listing the same abilities, with no change to the+ * agent, the approvals or the grants: all three only know ability ids.+ *+ * Three abilities, each asked for by the agent and approved by the person:+ *+ * - `spaces.list`: see Spaces. Only the ones the person @mentioned until+ * they approve listing all (once, remembered per agent);+ * - `spaces.spawn`: make a child Space with an OS, an image and a budget,+ * inside the tree's budget. Always available in a home; the person+ * already set the budget;+ * - `machines.use`: use one of the person's machines (their Mac, say).+ * "Let this agent use this Mac?" once, remembered per agent. An+ * @mentioned Space or machine counts as the grant.+ */++import type { SpaceOs } from "@/bridge";++export type AbilityId = "spaces.list" | "spaces.spawn" | "machines.use";++export const ABILITY_IDS: readonly AbilityId[] = ["spaces.list", "spaces.spawn", "machines.use"];++/** One ability, as the agent is told about it and as the person is asked. */+export interface AbilityDescriptor {+ id: AbilityId;+ /** How the agent calls it in this home (a command, a tool). */+ call: string;+ /** What the agent is told it does. */+ summary: string;+ /** The person is asked before it works beyond what they already named. */+ asksFirst: boolean;+}++/** What `spaces.spawn` takes: the child's OS, image and budget. */+export interface SpawnRequest {+ os: SpaceOs;+ image?: string;+ name?: string;+ /** Dollars per hour this child may cost; it must fit what is left of the tree's budget. */+ budgetUsdPerHour?: number;+}++/** The grants one agent holds, remembered per agent. */+export interface AgentGrants {+ /** The person let this agent list every Space. */+ listAll: boolean;+ /** Machines (ids) the person let this agent use. */+ machines: string[];+}++export const NO_GRANTS: AgentGrants = { listAll: false, machines: [] };++/** What the person already named in the request: @mentions and a place. */+export interface HomeMentions {+ /** Spaces @mentioned, by id and name. */+ spaces: { id: string; name: string }[];+ /** Machines @mentioned or asked for ("on my Mac", "connect to <x>"), by id and name. */+ machines: { id: string; name: string }[];+}++export const NO_MENTIONS: HomeMentions = { spaces: [], machines: [] };++/** What a new home is made with. */+export interface HomeSetup {+ agent: string;+ grants: AgentGrants;+ mentions: HomeMentions;+}++/** The create options a runtime asks for (the SDK's create config, plus the home's labels). */+export interface HomeCreate {+ image: string;+ on: "local";+ kind: "container";+ name: string;+ cpus: number;+ memoryMb: number;+ spacesd: true;+ /** The home may make child Spaces (the spawn capability). */+ children: true;+ labels: Record<string, string>;+}++/** An agent home: a container today, wasm later. */+export interface AgentHomeRuntime {+ readonly kind: "container" | "wasm";+ /** The abilities this home offers, in the words the agent is told. */+ abilities(): AbilityDescriptor[];+ /** What to create for `setup`. */+ create(setup: HomeSetup, name: string): HomeCreate;+}diff --git a/apps/cua-spaces-web/src/lib/agent-home/agent-home.test.ts b/apps/cua-spaces-web/src/lib/agent-home/agent-home.test.tsnew file mode 100644index 0000000000..9f73be2671--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/agent-home.test.ts@@ -0,0 +1,221 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { readFileSync } from "node:fs";+import { resolve } from "node:path";++import { beforeEach, describe, expect, it } from "vitest";++import type { ThreadEntry } from "@/bridge/ops/thread";++import { ABILITY_IDS, NO_GRANTS, NO_MENTIONS } from "./abilities";+import { AGENT_HOME_IMAGE, containerHome, HOME_LABELS, joinLabel } from "./container";+import { allowListAll, allowMachine, grantsFor, homeMentionsArg, resetGrants } from "./grants";+import { parseMentions, saidWhere } from "./mentions";+import { abilityOfAction, approvalAction, homePrompt } from "./prompt";+import { askText, covered, openAbilityRequests } from "./requests";+import { forgetHome, homeSpaceId, isHomeSpaceId, rememberHome, resetHomes, reusableHome } from "./home-space";++beforeEach(() => {+ localStorage.clear();+ resetGrants();+ resetHomes();+});++const place = {+ spaces: [+ { id: "local:ci-linux", name: "ci-linux" },+ { id: "local:studio", name: "studio" },+ ],+ machines: [+ { id: "m-air", name: "Dillon's MacBook Air", current: true },+ { id: "m-mini", name: "spare mac mini", current: false },+ ],+};++describe("where the person said the job runs", () => {+ it("reads @mentions of Spaces and machines, by name or first word", () => {+ const m = parseMentions('Run the tests on @ci-linux and @"spare mac mini", then @Dillon', place);+ expect(m.spaces).toEqual([{ id: "local:ci-linux", name: "ci-linux" }]);+ expect(m.machines.map((x) => x.id).sort()).toEqual(["m-air", "m-mini"]);+ expect(saidWhere(m)).toBe(true);+ });++ it('reads "on my Mac" as this machine and "connect to <x>" as that one', () => {+ expect(parseMentions("build it on my Mac", place).machines.map((m) => m.id)).toEqual(["m-air"]);+ expect(parseMentions("connect to spare mac mini and look", place).machines.map((m) => m.id)).toEqual(["m-mini"]);+ expect(parseMentions("connect to studio", place).spaces.map((s) => s.id)).toEqual(["local:studio"]);+ });++ it("leaves the choice to the agent when nothing is named", () => {+ const m = parseMentions("test https://github.com/acme/app", place);+ expect(m).toEqual(NO_MENTIONS);+ expect(saidWhere(m)).toBe(false);+ });+});++describe("what the person approved is remembered per agent", () => {+ it("starts with nothing and keeps each agent's grants apart", () => {+ expect(grantsFor("claude-code")).toEqual(NO_GRANTS);+ allowListAll("claude-code");+ allowMachine("claude-code", "m-air");+ allowMachine("openai-codex", "m-mini");+ resetGrants();+ expect(grantsFor("claude-code")).toEqual({ listAll: true, machines: ["m-air"] });+ expect(grantsFor("openai-codex")).toEqual({ listAll: false, machines: ["m-mini"] });+ allowMachine("claude-code", "m-air", false);+ expect(grantsFor("claude-code").machines).toEqual([]);+ });+});++describe("the container home", () => {+ it("is the slim Linux image with the spawn capability on", () => {+ const c = containerHome.create({ agent: "claude-code", grants: NO_GRANTS, mentions: NO_MENTIONS }, "home-x");+ expect(c).toMatchObject({ image: AGENT_HOME_IMAGE, kind: "container", on: "local", children: true, spacesd: true });+ expect(c.labels).toEqual({ [HOME_LABELS.home]: "1", [HOME_LABELS.agent]: "claude-code" });+ });++ it("carries what was granted and named as labels the daemon reads", () => {+ const c = containerHome.create(+ {+ agent: "claude-code",+ grants: { listAll: true, machines: ["m-air"] },+ mentions: { spaces: [{ id: "local:studio", name: "studio" }], machines: [{ id: "m-mini", name: "spare mac mini" }] },+ },+ "home-x",+ );+ expect(c.labels[HOME_LABELS.list]).toBe("all");+ expect(c.labels[HOME_LABELS.mentions]).toBe("local:studio,m-mini,spare mac mini,studio");+ expect(c.labels[HOME_LABELS.machines]).toBe("m-air,m-mini,spare mac mini");+ });++ it("keeps a label value within the daemon's 256 bytes", () => {+ const many = Array.from({ length: 80 }, (_, i) => `space-number-${i}`);+ expect(new TextEncoder().encode(joinLabel(many)).length).toBeLessThanOrEqual(256);+ });++ it("offers the three abilities the agent is told about", () => {+ expect(containerHome.abilities().map((a) => a.id)).toEqual([...ABILITY_IDS]);+ });++ it("uses the labels the daemon reads (children/home.rs)", () => {+ const rs = readFileSync(resolve(__dirname, "../../../../../libs/cua/crates/cua-daemon/src/children/home.rs"), "utf8");+ for (const label of Object.values(HOME_LABELS)) expect(rs).toContain(`"${label}"`);+ });++ it("runs on the slim Linux image of the catalog", () => {+ const root = resolve(__dirname, "../../../../../");+ const catalog = JSON.parse(readFileSync(resolve(root, "libs/images/sandbox-images.json"), "utf8")) as { images: { ref: string; variant: string; os: string; spacesd: boolean; tier?: string }[] };+ const entry = catalog.images.find((i) => i.ref === AGENT_HOME_IMAGE);+ expect(entry).toMatchObject({ variant: "container", os: "linux", spacesd: true, tier: "slim" });+ });+});++describe("the agent's prompt", () => {+ const setup = { agent: "claude-code", grants: NO_GRANTS, mentions: NO_MENTIONS };+ it("says where it is, what it can do and how to ask", () => {+ const p = homePrompt("test https://github.com/acme/app", setup, containerHome.abilities());+ expect(p).toContain("your own small Linux Space");+ expect(p).toContain("cua spaces ls");+ expect(p).toContain(approvalAction("machines.use"));+ expect(p).toContain("Unless the person says where");+ expect(p.endsWith("test https://github.com/acme/app")).toBe(true);+ });+ it("treats a named Space or machine as the grant", () => {+ const p = homePrompt("x", { ...setup, mentions: { spaces: [], machines: [{ id: "m-air", name: "my Air" }] } }, containerHome.abilities());+ expect(p).toContain('the computer "my Air"');+ expect(p).toContain("without asking");+ });+ it("round-trips an ability's action word", () => {+ for (const id of ABILITY_IDS) expect(abilityOfAction(approvalAction(id))).toBe(id);+ expect(abilityOfAction("Push to main")).toBeNull();+ });+});++describe("the agent's requests", () => {+ const entry = (seq: number, e: Partial<ThreadEntry>): ThreadEntry => ({ seq, id: String(seq), tsMs: seq, kind: "message", text: "", mentions: [], replyTo: null, task: null, attachments: [], approval: null, answer: null, noteFor: null, update: null, runsOnKeysOf: null, event: null, author: { kind: "agent", id: "agent:claude", name: "claude" }, ...e });+ const ask = (seq: number, id: string, details = "") => entry(seq, { kind: "approval", approval: { action: approvalAction(id as never), details, state: "open" } });++ it("lists the open ones and skips answered and other approvals", () => {+ const entries = [+ ask(1, "spaces.list"),+ ask(2, "machines.use", "the spare mac mini"),+ entry(3, { kind: "answer", answer: { approval: 1, approve: true, note: null } }),+ entry(4, { kind: "approval", approval: { action: "Push to main", details: "", state: "open" } }),+ ];+ expect(openAbilityRequests(entries).map((r) => [r.seq, r.ability])).toEqual([[2, "machines.use"]]);+ });++ it("is covered by a remembered grant, and spawning never asks", () => {+ const [list, mac, spawn] = openAbilityRequests([ask(1, "spaces.list"), ask(2, "machines.use", "use the spare mac mini"), ask(3, "spaces.spawn")]);+ const names = new Map([["m-mini", "spare mac mini"]]);+ expect(covered(list!, NO_GRANTS, names)).toBe(false);+ expect(covered(list!, { listAll: true, machines: [] }, names)).toBe(true);+ expect(covered(mac!, NO_GRANTS, names)).toBe(false);+ expect(covered(mac!, { listAll: false, machines: ["m-mini"] }, names)).toBe(true);+ expect(covered(spawn!, NO_GRANTS, names)).toBe(true);+ });++ it("asks in plain words, never with a middle dot", () => {+ const [list, mac] = openAbilityRequests([ask(1, "spaces.list"), ask(2, "machines.use", "build the app")]);+ expect(askText(list!, null).title).toBe("Let this agent see all your Spaces?");+ expect(askText(mac!, "this Mac").title).toBe("Let this agent use this Mac?");+ for (const t of [askText(list!, null), askText(mac!, "this Mac")]) expect(`${t.title}${t.detail}${t.allow}`).not.toContain("·");+ });+});++describe("an @mention to a home that already runs is the grant", () => {+ it("sends every id and name of what was named, so the daemon matches either, and nothing else", () => {+ const named = parseMentions("check @studio and use @my-mac", {+ spaces: [{ id: "local:studio", name: "studio" }],+ machines: [{ id: "m-air", name: "my-mac", current: false }],+ });+ expect(homeMentionsArg(named)).toEqual(["local:studio", "m-air", "my-mac", "studio"]);+ expect(homeMentionsArg(NO_MENTIONS)).toEqual([]);+ // It never turns on listing everything.+ expect(grantsFor("claude-code").listAll).toBe(false);+ });+});++describe("the home Space is made once and reused", () => {+ const spaces = [+ { id: "local:home-a", status: "running" as const },+ { id: "local:other", status: "running" as const },+ ];++ it("remembers one home per agent and tells the list which Space it is", () => {+ expect(homeSpaceId("claude-code")).toBeNull();+ rememberHome("claude-code", "local:home-a");+ rememberHome("openai-codex", "local:home-b");+ resetHomes();+ expect(homeSpaceId("claude-code")).toBe("local:home-a");+ expect(homeSpaceId("openai-codex")).toBe("local:home-b");+ expect(isHomeSpaceId("local:home-a")).toBe(true);+ expect(isHomeSpaceId("local:other")).toBe(false);+ forgetHome("claude-code");+ expect(isHomeSpaceId("local:home-a")).toBe(false);+ });++ it("reuses the home while it is listed, and starts a new one when asked or when it is gone", () => {+ rememberHome("claude-code", "local:home-a");+ expect(reusableHome("claude-code", spaces)).toBe("local:home-a");+ expect(reusableHome("claude-code", spaces, true)).toBeNull();+ expect(reusableHome("claude-code", [spaces[1]!])).toBeNull();+ expect(reusableHome("claude-code", [{ id: "local:home-a", status: "deleting" }])).toBeNull();+ expect(reusableHome("openai-codex", spaces)).toBeNull();+ });++ it("finds the home again by its label when this device remembers nothing", () => {+ // A new device, or the app's storage was cleared: the host says which Spaces are homes.+ expect(homeSpaceId("claude-code")).toBeNull();+ expect(reusableHome("claude-code", spaces, false, ["local:home-a"])).toBe("local:home-a");+ // Gone or being deleted: not offered; the next labelled one is.+ expect(reusableHome("claude-code", [spaces[1]!], false, ["local:home-a"])).toBeNull();+ expect(reusableHome("claude-code", [{ id: "local:home-a", status: "deleting" }, spaces[1]!], false, ["local:home-a", "local:other"])).toBe("local:other");+ // A fresh home is asked for: the label does not bring the old one back.+ expect(reusableHome("claude-code", spaces, true, ["local:home-a"])).toBeNull();+ // What this device remembers still wins over the labels.+ rememberHome("claude-code", "local:other");+ expect(reusableHome("claude-code", spaces, false, ["local:home-a"])).toBe("local:other");+ });+});diff --git a/apps/cua-spaces-web/src/lib/agent-home/answer.ts b/apps/cua-spaces-web/src/lib/agent-home/answer.tsnew file mode 100644index 0000000000..2d68ef502e--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/answer.ts@@ -0,0 +1,93 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Answers for an agent's ability requests, in the Space's normal thread.+ *+ * The agent asks with a standard approval whose action is `ability:<id>`+ * (`prompt.ts`); the thread draws it as any agent's approval card, in plain+ * words (`requests.ts` `askText`). This hook sits between that card and the+ * thread's `answer`: allowing remembers the grant for that agent, tells this+ * machine's daemon so the running home takes it at once, and a request the+ * agent already holds is answered without asking.+ */++import { useCallback, useEffect, useMemo, useRef } from "react";++import { useBridge, useMachines, type ThreadItem } from "@/bridge";+import { toastError } from "@/components/ui/toast";+import type { Roster } from "@/components/space-thread/roster";++import { allowListAll, allowMachine, grantsFor, homeGrantsArg } from "./grants";+import { isHomeSpaceId } from "./home-space";+import { abilityOfAction } from "./prompt";+import { covered, type AbilityRequest } from "./requests";++type ApprovalItem = Extract<ThreadItem, { type: "approval" }>;++/** The ability an approval item asks for, and who asked. */+function requestOf(item: ApprovalItem, roster: Pick<Roster, "agents">): { req: AbilityRequest; agent: string } | null {+ const action = item.entry.approval?.action;+ const ability = action ? abilityOfAction(action) : null;+ if (!ability) return null;+ const asker = item.entry.author.kind === "agent" ? roster.agents.find((a) => a.id === item.entry.author.id) : undefined;+ return {+ req: { seq: item.entry.seq, ability, detail: (item.entry.approval?.details ?? "").trim(), tsMs: item.entry.tsMs },+ agent: asker?.harness ?? "",+ };+}++/** The machine a request names (by name or id in the agent's words), among the person's machines. */+function machineFor(req: AbilityRequest, machines: ReadonlyMap<string, string>): [string, string] | null {+ const named = req.detail.toLowerCase();+ return [...machines].find(([id, n]) => named.includes(n.toLowerCase()) || named.includes(id.toLowerCase())) ?? null;+}++/**+ * `answer` for the thread's approval cards: the thread's own answer, with an+ * ability request's grant kept first. Also answers, once, the open requests+ * that what the agent already holds covers.+ */+export function useAbilityAnswer(spaceId: string, items: readonly ThreadItem[], roster: Pick<Roster, "agents">, answer: (approval: number, approve: boolean) => Promise<void>): (approval: number, approve: boolean) => Promise<void> {+ const { data } = useBridge();+ const { data: machineRows } = useMachines();+ const machines = useMemo(() => new Map((machineRows ?? []).map((m) => [m.id, m.name] as const)), [machineRows]);+ const home = isHomeSpaceId(spaceId);+ const asked = useRef(new Set<number>());++ const decide = useCallback(+ async (approval: number, approve: boolean) => {+ const item = items.find((i): i is ApprovalItem => i.type === "approval" && i.entry.seq === approval);+ const found = item ? requestOf(item, roster) : null;+ if (found && approve) {+ const { req, agent } = found;+ if (req.ability === "spaces.list") allowListAll(agent);+ if (req.ability === "machines.use") {+ const m = machineFor(req, machines);+ if (m) allowMachine(agent, m[0]);+ }+ // The running home's grants change now: this machine's daemon reads them each time the home asks.+ if (home && req.ability !== "spaces.spawn") {+ await data?.call("spaces.setAccess", { spaceId, home: homeGrantsArg(grantsFor(agent), machines) }).catch(toastError("Couldn't let it through yet"));+ }+ }+ asked.current.add(approval);+ await answer(approval, approve);+ },+ [items, roster, machines, home, data, spaceId, answer],+ );++ useEffect(() => {+ // What it already holds is answered at once; the rest waits for the person.+ for (const item of items) {+ if (item.type !== "approval" || item.answer || (item.entry.approval?.state ?? "open") !== "open") continue;+ const found = requestOf(item, roster);+ if (!found || asked.current.has(found.req.seq)) continue;+ if (!covered(found.req, grantsFor(found.agent), machines)) continue;+ asked.current.add(found.req.seq);+ void answer(found.req.seq, true).catch(() => asked.current.delete(found.req.seq));+ }+ }, [items, roster, machines, answer]);++ return decide;+}diff --git a/apps/cua-spaces-web/src/lib/agent-home/container.ts b/apps/cua-spaces-web/src/lib/agent-home/container.tsnew file mode 100644index 0000000000..714e411e6e--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/container.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import type { AbilityDescriptor, AgentHomeRuntime, HomeCreate, HomeSetup } from "./abilities";++/**+ * The agent home runs on the slim tier of the Linux image: the catalog entry+ * `ghcr.io/trycua/linux:24.04-slim` (libs/images/sandbox-images.json). It needs+ * the `cua` CLI and a spawn-capable cua-spacesd in that image, which the image+ * recipe provides. A test keeps this constant equal to that entry.+ */+export const AGENT_HOME_IMAGE = "ghcr.io/trycua/linux:24.04-slim";++/** The labels the daemon reads (`children/home.rs`); a test keeps the two in step. */+export const HOME_LABELS = {+ home: "cua.home",+ agent: "cua.home.agent",+ list: "cua.home.list",+ mentions: "cua.home.mentions",+ machines: "cua.home.machines",+} as const;++/** The container home's abilities, as `cua` commands the agent runs inside it. */+const ABILITIES: AbilityDescriptor[] = [+ {+ id: "spaces.list",+ call: "cua spaces ls",+ summary: "See Spaces. You see this tree and the Spaces the person @mentioned. Seeing every Space needs their OK.",+ asksFirst: true,+ },+ {+ id: "spaces.spawn",+ call: "cua spaces create <linux|windows|macos> --name <name> [--image <image>]",+ summary: "Make a child Space of the OS and image you need. It must fit this tree's budget and it can only have less network than you do.",+ asksFirst: false,+ },+ {+ id: "machines.use",+ call: "cua spaces create <os> --on host:<computer>",+ summary: "Put a child on one of the person's computers. The person must let you use that computer first, unless they named it.",+ asksFirst: true,+ },+];++/** A label value holds up to 256 bytes (the daemon's limit): keep the first words that fit. */+export function joinLabel(xs: readonly string[], max = 256): string {+ let out = "";+ for (const x of [...new Set(xs.filter(Boolean))].sort()) {+ const next = out ? `${out},${x}` : x;+ if (new TextEncoder().encode(next).length > max) break;+ out = next;+ }+ return out;+}+const join = (xs: readonly string[]) => joinLabel(xs);++export const containerHome: AgentHomeRuntime = {+ kind: "container",+ abilities: () => ABILITIES.map((a) => ({ ...a })),+ create(setup: HomeSetup, name: string): HomeCreate {+ const labels: Record<string, string> = { [HOME_LABELS.home]: "1", [HOME_LABELS.agent]: setup.agent };+ if (setup.grants.listAll) labels[HOME_LABELS.list] = "all";+ const mentions = [...setup.mentions.spaces.flatMap((s) => [s.id, s.name]), ...setup.mentions.machines.flatMap((m) => [m.id, m.name])];+ if (mentions.length) labels[HOME_LABELS.mentions] = join(mentions);+ // A machine the person granted before, or named now, may take children.+ const machines = [...setup.grants.machines, ...setup.mentions.machines.flatMap((m) => [m.id, m.name])];+ if (machines.length) labels[HOME_LABELS.machines] = join(machines);+ return { image: AGENT_HOME_IMAGE, on: "local", kind: "container", name, cpus: 1, memoryMb: 1024, spacesd: true, children: true, labels };+ },+};diff --git a/apps/cua-spaces-web/src/lib/agent-home/grants.ts b/apps/cua-spaces-web/src/lib/agent-home/grants.tsnew file mode 100644index 0000000000..0d10a3e89e--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/grants.ts@@ -0,0 +1,110 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * What the person has approved for each agent, remembered per agent on this+ * device (`localStorage`, like the ask-first tasks): "list all my Spaces"+ * once, "use this Mac" once per machine. A new home for the same agent is+ * made with them, so the agent is not asked again. Revoking takes effect for+ * the next home.+ */++import { useSyncExternalStore } from "react";++import { NO_GRANTS, type AgentGrants } from "./abilities";++const KEY = "cua.agentHome.grants";++type Store = Record<string, AgentGrants>;++let cache: Store | null = null;+const listeners = new Set<() => void>();++function load(): Store {+ if (cache) return cache;+ try {+ const raw = globalThis.localStorage?.getItem(KEY);+ const parsed = raw ? (JSON.parse(raw) as unknown) : {};+ cache = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Store) : {};+ } catch {+ cache = {};+ }+ return cache;+}++function save(next: Store): void {+ cache = next;+ try {+ globalThis.localStorage?.setItem(KEY, JSON.stringify(next));+ } catch {+ // Kept for this session only.+ }+ for (const l of [...listeners]) l();+}++/** What `agent` (a harness id) may do. */+export function grantsFor(agent: string): AgentGrants {+ const g = load()[agent];+ return g ? { listAll: Boolean(g.listAll), machines: Array.isArray(g.machines) ? [...g.machines] : [] } : { ...NO_GRANTS, machines: [] };+}++export function allowListAll(agent: string, on = true): void {+ save({ ...load(), [agent]: { ...grantsFor(agent), listAll: on } });+}++export function allowMachine(agent: string, machine: string, on = true): void {+ const g = grantsFor(agent);+ const machines = on ? [...new Set([...g.machines, machine])] : g.machines.filter((m) => m !== machine);+ save({ ...load(), [agent]: { ...g, machines } });+}++/** For tests: forget the cached grants. */+export function resetGrants(): void {+ cache = null;+}++const subscribe = (l: () => void) => {+ listeners.add(l);+ const onStorage = (e: StorageEvent) => {+ if (e.key === null || e.key === KEY) {+ cache = null;+ l();+ }+ };+ globalThis.addEventListener?.("storage", onStorage);+ return () => {+ listeners.delete(l);+ globalThis.removeEventListener?.("storage", onStorage);+ };+};++export function useGrants(agent: string): AgentGrants {+ // The snapshot is the stored object itself, so it only changes when a grant does.+ const stored = useSyncExternalStore(subscribe, () => load()[agent], () => undefined);+ return stored ? { listAll: Boolean(stored.listAll), machines: stored.machines ?? [] } : NO_GRANTS;+}++/**+ * What this machine's daemon is told when the person approves something+ * mid-run: every id and name of the machines the agent may use, so it+ * matches however the agent names one (`children/home.rs`).+ */+export function homeGrantsArg(g: AgentGrants, machines: ReadonlyMap<string, string>): { listAll: boolean; machines: string[] } {+ const out = new Set<string>();+ for (const id of g.machines) {+ out.add(id);+ const name = machines.get(id);+ if (name) out.add(name);+ }+ return { listAll: g.listAll, machines: [...out].sort() };+}++/**+ * What an @mention in a request to a home that already runs gives it: every+ * id and name of the Spaces and machines the person named, for the daemon to+ * match however the agent names one. An @mention counts as the grant, so no+ * approval card is asked for it (`children/home.rs`, `Grants.mentions`).+ */+export function homeMentionsArg(mentions: { spaces: readonly { id: string; name: string }[]; machines: readonly { id: string; name: string }[] }): string[] {+ return [...new Set([...mentions.spaces, ...mentions.machines].flatMap((m) => [m.id, m.name]).filter(Boolean))].sort();+}diff --git a/apps/cua-spaces-web/src/lib/agent-home/home-space.ts b/apps/cua-spaces-web/src/lib/agent-home/home-space.tsnew file mode 100644index 0000000000..0d77ff644b--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/home-space.ts@@ -0,0 +1,110 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The agent home is a Space like any other (CUA-2630): made on the first+ * request, reused by the next ones, listed with the person's Spaces. This+ * remembers, per agent on this device, which Space is its home so a later+ * request goes to the same one (`localStorage`, like the grants), and lets+ * the Spaces list tag it "Home".+ *+ * One home per person and agent unless they ask for a fresh one: a fresh one+ * replaces the remembered id; the old Space stays in the list as any Space.+ */++import { useSyncExternalStore } from "react";++import type { Space } from "@/bridge";++const KEY = "cua.agentHome.spaces";++/** Agent (harness id) to the id of its home Space. */+type Store = Record<string, string>;++let cache: Store | null = null;+const listeners = new Set<() => void>();++function load(): Store {+ if (cache) return cache;+ try {+ const raw = globalThis.localStorage?.getItem(KEY);+ const parsed = raw ? (JSON.parse(raw) as unknown) : {};+ cache = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Store) : {};+ } catch {+ cache = {};+ }+ return cache;+}++function save(next: Store): void {+ cache = next;+ try {+ globalThis.localStorage?.setItem(KEY, JSON.stringify(next));+ } catch {+ // Kept for this session only.+ }+ for (const l of [...listeners]) l();+}++/** The id of the Space that is `agent`'s home, if one was made. */+export function homeSpaceId(agent: string): string | null {+ return load()[agent] ?? null;+}++export function rememberHome(agent: string, spaceId: string): void {+ save({ ...load(), [agent]: spaceId });+}++export function forgetHome(agent: string): void {+ const { [agent]: _gone, ...rest } = load();+ save(rest);+}++/** For tests: forget the cached homes. */+export function resetHomes(): void {+ cache = null;+}++/** Whether `spaceId` is a remembered home. */+export function isHomeSpaceId(spaceId: string): boolean {+ return Object.values(load()).includes(spaceId);+}++/** A Space as the home lookup reads it. */+export type HomeCandidate = Pick<Space, "id" | "status"> & Partial<Pick<Space, "lastUsedAt">>;++/**+ * The home to reuse for `agent` among the listed Spaces: still there and not broken. `fresh` asks for a+ * new one. The one this device remembers wins; with none (a new device, cleared storage) it is a Space+ * the host says is a home (`labelled`: ids from the Spaces' `cua.home` labels, the ones made for `agent`+ * first). A home is therefore found again with no help from this device.+ */+export function reusableHome(agent: string, spaces: readonly HomeCandidate[] | undefined, fresh = false, labelled: readonly string[] = []): string | null {+ if (fresh) return null;+ // A list that doesn't show it any more means it was removed.+ const alive = (id: string) => spaces?.find((s) => s.id === id && s.status !== "deleting");+ const id = homeSpaceId(agent);+ if (id && alive(id)) return id;+ const found = labelled.map(alive).find((s) => s !== undefined);+ return found ? found.id : null;+}++const subscribe = (l: () => void) => {+ listeners.add(l);+ const onStorage = (e: StorageEvent) => {+ if (e.key === null || e.key === KEY) {+ cache = null;+ l();+ }+ };+ globalThis.addEventListener?.("storage", onStorage);+ return () => {+ listeners.delete(l);+ globalThis.removeEventListener?.("storage", onStorage);+ };+};++/** Whether this Space is an agent's home (the Spaces list tags it "Home"). */+export function useIsHomeSpace(spaceId: string): boolean {+ return useSyncExternalStore(subscribe, () => isHomeSpaceId(spaceId), () => false);+}diff --git a/apps/cua-spaces-web/src/lib/agent-home/mentions.ts b/apps/cua-spaces-web/src/lib/agent-home/mentions.tsnew file mode 100644index 0000000000..d4d04fbdef--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/mentions.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Where the person said the job runs, in their own words: an @mention of a+ * Space or a machine, "on my Mac", or "connect to <name>". Anything else is+ * left to the agent, which decides.+ */++import type { HomeMentions } from "./abilities";++export interface Named {+ id: string;+ name: string;+}++export interface Place {+ /** Spaces and machines the person can name. */+ spaces: readonly Named[];+ machines: readonly (Named & { current?: boolean })[];+}++const norm = (s: string) => s.trim().toLowerCase();+/** The first word of a name, without a possessive ("Dillon's MacBook" is "dillon"). */+const firstWord = (s: string) => norm(s.split(/\s+/)[0] ?? "").replace(/['\u2019]s$/, "");++/** Names with spaces in them can be mentioned as `@"spare mac"` or by their first word. */+function mentionTokens(text: string): string[] {+ const out: string[] = [];+ for (const m of text.matchAll(/@"([^"]+)"|@([\w.:-]+)/g)) out.push(m[1] ?? m[2] ?? "");+ return out.filter(Boolean);+}++/** The Spaces and machines a request names. */+export function parseMentions(text: string, place: Place): HomeMentions {+ const spaces = new Map<string, Named>();+ const machines = new Map<string, Named>();+ const by = <T extends Named>(list: readonly T[], t: string) => list.find((x) => norm(x.name) === norm(t) || x.id === t) ?? list.find((x) => firstWord(x.name) === norm(t));+ for (const t of mentionTokens(text)) {+ const machine = by(place.machines, t);+ if (machine) machines.set(machine.id, { id: machine.id, name: machine.name });+ else {+ const space = by(place.spaces, t);+ if (space) spaces.set(space.id, { id: space.id, name: space.name });+ }+ }+ // "on my Mac", "on this Mac", "use my laptop": this machine.+ if (/\bon (my|this) (mac|laptop|machine|computer)\b|\buse my (mac|laptop|machine)\b/i.test(text)) {+ const here = place.machines.find((m) => m.current);+ if (here) machines.set(here.id, { id: here.id, name: here.name });+ }+ // "connect to <name>": a machine or Space by that name.+ for (const m of text.matchAll(/\bconnect to (?:@?"([^"]+)"|@?([\w.:-]+))/gi)) {+ const t = m[1] ?? m[2] ?? "";+ const machine = by(place.machines, t);+ if (machine) machines.set(machine.id, { id: machine.id, name: machine.name });+ else {+ const space = by(place.spaces, t);+ if (space) spaces.set(space.id, { id: space.id, name: space.name });+ }+ }+ return { spaces: [...spaces.values()], machines: [...machines.values()] };+}++/** Whether the person said where (so the agent need not decide). */+export function saidWhere(m: HomeMentions): boolean {+ return m.spaces.length + m.machines.length > 0;+}diff --git a/apps/cua-spaces-web/src/lib/agent-home/prompt.ts b/apps/cua-spaces-web/src/lib/agent-home/prompt.tsnew file mode 100644index 0000000000..e7d5f3a749--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/prompt.ts@@ -0,0 +1,49 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * What the agent is told when it starts in its home: where it is, what it+ * can do, how to ask, and where the job runs if the person said. It is+ * written once for every home; the runtime only supplies the abilities.+ */++import { ABILITY_IDS, type AbilityDescriptor, type AbilityId, type HomeSetup } from "./abilities";++/** The action word on an approval the agent posts to ask for an ability. */+export const approvalAction = (id: AbilityId) => `ability:${id}`;++export function abilityOfAction(action: string): AbilityId | null {+ const id = action.startsWith("ability:") ? action.slice("ability:".length) : "";+ return (ABILITY_IDS as readonly string[]).includes(id) ? (id as AbilityId) : null;+}++/**+ * What the home's agent is told once per run (the host puts it in front of the first message the run takes,+ * so the thread shows only what the person wrote): where it is, what it can do, how to ask.+ */+export function homeBrief(setup: HomeSetup, abilities: readonly AbilityDescriptor[]): string {+ const lines: string[] = [+ "You are working in your own small Linux Space, a home with a shell. It is the root of the tree of Spaces for the person's jobs.",+ "Do each job by making Spaces of the kind it needs (Linux, Windows or macOS) and running the work in them, then report back here. Clean up the Spaces you made when you are done.",+ "",+ "What you can do:",+ ...abilities.map((a) => `- ${a.summary} Run: ${a.call}`),+ "",+ "Before an ability that needs the person's OK, ask in this thread with an approval whose action is the ability, for example",+ `${approvalAction("spaces.list")} (to see all their Spaces) or ${approvalAction("machines.use")} with the computer's name in the details, and wait for the answer. Do not look for another way around a refusal.`,+ ];+ const named = [...setup.mentions.spaces.map((s) => `the Space "${s.name}"`), ...setup.mentions.machines.map((m) => `the computer "${m.name}"`)];+ lines.push("");+ if (named.length) lines.push(`The person named where to run: ${named.join(", ")}. You may use ${named.length === 1 ? "it" : "them"} without asking.`);+ else lines.push("Unless the person says where to run, choose where, and use the least that does the job.");+ if (setup.grants.listAll) lines.push("The person already let you see all their Spaces.");+ return lines.join("\n");+}++export function homePrompt(job: string, setup: HomeSetup, abilities: readonly AbilityDescriptor[], repo?: { url: string; label: string }): string {+ const lines: string[] = [homeBrief(setup, abilities)];+ // The repo is the person's pick in the box: said once, in plain words, so the first thing the agent does is get it.+ if (repo) lines.push(`The person picked the repo ${repo.label} (${repo.url}) for this job. Get it first and work in it.`);+ lines.push("", "The job:", job.trim());+ return lines.join("\n");+}diff --git a/apps/cua-spaces-web/src/lib/agent-home/requests.ts b/apps/cua-spaces-web/src/lib/agent-home/requests.tsnew file mode 100644index 0000000000..650c3e6589--- /dev/null+++ b/apps/cua-spaces-web/src/lib/agent-home/requests.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The agent's requests for abilities, read from its home's thread. An agent+ * asks the way it asks for anything else: an approval entry whose action is+ * `ability:<id>` (see `prompt.ts`). The person answers it on the+ * standard approval card in the home Space's normal thread (`answer.ts`); an answer to "list all" or "use this machine" is remembered for+ * that agent (`grants.ts`) when they say so, and a remembered one is+ * answered at once.+ */++import type { ThreadEntry } from "@/bridge/ops/thread";++import type { AbilityId, AgentGrants } from "./abilities";+import { abilityOfAction } from "./prompt";++export interface AbilityRequest {+ /** The approval entry's seq: what an answer refers to. */+ seq: number;+ ability: AbilityId;+ /** The agent's own words for what it wants ("the Mac mini"). */+ detail: string;+ tsMs: number;+}++/** The ability requests nobody has answered yet, oldest first. */+export function openAbilityRequests(entries: readonly ThreadEntry[]): AbilityRequest[] {+ const answered = new Set(entries.filter((e) => e.kind === "answer" && e.answer).map((e) => e.answer!.approval));+ const out: AbilityRequest[] = [];+ for (const e of entries) {+ if (e.kind !== "approval" || !e.approval || answered.has(e.seq)) continue;+ const ability = abilityOfAction(e.approval.action);+ if (ability) out.push({ seq: e.seq, ability, detail: e.approval.details.trim(), tsMs: e.tsMs });+ }+ return out.sort((a, b) => a.seq - b.seq);+}++/** Whether what the agent holds already covers this request (so no question is needed). */+export function covered(req: AbilityRequest, grants: AgentGrants, machineIds: ReadonlyMap<string, string>): boolean {+ if (req.ability === "spaces.spawn") return true;+ if (req.ability === "spaces.list") return grants.listAll;+ // `machines.use`: the machine the agent named, matched by name or id.+ const named = req.detail.toLowerCase();+ for (const [id, name] of machineIds) {+ if (grants.machines.includes(id) && (named.includes(name.toLowerCase()) || named.includes(id.toLowerCase()))) return true;+ }+ return false;+}++/** The question the person is asked, in plain words. */+export function askText(req: AbilityRequest, machineName: string | null): { title: string; detail: string; allow: string } {+ switch (req.ability) {+ case "spaces.list":+ return { title: "Let this agent see all your Spaces?", detail: "Until you say yes it only sees the Spaces you @mention. It can look at them, not change them.", allow: "Allow" };+ case "machines.use":+ return { title: machineName ? `Let this agent use ${machineName}?` : "Let this agent use this computer?", detail: req.detail || "It will put work on that computer.", allow: "Allow" };+ default:+ return { title: "Let this agent make a Space?", detail: req.detail, allow: "Allow" };+ }+}diff --git a/apps/cua-spaces-web/src/lib/ask-first-model.test.ts b/apps/cua-spaces-web/src/lib/ask-first-model.test.tsnew file mode 100644index 0000000000..53ca8281cd--- /dev/null+++ b/apps/cua-spaces-web/src/lib/ask-first-model.test.ts@@ -0,0 +1,97 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { beforeEach, describe, expect, it } from "vitest";++import type { AgentAccount, AgentGroup, AgentsView } from "@/bridge";++import { agentLine, pickAccount, pickedAgent, pickOf, rememberAgent, resetPickedAgent, resolveAgent } from "./ask-first-model";++const account = (line: string, extra: Partial<AgentAccount> = {}): AgentAccount => ({+ provider: "anthropic",+ providerLabel: "Anthropic",+ icon: "anthropic",+ env: "CLAUDE_CODE_OAUTH_TOKEN",+ slot: null,+ line,+ via: "sign-in",+ selected: false,+ models: [+ { id: "haiku", label: "Claude Haiku 4.5", fast: true, default: false },+ { id: "sonnet", label: "Claude Sonnet 5", fast: false, default: true },+ ],+ defaultModel: "haiku",+ ...extra,+});+const group = (app: string, accounts: AgentAccount[], extra: Partial<AgentGroup> = {}): AgentGroup => ({+ harness: app === "codex" ? "openai-codex" : app,+ app,+ label: app === "codex" ? "OpenAI Codex" : app === "claude-code" ? "Claude Code" : app,+ state: accounts.length ? "connected" : "not-connected",+ accounts,+ signInLabel: "Sign in",+ ...extra,+});+const claude = group("claude-code", [account("personal", { selected: true }), account("work Max", { slot: "work" }), account("side Max", { slot: "side" })]);+const view = (groups: AgentGroup[]): AgentsView => ({+ groups,+ default: null,+ empty: null,+});++beforeEach(() => {+ localStorage.clear();+ resetPickedAgent();+});++describe("the agent the box starts with", () => {+ it("is the first connected app with its own account and quick model when nothing was picked", () => {+ const v = { ...view([group("codex", []), claude]), default: { harness: "claude-code", provider: "anthropic", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: null, model: "haiku" } };+ const s = resolveAgent(v, null)!;+ expect(s.harness).toBe("claude-code");+ expect(agentLine(s)).toBe("Claude Code");+ expect(s.model.id).toBe("haiku");+ });++ it("is the last pick while that app and account are still there, with its model", () => {+ const s = resolveAgent(view([claude]), { harness: "claude-code", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: "work", model: "sonnet" })!;+ expect(agentLine(s)).toBe("Claude Code");+ expect(s.account.line).toBe("work Max");+ expect(s.model.id).toBe("sonnet");+ });++ it("never uses a remembered account that is gone: the app's own choice stands in", () => {+ const s = resolveAgent(view([claude]), { harness: "claude-code", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: "removed", model: "sonnet" })!;+ expect(agentLine(s)).toBe("Claude Code");+ expect(s.account.line).toBe("personal");+ // The model it remembered is kept while the account offers it.+ expect(s.model.id).toBe("sonnet");+ });++ it("falls back to the default when the remembered app is no longer connected, and to nothing when none is", () => {+ const v = { ...view([group("codex", []), claude]), default: { harness: "claude-code", provider: "anthropic", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: null, model: "haiku" } };+ expect(resolveAgent(v, { harness: "openai-codex", env: "CODEX_AUTH_JSON" })!.harness).toBe("claude-code");+ expect(resolveAgent(view([group("codex", [])]), null)).toBeNull();+ expect(resolveAgent(null, null)).toBeNull();+ });++ it("picking an account starts with its quick model, or the last model while it offers it", () => {+ const work = claude.accounts[1]!;+ expect(pickAccount(claude, work, null)).toEqual({ harness: "claude-code", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: "work", model: "haiku" });+ expect(pickAccount(claude, work, { harness: "claude-code", model: "sonnet" }).model).toBe("sonnet");+ expect(pickAccount(claude, work, { harness: "openai-codex", model: "sonnet" }).model).toBe("haiku");+ });+});++describe("the last pick, kept on this computer", () => {+ it("is read back, and a malformed one is ignored", () => {+ expect(pickedAgent()).toBeNull();+ const s = resolveAgent(view([claude]), { harness: "claude-code", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: "side", model: "haiku" })!;+ rememberAgent(pickOf(s));+ resetPickedAgent();+ expect(pickedAgent()).toEqual({ harness: "claude-code", model: "haiku", env: "CLAUDE_CODE_OAUTH_TOKEN", slot: "side" });+ localStorage.setItem("cua.askFirst.agent", "{not json");+ resetPickedAgent();+ expect(pickedAgent()).toBeNull();+ });+});diff --git a/apps/cua-spaces-web/src/lib/ask-first-model.ts b/apps/cua-spaces-web/src/lib/ask-first-model.tsnew file mode 100644index 0000000000..1f6325aea3--- /dev/null+++ b/apps/cua-spaces-web/src/lib/ask-first-model.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The agent the ask box starts a task with: a coding app, one of the+ * accounts (sign-ins) the person has for it and, when the account offers a+ * choice, a model. What each app can run on is the core's+ * (`connectors.agents`); this finds the last pick again and names it.+ *+ * What is kept: the account is the app's own choice, saved by the host+ * (`agentKeys.use`) so it outlives the page and is the one a run uses; the+ * app and the model are kept on this computer. A remembered account that+ * is no longer saved is never used: the app's own choice, else its first+ * account, stands in. With nothing remembered, the first connected app.+ */++import { useSyncExternalStore } from "react";++import type { AgentAccount, AgentGroup, AgentsView, ModelChoice } from "@/bridge";++/** What was picked: an app and, when the person chose, its account and model. */+export interface PickedAgent {+ harness: string;+ model?: string;+ env?: string;+ slot?: string;+}++/** A pick with the rows it names. */+export interface AgentSelection {+ group: AgentGroup;+ account: AgentAccount;+ model: ModelChoice;+ /** The harness id a run uses. */+ harness: string;+}++const sameAccount = (a: AgentAccount, p: { env?: string; slot?: string | null }) => a.env === p.env && (a.slot ?? null) === (p.slot ?? null);++/** The account an app runs with: the remembered one while it is still saved, else the app's own choice, else its first. */+function accountOf(group: AgentGroup, p: PickedAgent | null): AgentAccount | null {+ const remembered = p?.harness === group.harness && p.env ? group.accounts.find((a) => sameAccount(a, p)) : undefined;+ return remembered ?? group.accounts.find((a) => a.selected) ?? group.accounts[0] ?? null;+}++function select(group: AgentGroup | undefined, p: PickedAgent | null, wanted?: string | null): AgentSelection | null {+ if (!group || group.state !== "connected") return null;+ const account = accountOf(group, p);+ if (!account) return null;+ const id = [wanted, p?.harness === group.harness ? p.model : undefined].find((m) => m && account.models.some((x) => x.id === m)) ?? account.defaultModel;+ const model = account.models.find((m) => m.id === id) ?? account.models[0];+ return model ? { group, account, model, harness: group.harness } : null;+}++/**+ * The agent to start with: the person's last pick while it is still offered, else the first connected app+ * (the menu's order) with its own account and quick model, else nothing.+ */+export function resolveAgent(view: AgentsView | null | undefined, picked: PickedAgent | null): AgentSelection | null {+ if (!view) return null;+ const last = picked ? select(view.groups.find((g) => g.harness === picked.harness), picked) : null;+ if (last) return last;+ const d = view.default;+ return d ? select(view.groups.find((g) => g.harness === d.harness), { harness: d.harness, env: d.env, ...(d.slot ? { slot: d.slot } : {}) }, d.model) : null;+}++/** What picking `account` of `group` starts with: that account and its quick model (the last model while it is offered). */+export function pickAccount(group: AgentGroup, account: AgentAccount, picked: PickedAgent | null): PickedAgent {+ const keep = picked?.harness === group.harness && picked.model && account.models.some((m) => m.id === picked.model) ? picked.model : account.defaultModel;+ return { harness: group.harness, env: account.env, ...(account.slot ? { slot: account.slot } : {}), ...(keep ? { model: keep } : {}) };+}++/** The pick as the chip says it: just the app ("Claude Code"). The account is chosen inside the menu. */+export const agentLine = (s: AgentSelection) => s.group.label;++/** The pick to remember for a selection. */+export const pickOf = (s: AgentSelection): PickedAgent => ({ harness: s.harness, model: s.model.id, env: s.account.env, ...(s.account.slot ? { slot: s.account.slot } : {}) });++/* ---- the last pick, per computer ---- */++const KEY = "cua.askFirst.agent";+let cache: PickedAgent | null | undefined;+const listeners = new Set<() => void>();++function load(): PickedAgent | null {+ if (cache !== undefined) return cache;+ try {+ const raw = globalThis.localStorage?.getItem(KEY);+ const v = raw ? (JSON.parse(raw) as Partial<PickedAgent>) : null;+ cache =+ v && typeof v.harness === "string"+ ? {+ harness: v.harness,+ ...(typeof v.model === "string" ? { model: v.model } : {}),+ ...(typeof v.env === "string" ? { env: v.env } : {}),+ ...(typeof v.slot === "string" ? { slot: v.slot } : {}),+ }+ : null;+ } catch {+ cache = null;+ }+ return cache;+}++export function pickedAgent(): PickedAgent | null {+ return load();+}++export function rememberAgent(p: PickedAgent): void {+ cache = p;+ try {+ globalThis.localStorage?.setItem(KEY, JSON.stringify(p));+ } catch {+ // Kept for this session only.+ }+ for (const l of [...listeners]) l();+}++/** For tests: forget the cached pick. */+export function resetPickedAgent(): void {+ cache = undefined;+}++const subscribe = (l: () => void) => {+ listeners.add(l);+ return () => listeners.delete(l);+};++/** The last picked agent (re-renders when it changes). */+export function usePickedAgent(): PickedAgent | null {+ return useSyncExternalStore(subscribe, load, () => null);+}diff --git a/apps/cua-spaces-web/src/lib/ask-first-repo.test.ts b/apps/cua-spaces-web/src/lib/ask-first-repo.test.tsnew file mode 100644index 0000000000..afe864dfb1--- /dev/null+++ b/apps/cua-spaces-web/src/lib/ask-first-repo.test.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { beforeEach, describe, expect, it } from "vitest";++import { chooseRepo, clearRepo, parseRepo, resetRepos } from "./ask-first-repo";++const repo = (url: string, label: string) => ({ url, label });++describe("what a typed repo means", () => {+ it("reads owner/name, links to the repo or to one of its pages, and ssh links", () => {+ const want = repo("https://github.com/trycua/demo-failing-tests", "trycua/demo-failing-tests");+ expect(parseRepo("trycua/demo-failing-tests")).toEqual(want);+ expect(parseRepo(" https://github.com/trycua/demo-failing-tests ")).toEqual(want);+ expect(parseRepo("https://github.com/trycua/demo-failing-tests.git")).toEqual(want);+ expect(parseRepo("github.com/trycua/demo-failing-tests")).toEqual(want);+ expect(parseRepo("https://github.com/trycua/demo-failing-tests/pull/12")).toEqual(want);+ expect(parseRepo("https://github.com/trycua/demo-failing-tests/tree/main/tests?x=1")).toEqual(want);+ expect(parseRepo("[email protected]:trycua/demo-failing-tests.git")).toEqual(want);+ expect(parseRepo("https://gitlab.com/group/project")).toEqual(repo("https://gitlab.com/group/project", "group/project"));+ });++ it("refuses what is not a repo", () => {+ for (const bad of ["", " ", "trycua", "a b/c", "https://github.com/trycua", "trycua/..", "../etc/passwd", "ftp://x", "just some words about a repo"]) {+ expect(parseRepo(bad), bad).toBeNull();+ }+ });+});++describe("the repo of the next task", () => {+ beforeEach(() => {+ localStorage.clear();+ resetRepos();+ });++ it("is kept, with the ones used lately newest first and each once, until it is removed", () => {+ chooseRepo(repo("https://github.com/a/one", "a/one"));+ chooseRepo(repo("https://github.com/b/two", "b/two"));+ chooseRepo(repo("https://github.com/a/one", "a/one"));+ const saved = JSON.parse(localStorage.getItem("cua.askFirst.repos")!);+ expect(saved.current.label).toBe("a/one");+ expect(saved.recent.map((r: { label: string }) => r.label)).toEqual(["a/one", "b/two"]);+ clearRepo();+ const after = JSON.parse(localStorage.getItem("cua.askFirst.repos")!);+ expect(after.current).toBeNull();+ expect(after.recent).toHaveLength(2);+ });++ it("keeps five", () => {+ for (let i = 0; i < 8; i++) chooseRepo(repo(`https://github.com/o/r${i}`, `o/r${i}`));+ expect(JSON.parse(localStorage.getItem("cua.askFirst.repos")!).recent).toHaveLength(5);+ });+});diff --git a/apps/cua-spaces-web/src/lib/ask-first-repo.ts b/apps/cua-spaces-web/src/lib/ask-first-repo.tsnew file mode 100644index 0000000000..74b87f2ae4--- /dev/null+++ b/apps/cua-spaces-web/src/lib/ask-first-repo.ts@@ -0,0 +1,110 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The repo chip's data: what a pasted link or `owner/name` means, and the+ * repos used lately (kept on this computer). Only the shape is checked here;+ * whether the repo can be read is the host's to say once a GitHub+ * connection holds the access (a private repo cannot be probed without it).+ */++import { useSyncExternalStore } from "react";++/** A repo a task starts from. */+export interface AskRepo {+ /** The clone URL, always https. */+ url: string;+ /** What the chip shows: `owner/name`. */+ label: string;+}++const NAME = "[A-Za-z0-9_.-]+";++/**+ * A repo from what was typed: `owner/name`, `github.com/owner/name`, an+ * https link to a repo or to one of its pages (an issue, a pull request, a+ * folder), or an ssh link. Null for anything else.+ */+export function parseRepo(input: string): AskRepo | null {+ const t = input.trim();+ if (!t || /\s/.test(t)) return null;+ const short = new RegExp(`^(${NAME})/(${NAME})$`).exec(t);+ if (short && !t.includes("..")) return repo("github.com", short[1]!, short[2]!);+ const ssh = new RegExp(`^git@([A-Za-z0-9.-]+):(${NAME})/(${NAME})$`).exec(t);+ if (ssh) return repo(ssh[1]!, ssh[2]!, ssh[3]!);+ const web = new RegExp(`^(?:https?://)?([A-Za-z0-9.-]+\\.[A-Za-z]{2,})/(${NAME})/(${NAME})(?:[/?#].*)?$`).exec(t);+ if (web) return repo(web[1]!.toLowerCase(), web[2]!, web[3]!);+ return null;+}++function repo(host: string, owner: string, name: string): AskRepo | null {+ const clean = name.replace(/\.git$/, "");+ if (!owner || !clean || owner === "." || clean === "." || clean.startsWith("..")) return null;+ return { url: `https://${host}/${owner}/${clean}`, label: `${owner}/${clean}` };+}++/* ---- the repo of the next task, and the ones used lately ---- */++const KEY = "cua.askFirst.repos";+const RECENT = 5;++interface Saved {+ /** The repo the next task starts from (kept until removed). */+ current: AskRepo | null;+ recent: AskRepo[];+}++let cache: Saved | undefined;+const listeners = new Set<() => void>();++function load(): Saved {+ if (cache) return cache;+ try {+ const raw = globalThis.localStorage?.getItem(KEY);+ const v = raw ? (JSON.parse(raw) as Partial<Saved>) : {};+ const ok = (r: unknown): r is AskRepo => !!r && typeof (r as AskRepo).url === "string" && typeof (r as AskRepo).label === "string";+ cache = { current: ok(v.current) ? v.current : null, recent: (Array.isArray(v.recent) ? v.recent : []).filter(ok).slice(0, RECENT) };+ } catch {+ cache = { current: null, recent: [] };+ }+ return cache;+}++function save(next: Saved): void {+ cache = next;+ try {+ globalThis.localStorage?.setItem(KEY, JSON.stringify(next));+ } catch {+ // Kept for this session only.+ }+ for (const l of [...listeners]) l();+}++/** Picks `r` for the next task and puts it first among the recent ones. */+export function chooseRepo(r: AskRepo): void {+ const s = load();+ save({ current: r, recent: [r, ...s.recent.filter((x) => x.url !== r.url)].slice(0, RECENT) });+}++/** Takes the repo off the next task (it stays among the recent ones). */+export function clearRepo(): void {+ save({ ...load(), current: null });+}++/** For tests: forget everything kept. */+export function resetRepos(): void {+ cache = undefined;+}++const subscribe = (l: () => void) => {+ listeners.add(l);+ return () => listeners.delete(l);+};++const snapshot = () => load();+const empty: Saved = { current: null, recent: [] };++/** The repo of the next task and the recent ones (re-renders when they change). */+export function useRepos(): Saved {+ return useSyncExternalStore(subscribe, snapshot, () => empty);+}diff --git a/apps/cua-spaces-web/src/lib/ask-first.ts b/apps/cua-spaces-web/src/lib/ask-first.tsindex 45f3002053..8a47d24072 100644--- a/apps/cua-spaces-web/src/lib/ask-first.ts+++ b/apps/cua-spaces-web/src/lib/ask-first.ts@@ -44,6 +44,13 @@ export interface AskTask {transcript: TranscriptItem[] | null;/** The status the run last had, for a thrown-away task's line. */lastStatus: AgentRunStatus | null;+ /**+ * The Space is an agent home (CUA-2630): the root of this task's tree, where+ * the agent decides where to run. Absent on tasks made before it.+ */+ home?: boolean;+ /** Names the person gave as where to run (@mentions, "on my Mac"), for the thread's first line. */+ named?: string[];/** It runs on this Mac itself (its own Space id is in `spaceId`): nothing to throw away. */onHost?: boolean;/** Started in its Space's thread: the job is the Space's first message, @mentioning the agent. */@@ -56,6 +63,10 @@ export interface AskTask {* this device's user. The first message the person sends resumes it.*/imported?: ImportedChat;+ /** The model the person picked (its id), when they did. */+ model?: string;+ /** The repo the task starts from, when one was chosen. */+ repo?: { url: string; label: string };}/** Which of the agent's own chats a task continues. */@@ -210,8 +221,19 @@ export function taskTitle(prompt: string, max = 80): string {return [...line].length <= max ? line : `${[...line].slice(0, max - 1).join("").trimEnd()}…`;}-/** Where the job runs, as picked: a new computer of a kind on this Mac, a Space you already have, or this Mac itself. */-export type TaskWhere = { kind: "new"; os: SpaceOs } | { kind: "space"; space: Space } | { kind: "this-mac" };+/**+ * Where the job runs, as picked: a new computer of a kind on this Mac, a Space+ * you already have, or this Mac itself. With the Child Spaces experiment on+ * (agent homes, CUA-2630) the agent may also decide (`agent`: it starts in its+ * own home Space and makes what the job needs) or be told one of your machines+ * (`machine`).+ */+export type TaskWhere =+ | { kind: "new"; os: SpaceOs }+ | { kind: "space"; space: Space }+ | { kind: "this-mac" }+ | { kind: "agent"; fresh?: boolean }+ | { kind: "machine"; machine: { id: string; name: string } };/*** What `agents.start` is pointed at. The core's `agent_start` only takes a@@ -249,12 +271,15 @@ export function hostSpaceId(status: Pick<HostStatus, "configured" | "mode" | "ma}export function taskTarget(where: TaskWhere): TaskTarget {+ // An agent home is a Linux Space made for the task (`useStartTask` decides whether it is a home).+ if (where.kind === "agent" || where.kind === "machine") return { kind: "create", os: "linux" };if (where.kind === "new") return { kind: "create", os: where.os };if (where.kind === "this-mac" || where.space.id === THIS_MAC_ID) return { kind: "host" };return { kind: "space", spaceId: where.space.id };}-export const whereOs = (where: TaskWhere): SpaceOs => (where.kind === "new" ? where.os : where.kind === "space" ? where.space.os : "macos");+export const whereOs = (where: TaskWhere): SpaceOs =>+ where.kind === "new" ? where.os : where.kind === "space" ? where.space.os : where.kind === "agent" || where.kind === "machine" ? "linux" : "macos";/** A kept task's target, for Try again: its computer if it has one (the row, when listed, decides), else a new one. */export function retryTarget(task: Pick<AskTask, "spaceId" | "os" | "onHost">): TaskTarget {@@ -284,7 +309,7 @@ export function defaultWhere(kinds: readonly NewKind[]): TaskWhere {/** The pick if it's still offered, else the default (a picked Space that went away falls back). */export function currentWhere(picked: TaskWhere | null, kinds: readonly NewKind[], spaces: readonly Space[]): TaskWhere {- if (picked?.kind === "this-mac") return picked;+ if (picked?.kind === "this-mac" || picked?.kind === "agent" || picked?.kind === "machine") return picked;if (picked?.kind === "new" && kinds.some((k) => k.os === picked.os && !k.blocked)) return picked;if (picked?.kind === "space") {const row = spaces.find((s) => s.id === picked.space.id);@@ -411,6 +436,16 @@ export const TASK_STATE_TEXT: Record<TaskState, string> = {thrown: "Done. Computer thrown away",};+/** The same states for a task in an agent home: its Space is a home, not a computer made for the job. */+export const TASK_STATE_TEXT_HOME: Partial<Record<TaskState, string>> = {+ starting: "Getting its home ready",+ kept: "Done. Home kept",+ thrown: "Done. Home thrown away",+};++/** A task's state line. */+export const taskStateText = (state: TaskState, task: Pick<AskTask, "home">): string => (task.home ? TASK_STATE_TEXT_HOME[state] : undefined) ?? TASK_STATE_TEXT[state];+/** Home's order: needs you first, then running, then the rest, newest first. */export function orderTasks<T extends { state: TaskState; task: AskTask }>(rows: T[]): T[] {const rank = (s: TaskState) => (s === "needs-you" || s === "stuck" ? 0 : s === "working" || s === "starting" ? 1 : 2);@@ -420,10 +455,10 @@ export function orderTasks<T extends { state: TaskState; task: AskTask }>(rows:/** The jobs offered on an empty Home: real dev work where a fresh computer matters. */export const SUGGESTIONS: { title: string; detail: string; os: SpaceOs; prompt: string }[] = [{- title: "Run my project's tests on a clean Linux computer",- detail: "Find out if it works on a computer that has never seen your code.",+ title: "Run my project's tests on a clean Linux Space",+ detail: "Find out if it works somewhere that has never seen your code.",os: "linux",- prompt: "Copy my project onto this machine, install what it needs and run its tests. Tell me what passed and what failed: ",+ prompt: "Get my project, make a clean Linux Space for it, install what it needs and run its tests. Tell me what passed and what failed: ",},{title: "Try a pull request before merging",@@ -433,8 +468,8 @@ export const SUGGESTIONS: { title: string; detail: string; os: SpaceOs; prompt:},{title: "Check my site works on Safari",- detail: "It clicks through your pages on a Mac and shows you what looks wrong.",+ detail: "It clicks through your pages on a macOS Space and shows you what looks wrong.",os: "macos",- prompt: "Open my site in Safari, click through the main pages and tell me what looks or works wrong: ",+ prompt: "Make a macOS Space, open my site in Safari, click through the main pages and tell me what looks or works wrong: ",},];diff --git a/libs/cua/crates/cua-daemon/src/children/api.rs b/libs/cua/crates/cua-daemon/src/children/api.rsindex 7eeaec7e28..cab1ea6201 100644--- a/libs/cua/crates/cua-daemon/src/children/api.rs+++ b/libs/cua/crates/cua-daemon/src/children/api.rs@@ -113,12 +113,50 @@ impl Scoped {.into_iter().filter(|r| below.contains(&r.id)).collect();- for r in &mut records {+ self.fill(&mut records);+ Ok(records)+ }++ /// Power, stop reason and the rest of a record's live fields.+ fn fill(&self, records: &mut [pb::Space]) {+ for r in records.iter_mut() {(r.power, r.power_state) = self.spaces().power_of(&r.id);r.stop_reason = self.spaces().stop_reason_of(&r.id);}- self.spaces().fill_records(&mut records);- crate::spaces_svc::imp::mark_children(self.spaces(), &mut records);+ self.spaces().fill_records(records);+ crate::spaces_svc::imp::mark_children(self.spaces(), records);+ }++ /// What an agent home reaches beyond its tree (none for any other Space).+ fn home_scope(&self) -> super::home::HomeScope {+ // What the home was made with, plus what the person approved since.+ self.own_meta()+ .map(|m| super::home::HomeScope::from_labels(&m.labels))+ .unwrap_or_default()+ .with_grants(super::home::read_grants(+ self.spaces().home_dir(),+ &self.space,+ ))+ }++ /// The Spaces outside the caller's subtree that an agent home may see:+ /// the ones the person @mentioned, or all once the person approved+ /// listing all. Read only: they are never resolved by the calls that+ /// change or connect to a Space.+ fn granted_records(&self, seen: &[pb::Space]) -> Result<Vec<pb::Space>, Status> {+ let scope = self.home_scope();+ if !scope.is_home {+ return Ok(Vec::new());+ }+ let mut records: Vec<pb::Space> = self+ .spaces()+ .registry()+ .list()+ .map_err(|e| Status::internal(e.to_string()))?+ .into_iter()+ .filter(|r| !seen.iter().any(|s| s.id == r.id) && scope.may_list(&r.id, &r.name))+ .collect();+ self.fill(&mut records);Ok(records)}@@ -206,6 +244,17 @@ impl Scoped {)));}}+ // An agent home puts children on the person's computers only where+ // the person said so (an approval, or an @mention).+ if let On::Host(machine) = &on {+ let scope = self.home_scope();+ if scope.is_home && !scope.may_use_machine(machine) {+ return Err(refused(&format!(+ "use the computer {machine:?} once the person lets this agent use it \+ (ask them, or have them @mention it); for now it can make children here or with `auto`"+ )));+ }+ }r.location = on.to_string();let local = matches!(on, On::Local);if r.reuse {@@ -549,8 +598,11 @@ impl SpaceService for Scoped {}async fn list_spaces(&self, _: Request<pb::ListSpacesRequest>) -> R<pb::ListSpacesResponse> {+ let mut spaces = self.subtree_records()?;+ let granted = self.granted_records(&spaces)?;+ spaces.extend(granted);Ok(Response::new(pb::ListSpacesResponse {- spaces: self.subtree_records()?,+ spaces,..Default::default()}))}diff --git a/libs/cua/crates/cua-daemon/src/children/home.rs b/libs/cua/crates/cua-daemon/src/children/home.rsnew file mode 100644index 0000000000..6972bd0829--- /dev/null+++ b/libs/cua/crates/cua-daemon/src/children/home.rs@@ -0,0 +1,323 @@+//! The agent home's abilities, as this host enforces them.+//!+//! An agent home is a Space made on a person's first ask-first request and+//! reused by the next ones (image `linux:24.04-slim`): the root of their+//! tree of Spaces. It starts with the+//! narrowest reach there is, its own children, and the person widens it one+//! ability at a time:+//!+//! - **list Spaces** ([`Ability::ListSpaces`]): the Spaces the person+//! @mentioned by name, or every Space once the person approved listing all;+//! - **spawn a child** ([`Ability::SpawnChild`]): always on for a home (the+//! spawn capability, inside the tree's budget); it cannot widen what a+//! child gets;+//! - **use a machine** ([`Ability::UseMachine`]): put a child on one of the+//! person's machines (`host:<name>`), only the ones granted.+//!+//! The grants ride on the home's record as `cua.home.*` labels, written by+//! the host when it makes the home (a grant remembered for the agent, or an+//! @mention, is known by then). Labels starting with `cua.` cannot be set+//! by a Space on a child ([`super::api::Scoped::child_request`]), so a home+//! cannot hand its own reach on or widen it.+//!+//! A grant the person gives while the home runs (list all, use a machine)+//! is written by the app to `<cua home>/agent-home/grants.json`, outside+//! the home, and read with [`read_grants`] each time the home asks, so it+//! takes effect at once ([`HomeScope::with_grants`]). Only the app, on this+//! machine, writes it: the agent in the home cannot. A Space or machine the+//! person @mentions in a later request to the same home is written there as+//! a `mentions` entry: an @mention counts as the grant, with no card.+//!+//! [`HomeScope`] is the whole decision, pure and free of the runtime, so a+//! different home (a wasm module, say) answers the same abilities with the+//! same checks: see `AgentHomeCapabilities` in the web UI's+//! `lib/agent-home` for the interface the agent sees.++use std::collections::{BTreeMap, BTreeSet};+use std::path::{Path, PathBuf};++/// Marks a Space as an agent home.+pub const LABEL_HOME: &str = "cua.home";+/// The agent (harness id) the home was made for; grants are remembered per agent.+pub const LABEL_AGENT: &str = "cua.home.agent";+/// `all` once the person approved listing every Space; absent or `mentions` otherwise.+pub const LABEL_LIST: &str = "cua.home.list";+/// The Spaces the person @mentioned (ids or names, comma separated).+pub const LABEL_MENTIONS: &str = "cua.home.mentions";+/// The machines the agent may use (ids or names, comma separated).+pub const LABEL_MACHINES: &str = "cua.home.machines";++/// Where the app writes what the person approved while a home runs.+pub fn grants_path(cua_home: &Path) -> PathBuf {+ cua_home.join("agent-home").join("grants.json")+}++/// What the person approved for one home while it runs.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct Grants {+ pub list_all: bool,+ pub machines: BTreeSet<String>,+ /// Spaces and machines the person @mentioned in a request to this home+ /// after it was made (ids or names): the same as naming them when it+ /// was made. An @mention counts as the grant, so no card asks.+ pub mentions: BTreeSet<String>,+}++fn string_set(v: Option<&serde_json::Value>) -> BTreeSet<String> {+ v.and_then(|v| v.as_array())+ .map(|a| {+ a.iter()+ .filter_map(|m| m.as_str())+ .map(str::trim)+ .filter(|m| !m.is_empty())+ .map(str::to_owned)+ .collect()+ })+ .unwrap_or_default()+}++/// The grants kept for `space` (none when there is no file, no entry or it+/// does not read: a home then has what its labels gave it).+pub fn read_grants(cua_home: &Path, space: &str) -> Grants {+ let Ok(text) = std::fs::read_to_string(grants_path(cua_home)) else {+ return Grants::default();+ };+ let Ok(all) = serde_json::from_str::<serde_json::Value>(&text) else {+ return Grants::default();+ };+ let Some(entry) = all.get(space) else {+ return Grants::default();+ };+ Grants {+ list_all: entry.get("list_all").and_then(|v| v.as_bool()) == Some(true),+ machines: string_set(entry.get("machines")),+ mentions: string_set(entry.get("mentions")),+ }+}++/// What an agent home can ask for.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Ability {+ ListSpaces,+ SpawnChild,+ UseMachine,+}++/// What one agent home may reach beyond its own tree.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct HomeScope {+ /// The Space is an agent home. Any other Space is unchanged by this module.+ pub is_home: bool,+ /// The agent that runs in it.+ pub agent: String,+ /// The person approved listing every Space.+ pub list_all: bool,+ /// Spaces named (@mentioned): listable, whatever `list_all` says.+ pub mentions: BTreeSet<String>,+ /// Machines the agent may place children on.+ pub machines: BTreeSet<String>,+}++fn words(v: Option<&String>) -> BTreeSet<String> {+ v.map(|s| {+ s.split(',')+ .map(|w| w.trim().to_owned())+ .filter(|w| !w.is_empty())+ .collect()+ })+ .unwrap_or_default()+}++impl HomeScope {+ /// Reads a Space's labels. A Space without `cua.home` is no home.+ pub fn from_labels(labels: &BTreeMap<String, String>) -> Self {+ if labels.get(LABEL_HOME).map(String::as_str) != Some("1") {+ return Self::default();+ }+ Self {+ is_home: true,+ agent: labels.get(LABEL_AGENT).cloned().unwrap_or_default(),+ list_all: labels.get(LABEL_LIST).map(String::as_str) == Some("all"),+ mentions: words(labels.get(LABEL_MENTIONS)),+ machines: words(labels.get(LABEL_MACHINES)),+ }+ }++ /// The labels a host puts on a new home (the inverse of [`Self::from_labels`]).+ pub fn to_labels(&self) -> BTreeMap<String, String> {+ let mut l = BTreeMap::new();+ if !self.is_home {+ return l;+ }+ l.insert(LABEL_HOME.into(), "1".into());+ if !self.agent.is_empty() {+ l.insert(LABEL_AGENT.into(), self.agent.clone());+ }+ if self.list_all {+ l.insert(LABEL_LIST.into(), "all".into());+ }+ if !self.mentions.is_empty() {+ l.insert(LABEL_MENTIONS.into(), join(&self.mentions));+ }+ if !self.machines.is_empty() {+ l.insert(LABEL_MACHINES.into(), join(&self.machines));+ }+ l+ }++ /// Adds what the person approved while the home runs. It only widens a+ /// home that is one.+ pub fn with_grants(mut self, g: Grants) -> Self {+ if self.is_home {+ self.list_all |= g.list_all;+ self.machines.extend(g.machines);+ self.mentions.extend(g.mentions);+ }+ self+ }++ /// May the home see this Space (outside its own tree) in a listing?+ pub fn may_list(&self, id: &str, name: &str) -> bool {+ self.is_home+ && (self.list_all || self.mentions.contains(id) || self.mentions.contains(name))+ }++ /// May the home put a child on this machine? A machine named in+ /// `machines` or @mentioned counts as granted.+ pub fn may_use_machine(&self, machine: &str) -> bool {+ self.is_home && (self.machines.contains(machine) || self.mentions.contains(machine))+ }++ /// Whether `ability` is available at all with no further question+ /// (spawning is; listing everything and machines are not).+ pub fn has(&self, ability: Ability) -> bool {+ match ability {+ Ability::SpawnChild => self.is_home,+ Ability::ListSpaces => self.is_home && self.list_all,+ Ability::UseMachine => self.is_home && !self.machines.is_empty(),+ }+ }+}++fn join(s: &BTreeSet<String>) -> String {+ s.iter().cloned().collect::<Vec<_>>().join(",")+}++#[cfg(test)]+mod tests {+ use super::*;++ fn labels(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {+ pairs+ .iter()+ .map(|(k, v)| ((*k).into(), (*v).into()))+ .collect()+ }++ #[test]+ fn a_space_without_the_mark_is_no_home() {+ let s = HomeScope::from_labels(&labels(&[(LABEL_LIST, "all")]));+ assert!(!s.is_home && !s.may_list("a", "a") && !s.has(Ability::SpawnChild));+ }++ #[test]+ fn a_new_home_sees_only_what_is_mentioned() {+ let s = HomeScope::from_labels(&labels(&[+ (LABEL_HOME, "1"),+ (LABEL_MENTIONS, "studio, local:ci"),+ ]));+ assert!(s.is_home);+ assert!(s.may_list("x", "studio") && s.may_list("local:ci", "whatever"));+ assert!(!s.may_list("other", "other"));+ assert!(!s.has(Ability::ListSpaces));+ }++ #[test]+ fn listing_all_is_the_persons_approval() {+ let s = HomeScope::from_labels(&labels(&[(LABEL_HOME, "1"), (LABEL_LIST, "all")]));+ assert!(s.may_list("any", "any") && s.has(Ability::ListSpaces));+ }++ #[test]+ fn a_machine_needs_a_grant_or_a_mention() {+ let s = HomeScope::from_labels(&labels(&[+ (LABEL_HOME, "1"),+ (LABEL_MACHINES, "my-mac"),+ (LABEL_MENTIONS, "spare"),+ ]));+ assert!(s.may_use_machine("my-mac") && s.may_use_machine("spare"));+ assert!(!s.may_use_machine("other"));+ }++ #[test]+ fn a_grant_given_while_it_runs_widens_a_home_and_only_a_home() {+ let home = HomeScope::from_labels(&labels(&[(LABEL_HOME, "1")]));+ let g = Grants {+ list_all: true,+ machines: ["my-mac".to_owned()].into(),+ ..Default::default()+ };+ let s = home.with_grants(g.clone());+ assert!(s.may_list("any", "any") && s.may_use_machine("my-mac"));+ let plain = HomeScope::default().with_grants(g);+ assert!(+ !plain.is_home && !plain.may_list("any", "any") && !plain.may_use_machine("my-mac")+ );+ }++ #[test]+ fn the_grants_file_is_read_per_space_and_a_bad_one_grants_nothing() {+ let dir = tempfile::tempdir().unwrap();+ assert_eq!(read_grants(dir.path(), "local:h"), Grants::default());+ std::fs::create_dir_all(grants_path(dir.path()).parent().unwrap()).unwrap();+ std::fs::write(+ grants_path(dir.path()),+ r#"{"local:h":{"list_all":true,"machines":["m-air"," ",7]},"local:o":{"list_all":false}}"#,+ )+ .unwrap();+ let g = read_grants(dir.path(), "local:h");+ assert!(g.list_all);+ assert_eq!(g.machines, BTreeSet::from(["m-air".to_owned()]));+ assert_eq!(read_grants(dir.path(), "local:o"), Grants::default());+ assert_eq!(read_grants(dir.path(), "local:none"), Grants::default());+ std::fs::write(grants_path(dir.path()), "not json").unwrap();+ assert_eq!(read_grants(dir.path(), "local:h"), Grants::default());+ }++ #[test]+ fn a_space_mentioned_after_the_home_was_made_is_listable_and_a_machine_usable_with_no_card() {+ let home = HomeScope::from_labels(&labels(&[(LABEL_HOME, "1")]));+ assert!(!home.may_list("local:ci", "ci") && !home.may_use_machine("studio"));+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(grants_path(dir.path()).parent().unwrap()).unwrap();+ std::fs::write(+ grants_path(dir.path()),+ r#"{"local:h":{"mentions":["local:ci","ci","studio",""," ",4]}}"#,+ )+ .unwrap();+ let g = read_grants(dir.path(), "local:h");+ assert_eq!(+ g.mentions,+ BTreeSet::from(["local:ci".to_owned(), "ci".to_owned(), "studio".to_owned()])+ );+ let s = home.with_grants(g);+ // By id or by name, with the daemon reading the file each time (no restart).+ assert!(s.may_list("local:ci", "x") && s.may_list("y", "ci"));+ assert!(s.may_use_machine("studio"));+ assert!(!s.may_list("other", "other") && !s.has(Ability::ListSpaces));+ // A mention never lists everything.+ assert!(!s.list_all);+ }++ #[test]+ fn labels_round_trip() {+ let s = HomeScope {+ is_home: true,+ agent: "claude-code".into(),+ list_all: true,+ mentions: ["a".to_owned()].into(),+ machines: ["m".to_owned()].into(),+ };+ assert_eq!(HomeScope::from_labels(&s.to_labels()), s);+ }+}diff --git a/libs/cua/crates/cua-daemon/src/children/mod.rs b/libs/cua/crates/cua-daemon/src/children/mod.rsindex c3c0c0bad7..9de0d1e2db 100644--- a/libs/cua/crates/cua-daemon/src/children/mod.rs+++ b/libs/cua/crates/cua-daemon/src/children/mod.rs@@ -2,6 +2,8 @@//! narrow channel only it can reach.//!//! - [`capability`]: the per-Space spawn capability this host mints.+//! - [`home`]: what an agent home (a Space made on the first ask-first request and reused)+//! may reach beyond its own tree, and what the person must approve.//! - [`tree`]: who is whose child; every answer stays inside the caller's//! subtree.//! - [`api`]: `SpaceService` and `DaemonService` answered for one Space's@@ -17,6 +19,7 @@ pub mod api;pub mod bridge;pub mod budget;pub mod capability;+pub mod home;pub mod reaper;#[cfg(test)]mod tests;diff --git a/libs/cua/crates/cua-daemon/src/children/tests.rs b/libs/cua/crates/cua-daemon/src/children/tests.rsindex 6dcaca28b8..b1f31c96f9 100644--- a/libs/cua/crates/cua-daemon/src/children/tests.rs+++ b/libs/cua/crates/cua-daemon/src/children/tests.rs@@ -643,3 +643,160 @@ fn orphans_are_listed_and_only_provable_ones_will_end() {// Children whose parents are here are not orphans.assert!(orphans.iter().all(|o| !o.space.starts_with("local:a")));}++/// Marks `space` as an agent home with the given grants.+fn make_home(w: &World, space: &str, scope: super::home::HomeScope) {+ w.shared+ .runtime+ .spaces()+ .registry()+ .update_meta(space, |m| m.labels.extend(scope.to_labels()))+ .unwrap();+}++#[tokio::test]+async fn an_agent_home_lists_only_what_it_was_granted() {+ use super::home::HomeScope;+ let w = world();+ let cap = mint(&w.shared, "local:root", "local:root", 0);+ let ids = |w: &World, cap: String| {+ let shared = w.shared.clone();+ async move {+ let mut c = SpaceServiceClient::new(channel(&shared, "local:root").await);+ let mut ids: Vec<String> = c+ .list_spaces(with(&cap, pb::ListSpacesRequest::default()))+ .await+ .unwrap()+ .into_inner()+ .spaces+ .into_iter()+ .map(|s| s.id)+ .collect();+ ids.sort();+ ids+ }+ };+ // A Space that is no home sees its subtree only (as before).+ assert_eq!(+ ids(&w, cap.clone()).await,+ ["local:a", "local:a1", "local:b"]+ );++ // A new home: its tree and the Space the person @mentioned by name.+ make_home(+ &w,+ "local:root",+ HomeScope {+ is_home: true,+ agent: "claude-code".into(),+ mentions: ["other".to_owned()].into(),+ ..Default::default()+ },+ );+ assert_eq!(+ ids(&w, cap.clone()).await,+ ["local:a", "local:a1", "local:b", "local:other"]+ );++ // Listing all, once the person approved it.+ make_home(+ &w,+ "local:root",+ HomeScope {+ is_home: true,+ list_all: true,+ ..Default::default()+ },+ );+ assert_eq!(ids(&w, cap).await.len(), 7);+}++#[tokio::test]+async fn an_agent_home_uses_a_machine_only_when_granted() {+ use super::home::HomeScope;+ let w = world();+ let scoped = super::api::Scoped {+ shared: w.shared.clone(),+ space: "local:root".into(),+ };+ let claims = super::capability::Claims {+ space: "local:root".into(),+ root: "local:root".into(),+ depth: 0,+ max_depth: 2,+ exp: u64::MAX,+ iat: 0,+ jti: String::new(),+ kid: String::new(),+ };+ let on_host = || pb::CreateSpaceRequest {+ location: "host:my-mac".into(),+ ..Default::default()+ };+ // Not a home: unchanged.+ assert!(scoped.child_request(&claims, on_host()).is_ok());+ // A home that was not given the machine: refused in words the agent can act on.+ make_home(+ &w,+ "local:root",+ HomeScope {+ is_home: true,+ ..Default::default()+ },+ );+ let e = scoped.child_request(&claims, on_host()).unwrap_err();+ assert_eq!(e.code(), Code::PermissionDenied);+ assert!(e.message().contains("my-mac"), "{}", e.message());+ // `auto` and this machine need no grant.+ for loc in ["auto", "local"] {+ let r = pb::CreateSpaceRequest {+ location: loc.into(),+ ..Default::default()+ };+ assert!(scoped.child_request(&claims, r).is_ok(), "{loc}");+ }+ // Granted (or @mentioned).+ make_home(+ &w,+ "local:root",+ HomeScope {+ is_home: true,+ machines: ["my-mac".to_owned()].into(),+ ..Default::default()+ },+ );+ assert!(scoped.child_request(&claims, on_host()).is_ok());+}++#[tokio::test]+async fn a_grant_given_while_the_home_runs_takes_effect_at_once() {+ use super::home::{HomeScope, grants_path};+ let w = world();+ make_home(+ &w,+ "local:root",+ HomeScope {+ is_home: true,+ ..Default::default()+ },+ );+ let cap = mint(&w.shared, "local:root", "local:root", 0);+ let c = SpaceServiceClient::new(channel(&w.shared, "local:root").await);+ let count = |mut c: SpaceServiceClient<Chan>, cap: String| async move {+ c.list_spaces(with(&cap, pb::ListSpacesRequest::default()))+ .await+ .unwrap()+ .into_inner()+ .spaces+ .len()+ };+ assert_eq!(count(c.clone(), cap.clone()).await, 3, "its tree only");+ // The app writes the person's approval outside the home; no restart.+ let file = grants_path(w.shared.runtime.spaces().home_dir());+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(&file, r#"{"local:root":{"list_all":true,"machines":[]}}"#).unwrap();+ assert_eq!(count(c.clone(), cap.clone()).await, 7);+ // Another home's grant does not widen this one.+ std::fs::write(&file, r#"{"local:other":{"list_all":true}}"#).unwrap();+ assert_eq!(count(c, cap).await, 3);+}diff --git a/libs/cua/crates/cua-spaces-app-core/parity/connectors.json b/libs/cua/crates/cua-spaces-app-core/parity/connectors.jsonindex eb4eac24df..d41677ee32 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/connectors.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/connectors.json@@ -72,6 +72,23 @@{ "forApp": "claude-code", "query": "", "expanded": false },{ "forApp": null, "query": "kimi", "expanded": false }],+ "agents": [+ { "step": "nothing signed in", "input": { "keys": { "keys": [] } } },+ { "step": "three Claude sign-ins, one ChatGPT sign-in and an OpenAI key", "input": {+ "keys": { "keys": [+ { "provider": "anthropic", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000100000, "label": "Signed in as [email protected] (Claude Max)" },+ { "provider": "openai", "env": "CODEX_AUTH_JSON", "last4": "", "addedMs": 1790000200000, "label": "Signed in with ChatGPT" },+ { "provider": "openai", "env": "OPENAI_API_KEY", "last4": "bb22", "addedMs": 1790000300000 }+ ] },+ "keyExtras": [+ { "provider": "anthropic", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000400000, "label": "work Max", "slot": "work" },+ { "provider": "anthropic", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000500000, "label": "side project Max", "slot": "side" }+ ],+ "uses": { "claude-code": { "provider": "anthropic", "env": "CLAUDE_CODE_OAUTH_TOKEN", "slot": "work" } }+ } },+ { "step": "a Claude sign-in that ran out", "input": { "keys": { "keys": [+ { "provider": "anthropic", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000100000, "expired": true } ] } } }+ ],"models": [{ "step": "nothing connected", "input": { "keys": { "keys": [] } } },{ "step": "an Anthropic key, an OpenAI key and a DeepSeek key", "input": { "keys": { "keys": [@@ -110,5 +127,198 @@{ "id": "b", "spaceId": "pending:b", "spaceName": "space-2", "harness": "codex", "label": "Codex", "job": "update the README", "atMs": 11, "state": "creating" },{ "id": "c", "spaceId": "", "spaceName": "", "harness": "hermes", "label": "Hermes", "job": "tidy the repo", "atMs": 3, "state": "failed" }]- }+ },+ "agentMenu": [+ {+ "step": "nothing chosen, nothing signed in",+ "input": {+ "keys": {+ "keys": []+ }+ },+ "menu": {},+ "choose": []+ },+ {+ "step": "nothing chosen, accounts that also run Goose and Pi",+ "input": {+ "keys": {+ "keys": [+ {+ "provider": "anthropic",+ "env": "CLAUDE_CODE_OAUTH_TOKEN",+ "last4": "",+ "addedMs": 1790000100000,+ "label": "Signed in as [email protected] (Claude Max)"+ },+ {+ "provider": "openai",+ "env": "CODEX_AUTH_JSON",+ "last4": "",+ "addedMs": 1790000200000,+ "label": "Signed in with ChatGPT"+ },+ {+ "provider": "anthropic",+ "env": "ANTHROPIC_API_KEY",+ "last4": "4f2a",+ "addedMs": 1790000300000+ }+ ]+ }+ },+ "menu": {},+ "choose": []+ },+ {+ "step": "Hermes hidden, Goose hidden",+ "input": {+ "keys": {+ "keys": [+ {+ "provider": "anthropic",+ "env": "CLAUDE_CODE_OAUTH_TOKEN",+ "last4": "",+ "addedMs": 1790000100000,+ "label": "Signed in as [email protected] (Claude Max)"+ },+ {+ "provider": "openai",+ "env": "CODEX_AUTH_JSON",+ "last4": "",+ "addedMs": 1790000200000,+ "label": "Signed in with ChatGPT"+ },+ {+ "provider": "anthropic",+ "env": "ANTHROPIC_API_KEY",+ "last4": "4f2a",+ "addedMs": 1790000300000+ }+ ]+ }+ },+ "menu": {+ "hidden": [+ "hermes",+ "goose"+ ]+ },+ "choose": []+ },+ {+ "step": "Antigravity shown before it is signed in",+ "input": {+ "keys": {+ "keys": []+ }+ },+ "menu": {+ "shown": [+ "antigravity"+ ]+ },+ "choose": []+ },+ {+ "step": "hiding one app at a time down to the last one",+ "input": {+ "keys": {+ "keys": []+ }+ },+ "menu": {},+ "choose": [+ {+ "app": "codex",+ "on": false+ },+ {+ "app": "hermes",+ "on": false+ },+ {+ "app": "claude-code",+ "on": false+ },+ {+ "app": "opencode",+ "on": false+ },+ {+ "app": "opencode",+ "on": true+ },+ {+ "app": "nope",+ "on": false+ }+ ]+ },+ {+ "step": "a file that hides all four reads as the defaults",+ "input": {+ "keys": {+ "keys": []+ }+ },+ "menu": {+ "hidden": [+ "codex",+ "hermes",+ "claude-code",+ "opencode"+ ]+ },+ "choose": []+ },+ {+ "step": "Claude Code hidden while signed out, then an account is added",+ "input": {+ "keys": {+ "keys": [+ {+ "provider": "anthropic",+ "env": "CLAUDE_CODE_OAUTH_TOKEN",+ "last4": "",+ "addedMs": 1790000100000,+ "label": "Signed in as [email protected] (Claude Max)"+ }+ ]+ }+ },+ "menu": {+ "hidden": [+ "claude-code"+ ],+ "seen": []+ },+ "choose": []+ },+ {+ "step": "Claude Code hidden with its account already seen: stays hidden",+ "input": {+ "keys": {+ "keys": [+ {+ "provider": "anthropic",+ "env": "CLAUDE_CODE_OAUTH_TOKEN",+ "last4": "",+ "addedMs": 1790000100000,+ "label": "Signed in as [email protected] (Claude Max)"+ }+ ]+ }+ },+ "menu": {+ "hidden": [+ "claude-code"+ ],+ "seen": [+ "claude-code|CLAUDE_CODE_OAUTH_TOKEN|"+ ]+ },+ "choose": []+ }+ ]}diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.jsonindex 090d719274..d3a1860f1a 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.json@@ -349,6 +349,331 @@],"models": "a provider with no list falls back to its default"},+ {+ "agents": "nothing signed in",+ "default": "- | - | - | -",+ "empty": "Sign in to an agent to start.",+ "groups": [+ "openai-codex | codex | OpenAI Codex | not-connected | Sign in :: ",+ "hermes | hermes | Hermes | not-connected | Sign in :: ",+ "claude-code | claude-code | Claude Code | not-connected | Sign in :: ",+ "opencode | opencode | OpenCode | not-connected | Sign in :: "+ ]+ },+ {+ "agents": "three Claude sign-ins, one ChatGPT sign-in and an OpenAI key",+ "default": "openai-codex | OPENAI_API_KEY | - | gpt-5.5",+ "empty": null,+ "groups": [+ "openai-codex | codex | OpenAI Codex | connected | Sign in :: openai | OPENAI_API_KEY | - | API Key (*bb22) | key | true | gpt-5.5 :: gpt-5.5 | false | true // openai | CODEX_AUTH_JSON | - | ChatGPT | sign-in | false | gpt-5.5 :: gpt-5.5 | false | true",+ "hermes | hermes | Hermes | connected | Sign in :: openai | OPENAI_API_KEY | - | API Key (*bb22) | key | true | gpt-5.5 :: gpt-5.5 | false | true",+ "claude-code | claude-code | Claude Code | connected | Sign in :: anthropic | CLAUDE_CODE_OAUTH_TOKEN | - | [email protected] (Max) | sign-in | false | claude-haiku-4-5 :: claude-haiku-4-5 | true | false / claude-sonnet-5 | false | true / claude-opus-5-5 | false | false // anthropic | CLAUDE_CODE_OAUTH_TOKEN | work | work Max | sign-in | true | claude-haiku-4-5 :: claude-haiku-4-5 | true | false / claude-sonnet-5 | false | true / claude-opus-5-5 | false | false // anthropic | CLAUDE_CODE_OAUTH_TOKEN | side | side project Max | sign-in | false | claude-haiku-4-5 :: claude-haiku-4-5 | true | false / claude-sonnet-5 | false | true / claude-opus-5-5 | false | false",+ "opencode | opencode | OpenCode | connected | Sign in :: openai | OPENAI_API_KEY | - | API Key (*bb22) | key | true | gpt-5.5 :: gpt-5.5 | false | true",+ "goose | goose | Goose | connected | Sign in :: openai | OPENAI_API_KEY | - | API Key (*bb22) | key | true | gpt-5.5 :: gpt-5.5 | false | true",+ "pi | pi | Pi | connected | Sign in :: openai | OPENAI_API_KEY | - | API Key (*bb22) | key | true | gpt-5.5 :: gpt-5.5 | false | true",+ "openclaw | openclaw | OpenClaw | connected | Sign in :: openai | OPENAI_API_KEY | - | API Key (*bb22) | key | true | gpt-5.5 :: gpt-5.5 | false | true"+ ]+ },+ {+ "agents": "a Claude sign-in that ran out",+ "default": "- | - | - | -",+ "empty": "Sign in to an agent to start.",+ "groups": [+ "openai-codex | codex | OpenAI Codex | not-connected | Sign in :: ",+ "hermes | hermes | Hermes | not-connected | Sign in :: ",+ "claude-code | claude-code | Claude Code | needs-reconnect | Sign in again :: ",+ "opencode | opencode | OpenCode | not-connected | Sign in :: "+ ]+ },+ {+ "agentMenu": "nothing chosen, nothing signed in",+ "choices": [],+ "default": "- | - | - | -",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | not-connected",+ "hermes | not-connected",+ "claude-code | not-connected",+ "opencode | not-connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Not signed in | false",+ "hermes | Hermes | true | Not signed in | false",+ "claude-code | Claude Code | true | Not signed in | false",+ "opencode | OpenCode | true | Not signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | false | Not signed in | false",+ "goose | Goose | false | Not signed in | false",+ "pi | Pi | false | Not signed in | false",+ "openclaw | OpenClaw | false | Not signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [],+ "seen": [],+ "shown": []+ },+ "title": "Agent menu"+ },+ {+ "agentMenu": "nothing chosen, accounts that also run Goose and Pi",+ "choices": [],+ "default": "openai-codex | CODEX_AUTH_JSON | - | gpt-5.5",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | connected",+ "hermes | connected",+ "claude-code | connected",+ "opencode | connected",+ "goose | connected",+ "pi | connected",+ "openclaw | connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Signed in | false",+ "hermes | Hermes | true | Signed in | false",+ "claude-code | Claude Code | true | Signed in | false",+ "opencode | OpenCode | true | Signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | false | Not signed in | false",+ "goose | Goose | true | Signed in | false",+ "pi | Pi | true | Signed in | false",+ "openclaw | OpenClaw | true | Signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [],+ "seen": [+ "codex|CODEX_AUTH_JSON|",+ "hermes|ANTHROPIC_API_KEY|",+ "claude-code|ANTHROPIC_API_KEY|",+ "claude-code|CLAUDE_CODE_OAUTH_TOKEN|",+ "opencode|ANTHROPIC_API_KEY|",+ "goose|ANTHROPIC_API_KEY|",+ "pi|ANTHROPIC_API_KEY|",+ "openclaw|ANTHROPIC_API_KEY|"+ ],+ "shown": []+ },+ "title": "Agent menu"+ },+ {+ "agentMenu": "Hermes hidden, Goose hidden",+ "choices": [],+ "default": "openai-codex | CODEX_AUTH_JSON | - | gpt-5.5",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | connected",+ "claude-code | connected",+ "opencode | connected",+ "pi | connected",+ "openclaw | connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Signed in | false",+ "hermes | Hermes | false | Signed in | false",+ "claude-code | Claude Code | true | Signed in | false",+ "opencode | OpenCode | true | Signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | false | Not signed in | false",+ "goose | Goose | false | Signed in | false",+ "pi | Pi | true | Signed in | false",+ "openclaw | OpenClaw | true | Signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [],+ "seen": [+ "codex|CODEX_AUTH_JSON|",+ "hermes|ANTHROPIC_API_KEY|",+ "claude-code|ANTHROPIC_API_KEY|",+ "claude-code|CLAUDE_CODE_OAUTH_TOKEN|",+ "opencode|ANTHROPIC_API_KEY|",+ "goose|ANTHROPIC_API_KEY|",+ "pi|ANTHROPIC_API_KEY|",+ "openclaw|ANTHROPIC_API_KEY|"+ ],+ "shown": []+ },+ "title": "Agent menu"+ },+ {+ "agentMenu": "Antigravity shown before it is signed in",+ "choices": [],+ "default": "- | - | - | -",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | not-connected",+ "hermes | not-connected",+ "claude-code | not-connected",+ "opencode | not-connected",+ "antigravity | not-connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Not signed in | false",+ "hermes | Hermes | true | Not signed in | false",+ "claude-code | Claude Code | true | Not signed in | false",+ "opencode | OpenCode | true | Not signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | true | Not signed in | false",+ "goose | Goose | false | Not signed in | false",+ "pi | Pi | false | Not signed in | false",+ "openclaw | OpenClaw | false | Not signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [],+ "seen": [],+ "shown": [+ "antigravity"+ ]+ },+ "title": "Agent menu"+ },+ {+ "agentMenu": "hiding one app at a time down to the last one",+ "choices": [+ "codex off :: shown [] / hidden [\"codex\"] :: -",+ "hermes off :: shown [] / hidden [\"codex\",\"hermes\"] :: -",+ "claude-code off :: shown [] / hidden [\"codex\",\"hermes\",\"claude-code\"] :: -",+ "opencode off :: shown [] / hidden [\"codex\",\"hermes\",\"claude-code\"] :: OpenCode stays in the menu: at least one coding app has to be shown.",+ "opencode on :: shown [] / hidden [\"codex\",\"hermes\",\"claude-code\"] :: -",+ "nope off :: shown [] / hidden [\"codex\",\"hermes\",\"claude-code\"] :: -"+ ],+ "default": "- | - | - | -",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | not-connected",+ "hermes | not-connected",+ "claude-code | not-connected",+ "opencode | not-connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Not signed in | false",+ "hermes | Hermes | true | Not signed in | false",+ "claude-code | Claude Code | true | Not signed in | false",+ "opencode | OpenCode | true | Not signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | false | Not signed in | false",+ "goose | Goose | false | Not signed in | false",+ "pi | Pi | false | Not signed in | false",+ "openclaw | OpenClaw | false | Not signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [],+ "seen": [],+ "shown": []+ },+ "title": "Agent menu"+ },+ {+ "agentMenu": "a file that hides all four reads as the defaults",+ "choices": [],+ "default": "- | - | - | -",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | not-connected",+ "hermes | not-connected",+ "claude-code | not-connected",+ "opencode | not-connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Not signed in | false",+ "hermes | Hermes | true | Not signed in | false",+ "claude-code | Claude Code | true | Not signed in | false",+ "opencode | OpenCode | true | Not signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | false | Not signed in | false",+ "goose | Goose | false | Not signed in | false",+ "pi | Pi | false | Not signed in | false",+ "openclaw | OpenClaw | false | Not signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [+ "codex",+ "hermes",+ "claude-code",+ "opencode"+ ],+ "seen": [],+ "shown": []+ },+ "title": "Agent menu"+ },+ {+ "agentMenu": "Claude Code hidden while signed out, then an account is added",+ "choices": [],+ "default": "- | - | - | -",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | not-connected",+ "hermes | not-connected",+ "opencode | not-connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Not signed in | false",+ "hermes | Hermes | true | Not signed in | false",+ "claude-code | Claude Code | false | Signed in | false",+ "opencode | OpenCode | true | Not signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | false | Not signed in | false",+ "goose | Goose | false | Not signed in | false",+ "pi | Pi | false | Not signed in | false",+ "openclaw | OpenClaw | false | Not signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [],+ "seen": [+ "claude-code|CLAUDE_CODE_OAUTH_TOKEN|"+ ],+ "shown": []+ },+ "title": "Agent menu"+ },+ {+ "agentMenu": "Claude Code hidden with its account already seen: stays hidden",+ "choices": [],+ "default": "- | - | - | -",+ "help": "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.",+ "lastNote": null,+ "menu": [+ "codex | not-connected",+ "hermes | not-connected",+ "opencode | not-connected"+ ],+ "rows": [+ "codex | OpenAI Codex | true | Not signed in | false",+ "hermes | Hermes | true | Not signed in | false",+ "claude-code | Claude Code | false | Signed in | false",+ "opencode | OpenCode | true | Not signed in | false",+ "gemini-cli | Gemini CLI | false | Not signed in | false",+ "antigravity | Google Antigravity | false | Not signed in | false",+ "goose | Goose | false | Not signed in | false",+ "pi | Pi | false | Not signed in | false",+ "openclaw | OpenClaw | false | Not signed in | false"+ ],+ "switch": "Show in the agent menu",+ "synced": {+ "hidden": [+ "claude-code"+ ],+ "seen": [+ "claude-code|CLAUDE_CODE_OAUTH_TOKEN|"+ ],+ "shown": []+ },+ "title": "Agent menu"+ },{"buttons": "Use my sign-in | Cancel | Reading your Claude Code sign-in…","importSheet": "macos",diff --git a/libs/cua/crates/cua-spaces-app-core/src/agent_menu.rs b/libs/cua/crates/cua-spaces-app-core/src/agent_menu.rsnew file mode 100644index 0000000000..e68f91c1ce--- /dev/null+++ b/libs/cua/crates/cua-spaces-app-core/src/agent_menu.rs@@ -0,0 +1,462 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Which coding apps the agent menu of Home shows (Settings, Connections). One rule for the web, SwiftUI and Electron apps.+//!+//! By default Codex, Hermes, Claude Code and OpenCode are shown, and any other+//! app only while one of its accounts works (today's menu). The person can+//! hide a leading app or show another one; the choice is kept in+//! `AppSettings.agent_menu_shown` and `agent_menu_hidden` as the apps that+//! differ from the default, so a new default still reaches everyone who did+//! not choose. Hiding changes only the menu: the app stays on the Agents page+//! and answers to its name (@mention, CLI, MCP), and its sign-ins are kept.+//!+//! The menu is never empty: the last app shown cannot be hidden, and a choice+//! that would leave nothing (an app signed out since) is read as the defaults.++use serde::{Deserialize, Serialize};++use crate::connectors::{self, AgentGroup, ConnectorsInput, MENU_FIRST};++/// The apps whose default the person changed.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct AgentMenuPrefs {+ /// Apps shown although the default hides them (an app outside the leading four, not signed in).+ pub shown: Vec<String>,+ /// Apps hidden although the default shows them.+ pub hidden: Vec<String>,+ /// The working accounts last seen, as `app|variable|slot`: a new one is a connect, which brings its+ /// app back into the menu ([`sync`]). Nothing secret.+ pub seen: Vec<String>,+}++/// The working accounts of every app, as `app|variable|slot`.+fn account_ids(input: &ConnectorsInput) -> Vec<String> {+ let mut out = vec![];+ for g in connectors::menu_groups(input) {+ for a in &g.accounts {+ out.push(format!(+ "{}|{}|{}",+ g.app,+ a.env,+ a.slot.as_deref().unwrap_or("")+ ));+ }+ }+ out+}++/// The choice after the accounts changed: an app that is hidden and gained a working account (signed in,+/// a key added, a sign-in that ran out renewed, from the menu, Connections, onboarding or the CLI) is+/// shown again. An app that was already connected stays as it is, and an account taken away changes+/// nothing. Run it whenever the accounts are read; the result is what to keep.+pub fn sync(input: &ConnectorsInput, prefs: &AgentMenuPrefs) -> AgentMenuPrefs {+ let now = account_ids(input);+ let mut next = prefs.clone();+ next.hidden.retain(|app| {+ let prefix = format!("{app}|");+ !now.iter()+ .any(|id| id.starts_with(&prefix) && !prefs.seen.contains(id))+ });+ next.seen = now;+ next+}++/// Whether the default shows `group`: the leading four always, the others while an account works.+fn default_shown(group: &AgentGroup) -> bool {+ MENU_FIRST.contains(&group.app.as_str()) || group.state != "not-connected"+}++fn chosen(prefs: &AgentMenuPrefs, group: &AgentGroup) -> bool {+ if prefs.hidden.contains(&group.app) {+ false+ } else if prefs.shown.contains(&group.app) {+ true+ } else {+ default_shown(group)+ }+}++/// The apps (setup ids) the menu shows, in menu order. Never empty while there is an app: when the+/// choice would leave none, the defaults apply.+pub fn shown_apps(prefs: &AgentMenuPrefs, groups: &[AgentGroup]) -> Vec<String> {+ let picked: Vec<String> = groups+ .iter()+ .filter(|g| chosen(prefs, g))+ .map(|g| g.app.clone())+ .collect();+ if !picked.is_empty() {+ return picked;+ }+ groups+ .iter()+ .filter(|g| default_shown(g))+ .map(|g| g.app.clone())+ .collect()+}++/// One row of Settings, Connections, Agent menu.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentMenuRow {+ /// The setup id (`codex`).+ pub app: String,+ pub label: String,+ /// The app is in the agent menu.+ pub shown: bool,+ /// What the app's sign-in is: "Signed in", "Sign in again" or "Not signed in".+ pub status: String,+ /// The switch cannot be turned off: this is the last app shown.+ pub locked: bool,+}++/// Settings, Connections, Agent menu.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentMenuSettings {+ pub title: String,+ /// The switch's name on every row.+ pub switch_label: String,+ /// What hiding does, in a line.+ pub help: String,+ pub rows: Vec<AgentMenuRow>,+ /// Said while one app is left: why its switch is off limits.+ pub last_note: Option<String>,+}++const SWITCH: &str = "Show in the agent menu";++fn status(group: &AgentGroup) -> &'static str {+ match group.state.as_str() {+ "connected" => "Signed in",+ "needs-reconnect" => "Sign in again",+ _ => "Not signed in",+ }+}++/// The rows of Settings, Connections, Agent menu: every coding app, the leading four first.+pub fn settings_view(input: &ConnectorsInput, prefs: &AgentMenuPrefs) -> AgentMenuSettings {+ let all = connectors::menu_groups(input);+ let shown = shown_apps(prefs, &all);+ let only = shown.len() == 1;+ let last = shown.first().and_then(|a| all.iter().find(|g| &g.app == a));+ AgentMenuSettings {+ title: "Agent menu".into(),+ switch_label: SWITCH.into(),+ help: "Choose which coding apps Home's agent menu lists. A hidden app keeps its sign-ins and stays on the Agents page and available by name. Connecting it again shows it.".into(),+ rows: all+ .iter()+ .map(|g| {+ let on = shown.contains(&g.app);+ AgentMenuRow {+ app: g.app.clone(),+ label: g.label.clone(),+ shown: on,+ status: status(g).into(),+ locked: on && only,+ }+ })+ .collect(),+ last_note: only+ .then(|| {+ last.map(|g| {+ format!(+ "{} stays in the menu: at least one coding app has to be shown.",+ g.label+ )+ })+ })+ .flatten(),+ }+}++/// The result of a switch.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentMenuChange {+ /// The choice to keep (unchanged when refused).+ pub prefs: AgentMenuPrefs,+ /// Said when the switch was refused: the last app cannot be hidden.+ pub refused: Option<String>,+}++/// The choice after `app` is switched on or off. Hiding the last app shown is refused; an unknown app+/// changes nothing. The result holds only what differs from the default.+pub fn choose(+ input: &ConnectorsInput,+ prefs: &AgentMenuPrefs,+ app: &str,+ on: bool,+) -> AgentMenuChange {+ let all = connectors::menu_groups(input);+ let keep = |refused: Option<String>| AgentMenuChange {+ prefs: prefs.clone(),+ refused,+ };+ let Some(group) = all.iter().find(|g| g.app == app) else {+ return keep(None);+ };+ let shown = shown_apps(prefs, &all);+ if !on && shown.contains(&group.app) && shown.len() == 1 {+ return keep(Some(format!(+ "{} stays in the menu: at least one coding app has to be shown.",+ group.label+ )));+ }+ let mut next = prefs.clone();+ // What is connected now is the baseline: only an account added after this is a new connect.+ next.seen = account_ids(input);+ next.shown.retain(|a| a != app);+ next.hidden.retain(|a| a != app);+ if on != default_shown(group) {+ if on {+ next.shown.push(app.into());+ } else {+ next.hidden.push(app.into());+ }+ }+ // A choice for an app that is gone is kept out of the file.+ next.shown.retain(|a| all.iter().any(|g| &g.app == a));+ next.hidden.retain(|a| all.iter().any(|g| &g.app == a));+ AgentMenuChange {+ prefs: next,+ refused: None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::agent_keys::{AgentKeyInput, AgentKeysInput};+ use crate::connectors::{agents_view, agents_view_with};++ fn input_with(envs: &[&str]) -> ConnectorsInput {+ ConnectorsInput {+ keys: AgentKeysInput {+ keys: envs+ .iter()+ .map(|env| AgentKeyInput {+ provider: "anthropic".into(),+ env: (*env).into(),+ last4: "4f2a".into(),+ added_ms: 1_000,+ expired: false,+ label: None,+ region: None,+ fields: Default::default(),+ })+ .collect(),+ ..Default::default()+ },+ ..Default::default()+ }+ }++ fn apps(i: &ConnectorsInput, p: &AgentMenuPrefs) -> Vec<String> {+ agents_view_with(i, p)+ .groups+ .into_iter()+ .map(|g| g.app)+ .collect()+ }++ #[test]+ fn the_default_is_todays_menu() {+ let none = input_with(&[]);+ assert_eq!(+ apps(&none, &AgentMenuPrefs::default()),+ ["codex", "hermes", "claude-code", "opencode"]+ );+ assert_eq!(+ agents_view(&none),+ agents_view_with(&none, &AgentMenuPrefs::default())+ );+ }++ #[test]+ fn another_app_is_shown_while_an_account_works() {+ let i = input_with(&["ANTHROPIC_API_KEY"]);+ let a = apps(&i, &AgentMenuPrefs::default());+ assert!(a.contains(&"goose".to_string()), "{a:?}");+ // Hiding it keeps its key.+ let hidden = choose(&i, &AgentMenuPrefs::default(), "goose", false);+ assert!(!apps(&i, &hidden.prefs).contains(&"goose".to_string()));+ assert_eq!(hidden.prefs.hidden, ["goose"]);+ }++ #[test]+ fn hiding_leaves_the_app_out_and_showing_brings_it_back() {+ let i = input_with(&[]);+ let hidden = choose(&i, &AgentMenuPrefs::default(), "hermes", false);+ assert!(hidden.refused.is_none());+ assert_eq!(hidden.prefs.hidden, ["hermes"]);+ assert_eq!(+ apps(&i, &hidden.prefs),+ ["codex", "claude-code", "opencode"]+ );+ let back = choose(&i, &hidden.prefs, "hermes", true);+ assert_eq!(+ back.prefs,+ AgentMenuPrefs::default(),+ "back to the default keeps nothing"+ );+ }++ #[test]+ fn an_app_outside_the_four_can_be_shown_before_it_is_signed_in() {+ let i = input_with(&[]);+ let on = choose(&i, &AgentMenuPrefs::default(), "goose", true);+ assert_eq!(on.prefs.shown, ["goose"]);+ assert!(apps(&i, &on.prefs).contains(&"goose".to_string()));+ let off = choose(&i, &on.prefs, "goose", false);+ assert_eq!(off.prefs, AgentMenuPrefs::default());+ }++ #[test]+ fn the_last_app_cannot_be_hidden() {+ let i = input_with(&[]);+ let mut p = AgentMenuPrefs::default();+ for app in ["codex", "hermes", "claude-code"] {+ let c = choose(&i, &p, app, false);+ assert!(c.refused.is_none(), "{app}");+ p = c.prefs;+ }+ assert_eq!(apps(&i, &p), ["opencode"]);+ let v = settings_view(&i, &p);+ assert_eq!(+ v.last_note.as_deref(),+ Some("OpenCode stays in the menu: at least one coding app has to be shown.")+ );+ assert!(v.rows.iter().find(|r| r.app == "opencode").unwrap().locked);+ let refused = choose(&i, &p, "opencode", false);+ assert_eq!(refused.prefs, p);+ assert!(refused.refused.is_some());+ // Another app on lets the last one go.+ let more = choose(&i, &p, "goose", true).prefs;+ assert!(choose(&i, &more, "opencode", false).refused.is_none());+ }++ #[test]+ fn a_file_that_hides_everything_reads_as_the_defaults() {+ let i = input_with(&[]);+ let p = AgentMenuPrefs {+ shown: vec![],+ hidden: ["codex", "hermes", "claude-code", "opencode"]+ .map(String::from)+ .to_vec(),+ seen: vec![],+ };+ assert_eq!(apps(&i, &p), ["codex", "hermes", "claude-code", "opencode"]);+ }++ #[test]+ fn rows_list_every_app_with_the_four_first() {+ let i = input_with(&[]);+ let v = settings_view(&i, &AgentMenuPrefs::default());+ let apps: Vec<&str> = v.rows.iter().map(|r| r.app.as_str()).collect();+ assert_eq!(&apps[..4], ["codex", "hermes", "claude-code", "opencode"]);+ assert_eq!(apps.len(), connectors::HARNESS_APPS.len());+ assert!(v.rows[..4].iter().all(|r| r.shown && !r.locked));+ assert!(v.rows[4..].iter().all(|r| !r.shown));+ assert!(v.last_note.is_none());+ assert_eq!(v.switch_label, "Show in the agent menu");+ }++ fn key_for(env: &str, label: Option<&str>) -> AgentKeyInput {+ AgentKeyInput {+ provider: "anthropic".into(),+ env: env.into(),+ last4: String::new(),+ added_ms: 1_000,+ expired: false,+ label: label.map(String::from),+ region: None,+ fields: Default::default(),+ }+ }++ fn with_claude(slots: &[(&str, &str)]) -> ConnectorsInput {+ let mut i = input_with(&[]);+ let mut it = slots.iter();+ if let Some((_, label)) = it.next() {+ i.keys+ .keys+ .push(key_for("CLAUDE_CODE_OAUTH_TOKEN", Some(label)));+ }+ for (slot, label) in it {+ i.key_extras.push(connectors::ExtraKeyInput {+ key: key_for("CLAUDE_CODE_OAUTH_TOKEN", Some(label)),+ slot: Some((*slot).into()),+ });+ }+ i+ }++ #[test]+ fn connecting_a_hidden_app_shows_it_again() {+ let none = with_claude(&[]);+ let hid = choose(&none, &AgentMenuPrefs::default(), "claude-code", false).prefs;+ assert!(!apps(&none, &hid).contains(&"claude-code".to_string()));+ // Nothing changes (a refresh, a relaunch): it stays hidden.+ assert_eq!(sync(&none, &hid), hid);+ // An account is added: shown again, and the choice no longer holds it.+ let one = with_claude(&[("", "a")]);+ let back = sync(&one, &hid);+ assert!(back.hidden.is_empty());+ assert!(apps(&one, &back).contains(&"claude-code".to_string()));+ }++ #[test]+ fn a_hidden_app_that_was_connected_stays_hidden_when_nothing_is_added() {+ let two = with_claude(&[("", "a"), ("w", "b")]);+ let hid = choose(&two, &AgentMenuPrefs::default(), "claude-code", false).prefs;+ assert_eq!(+ sync(&two, &hid),+ hid,+ "a refresh or relaunch changes nothing"+ );+ // One of two accounts is removed: still hidden.+ let one = with_claude(&[("", "a")]);+ let after = sync(&one, &hid);+ assert_eq!(after.hidden, ["claude-code"]);+ assert!(!apps(&one, &after).contains(&"claude-code".to_string()));+ // A new account after that brings it back.+ let three = with_claude(&[("", "a"), ("x", "c")]);+ assert!(sync(&three, &after).hidden.is_empty());+ }++ #[test]+ fn the_first_connect_of_an_app_hidden_by_default_shows_it() {+ let none = input_with(&[]);+ // Goose is not shown until an account works; the person also hid it.+ let hid = choose(&none, &AgentMenuPrefs::default(), "goose", true).prefs;+ let hid = choose(&none, &hid, "goose", false).prefs;+ assert_eq!(hid, AgentMenuPrefs::default());+ let key = input_with(&["ANTHROPIC_API_KEY"]);+ let p = sync(&key, &hid);+ assert!(apps(&key, &p).contains(&"goose".to_string()));+ // Hidden after it is connected, then synced again: it stays hidden.+ let h2 = choose(&key, &p, "goose", false).prefs;+ assert_eq!(sync(&key, &h2), h2);+ assert!(!apps(&key, &h2).contains(&"goose".to_string()));+ }++ #[test]+ fn an_account_renewed_after_it_ran_out_counts_as_a_connect() {+ let mut gone = with_claude(&[("", "a")]);+ gone.keys.keys[0].expired = true;+ let hid = choose(&gone, &AgentMenuPrefs::default(), "claude-code", false).prefs;+ assert_eq!(sync(&gone, &hid), hid);+ let renewed = with_claude(&[("", "a")]);+ assert!(sync(&renewed, &hid).hidden.is_empty());+ }++ #[test]+ fn an_unknown_app_changes_nothing() {+ let i = input_with(&[]);+ let c = choose(&i, &AgentMenuPrefs::default(), "nope", false);+ assert_eq!(c.prefs, AgentMenuPrefs::default());+ assert!(c.refused.is_none());+ }+}diff --git a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs b/libs/cua/crates/cua-spaces-app-core/src/connectors.rsindex dda0f54f9a..36cb662379 100644--- a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs@@ -1675,6 +1675,307 @@ pub fn models_view(input: &ConnectorsInput) -> ModelsView {}}+/// One sign-in or key a coding app can run with (an account of the agent menu).+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentAccount {+ pub provider: String,+ pub provider_label: String,+ pub icon: String,+ pub env: String,+ pub slot: Option<String>,+ /// What the person sees for it: `[email protected] (Max)` (the identifier and, when known, the plan),+ /// the name the person gave it, `ChatGPT` when no email is known, or `API Key (*4f2a)`.+ pub line: String,+ /// `sign-in` for the app's own sign-in, `key` for an API key.+ pub via: String,+ /// The account runs use now: the one the app was told to use, else the first.+ pub selected: bool,+ /// The models it can run.+ pub models: Vec<ModelChoice>,+ /// The model a pick of this account starts with: its quick one, else its default, else the first.+ pub default_model: Option<String>,+}++/// One coding app (harness) of the agent menu, with the accounts the person has for it.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentGroup {+ /// The harness id a run uses (`openai-codex`).+ pub harness: String,+ /// The setup id of its Connectors row (`codex`), where its sign-ins are managed.+ pub app: String,+ pub label: String,+ /// `connected` (an account works), `needs-reconnect` (only sign-ins that ran out) or `not-connected`.+ pub state: String,+ pub accounts: Vec<AgentAccount>,+ /// The words of the row that signs in, for an app with no account.+ pub sign_in_label: String,+}++/// A coding app, an account and a model picked together.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentRef {+ pub harness: String,+ pub provider: String,+ pub env: String,+ pub slot: Option<String>,+ pub model: String,+}++/// What the agent menu of the prompt box reads (`connectors.agents`).+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentsView {+ /// Codex, Hermes, Claude Code and OpenCode first, always; the other apps only when an account works.+ pub groups: Vec<AgentGroup>,+ /// Where to start when nothing was picked: the first app with an account, its account, its quick model.+ pub default: Option<AgentRef>,+ /// Said when no app has an account.+ pub empty: Option<String>,+}++/// The apps the menu always lists, in its order.+pub(crate) const MENU_FIRST: &[&str] = &["codex", "hermes", "claude-code", "opencode"];++/// One credential an app can run with: its provider, variable, slot and the saved key.+type Credential<'a> = (+ &'static reg::Provider,+ &'static str,+ Option<&'a str>,+ &'a AgentKeyInput,+);++/// The credentials `app` can run with now, in the order of preference: the providers by rank, the first+/// of each variable before those saved beside it. An app with its own sign-ins (Claude Code, Codex) lists+/// what it reads; an app that takes any provider lists every key it can use.+fn agent_credentials<'a>(input: &'a ConnectorsInput, app: &str) -> Vec<Credential<'a>> {+ let Some(a) = app_sign_in(app) else {+ return vec![];+ };+ let harness = harness_of_app(app).unwrap_or(app);+ let mut out = vec![];+ for p in &a.providers {+ for env in provider_envs(p) {+ let allowed = if a.reads.is_empty() {+ p.scope_of(env).is_none() && reg::can_read(harness, env)+ } else {+ a.reads.contains(&env)+ };+ if !allowed {+ continue;+ }+ for (k, slot) in input.keys_of(env).filter(|(k, _)| !k.expired) {+ if p.kind == reg::Kind::Custom && !endpoint_fields(k) {+ continue;+ }+ out.push((*p, env, slot, k));+ }+ }+ }+ out+}++/// A custom endpoint has the URL and model it needs.+fn endpoint_fields(k: &AgentKeyInput) -> bool {+ k.fields.get("base_url").is_some_and(|v| !v.is_empty())+ && k.fields.get("model").is_some_and(|v| !v.is_empty())+}++/// Who a saved sign-in is and its plan, from the name the host saved for it: "Signed in as [email protected]+/// (Claude Max)" is `[email protected]` on the `Max` plan; a name the person gave ("work Max") is that name.+fn signin_parts(label: &str) -> (String, Option<String>) {+ let mut s = label.trim();+ for prefix in [+ "Signed in with ChatGPT as ",+ "Signed in as ",+ "Signed in to ",+ ] {+ if let Some(rest) = s.strip_prefix(prefix) {+ s = rest.trim();+ break;+ }+ }+ if s == "Signed in with ChatGPT" || s.starts_with("Signed in with ChatGPT (") {+ s = s.trim_start_matches("Signed in with ").trim();+ }+ let (who, plan) = match (s.rfind(" ("), s.strip_suffix(')')) {+ (Some(i), Some(_)) => (s[..i].trim(), Some(&s[i + 2..s.len() - 1])),+ _ => (s, None),+ };+ let plan = plan+ .map(|p| {+ p.trim()+ .trim_start_matches("Claude ")+ .trim_start_matches("ChatGPT ")+ })+ .filter(|p| !p.is_empty())+ .map(str::to_string);+ (who.to_string(), plan)+}++/// What one credential reads as in the agent menu: `{identifier}` or `{identifier} ({Plan})` for a+/// sign-in (the name the person gave it when they renamed it), `API Key (*abcd)` for a key. One label+/// for the web, SwiftUI and Electron.+fn account_line(p: ®::Provider, env: &str, k: &AgentKeyInput) -> String {+ let named = k.label.as_deref().filter(|l| !l.is_empty());+ match env {+ "CLAUDE_CODE_OAUTH_TOKEN" | "CODEX_AUTH_JSON" => {+ let fallback = if env == "CODEX_AUTH_JSON" {+ "ChatGPT"+ } else {+ "Claude"+ };+ let (who, plan) = named.map(signin_parts).unwrap_or((fallback.into(), None));+ let who = if who.is_empty() {+ fallback.to_string()+ } else {+ who+ };+ match plan {+ Some(plan) => format!("{who} ({plan})"),+ None => who,+ }+ }+ _ => use_line(p, k),+ }+}++/// The agent menu: the coding apps the person can run, each with the accounts they have for it and+/// the models those accounts offer. A Claude sign-in is Claude Code's and a ChatGPT sign-in is+/// Codex's; the apps that take any provider list their API keys. An app with no account says how to+/// sign in.+pub fn agents_view(input: &ConnectorsInput) -> AgentsView {+ agents_view_with(input, &crate::agent_menu::AgentMenuPrefs::default())+}++/// Every coding app as a menu group, the four that lead first, then the rest in the page's order,+/// whether or not it is shown ([`crate::agent_menu`] decides that).+pub(crate) fn menu_groups(input: &ConnectorsInput) -> Vec<AgentGroup> {+ let build = |h: &HarnessApp| -> AgentGroup {+ let creds = agent_credentials(input, h.app);+ let told = input.uses.get(h.app);+ let picked = told.and_then(|u| {+ creds+ .iter()+ .position(|(_, env, slot, _)| *env == u.env && *slot == u.slot.as_deref())+ });+ // An app told to use a credential that is gone has none selected; it never moves to another.+ let selected_ix = match told {+ Some(_) => picked,+ None => (!creds.is_empty()).then_some(0),+ };+ let accounts: Vec<AgentAccount> = creds+ .iter()+ .enumerate()+ .map(|(i, (p, env, slot, k))| {+ let models: Vec<ModelChoice> = match k.fields.get("model").filter(|m| !m.is_empty())+ {+ Some(m) if p.kind == reg::Kind::Custom => vec![ModelChoice {+ id: m.clone(),+ label: m.clone(),+ fast: false,+ default: true,+ }],+ _ => p+ .model_list()+ .iter()+ .map(|m| ModelChoice {+ id: m.id.into(),+ label: m.name.into(),+ fast: m.fast,+ default: m.id == p.default_model,+ })+ .collect(),+ };+ AgentAccount {+ provider: p.id.into(),+ provider_label: p.name.into(),+ icon: p.icon.into(),+ env: (*env).into(),+ slot: slot.map(str::to_string),+ line: account_line(p, env, k),+ via: if p.scope_of(env).is_some() {+ "sign-in"+ } else {+ "key"+ }+ .into(),+ selected: Some(i) == selected_ix,+ default_model: models+ .iter()+ .find(|m| m.fast)+ .or_else(|| models.iter().find(|m| m.default))+ .or_else(|| models.first())+ .map(|m| m.id.clone()),+ models,+ }+ })+ .collect();+ let expired = accounts.is_empty()+ && app_sign_in(h.app).is_some_and(|a| {+ a.providers+ .iter()+ .any(|p| provider_expired_for(input, p, h.app))+ });+ AgentGroup {+ harness: h.harness.into(),+ app: h.app.into(),+ label: h.name.into(),+ state: if !accounts.is_empty() {+ "connected"+ } else if expired {+ "needs-reconnect"+ } else {+ "not-connected"+ }+ .into(),+ accounts,+ sign_in_label: if expired { "Sign in again" } else { "Sign in" }.into(),+ }+ };+ let mut groups: Vec<AgentGroup> = MENU_FIRST+ .iter()+ .filter_map(|app| HARNESS_APPS.iter().find(|h| h.app == *app))+ .map(build)+ .collect();+ groups.extend(+ HARNESS_APPS+ .iter()+ .filter(|h| !MENU_FIRST.contains(&h.app))+ .map(build),+ );+ groups+}++/// [`agents_view`] with the person's choice of which apps the menu shows ([`crate::agent_menu`]): a+/// hidden app is left out (its sign-ins stay), and a pick of one falls to the first app shown.+pub fn agents_view_with(+ input: &ConnectorsInput,+ prefs: &crate::agent_menu::AgentMenuPrefs,+) -> AgentsView {+ let all = menu_groups(input);+ let shown = crate::agent_menu::shown_apps(prefs, &all);+ let groups: Vec<AgentGroup> = all.into_iter().filter(|g| shown.contains(&g.app)).collect();+ let default = groups.iter().find_map(|g| {+ let a = g.accounts.iter().find(|a| a.selected)?;+ Some(AgentRef {+ harness: g.harness.clone(),+ provider: a.provider.clone(),+ env: a.env.clone(),+ slot: a.slot.clone(),+ model: a.default_model.clone()?,+ })+ });+ let none = default.is_none();+ AgentsView {+ groups,+ default,+ empty: none.then(|| "Sign in to an agent to start.".to_string()),+ }+}+/// What importing Claude Code's sign-in says before it reads anything, and/// what it offers when there is nothing to import.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]@@ -1814,7 +2115,7 @@ pub struct UseOption {/// The variable the credential is saved as, and which of its keys.pub env: String,pub slot: Option<String>,- /// "API key ending 4f2a", or the key's own name ("Work key").+ /// "API Key (*4f2a)", or the key's own name ("Work key").pub line: String,/// The model the app is told to use with it, when the person set one.pub model: Option<String>,@@ -1861,50 +2162,31 @@ fn use_line(p: ®::Provider, k: &AgentKeyInput) -> String {.region.as_deref().and_then(|r| p.regions.iter().find(|x| x.id == r))- .map(|r| format!(", {}", r.name))+ .map(|r| format!(" ({})", r.name)).unwrap_or_default();if k.last4.is_empty() {- format!("API key{plan}")+ format!("API Key{plan}")} else {- format!("API key ending {}{plan}", k.last4)+ format!("API Key (*{}){plan}", k.last4)}}/// Every credential `app` can use now, in the order of preference: providers by rank, the/// first key of each before the keys saved beside it.fn use_options(input: &ConnectorsInput, app: &str) -> Vec<UseOption> {- let Some(a) = app_sign_in(app) else {- return vec![];- };- let harness = harness_of_app(app).unwrap_or(app);- let mut out = vec![];- for p in &a.providers {- for env in provider_envs(p) {- for (k, slot) in input.keys_of(env).filter(|(k, _)| !k.expired) {- // A sign-in scoped to another app is never offered; a custom endpoint needs its URL and model.- if p.scope_of(env).is_some() || !reg::can_read(harness, env) {- continue;- }- if p.kind == reg::Kind::Custom- && !(k.fields.get("base_url").is_some_and(|v| !v.is_empty())- && k.fields.get("model").is_some_and(|v| !v.is_empty()))- {- continue;- }- out.push(UseOption {- provider: p.id.into(),- provider_name: p.name.into(),- icon: p.id.into(),- env: env.into(),- slot: slot.map(str::to_string),- line: use_line(p, k),- model: k.fields.get("model").filter(|m| !m.is_empty()).cloned(),- selected: false,- });- }- }- }- out+ agent_credentials(input, app)+ .into_iter()+ .map(|(p, env, slot, k)| UseOption {+ provider: p.id.into(),+ provider_name: p.name.into(),+ icon: p.id.into(),+ env: env.into(),+ slot: slot.map(str::to_string),+ line: account_line(p, env, k),+ model: k.fields.get("model").filter(|m| !m.is_empty()).cloned(),+ selected: false,+ })+ .collect()}/// The option an app was told to use, while it is still saved and works.@@ -3380,7 +3662,7 @@ mod tests {assert_eq!(cur.env, u.options[0].env, "{app}: the first that works");assert!(cur.selected);assert_eq!(u.options.iter().filter(|o| o.selected).count(), 1, "{app}");- assert!(u.options[0].line.contains("ending"), "{app}");+ assert!(u.options[0].line.starts_with("API Key (*"), "{app}");}}@@ -3517,4 +3799,232 @@ mod tests {assert!(text.contains("Takes effect the next time"), "{text}");}}++ fn with_keys(keys: Vec<AgentKeyInput>, extras: Vec<(AgentKeyInput, &str)>) -> ConnectorsInput {+ let mut i = input();+ i.keys.keys = keys;+ i.key_extras = extras+ .into_iter()+ .map(|(key, slot)| ExtraKeyInput {+ key,+ slot: Some(slot.into()),+ })+ .collect();+ i+ }++ fn named(env: &str, label: &str) -> AgentKeyInput {+ let mut k = key(env, "");+ k.label = Some(label.into());+ k+ }++ fn group<'a>(v: &'a AgentsView, app: &str) -> &'a AgentGroup {+ v.groups.iter().find(|g| g.app == app).unwrap()+ }++ #[test]+ fn the_agent_menu_lists_the_top_four_with_sign_in_when_nothing_is_saved() {+ let v = agents_view(&with_keys(vec![], vec![]));+ let apps: Vec<&str> = v.groups.iter().map(|g| g.app.as_str()).collect();+ assert_eq!(apps, ["codex", "hermes", "claude-code", "opencode"]);+ for g in &v.groups {+ assert_eq!(g.state, "not-connected");+ assert!(g.accounts.is_empty());+ assert_eq!(g.sign_in_label, "Sign in");+ }+ assert!(v.default.is_none() && v.empty.is_some());+ }++ #[test]+ fn a_harness_lists_every_account_the_person_has_for_it() {+ let v = agents_view(&with_keys(+ vec![+ named(+ "CLAUDE_CODE_OAUTH_TOKEN",+ "Signed in as [email protected] (Claude Max)",+ ),+ named("CODEX_AUTH_JSON", ""),+ ],+ vec![+ (named("CLAUDE_CODE_OAUTH_TOKEN", "work Max"), "work"),+ (named("CLAUDE_CODE_OAUTH_TOKEN", "side project Max"), "side"),+ ],+ ));+ let cc = group(&v, "claude-code");+ let lines: Vec<&str> = cc.accounts.iter().map(|a| a.line.as_str()).collect();+ assert_eq!(+ lines,+ ["[email protected] (Max)", "work Max", "side project Max"]+ );+ assert!(+ cc.accounts+ .iter()+ .all(|a| a.via == "sign-in" && a.provider == "anthropic")+ );+ assert_eq!(cc.accounts.iter().filter(|a| a.selected).count(), 1);+ assert!(cc.accounts[0].selected);+ assert!(!cc.accounts[0].models.is_empty() && cc.accounts[0].default_model.is_some());+ // Codex has its one ChatGPT sign-in; Hermes and OpenCode read no sign-in.+ let cx = group(&v, "codex");+ assert_eq!(cx.accounts.len(), 1);+ assert_eq!(cx.accounts[0].line, "ChatGPT");+ for app in ["hermes", "opencode"] {+ assert_eq!(group(&v, app).state, "not-connected", "{app}");+ }+ // The default is the first connected app in the menu's order (Codex), its account and quick model.+ let d = v.default.unwrap();+ assert_eq!(+ (d.harness.as_str(), d.env.as_str()),+ ("openai-codex", "CODEX_AUTH_JSON")+ );+ }++ #[test]+ fn an_app_told_which_account_to_use_selects_it_and_one_that_is_gone_selects_none() {+ let mut i = with_keys(+ vec![named("CLAUDE_CODE_OAUTH_TOKEN", "personal")],+ vec![(named("CLAUDE_CODE_OAUTH_TOKEN", "work Max"), "work")],+ );+ i.uses.insert(+ "claude-code".into(),+ UseInput {+ provider: "anthropic".into(),+ env: "CLAUDE_CODE_OAUTH_TOKEN".into(),+ slot: Some("work".into()),+ },+ );+ let v = agents_view(&i);+ let sel: Vec<&str> = group(&v, "claude-code")+ .accounts+ .iter()+ .filter(|a| a.selected)+ .map(|a| a.line.as_str())+ .collect();+ assert_eq!(sel, ["work Max"]);+ i.uses.insert(+ "claude-code".into(),+ UseInput {+ provider: "anthropic".into(),+ env: "CLAUDE_CODE_OAUTH_TOKEN".into(),+ slot: Some("removed".into()),+ },+ );+ let v = agents_view(&i);+ assert!(+ group(&v, "claude-code")+ .accounts+ .iter()+ .all(|a| !a.selected)+ );+ }++ #[test]+ fn api_keys_are_accounts_of_the_apps_that_take_any_provider_and_other_apps_show_when_connected()+ {+ let v = agents_view(&with_keys(+ vec![+ key("ANTHROPIC_API_KEY", "aa11"),+ key("OPENAI_API_KEY", "bb22"),+ ],+ vec![(named("OPENAI_API_KEY", "Work key"), "work")],+ ));+ let h = group(&v, "hermes");+ assert_eq!(h.state, "connected");+ let lines: Vec<&str> = h.accounts.iter().map(|a| a.line.as_str()).collect();+ assert!(+ lines.contains(&"Work key") && lines.contains(&"API Key (*bb22)"),+ "{lines:?}"+ );+ assert!(h.accounts.iter().all(|a| a.via == "key"));+ // An app outside the first four shows only once it has an account.+ let apps: Vec<&str> = v.groups.iter().map(|g| g.app.as_str()).collect();+ assert_eq!(&apps[..4], ["codex", "hermes", "claude-code", "opencode"]);+ assert!(apps[4..].iter().all(|a| group(&v, a).state == "connected"));+ }++ #[test]+ fn a_sign_in_that_ran_out_asks_to_sign_in_again() {+ let mut expired = named("CLAUDE_CODE_OAUTH_TOKEN", "work");+ expired.expired = true;+ let v = agents_view(&with_keys(vec![expired], vec![]));+ let cc = group(&v, "claude-code");+ assert_eq!(+ (cc.state.as_str(), cc.sign_in_label.as_str()),+ ("needs-reconnect", "Sign in again")+ );+ }++ #[test]+ fn no_agent_menu_string_says_machine_device_or_has_a_middle_dot() {+ let v = agents_view(&with_keys(vec![], vec![]));+ let text = serde_json::to_string(&v).unwrap().to_lowercase();+ assert!(!text.contains('\u{b7}') && !text.contains("device") && !text.contains("machine"));+ }++ #[test]+ fn an_accounts_label_is_the_identifier_and_the_plan_or_the_name_it_was_given() {+ let p = reg::provider("anthropic").unwrap();+ let line = |env: &str, label: &str, last4: &str| {+ let mut k = key(env, last4);+ if !label.is_empty() {+ k.label = Some(label.into());+ }+ account_line(p, env, &k)+ };+ // Claude Code: the email, and the plan without the product's name.+ assert_eq!(+ line(+ "CLAUDE_CODE_OAUTH_TOKEN",+ "Signed in as [email protected] (Claude Max)",+ ""+ ),+ "[email protected] (Max)"+ );+ assert_eq!(+ line(+ "CLAUDE_CODE_OAUTH_TOKEN",+ "Signed in as [email protected]",+ ""+ ),+ );+ assert_eq!(line("CLAUDE_CODE_OAUTH_TOKEN", "", ""), "Claude");+ // A name the person gave stays as it is.+ assert_eq!(line("CLAUDE_CODE_OAUTH_TOKEN", "work Max", ""), "work Max");+ assert_eq!(+ line("CLAUDE_CODE_OAUTH_TOKEN", "work (Max)", ""),+ "work (Max)"+ );+ // ChatGPT: the email and plan when known, else ChatGPT.+ assert_eq!(+ line(+ "CODEX_AUTH_JSON",+ "Signed in with ChatGPT as [email protected] (ChatGPT Plus)",+ ""+ ),+ "[email protected] (Plus)"+ );+ assert_eq!(+ line("CODEX_AUTH_JSON", "Signed in with ChatGPT", ""),+ "ChatGPT"+ );+ assert_eq!(line("CODEX_AUTH_JSON", "", ""), "ChatGPT");+ // An API key: the last four characters, never more; a named key keeps its name.+ assert_eq!(line("ANTHROPIC_API_KEY", "", "aa11"), "API Key (*aa11)");+ assert_eq!(line("ANTHROPIC_API_KEY", "", ""), "API Key");+ assert_eq!(line("ANTHROPIC_API_KEY", "Work key", "aa11"), "Work key");+ // No label says "Signed in".+ let v = agents_view(&with_keys(+ vec![+ named(+ "CLAUDE_CODE_OAUTH_TOKEN",+ "Signed in as [email protected] (Claude Max)",+ ),+ named("CODEX_AUTH_JSON", ""),+ ],+ vec![],+ ));+ assert!(!serde_json::to_string(&v).unwrap().contains("Signed in"));+ }}diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex 7e8d032199..d80f9a531e 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -16,7 +16,7 @@ use crate::profile_card;use crate::spaces::{self, creating, roster, sidebar, stream};use crate::teleport::{drag, flow, grid, transfer, windows};use crate::{- CoreError, about, account, agent_keys, agents, bulk_confirm, checklist, ci_runners,+ CoreError, about, account, agent_keys, agent_menu, agents, bulk_confirm, checklist, ci_runners,cloud_connect, cloud_page, cloud_sheet, connectors, devices, diagnostics, drive_mount_preview,drive_page, drive_settings, driver_preview, experiments, github_connection, host,local_network, login_item, machines, notch, notifications, nudges, onboarding,@@ -204,6 +204,10 @@ pub const METHODS: &[&str] = &["connectors.providerSheet","connectors.providerPicker","connectors.models",+ "connectors.agents",+ "agentMenu.view",+ "agentMenu.choose",+ "agentMenu.sync","connectors.importSheet","connectors.appDetail","connectors.setupCard",@@ -1070,6 +1074,28 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {a.get::<Option<bool>>("expanded")?.unwrap_or(false),)),"connectors.models" => out(connectors::models_view(&a.get("input")?)),+ "connectors.agents" => out(connectors::agents_view_with(+ &a.get("input")?,+ &a.get::<Option<agent_menu::AgentMenuPrefs>>("menu")?+ .unwrap_or_default(),+ )),+ "agentMenu.view" => out(agent_menu::settings_view(+ &a.get("input")?,+ &a.get::<Option<agent_menu::AgentMenuPrefs>>("menu")?+ .unwrap_or_default(),+ )),+ "agentMenu.sync" => out(agent_menu::sync(+ &a.get("input")?,+ &a.get::<Option<agent_menu::AgentMenuPrefs>>("menu")?+ .unwrap_or_default(),+ )),+ "agentMenu.choose" => out(agent_menu::choose(+ &a.get("input")?,+ &a.get::<Option<agent_menu::AgentMenuPrefs>>("menu")?+ .unwrap_or_default(),+ &a.get::<String>("app")?,+ a.get::<Option<bool>>("on")?.unwrap_or(false),+ )),"connectors.importSheet" => out(connectors::import_sheet_on(a.get::<Option<SpaceOs>>("hostOs")?.unwrap_or(SpaceOs::Macos),diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rsindex fc713ebb49..c1f5a07179 100644--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs@@ -66,6 +66,7 @@ pub mod about;pub mod account;pub mod agent_keys;pub mod agent_list;+pub mod agent_menu;pub mod agent_prompts;pub mod agents;pub mod bulk_confirm;diff --git a/libs/cua/crates/cua-spaces-app-core/src/parity.rs b/libs/cua/crates/cua-spaces-app-core/src/parity.rsindex 2cb31f319b..2df8e1068c 100644--- a/libs/cua/crates/cua-spaces-app-core/src/parity.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/parity.rs@@ -5744,6 +5744,128 @@ fn run_connectors(f: &Value, h: &dyn Host) -> Result<Value, String> {"connect": line(&[&v["connectLabel"], &v["empty"]]),}));}+ for step in f["agents"].as_array().into_iter().flatten() {+ let v = c(h, "connectors.agents", json!({ "input": step["input"] }))?;+ let groups: Vec<String> = v["groups"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|g| {+ let accounts: Vec<String> = g["accounts"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|a| {+ let models: Vec<String> = a["models"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|m| line(&[&m["id"], &m["fast"], &m["default"]]))+ .collect();+ format!(+ "{} :: {}",+ line(&[+ &a["provider"],+ &a["env"],+ &a["slot"],+ &a["line"],+ &a["via"],+ &a["selected"],+ &a["defaultModel"]+ ]),+ models.join(" / ")+ )+ })+ .collect();+ format!(+ "{} :: {}",+ line(&[+ &g["harness"],+ &g["app"],+ &g["label"],+ &g["state"],+ &g["signInLabel"]+ ]),+ accounts.join(" // ")+ )+ })+ .collect();+ frames.push(json!({+ "agents": step["step"],+ "groups": groups,+ "default": line(&[&v["default"]["harness"], &v["default"]["env"], &v["default"]["slot"], &v["default"]["model"]]),+ "empty": v["empty"],+ }));+ }+ // Which coding apps the agent menu shows (`agentMenu.*`, Settings, Connections): what the menu lists,+ // the rows of the switches and the result of each switch in turn.+ for step in f["agentMenu"].as_array().into_iter().flatten() {+ let menu = step.get("menu").cloned().unwrap_or(json!({}));+ let view = c(+ h,+ "connectors.agents",+ json!({ "input": step["input"], "menu": menu }),+ )?;+ let menu_apps: Vec<String> = view["groups"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|g| line(&[&g["app"], &g["state"]]))+ .collect();+ let rows = c(+ h,+ "agentMenu.view",+ json!({ "input": step["input"], "menu": menu }),+ )?;+ let row_lines: Vec<String> = rows["rows"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|r| {+ line(&[+ &r["app"],+ &r["label"],+ &r["shown"],+ &r["status"],+ &r["locked"],+ ])+ })+ .collect();+ let mut current = menu.clone();+ let mut choices: Vec<String> = vec![];+ for ch in step["choose"].as_array().into_iter().flatten() {+ let r = c(+ h,+ "agentMenu.choose",+ json!({ "input": step["input"], "menu": current, "app": ch["app"], "on": ch["on"] }),+ )?;+ choices.push(format!(+ "{} {} :: shown {} / hidden {} :: {}",+ ch["app"].as_str().unwrap_or(""),+ if ch["on"].as_bool().unwrap_or(false) {+ "on"+ } else {+ "off"+ },+ r["prefs"]["shown"],+ r["prefs"]["hidden"],+ line(&[&r["refused"]])+ ));+ current = r["prefs"].clone();+ }+ frames.push(json!({+ "agentMenu": step["step"],+ "menu": menu_apps,+ "default": line(&[&view["default"]["harness"], &view["default"]["env"], &view["default"]["slot"], &view["default"]["model"]]),+ "title": rows["title"],+ "switch": rows["switchLabel"],+ "help": rows["help"],+ "rows": row_lines,+ "lastNote": rows["lastNote"],+ "choices": choices,+ "synced": c(h, "agentMenu.sync", json!({ "input": step["input"], "menu": menu }))?,+ }));+ }for os in ["macos", "linux"] {let s = c(h, "connectors.importSheet", json!({ "hostOs": os }))?;let options: Vec<String> = s["options"]diff --git a/libs/cua/crates/cua-spaces-app-core/src/settings.rs b/libs/cua/crates/cua-spaces-app-core/src/settings.rsindex 8466e14a0e..0cc64b220a 100644--- a/libs/cua/crates/cua-spaces-app-core/src/settings.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/settings.rs@@ -100,6 +100,18 @@ pub struct AppSettings {/// Tips ([`crate::tips`]): "Don't show tips" and the ones done. An/// older settings file without it reads as tips on, none done.pub tips: crate::tips::TipsState,+ /// Settings, Connections, Agent menu ([`crate::agent_menu`]): the apps+ /// Home's agent menu shows although the default hides them (an app+ /// outside Codex, Hermes, Claude Code and OpenCode, not signed in).+ pub agent_menu_shown: Vec<String>,+ /// The apps the menu hides although the default shows them. Nothing is+ /// signed out: a hidden app keeps its sign-ins and stays on the Agents+ /// page and available by name.+ pub agent_menu_hidden: Vec<String>,+ /// The working accounts the menu last saw (`app|variable|slot`): a new+ /// one is a connect, which shows its app again+ /// ([`crate::agent_menu::sync`]).+ pub agent_menu_seen: Vec<String>,}impl Default for AppSettings {@@ -123,6 +135,9 @@ impl Default for AppSettings {auto_connect: true,current_team_id: None,tips: crate::tips::TipsState::default(),+ agent_menu_shown: vec![],+ agent_menu_hidden: vec![],+ agent_menu_seen: vec![],}}}diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rsindex 244cf02bec..69063a33ff 100644--- a/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs@@ -50,10 +50,11 @@ use cua_spaces::extension::Caller;use cua_spaces::mcp::ToolOutcome;use cua_spaces::{Error, Result, SpaceCreate, SpaceCreated, Spaces};-/// The agent home runs on the agent home image (the slim Linux image plus the-/// cua CLI, so the agent can make child Spaces); a test keeps it equal to the-/// image catalog and to the desktop app's `AGENT_HOME_IMAGE` where that exists.-pub const HOME_IMAGE: &str = "ghcr.io/trycua/agent-home:24.04";+/// The agent home runs on the slim Linux image (the `cua` CLI and a+/// spawn-capable cua-spacesd are baked into that tier, so the agent can make+/// child Spaces); a test keeps it equal to the image catalog and to the+/// desktop app's `AGENT_HOME_IMAGE` where that exists.+pub const HOME_IMAGE: &str = "ghcr.io/trycua/linux:24.04-slim";/// The labels the daemon reads on a home (`cua-daemon`'s `children::home`).pub const LABEL_HOME: &str = "cua.home";pub const LABEL_AGENT: &str = "cua.home.agent";@@ -873,7 +874,7 @@ mod tests {for call in ["cua spaces ls","cua spaces create <linux|windows|macos> --name <name> [--image <image>]",- "cua spaces create <os> --on host:<machine>",+ "cua spaces create <os> --on host:<computer>",] {assert!(container.contains(call), "{call}");}diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rsindex c5ada63c5e..93457dcaaf 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs@@ -7159,6 +7159,18 @@ pub struct AppSettings {/// Tips ([`crate::tips`]): "Don't show tips" and the ones done. An/// older settings file without it reads as tips on, none done.pub tips: AppTipsState,+ /// Settings, Connections, Agent menu ([`crate::agent_menu`]): the apps+ /// Home's agent menu shows although the default hides them (an app+ /// outside Codex, Hermes, Claude Code and OpenCode, not signed in).+ pub agent_menu_shown: Vec<String>,+ /// The apps the menu hides although the default shows them. Nothing is+ /// signed out: a hidden app keeps its sign-ins and stays on the Agents+ /// page and available by name.+ pub agent_menu_hidden: Vec<String>,+ /// The working accounts the menu last saw (`app|variable|slot`): a new+ /// one is a connect, which shows its app again+ /// ([`crate::agent_menu::sync`]).+ pub agent_menu_seen: Vec<String>,}/// A pressed key combination.diff --git a/libs/cua/crates/cua-spaces/src/agents/keys.rs b/libs/cua/crates/cua-spaces/src/agents/keys.rsindex 15e0ae513e..c3dfcd4188 100644--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs@@ -31,10 +31,29 @@ pub const SECRET_NAME: &str = "agent-keys";/// a provider, a variable name and a slot, kept beside the keys).pub const USES_NAME: &str = "agent-uses";-/// The apps that take any provider and so let the person pick which-/// credential they use (Settings, Connections, the app's page). Claude Code,-/// Codex, Gemini CLI and Antigravity read one fixed sign-in.-pub const SWITCHABLE_APPS: &[&str] = &["hermes", "opencode", "goose", "pi", "openclaw"];+/// The apps that let the person pick which credential they use (Settings, Connections, the app's+/// page, the prompt box's agent menu): the apps that take any provider, and Claude Code and Codex,+/// which can hold several sign-ins. Gemini CLI and Antigravity read one fixed sign-in.+pub const SWITCHABLE_APPS: &[&str] = &[+ "hermes",+ "opencode",+ "goose",+ "pi",+ "openclaw",+ "claude-code",+ "codex",+];++/// The id a choice is kept under: the app's setup id (`codex`), whichever of it and its harness id+/// (`openai-codex`) a caller has.+fn choice_app(app: &str) -> &str {+ if app == "openai-codex" { "codex" } else { app }+}++/// The harness id `app` runs as, for what it can read.+fn harness_of(app: &str) -> &str {+ if app == "codex" { "openai-codex" } else { app }+}/// The app's settings methods (`SpaceService.CallSpaceTool` names). They are/// not contract tools: no MCP server lists or calls them, so an agent can@@ -45,6 +64,7 @@ pub const APP_METHODS: &[&str] = &["agent_keys.set","agent_keys.remove","agent_keys.use",+ "agent_keys.rename","agent_keys.shell","agent_keys.from_shell",];@@ -671,13 +691,36 @@ impl AgentKeys {// key goes is a sign-in for Claude Code, not an API key: saved as one, so it// works for Claude Code and is never offered to another app as a key.if provider == "anthropic" && value.trim().contains("sk-ant-oat") {- if add {- return Err(Error::InvalidArgument(- "a Claude sign-in token is used by Claude Code only; it can't be added as another key".into(),- ));- }let copy = cua_agents::signin::claude_pasted_token(value).map_err(|r| Error::InvalidArgument(r.line().into()))?;+ if add && self.store.is_some() {+ let mut g = self.lock();+ let mut keys = self.read(&mut g, true)?;+ // Another Claude sign-in goes beside the first, named, and only Claude Code can use it.+ if keys.iter().any(|k| k.env == copy.env && k.slot.is_none()) {+ let stored = Stored {+ slot: Some(format!("k{:x}", now_ms())),+ provider: provider_of(©.env).into(),+ env: copy.env.clone(),+ value: validate_value(©.value)?.into(),+ added_ms: now_ms(),+ label: label.map(str::to_string).or(Some(copy.label.clone())),+ source: None,+ expires_ms: copy.expires_ms,+ rejected_ms: None,+ origin: copy.origin.clone(),+ region: None,+ fields: BTreeMap::new(),+ };+ let info = stored.info();+ keys.push(stored);+ keys.sort_by(|a, b| {+ (&a.env, &a.slot, a.added_ms).cmp(&(&b.env, &b.slot, b.added_ms))+ });+ self.write(&mut g, keys)?;+ return Ok(info);+ }+ }return self.import(©.source,©.env,@@ -752,6 +795,30 @@ impl AgentKeys {Ok(info)}+ /// Gives the key `env` (in `slot`, none for the first) a name; whether there was one.+ pub fn rename(&self, env: &str, slot: Option<&str>, label: &str) -> Result<bool> {+ let label = label.trim();+ if label.is_empty() || label.chars().count() > 40 || label.chars().any(|c| c.is_control()) {+ return Err(Error::InvalidArgument(+ "a key's name must be one line of at most 40 characters".into(),+ ));+ }+ if self.store.is_none() {+ return Ok(false);+ }+ let mut g = self.lock();+ let mut keys = self.read(&mut g, true)?;+ let Some(k) = keys+ .iter_mut()+ .find(|k| k.env == env && k.slot.as_deref() == slot)+ else {+ return Ok(false);+ };+ k.label = Some(label.to_string());+ self.write(&mut g, keys)?;+ Ok(true)+ }+/// Removes one key beside the first, named by its `slot`; whether there was one./// An app that was told to use it then has no credential (it says so), never/// another one.@@ -1090,6 +1157,7 @@ impl AgentKeys {/// or with `None` to use the first one that works again. The credential must/// be saved and one the app can read; nothing is signed out or deleted.pub fn set_use(&self, app: &str, choice: Option<(&str, Option<&str>)>) -> Result<()> {+ let app = choice_app(app);if !SWITCHABLE_APPS.contains(&app) {return Err(Error::InvalidArgument(format!("{app} reads one fixed sign-in; there is nothing to choose"@@ -1113,7 +1181,7 @@ impl AgentKeys {"that key isn't saved, or has stopped working".into(),)})?;- if !registry::can_read(app, env) {+ if !registry::can_read(harness_of(app), env) {return Err(Error::InvalidArgument(format!("{app} can't use that credential")));@@ -1147,6 +1215,7 @@ impl AgentKeys {/// What `app` was told to use, against what is saved now.pub fn chosen(&self, app: &str) -> Chosen {+ let app = choice_app(app);let Some(u) = self.uses().remove(app) else {return Chosen::NoChoice;};@@ -1156,7 +1225,7 @@ impl AgentKeys {.into_iter().find(|k| k.env == u.env && k.slot == u.slot && k.usable()){- Some(k) if registry::can_read(app, &k.env) => Chosen::Found {+ Some(k) if registry::can_read(harness_of(app), &k.env) => Chosen::Found {provider: k.provider,env: k.env,value: k.value,@@ -1464,7 +1533,7 @@ pub fn mark_rejected_for_run(harness: &str, provider: &str) {envs.sort_unstable();envs.dedup();// An app told to use a key beside the first one: that key is the one refused.- if let Some(u) = global().uses().remove(harness)+ if let Some(u) = global().uses().remove(choice_app(harness))&& u.provider == provider&& let Some(slot) = u.slot.as_deref(){@@ -1611,6 +1680,15 @@ struct RemoveArgs {keep_others: bool,}+#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+struct RenameArgs {+ env: String,+ #[serde(default)]+ slot: Option<String>,+ label: String,+}+#[derive(Deserialize)]#[serde(deny_unknown_fields)]struct UseArgs {@@ -1717,6 +1795,18 @@ pub fn app_call(}).and_then(|_| keys.report()),),+ "agent_keys.rename" => report(+ serde_json::from_value::<RenameArgs>(args)+ .map_err(|e| Error::InvalidArgument(format!("agent_keys.rename: {e}")))+ .and_then(|a| {+ if keys.rename(&a.env, a.slot.as_deref(), &a.label)? {+ Ok(())+ } else {+ Err(Error::InvalidArgument("that key isn't saved".into()))+ }+ })+ .and_then(|_| keys.report()),+ ),"agent_keys.use" => report(serde_json::from_value::<UseArgs>(args).map_err(|e| Error::InvalidArgument(format!("agent_keys.use: {e}")))@@ -2678,12 +2768,12 @@ mod tests {).is_err());- // A Claude sign-in token is never added as another key.+ // A Claude sign-in token is a sign-in for Claude Code, never another API key.let token = format!("sk-ant-oat01-{}", "y".repeat(40));- assert!(- keys.set_slot("anthropic", None, &token, None, &f, None, true)- .is_err()- );+ let saved = keys+ .set_slot("anthropic", None, &token, None, &f, None, true)+ .unwrap();+ assert_eq!(saved.env, "CLAUDE_CODE_OAUTH_TOKEN");// The report names both Anthropic keys and carries no value.let report = serde_json::to_string(&keys.report().unwrap()).unwrap();assert!(report.contains("Work key") && report.contains("bbbb") && report.contains("aaaa"));@@ -2726,10 +2816,96 @@ mod tests {);// A fresh handle reads the same store.let again = AgentKeys::new(cua_auth::Store::TestKeychain(dir.clone()));- assert_eq!(again.list().unwrap().len(), 1);+ assert_eq!(again.list().unwrap().len(), 2);let _ = std::fs::remove_dir_all(&dir);}+ #[test]+ fn another_claude_sign_in_is_kept_beside_the_first_and_can_be_renamed() {+ let (keys, _dir) = temp_keys();+ let f = BTreeMap::new();+ let first = format!("sk-ant-oat01-{}", "a".repeat(40));+ let second = format!("sk-ant-oat01-{}", "b".repeat(40));+ keys.set("anthropic", None, &first).unwrap();+ let added = keys+ .set_slot("anthropic", None, &second, None, &f, Some("work Max"), true)+ .unwrap();+ assert_eq!(added.env, "CLAUDE_CODE_OAUTH_TOKEN");+ let slot = added.slot.clone().expect("beside the first");+ assert_eq!(added.label.as_deref(), Some("work Max"));+ // Claude Code can be told to use it and then runs with it.+ keys.set_use(+ "claude-code",+ Some(("CLAUDE_CODE_OAUTH_TOKEN", Some(&slot))),+ )+ .unwrap();+ match keys.chosen("claude-code") {+ Chosen::Found { value, .. } => assert!(value.contains(&"b".repeat(40))),+ other => panic!("{other:?}"),+ }+ // A name is one line, and changes only the key it names.+ assert!(+ keys.rename("CLAUDE_CODE_OAUTH_TOKEN", Some(&slot), "")+ .is_err()+ );+ assert!(+ keys.rename("CLAUDE_CODE_OAUTH_TOKEN", Some(&slot), "side project")+ .unwrap()+ );+ let listed = keys.list().unwrap();+ let labels: Vec<Option<&str>> = listed.iter().map(|k| k.label.as_deref()).collect();+ assert!(labels.contains(&Some("side project")), "{labels:?}");+ assert!(+ !keys+ .rename("CLAUDE_CODE_OAUTH_TOKEN", Some("nope"), "x")+ .unwrap()+ );+ assert!(keys.remove_slot("CLAUDE_CODE_OAUTH_TOKEN", &slot).unwrap());+ }++ #[test]+ fn claude_code_and_codex_keep_which_account_they_use_under_the_apps_setup_id() {+ let (keys, _dir) = temp_keys();+ let f = BTreeMap::new();+ keys.set("anthropic", None, "sk-ant-api03-first-aaaa")+ .unwrap();+ let slot = keys+ .set_slot(+ "anthropic",+ None,+ "sk-ant-api03-work-bbbb",+ None,+ &f,+ None,+ true,+ )+ .unwrap()+ .slot+ .unwrap();+ keys.set_use("claude-code", Some(("ANTHROPIC_API_KEY", Some(&slot))))+ .unwrap();+ assert_eq!(+ keys.report().unwrap().uses["claude-code"].slot.as_deref(),+ Some(slot.as_str())+ );+ match keys.chosen("claude-code") {+ Chosen::Found { value, .. } => assert_eq!(value, "sk-ant-api03-work-bbbb"),+ other => panic!("{other:?}"),+ }+ // Codex is kept under its setup id whichever id a caller has, and reads OpenAI only.+ keys.set("openai", None, "sk-openai-cccc").unwrap();+ keys.set_use("openai-codex", Some(("OPENAI_API_KEY", None)))+ .unwrap();+ assert!(keys.report().unwrap().uses.contains_key("codex"));+ assert!(matches!(keys.chosen("openai-codex"), Chosen::Found { .. }));+ assert!(+ keys.set_use("codex", Some(("ANTHROPIC_API_KEY", None)))+ .is_err()+ );+ // Gemini CLI still reads one fixed sign-in.+ assert!(keys.set_use("gemini-cli", None).is_err());+ }+#[test]fn which_key_an_app_uses_is_kept_beside_the_keys_and_shown_without_values() {let (keys, dir) = temp_keys();diff --git a/libs/cua/crates/cua-spaces/src/agents/mod.rs b/libs/cua/crates/cua-spaces/src/agents/mod.rsindex 851d65119e..88caed05f8 100644--- a/libs/cua/crates/cua-spaces/src/agents/mod.rs+++ b/libs/cua/crates/cua-spaces/src/agents/mod.rs@@ -1262,18 +1262,12 @@ mod tests {}}- /// Fixed sign-in apps have nothing to choose, and the Claude token reaches no switchable app- /// whatever was chosen.+ /// An app is never pointed at a credential it can't read, and the Claude token reaches no app that takes+ /// any provider whatever was chosen.#[test]fn only_apps_that_take_any_provider_can_be_told_which_key() {let (k, dir) = saved(&[("anthropic", None, "sk-ant-api03-first-aaaa")]);- for app in [- "claude-code",- "openai-codex",- "codex",- "gemini-cli",- "google-antigravity",- ] {+ for app in ["openai-codex", "codex", "gemini-cli", "google-antigravity"] {assert!(k.set_use(app, Some(("ANTHROPIC_API_KEY", None))).is_err(),"{app}"diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swiftindex 9b64625c2e..daba5839c4 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift@@ -35882,6 +35882,24 @@ public struct AppSettings: Equatable, Hashable {* older settings file without it reads as tips on, none done.*/public var tips: AppTipsState+ /**+ * Settings, Connections, Agent menu ([`crate::agent_menu`]): the apps+ * Home's agent menu shows although the default hides them (an app+ * outside Codex, Hermes, Claude Code and OpenCode, not signed in).+ */+ public var agentMenuShown: [String]+ /**+ * The apps the menu hides although the default shows them. Nothing is+ * signed out: a hidden app keeps its sign-ins and stays on the Agents+ * page and available by name.+ */+ public var agentMenuHidden: [String]+ /**+ * The working accounts the menu last saw (`app|variable|slot`): a new+ * one is a connect, which shows its app again+ * ([`crate::agent_menu::sync`]).+ */+ public var agentMenuSeen: [String]// Default memberwise initializers are never public by default, so we// declare one manually.@@ -35963,7 +35981,22 @@ public struct AppSettings: Equatable, Hashable {/*** Tips ([`crate::tips`]): "Don't show tips" and the ones done. An* older settings file without it reads as tips on, none done.- */tips: AppTipsState) {+ */tips: AppTipsState,+ /**+ * Settings, Connections, Agent menu ([`crate::agent_menu`]): the apps+ * Home's agent menu shows although the default hides them (an app+ * outside Codex, Hermes, Claude Code and OpenCode, not signed in).+ */agentMenuShown: [String],+ /**+ * The apps the menu hides although the default shows them. Nothing is+ * signed out: a hidden app keeps its sign-ins and stays on the Agents+ * page and available by name.+ */agentMenuHidden: [String],+ /**+ * The working accounts the menu last saw (`app|variable|slot`): a new+ * one is a connect, which shows its app again+ * ([`crate::agent_menu::sync`]).+ */agentMenuSeen: [String]) {self.hotkey = hotkeyself.menuBar = menuBarself.theme = theme@@ -35982,6 +36015,9 @@ public struct AppSettings: Equatable, Hashable {self.autoConnect = autoConnectself.currentTeamId = currentTeamIdself.tips = tips+ self.agentMenuShown = agentMenuShown+ self.agentMenuHidden = agentMenuHidden+ self.agentMenuSeen = agentMenuSeen}@@ -36017,7 +36053,10 @@ public struct FfiConverterTypeAppSettings: FfiConverterRustBuffer {teleportChoices: FfiConverterSequenceTypeAppRememberedChoice.read(from: &buf),autoConnect: FfiConverterBool.read(from: &buf),currentTeamId: FfiConverterOptionString.read(from: &buf),- tips: FfiConverterTypeAppTipsState.read(from: &buf)+ tips: FfiConverterTypeAppTipsState.read(from: &buf),+ agentMenuShown: FfiConverterSequenceString.read(from: &buf),+ agentMenuHidden: FfiConverterSequenceString.read(from: &buf),+ agentMenuSeen: FfiConverterSequenceString.read(from: &buf))}@@ -36040,6 +36079,9 @@ public struct FfiConverterTypeAppSettings: FfiConverterRustBuffer {FfiConverterBool.write(value.autoConnect, into: &buf)FfiConverterOptionString.write(value.currentTeamId, into: &buf)FfiConverterTypeAppTipsState.write(value.tips, into: &buf)+ FfiConverterSequenceString.write(value.agentMenuShown, into: &buf)+ FfiConverterSequenceString.write(value.agentMenuHidden, into: &buf)+ FfiConverterSequenceString.write(value.agentMenuSeen, into: &buf)}}