Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

Connect apps in one step, per-kind runtime settings, Spaces at scale, host fixes; the new design is the default (#6079)

ddupontbb507dd282c5
diff --git a/apps/cua-spaces-desktop/src/bridge/agent-keys.ts b/apps/cua-spaces-desktop/src/bridge/agent-keys.ts
index 2c600e6138..75c5230a8b 100644
--- a/apps/cua-spaces-desktop/src/bridge/agent-keys.ts
+++ b/apps/cua-spaces-desktop/src/bridge/agent-keys.ts
@@ -18,5 +18,8 @@ export function agentKeysMethods({ model }: BridgeContext): Handlers {
return model.agents.keys.call("agent_keys.set", call);
},
"agentKeys.remove": (args) => model.agents.keys.call("agent_keys.remove", { env: string(args, "env") }),
+ // 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") }),
};
}
diff --git a/apps/cua-spaces-desktop/src/bridge/agents.ts b/apps/cua-spaces-desktop/src/bridge/agents.ts
index 7f54b266b0..9501377f99 100644
--- a/apps/cua-spaces-desktop/src/bridge/agents.ts
+++ b/apps/cua-spaces-desktop/src/bridge/agents.ts
@@ -124,7 +124,23 @@ export function agentsMethods({ model }: BridgeContext): Handlers {
},
"agents.disconnect": async (args) => {
needSetup();
- const out = await model.agents.coding.setup!.disconnectJson(strings(args, "agents"), args.signIn === true);
+ const setup = model.agents.coding.setup!;
+ // Some parts only (an app's page's switches), when the page says which.
+ const out =
+ typeof args.skills === "boolean" || typeof args.mcp === "boolean"
+ ? await setup.disconnectPartsJson(strings(args, "agents"), args.skills === true, args.mcp === true, args.signIn === true)
+ : await setup.disconnectJson(strings(args, "agents"), args.signIn === true);
+ await model.agents.coding.reload();
+ return JSON.parse(out);
+ },
+ // An agent's device-code sign-in made for Cua (Codex), started and waited in two calls.
+ "agents.signInStart": async (args) => {
+ needSetup();
+ return JSON.parse(await model.agents.coding.setup!.deviceSignInStartJson(string(args, "agent")));
+ },
+ "agents.signInWait": async (args) => {
+ needSetup();
+ const out = await model.agents.coding.setup!.deviceSignInWaitJson(string(args, "id"));
await model.agents.coding.reload();
return JSON.parse(out);
},
diff --git a/apps/cua-spaces-desktop/src/bridge/context.ts b/apps/cua-spaces-desktop/src/bridge/context.ts
index 0a653a5b0a..2e35d24206 100644
--- a/apps/cua-spaces-desktop/src/bridge/context.ts
+++ b/apps/cua-spaces-desktop/src/bridge/context.ts
@@ -26,6 +26,8 @@ export interface BridgeUi {
setDropTargets?(window: unknown, targets: DropTargetRect[]): void;
/** "Send file…": the native file picker over the calling window (files and folders, several); null when cancelled. */
chooseFiles?(window: unknown): Promise<string[] | null>;
+ /** Settings, Advanced's "Browse…": one program, over the calling window; null when cancelled. */
+ chooseProgram?(window: unknown): Promise<string | null>;
/** A Space's picture-in-picture panels (floating windows). */
pip?: PipPresenter;
/**
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.ts
index 9a6476457b..7cf7be3c41 100644
--- a/apps/cua-spaces-desktop/src/bridge/methods.ts
+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts
@@ -17,10 +17,10 @@ export const METHODS = [
"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.start", "agents.message",
+ "agents.status", "agents.connect", "agents.disconnect", "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.set", "agentKeys.remove",
+ "agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell",
"spaces.add", "clouds.status", "clouds.test", "clouds.connect", "clouds.disconnect", "clouds.approve",
"teleport.catalog", "teleport.entryForPath", "teleport.windows", "teleport.remoteWindows",
"teleport.icon", "teleport.thumbnail", "teleport.plan", "teleport.run", "teleport.sites",
@@ -39,6 +39,7 @@ export const METHODS = [
"spaces.chooseFiles", "spaces.droppedFiles", "spaces.sendFiles",
"host.setUp", "host.joinWithCode", "host.action", "host.openSettings",
"settings.get", "settings.choose", "settings.update",
+ "runtimes.check", "runtimes.browse",
"keyvault.get", "keyvault.lock", "keyvault.unlock",
"keyvault.unlockVault", "keyvault.setup", "keyvault.setDisabled",
"keyvault.approve", "keyvault.deny", "keyvault.revokeGrant",
diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.ts
index b196040d56..bbedc57745 100644
--- a/apps/cua-spaces-desktop/src/bridge/settings.ts
+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts
@@ -62,9 +62,8 @@ export function settingsPage(model: AppModel, parts: HostParts) {
keyvaultSiteIcons: model.settings.keyvaultSiteIcons,
keyvaultProtection: model.keyvault.page.protection,
autoConnect: model.settings.autoConnect,
- lumeSource: model.lumeSource ?? undefined,
- // The built-in Linux runtime is a gVisor VM on a Mac; Docker is the runtime elsewhere, so no row.
- linuxSource: process.platform === "darwin" ? (model.linuxSource ?? undefined) : undefined,
+ // Settings, Advanced: every kind of Space's runtime row ("Checking…" until read).
+ runtimes: model.runtimesInput(),
// Settings, General's Show tips (the tips themselves live in `AppSettings.tips`).
showTips: !model.settings.tips.off,
};
@@ -93,6 +92,8 @@ export function settingsState(model: AppModel, parts: HostParts) {
accountUrl: model.native.appAccountAppUrl(),
// The CLI this app installs and whether it is here (`cli.ts`).
cli: cliSetting(model),
+ // Settings, Advanced's runtimes as read (`runtimes::RuntimesInput`): the page's core lays out every kind's row.
+ runtimes: encode(model.runtimesInput()),
// The app core's own settings the page changes (`settings.update`).
tips: { off: model.settings.tips.off, done: [...model.settings.tips.done] },
};
@@ -141,10 +142,41 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
const [lume, linux] = await Promise.all([bounded(5, () => model.backend.lumeSource()), bounded(5, () => model.backend.linuxSource())]);
if (lume !== null) model.lumeSource = lume;
if (linux !== null) model.linuxSource = linux;
+ // What is installed for each kind and the doctor: in the background, the page hears `settings.changed`.
+ refreshRuntimes();
+ };
+
+ /** Reads the runtimes again unless a read is recent or running. */
+ let runtimesReadAt = 0;
+ let runtimesReading = false;
+ const refreshRuntimes = (force = false) => {
+ if (!model.servicesIn || runtimesReading || (!force && Date.now() - runtimesReadAt < 15_000)) return;
+ runtimesReading = true;
+ void model
+ .readRuntimes()
+ .then(() => {
+ runtimesReadAt = Date.now();
+ model.changed("settings");
+ })
+ .catch(() => {})
+ .finally(() => {
+ runtimesReading = false;
+ });
};
/** A choice row changed (`AppModel.choose`). */
const choose = async (row: string, option: string): Promise<void> => {
+ // Settings, Advanced's runtime rows: the setting the core names, written; the runtimes read again.
+ const change = row.startsWith("runtime") ? model.native.appRuntimesChoose(model.runtimesInput(), row, option) : undefined;
+ if (change) {
+ await model.backend.setRuntimeSetting(change.key, change.value ?? null);
+ await bounded(15, () => model.readRuntimes());
+ const [lume, linux] = await Promise.all([model.backend.lumeSource(), model.backend.linuxSource()]);
+ model.lumeSource = lume;
+ model.linuxSource = linux;
+ model.changed("settings");
+ return;
+ }
switch (row) {
case "team-current":
// Settings, Teams: the team to work in (saved; the option is its id).
@@ -154,16 +186,6 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
// "Spaces tab in the notch" (shown) or the menu bar only (hide); the notch follows `settings.changed`.
save({ menuBar: option === "hide" });
return;
- case "macos-runtime":
- await model.backend.setLumeSource(option);
- model.lumeSource = (await model.backend.lumeSource()) ?? option;
- model.changed("settings");
- return;
- case "linux-runtime":
- await model.backend.setLinuxSource(option);
- model.linuxSource = (await model.backend.linuxSource()) ?? option;
- model.changed("settings");
- return;
case "auto-connect":
save({ autoConnect: option === "on" });
return;
@@ -237,7 +259,8 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
},
"settings.choose": async (args) => {
const row = string(args, "row");
- const option = string(args, "option");
+ // An empty option only for a runtime path ("Reset to detected").
+ const option = row.startsWith("runtime-path:") && args.option === "" ? "" : string(args, "option");
if (row === "update-channel") {
// Settings → About's channel (saved in `AppSettings`).
const updates = parts().updates;
@@ -262,6 +285,20 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
}
return settingsState(model, parts());
},
+ // Settings, Advanced: what a typed path is, before it is saved.
+ "runtimes.check": async (args) => {
+ try {
+ return encode(await model.backend.runtimeCheckPath(string(args, "kind"), string(args, "path")));
+ } catch (error) {
+ throw Failure.failed(words(error));
+ }
+ },
+ // Settings, Advanced's "Browse…".
+ "runtimes.browse": async (args, caller) => {
+ string(args, "kind");
+ if (!ctx.ui.chooseProgram) throw Failure.unsupported("This build has no file picker");
+ return { path: (await ctx.ui.chooseProgram(caller.window)) ?? null };
+ },
// The page's tips (`AppSettings.tips`), saved as given.
"settings.update": (args) => {
save(settingsUpdate(args));
diff --git a/apps/cua-spaces-desktop/src/damaged.ts b/apps/cua-spaces-desktop/src/damaged.ts
new file mode 100644
index 0000000000..00ee0e47ae
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/damaged.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// A state file that is not what it should be (truncated by a crash or a full
+// disk, or garbage) must not crash the app, and must not take what it held
+// with it: the app starts from the defaults and the file stays beside it as
+// `<name>.damaged`, until the next save writes a good one over the original.
+// The core does the same for settings.json (`settings::load`).
+import { copyFileSync, statSync } from "node:fs";
+
+/** Files already copied this run (by path, size and time), so a file read on
+ * every call is kept once, not on each read. */
+const kept = new Set<string>();
+
+/** Keeps `file` as `<file>.damaged` (the latest damaged one replaces an older
+ * copy) and says so on stderr. Returns where it went, or null when it
+ * could not be kept. Never throws. */
+export function keepDamaged(file: string, why = "is damaged", warn: (message: string) => void = (m) => console.warn(m)): string | null {
+ try {
+ const st = statSync(file);
+ const key = `${file}|${st.size}|${st.mtimeMs}`;
+ const copy = `${file}.damaged`;
+ if (kept.has(key)) return copy;
+ // copyFileSync keeps the file's mode: a private file stays private.
+ copyFileSync(file, copy);
+ kept.add(key);
+ warn(`${file} ${why}; starting from the defaults, the file is kept as ${copy}`);
+ return copy;
+ } catch {
+ return null;
+ }
+}
+
+/** Tests: forget what was kept. */
+export function forgetKept(): void {
+ kept.clear();
+}
diff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.ts
index fd4e712844..1758746679 100644
--- a/apps/cua-spaces-desktop/src/main.ts
+++ b/apps/cua-spaces-desktop/src/main.ts
@@ -201,6 +201,11 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcu
const r = win instanceof BrowserWindow ? await dialog.showOpenDialog(win, { properties }) : await dialog.showOpenDialog({ properties });
return r.canceled ? null : r.filePaths;
},
+ chooseProgram: async (win) => {
+ const options = { properties: ["openFile", "showHiddenFiles", "treatPackageAsDirectory"] as ("openFile" | "showHiddenFiles" | "treatPackageAsDirectory")[], defaultPath: process.platform === "win32" ? undefined : "/usr/local/bin", buttonLabel: "Use" };
+ const r = win instanceof BrowserWindow ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options);
+ return r.canceled ? null : (r.filePaths[0] ?? null);
+ },
pip,
...prompts,
},
diff --git a/apps/cua-spaces-desktop/src/model/agents.ts b/apps/cua-spaces-desktop/src/model/agents.ts
index 91810d8a30..0e8739de49 100644
--- a/apps/cua-spaces-desktop/src/model/agents.ts
+++ b/apps/cua-spaces-desktop/src/model/agents.ts
@@ -328,7 +328,8 @@ export class AgentKeysModel {
async call(method: string, args: Record<string, unknown> = {}): Promise<unknown> {
if (!this.tools) throw new ToolError("Agent keys need the cua daemon");
const r = await this.tools(method, args);
- if (r && typeof r === "object" && !Array.isArray(r)) {
+ // Every method answers the list after it, except agent_keys.shell (the names your shell has).
+ if (method !== "agent_keys.shell" && r && typeof r === "object" && !Array.isArray(r)) {
this.report = r as Json;
this.error = null;
}
@@ -408,6 +409,12 @@ export interface AgentSetupRunning {
connectJson(agents: string[], signIn: boolean, skills: boolean, mcp: boolean): Promise<string>;
/** Disconnect: both undone. */
disconnectJson(agents: string[], signIn: boolean): Promise<string>;
+ /** Disconnect of some parts only (an app's page's switches). */
+ disconnectPartsJson(agents: string[], skills: boolean, mcp: boolean, signIn: boolean): Promise<string>;
+ /** An agent's device-code sign-in made for Cua: `{id, url, code}`. */
+ deviceSignInStartJson(agent: string): Promise<string>;
+ /** Waits for it and saves it in Keyvault: Connect's `sign_in`. */
+ deviceSignInWaitJson(id: string): Promise<string>;
/** Deletes the config copies (`.cua-backup-*`) earlier versions left, once per install. */
sweepLeftovers?(): void;
}
@@ -480,6 +487,18 @@ export class LiveAgentSetup implements AgentSetupRunning {
return this.inner.connectJson(agents, this.server, skills, mcp, signIn);
}
+ async disconnectPartsJson(agents: string[], skills: boolean, mcp: boolean, signIn: boolean): Promise<string> {
+ return this.inner.disconnectPartsJson(agents, skills, mcp, signIn);
+ }
+
+ async deviceSignInStartJson(agent: string): Promise<string> {
+ return this.inner.deviceSignInStartJson(agent);
+ }
+
+ async deviceSignInWaitJson(id: string): Promise<string> {
+ return this.inner.deviceSignInWaitJson(id);
+ }
+
async disconnectJson(agents: string[], signIn: boolean): Promise<string> {
return this.inner.disconnectJson(agents, signIn);
}
@@ -515,6 +534,9 @@ export class PendingAgentSetup implements AgentSetupRunning {
(await this.gate.wait()).agentSetup?.connectionStatusJson(refresh) ?? '{"agents":[],"checked_at_ms":0}';
connectJson = async (agents: string[], signIn: boolean, skills: boolean, mcp: boolean) => (await this.s()).connectJson(agents, signIn, skills, mcp);
disconnectJson = async (agents: string[], signIn: boolean) => (await this.s()).disconnectJson(agents, signIn);
+ disconnectPartsJson = async (agents: string[], skills: boolean, mcp: boolean, signIn: boolean) => (await this.s()).disconnectPartsJson(agents, skills, mcp, signIn);
+ deviceSignInStartJson = async (agent: string) => (await this.s()).deviceSignInStartJson(agent);
+ deviceSignInWaitJson = async (id: string) => (await this.s()).deviceSignInWaitJson(id);
sweepLeftovers = () => this.gate.current?.agentSetup?.sweepLeftovers?.();
}
diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.ts
index 6a2984ed60..86b5858283 100644
--- a/apps/cua-spaces-desktop/src/model/app-model.ts
+++ b/apps/cua-spaces-desktop/src/model/app-model.ts
@@ -13,6 +13,8 @@ import type {
AppCliInstallPlan,
AppCreateAction,
AppCreatesState,
+ AppRuntimeKindInput,
+ AppRuntimesInput,
AppCreateSpaceArgs,
AppGpuChoice,
AppLocalStorage,
@@ -170,6 +172,10 @@ export class AppModel {
runningMacosVms: number | null = null;
lumeSource: string | null = null;
linuxSource: string | null = null;
+ /** Settings, Advanced: each kind of Space's runtime setting and what is installed for it, once read. */
+ runtimeKinds: AppRuntimeKindInput[] | null = null;
+ /** Settings, Advanced: the runtime doctor's answer, once read. */
+ runtimeDoctor: LocalRuntimes | null = null;
/** Your machines that provide Spaces, as New Space last read them. */
hosts: AppSpaceHost[] = [];
/** Windows or Linux without a usable local runtime: why, and the fix New Space offers (null when one is ready). */
@@ -638,6 +644,25 @@ export class AppModel {
// MARK: New Space
+ /** What Settings, Advanced's runtime rows are laid out from (`runtimes::section`): every kind, "Checking…" until read. */
+ runtimesInput(): AppRuntimesInput {
+ const os = process.platform === "darwin" ? this.native.AppSpaceOs.Macos : process.platform === "win32" ? this.native.AppSpaceOs.Windows : this.native.AppSpaceOs.Linux;
+ return {
+ os,
+ hostArch: this.hostArch,
+ localBackends: this.runtimeDoctor?.ready,
+ localDetails: this.runtimeDoctor?.details,
+ kinds: this.runtimeKinds ?? undefined,
+ };
+ }
+
+ /** Reads each kind's runtime setting, what is installed and the doctor (each bounded). */
+ async readRuntimes(): Promise<void> {
+ const [doctor, kinds] = await Promise.all([this.backend.localRuntimes(), this.backend.runtimeKinds()]);
+ if (doctor) this.runtimeDoctor = doctor;
+ if (kinds) this.runtimeKinds = kinds;
+ }
+
/** What New Space knows, freshly probed; every probe runs at once and each is bounded. */
async newSpaceEnv(): Promise<AppWizardEnv> {
const b = this.backend;
diff --git a/apps/cua-spaces-desktop/src/model/backend.ts b/apps/cua-spaces-desktop/src/model/backend.ts
index 060ec2dc12..ec7ddc2836 100644
--- a/apps/cua-spaces-desktop/src/model/backend.ts
+++ b/apps/cua-spaces-desktop/src/model/backend.ts
@@ -10,6 +10,8 @@ import type {
AppCreateSpaceArgs,
AppGpuChoice,
AppRuntime,
+ AppRuntimeKindInput,
+ AppRuntimePathCheck,
AppSpaceAgentRun,
AppSpaceHost,
AppSpaceKind,
@@ -161,6 +163,12 @@ export interface SpacesBackend {
setLumeSource(value: string): Promise<void>;
linuxSource(): Promise<string | null>;
setLinuxSource(value: string): Promise<void>;
+ /** Each kind of Space's runtime setting and what is installed for it (`runtime_kinds`); null when unknown. */
+ runtimeKinds(): Promise<AppRuntimeKindInput[] | null>;
+ /** What `path` is for `kind` (`container`, `vm`, `microvm`). */
+ runtimeCheckPath(kind: string, path: string): Promise<AppRuntimePathCheck>;
+ /** Writes a runtime setting (`runtime.container`, `runtime.vm_path`), or unsets it (null). */
+ setRuntimeSetting(key: string, value: string | null): Promise<void>;
localStorage(): Promise<LocalStorage | null>;
/** A Cua account is signed in (or client credentials are set). */
loggedIn(): Promise<boolean>;
@@ -578,6 +586,20 @@ export class LiveSpacesBackend implements SpacesBackend {
this.native.configSet("runtime.linux", value);
}
+ async runtimeKinds(): Promise<AppRuntimeKindInput[] | null> {
+ const kinds = await bounded(PROBE_SECONDS, () => this.cua.local().runtimeKinds());
+ return kinds?.map((k) => ({ kind: k.kind, source: k.source, path: k.path, detected: k.detected, check: k.check, expected: k.expected })) ?? null;
+ }
+
+ async runtimeCheckPath(kind: string, path: string): Promise<AppRuntimePathCheck> {
+ return this.cua.local().runtimeCheckPath(kind, path);
+ }
+
+ async setRuntimeSetting(key: string, value: string | null): Promise<void> {
+ if (value === null) this.native.configUnset(key);
+ else this.native.configSet(key, value);
+ }
+
async localStorage(): Promise<LocalStorage | null> {
return bounded(PROBE_SECONDS, () => this.cua.local().storage());
}
diff --git a/apps/cua-spaces-desktop/src/model/checklist.ts b/apps/cua-spaces-desktop/src/model/checklist.ts
index af97209f6e..09e6bb28ea 100644
--- a/apps/cua-spaces-desktop/src/model/checklist.ts
+++ b/apps/cua-spaces-desktop/src/model/checklist.ts
@@ -12,6 +12,7 @@
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import * as path from "node:path";
import type { AppChecklistAction, AppChecklistState, AppChecklistStep, AppTelemetrySignal } from "../native/generated/index";
+import { keepDamaged } from "../damaged";
import type { Native } from "../native/load";
/** The state as the file and the page keep it: steps as their words. */
@@ -50,8 +51,9 @@ export class ChecklistModel {
seed: string | null = null,
) {
this.words = checklistWords(native);
- const read = (f: string | null) => (f ? this.read(f) : null);
- this.state = read(file) ?? read(seed) ?? { done: [], dismissed: false, shown: false, skipped: [] };
+ // Only its own file is kept when damaged: the seed is the Swift app's.
+ const read = (f: string | null, own: boolean) => (f ? this.read(f, own) : null);
+ this.state = read(file, true) ?? read(seed, false) ?? { done: [], dismissed: false, shown: false, skipped: [] };
}
/** The state with steps as words. */
@@ -92,14 +94,17 @@ export class ChecklistModel {
if (t.signals.length) this.telemetry?.record(t.signals);
}
- private read(file: string): AppChecklistState | null {
+ private read(file: string, own = true): AppChecklistState | null {
if (!existsSync(file)) return null;
try {
const raw = JSON.parse(readFileSync(file, "utf8")) as Partial<StoredChecklist> | null;
- return raw && typeof raw === "object" ? this.fromStored(raw) : null;
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) return this.fromStored(raw);
} catch {
- return null;
+ // damaged: below
}
+ // Truncated or garbage: the defaults, and the file kept as `.damaged`.
+ if (own) keepDamaged(file);
+ return null;
}
private save(): void {
diff --git a/apps/cua-spaces-desktop/src/model/onboarding.ts b/apps/cua-spaces-desktop/src/model/onboarding.ts
index 0098f73077..cfec836dbb 100644
--- a/apps/cua-spaces-desktop/src/model/onboarding.ts
+++ b/apps/cua-spaces-desktop/src/model/onboarding.ts
@@ -10,6 +10,8 @@
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import * as path from "node:path";
+import { keepDamaged } from "../damaged";
+
export type OnboardingMode = "client" | "host";
export interface OnboardingState {
@@ -23,12 +25,21 @@ export class OnboardingStore {
constructor(readonly file: string) {}
- /** What the file says (a missing or damaged file: the first run is due). */
+ /** What the file says (a missing or damaged file: the first run is due; a damaged one is kept as `.damaged`). */
read(): OnboardingState {
+ let text: string;
+ try {
+ text = readFileSync(this.file, "utf8");
+ } catch {
+ return { completed: false, mode: "client" };
+ }
try {
- const raw = JSON.parse(readFileSync(this.file, "utf8")) as { completed?: unknown; mode?: unknown };
- return { completed: raw.completed === true && !this.shownAgain, mode: raw.mode === "host" ? "host" : "client" };
+ const raw: unknown = JSON.parse(text);
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("not an object");
+ const { completed, mode } = raw as { completed?: unknown; mode?: unknown };
+ return { completed: completed === true && !this.shownAgain, mode: mode === "host" ? "host" : "client" };
} catch {
+ keepDamaged(this.file);
return { completed: false, mode: "client" };
}
}
diff --git a/apps/cua-spaces-desktop/src/model/pending.ts b/apps/cua-spaces-desktop/src/model/pending.ts
index 4e54d18866..462ba37e59 100644
--- a/apps/cua-spaces-desktop/src/model/pending.ts
+++ b/apps/cua-spaces-desktop/src/model/pending.ts
@@ -114,6 +114,9 @@ export class PendingSpacesBackend implements SpacesBackend {
setLumeSource = async (value: string) => (await this.b()).setLumeSource(value);
linuxSource = async () => (await this.b()).linuxSource();
setLinuxSource = async (value: string) => (await this.b()).setLinuxSource(value);
+ runtimeKinds = async () => (await this.b()).runtimeKinds();
+ runtimeCheckPath = async (kind: string, path: string) => (await this.b()).runtimeCheckPath(kind, path);
+ setRuntimeSetting = async (key: string, value: string | null) => (await this.b()).setRuntimeSetting(key, value);
localStorage = async () => (await this.b()).localStorage();
loggedIn = async () => (await this.b()).loggedIn();
runningMacosVms = async () => (await this.b()).runningMacosVms();
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts
index 0d882814cc..de49af636c 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts
@@ -1019,11 +1019,26 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_agentsetup_disconnect_json": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8, FfiType.Int8, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_agentsetup_install_skills": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
@@ -1429,6 +1444,16 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_local_runtime_check_path": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_fn_method_local_runtime_kinds": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_local_setup": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
@@ -3489,11 +3514,26 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_agentsetup_install_skills": {
args: [],
ret: FfiType.UInt16,
@@ -3899,6 +3939,16 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_local_runtime_check_path": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_checksum_method_local_runtime_kinds": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_local_setup": {
args: [],
ret: FfiType.UInt16,
@@ -5983,7 +6033,10 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_agentsetup_connect_json(uniffiSelf: bigint, agents: Uint8Array, server: Uint8Array, skills: number, mcp: number, signIn: number): bigint;
uniffi_cua_sdk_fn_method_agentsetup_connection_status_json(uniffiSelf: bigint, expected: Uint8Array, refresh: number, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_agentsetup_detect(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(uniffiSelf: bigint, agent: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(uniffiSelf: bigint, id: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_agentsetup_disconnect_json(uniffiSelf: bigint, agents: Uint8Array, signIn: number): bigint;
+ uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(uniffiSelf: bigint, agents: Uint8Array, skills: number, mcp: number, signIn: number): bigint;
uniffi_cua_sdk_fn_method_agentsetup_install_skills(uniffiSelf: bigint, agents: Uint8Array, skills: Uint8Array, force: number): bigint;
uniffi_cua_sdk_fn_method_agentsetup_onboarding_declined(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_sdk_fn_method_agentsetup_remove(uniffiSelf: bigint, agents: Uint8Array, skills: number, mcp: number): bigint;
@@ -6065,6 +6118,8 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_local_doctor(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_local_pull_image(uniffiSelf: bigint, reference: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_local_push_image(uniffiSelf: bigint, reference: Uint8Array, destination: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_local_runtime_check_path(uniffiSelf: bigint, kind: Uint8Array, path: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_local_runtime_kinds(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_local_setup(uniffiSelf: bigint, components: Uint8Array, dryRun: number): bigint;
uniffi_cua_sdk_fn_method_local_storage(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_loginattempt_method(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -6477,7 +6532,10 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_agentsetup_connect_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_detect(): number;
+ uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json(): number;
+ uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json(): number;
+ uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_install_skills(): number;
uniffi_cua_sdk_checksum_method_agentsetup_onboarding_declined(): number;
uniffi_cua_sdk_checksum_method_agentsetup_remove(): number;
@@ -6559,6 +6617,8 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_local_doctor(): number;
uniffi_cua_sdk_checksum_method_local_pull_image(): number;
uniffi_cua_sdk_checksum_method_local_push_image(): number;
+ uniffi_cua_sdk_checksum_method_local_runtime_check_path(): number;
+ uniffi_cua_sdk_checksum_method_local_runtime_kinds(): number;
uniffi_cua_sdk_checksum_method_local_setup(): number;
uniffi_cua_sdk_checksum_method_local_storage(): number;
uniffi_cua_sdk_checksum_method_loginattempt_method(): number;
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
index eb5aef1e8f..d3582d211f 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
@@ -6782,8 +6782,9 @@ const FfiConverterTypeComputerResources = (() => {
*/
export type ConfigEntry = {
/**
- * `default.on`, `default.kind`, `default.runtime`, `runtime.lume`,
- * `runtime.linux` or `telemetry.enabled`.
+ * `default.on`, `default.kind`, `default.runtime`, `runtime.container`,
+ * `runtime.vm`, `runtime.microvm` (and their `_path`) or
+ * `telemetry.enabled`.
*/
key: string,
/**
@@ -16263,6 +16264,245 @@ const FfiConverterTypeRoutineInfo = (() => {
return new FFIConverter();
})();
+/**
+ * A runtime installed on this machine for one kind of Space.
+ */
+export type RuntimeDetected = {
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */
+ tool: string,
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */
+ name: string,
+ path: string,
+ /**
+ * As `--version` says it (`27.3.1`).
+ */
+ version?: string,
+ /**
+ * The guest system it runs, when only one (`macOS`, `Linux`).
+ */
+ guests?: string
+}
+
+/**
+ * Generated factory for {@link RuntimeDetected} record objects.
+ */
+export const RuntimeDetected = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<RuntimeDetected, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<RuntimeDetected>,
+ });
+})();
+
+const FfiConverterTypeRuntimeDetected = (() => {
+ type TypeName = RuntimeDetected;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ tool: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ path: FfiConverterString.read(from),
+ version: FfiConverterOptionalString.read(from),
+ guests: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.tool, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.path, into);
+ FfiConverterOptionalString.write(value.version, into);
+ FfiConverterOptionalString.write(value.guests, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.tool) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.path) +
+ FfiConverterOptionalString.allocationSize(value.version) +
+ FfiConverterOptionalString.allocationSize(value.guests);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * What a binary is, for one kind of Space (`runtime_check_path`).
+ */
+export type RuntimePathProbe = {
+ path: string,
+ /**
+ * A file is there.
+ */
+ exists: boolean,
+ /**
+ * It can be run.
+ */
+ executable: boolean,
+ /**
+ * The tool it is, when it is one the kind takes.
+ */
+ tool?: string,
+ name?: string,
+ version?: string,
+ /**
+ * The oldest version cua runs on.
+ */
+ minVersion?: string,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ expected: Array<string>,
+ guests?: string
+}
+
+/**
+ * Generated factory for {@link RuntimePathProbe} record objects.
+ */
+export const RuntimePathProbe = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<RuntimePathProbe, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<RuntimePathProbe>,
+ });
+})();
+
+const FfiConverterTypeRuntimePathProbe = (() => {
+ type TypeName = RuntimePathProbe;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ path: FfiConverterString.read(from),
+ exists: FfiConverterBool.read(from),
+ executable: FfiConverterBool.read(from),
+ tool: FfiConverterOptionalString.read(from),
+ name: FfiConverterOptionalString.read(from),
+ version: FfiConverterOptionalString.read(from),
+ minVersion: FfiConverterOptionalString.read(from),
+ expected: FfiConverterSequenceString.read(from),
+ guests: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.path, into);
+ FfiConverterBool.write(value.exists, into);
+ FfiConverterBool.write(value.executable, into);
+ FfiConverterOptionalString.write(value.tool, into);
+ FfiConverterOptionalString.write(value.name, into);
+ FfiConverterOptionalString.write(value.version, into);
+ FfiConverterOptionalString.write(value.minVersion, into);
+ FfiConverterSequenceString.write(value.expected, into);
+ FfiConverterOptionalString.write(value.guests, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.path) +
+ FfiConverterBool.allocationSize(value.exists) +
+ FfiConverterBool.allocationSize(value.executable) +
+ FfiConverterOptionalString.allocationSize(value.tool) +
+ FfiConverterOptionalString.allocationSize(value.name) +
+ FfiConverterOptionalString.allocationSize(value.version) +
+ FfiConverterOptionalString.allocationSize(value.minVersion) +
+ FfiConverterSequenceString.allocationSize(value.expected) +
+ FfiConverterOptionalString.allocationSize(value.guests);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * One kind of Space's runtime, as Settings shows it.
+ */
+export type RuntimeKindState = {
+ /**
+ * `container`, `vm` or `microvm`.
+ */
+ kind: string,
+ /**
+ * `runtime.<kind>`: `auto`, `builtin` or `system`.
+ */
+ source: string,
+ /**
+ * `runtime.<kind>_path`, when set.
+ */
+ path?: string,
+ /**
+ * What is installed here for the kind, the one used first.
+ */
+ detected: Array<RuntimeDetected>,
+ /**
+ * The path in use (the custom one, else the first detected), probed.
+ */
+ check?: RuntimePathProbe,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ expected: Array<string>
+}
+
+/**
+ * Generated factory for {@link RuntimeKindState} record objects.
+ */
+export const RuntimeKindState = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<RuntimeKindState, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<RuntimeKindState>,
+ });
+})();
+
+const FfiConverterTypeRuntimeKindState = (() => {
+ type TypeName = RuntimeKindState;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ kind: FfiConverterString.read(from),
+ source: FfiConverterString.read(from),
+ path: FfiConverterOptionalString.read(from),
+ detected: FfiConverterSequenceTypeRuntimeDetected.read(from),
+ check: FfiConverterOptionalTypeRuntimePathProbe.read(from),
+ expected: FfiConverterSequenceString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.kind, into);
+ FfiConverterString.write(value.source, into);
+ FfiConverterOptionalString.write(value.path, into);
+ FfiConverterSequenceTypeRuntimeDetected.write(value.detected, into);
+ FfiConverterOptionalTypeRuntimePathProbe.write(value.check, into);
+ FfiConverterSequenceString.write(value.expected, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.kind) +
+ FfiConverterString.allocationSize(value.source) +
+ FfiConverterOptionalString.allocationSize(value.path) +
+ FfiConverterSequenceTypeRuntimeDetected.allocationSize(value.detected) +
+ FfiConverterOptionalTypeRuntimePathProbe.allocationSize(value.check) +
+ FfiConverterSequenceString.allocationSize(value.expected);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
// Enum: RegistrySecret
export enum RegistrySecret_Tags {
@@ -25509,12 +25749,29 @@ export interface AgentSetupLike {
* Every supported agent, installed or not (read-only).
*/
detect(): Array<AgentInfo>;
+/**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+ deviceSignInStartJson(agent: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+ deviceSignInWaitJson(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
* Keyvault). JSON `{outcomes, removed_sign_ins}`.
*/
disconnectJson(agents: Array<string>, signIn: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+ disconnectPartsJson(agents: Array<string>, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -25707,6 +25964,79 @@ private constructor(pointer: UniffiHandle) {
));
}
+/**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+ async deviceSignInStartJson(agent: string, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(
+ uniffiTypeAgentSetupObjectFactory.clonePointer(this),FfiConverterString.lower(agent, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+ async deviceSignInWaitJson(id: string, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(
+ uniffiTypeAgentSetupObjectFactory.clonePointer(this),FfiConverterString.lower(id, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
@@ -25744,6 +26074,43 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+ async disconnectPartsJson(agents: Array<string>, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(
+ uniffiTypeAgentSetupObjectFactory.clonePointer(this),FfiConverterSequenceString.lower(agents, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(skills, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(mcp, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(signIn, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -28156,6 +28523,20 @@ export interface LocalLike {
* pushed manifest digest.
*/
pushImage(reference: string, destination: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+ runtimeCheckPath(kind: string, path: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RuntimePathProbe>;
+/**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+ runtimeKinds(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<RuntimeKindState>>;
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -28338,6 +28719,82 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+ async runtimeCheckPath(kind: string, path: string, asyncOpts_?: { signal: AbortSignal }): Promise<RuntimePathProbe> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_local_runtime_check_path(
+ uniffiTypeLocalObjectFactory.clonePointer(this),FfiConverterString.lower(kind, nativeModule().rustbuffer_alloc),FfiConverterString.lower(path, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeRuntimePathProbe.lift.bind(FfiConverterTypeRuntimePathProbe),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+ async runtimeKinds(asyncOpts_?: { signal: AbortSignal }): Promise<Array<RuntimeKindState>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_local_runtime_kinds(
+ uniffiTypeLocalObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeRuntimeKindState.lift.bind(FfiConverterSequenceTypeRuntimeKindState),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -45662,6 +46119,12 @@ const FfiConverterSequenceTypeComputerResources = new FfiConverterArray(FfiConve
// FfiConverter for ComputerResources | undefined
const FfiConverterOptionalTypeComputerResources = new FfiConverterOptional(FfiConverterTypeComputerResources);
+// FfiConverter for Array<RuntimeDetected>
+const FfiConverterSequenceTypeRuntimeDetected = new FfiConverterArray(FfiConverterTypeRuntimeDetected);
+
+// FfiConverter for RuntimePathProbe | undefined
+const FfiConverterOptionalTypeRuntimePathProbe = new FfiConverterOptional(FfiConverterTypeRuntimePathProbe);
+
// FfiConverter for Array<ReadinessProbe>
const FfiConverterSequenceTypeReadinessProbe = new FfiConverterArray(FfiConverterTypeReadinessProbe);
@@ -45773,6 +46236,9 @@ const FfiConverterOptionalTypeAgentRunOptions = new FfiConverterOptional(FfiConv
// FfiConverter for Array<PairingCode>
const FfiConverterSequenceTypePairingCode = new FfiConverterArray(FfiConverterTypePairingCode);
+// FfiConverter for Array<RuntimeKindState>
+const FfiConverterSequenceTypeRuntimeKindState = new FfiConverterArray(FfiConverterTypeRuntimeKindState);
+
// FfiConverter for Array<SetupStep>
const FfiConverterSequenceTypeSetupStep = new FfiConverterArray(FfiConverterTypeSetupStep);
@@ -46164,9 +46630,18 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_detect() !== 59369) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_detect");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json() !== 18365) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json");
+ }
+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json() !== 39143) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json() !== 14363) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json() !== 37278) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_install_skills() !== 40049) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_install_skills");
}
@@ -46410,6 +46885,12 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_local_push_image() !== 29472) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_push_image");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_local_runtime_check_path() !== 59009) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_runtime_check_path");
+ }
+ if (nativeModule().uniffi_cua_sdk_checksum_method_local_runtime_kinds() !== 34595) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_runtime_kinds");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_local_setup() !== 57791) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_setup");
}
@@ -47652,6 +48133,9 @@ export default Object.freeze({
FfiConverterTypeRoutineInfo,
FfiConverterTypeRuntimeCheck,
FfiConverterTypeRuntimeCheckStatus,
+ FfiConverterTypeRuntimeDetected,
+ FfiConverterTypeRuntimeKindState,
+ FfiConverterTypeRuntimePathProbe,
FfiConverterTypeSandbox,
FfiConverterTypeSandboxCreateOptions,
FfiConverterTypeSandboxInfo,
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
index b9dba5a502..f8f3a8ad47 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
@@ -1407,6 +1407,16 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_spaces_ffi_fn_func_app_runtime_path_verdict": {
+ args: [FfiType.RustBuffer],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_spaces_ffi_fn_func_app_runtimes_choose": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_spaces_ffi_fn_func_app_sensitive_group_sdk": {
args: [FfiType.RustBuffer],
ret: FfiType.RustBuffer,
@@ -3317,6 +3327,16 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_spaces_ffi_checksum_func_app_runtime_path_verdict": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_spaces_ffi_checksum_func_app_runtimes_choose": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_spaces_ffi_checksum_func_app_sensitive_group_sdk": {
args: [],
ret: FfiType.UInt16,
@@ -4607,6 +4627,8 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_fn_func_app_roster_initial(spaces: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_roster_reduce(state: Uint8Array, action: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_rows_to_spaces(rows: Uint8Array, nowMs: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_runtime_path_verdict(check: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_runtimes_choose(input: Uint8Array, row: Uint8Array, option: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_sensitive_group_sdk(group: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_sent_file(report: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_sent_files_from_json(json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -4989,6 +5011,8 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_checksum_func_app_roster_initial(): number;
uniffi_cua_spaces_ffi_checksum_func_app_roster_reduce(): number;
uniffi_cua_spaces_ffi_checksum_func_app_rows_to_spaces(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_runtime_path_verdict(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_runtimes_choose(): number;
uniffi_cua_spaces_ffi_checksum_func_app_sensitive_group_sdk(): number;
uniffi_cua_spaces_ffi_checksum_func_app_sent_file(): number;
uniffi_cua_spaces_ffi_checksum_func_app_sent_files_from_json(): number;
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.ts
index da689322ed..736aa21d2b 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
@@ -4285,6 +4285,51 @@ export function appRowsToSpaces(rows: Array<AppSpaceRow>, nowMs: bigint): Array<
));
}
+/**
+ * A runtime binary's one line in Settings, Advanced ("Docker 27.3 found",
+ * "Not a Docker or Podman binary").
+ */
+export function appRuntimePathVerdict(check: AppRuntimePathCheck): AppRuntimePathVerdict {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeAppRuntimePathVerdict.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_runtime_path_verdict(
+ FfiConverterTypeAppRuntimePathCheck.lower(check, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * The setting a runtime row's choice changes (`runtime.<kind>` or
+ * `runtime.<kind>_path`; a `None` value unsets it), or none for any other
+ * row.
+ */
+export function appRuntimesChoose(input: AppRuntimesInput | undefined, row: string, option: string): AppRuntimeSettingChange | undefined {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterOptionalTypeAppRuntimeSettingChange.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_runtimes_choose(
+ FfiConverterOptionalTypeAppRuntimesInput.lower(input, nativeModule().rustbuffer_alloc),
+ FfiConverterString.lower(row, nativeModule().rustbuffer_alloc),
+ FfiConverterString.lower(option, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
/**
* The SDK's plan-option group for a picker group.
*/
@@ -20741,6 +20786,73 @@ const FfiConverterTypeAppDetailCopy = (() => {
return new FFIConverter();
})();
+export type AppDetectedRuntime = {
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */
+ tool: string,
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */
+ name: string,
+ path: string,
+ /**
+ * As its `--version` says it (`27.3.1`).
+ */
+ version?: string,
+ /**
+ * The one guest system it runs, when only one (`macOS`, `Linux`).
+ */
+ guests?: string
+}
+
+/**
+ * Generated factory for {@link AppDetectedRuntime} record objects.
+ */
+export const AppDetectedRuntime = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppDetectedRuntime, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppDetectedRuntime>,
+ });
+})();
+
+const FfiConverterTypeAppDetectedRuntime = (() => {
+ type TypeName = AppDetectedRuntime;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ tool: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ path: FfiConverterString.read(from),
+ version: FfiConverterOptionalString.read(from),
+ guests: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.tool, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.path, into);
+ FfiConverterOptionalString.write(value.version, into);
+ FfiConverterOptionalString.write(value.guests, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.tool) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.path) +
+ FfiConverterOptionalString.allocationSize(value.version) +
+ FfiConverterOptionalString.allocationSize(value.guests);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export enum AppBannerTone {
/**
* Informational.
@@ -31368,69 +31480,6 @@ const FfiConverterTypeAppMenuPreview = (() => {
return new FFIConverter();
})();
-export type AppMicrovmInput = {
- /**
- * This machine's system (`macos`, `linux`, `windows`).
- */
- os?: AppSpaceOs,
- /**
- * Ready backends (none: not read yet).
- */
- localBackends?: Array<string>,
- /**
- * Why each other backend is not ready, by backend name.
- */
- localDetails?: Map<string, string>,
- /**
- * This machine's architecture (`arm64`, `amd64`).
- */
- hostArch?: string
-}
-
-/**
- * Generated factory for {@link AppMicrovmInput} record objects.
- */
-export const AppMicrovmInput = (() => {
- const defaults = () => ({
- });
- const create = (() => {
- return uniffiCreateRecord<AppMicrovmInput, ReturnType<typeof defaults>>(defaults);
- })();
- return Object.freeze({
- create,
- new: create,
- defaults: () => Object.freeze(defaults()) as Partial<AppMicrovmInput>,
- });
-})();
-
-const FfiConverterTypeAppMicrovmInput = (() => {
- type TypeName = AppMicrovmInput;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
- return {
- os: FfiConverterOptionalTypeAppSpaceOs.read(from),
- localBackends: FfiConverterOptionalSequenceString.read(from),
- localDetails: FfiConverterOptionalMapStringString.read(from),
- hostArch: FfiConverterOptionalString.read(from)
- };
- }
- write(value: TypeName, into: RustBuffer): void {
- FfiConverterOptionalTypeAppSpaceOs.write(value.os, into);
- FfiConverterOptionalSequenceString.write(value.localBackends, into);
- FfiConverterOptionalMapStringString.write(value.localDetails, into);
- FfiConverterOptionalString.write(value.hostArch, into);
- }
- allocationSize(value: TypeName): number {
- return FfiConverterOptionalTypeAppSpaceOs.allocationSize(value.os) +
- FfiConverterOptionalSequenceString.allocationSize(value.localBackends) +
- FfiConverterOptionalMapStringString.allocationSize(value.localDetails) +
- FfiConverterOptionalString.allocationSize(value.hostArch);
-
- }
- };
- return new FFIConverter();
-})();
-
export enum AppOnboardingMode {
/**
* Access other machines (nothing installed).
@@ -39778,6 +39827,259 @@ const FfiConverterTypeAppRosterState = (() => {
return new FFIConverter();
})();
+export type AppRuntimePathCheck = {
+ path: string,
+ /**
+ * A file is there.
+ */
+ exists: boolean,
+ /**
+ * It can be run.
+ */
+ executable: boolean,
+ /**
+ * The tool it is, when it is one the kind takes.
+ */
+ tool?: string,
+ name?: string,
+ version?: string,
+ /**
+ * The oldest version Cua runs on.
+ */
+ minVersion?: string,
+ /**
+ * The tools the kind takes here (`Docker`, `Podman`).
+ */
+ expected: Array<string>,
+ guests?: string
+}
+
+/**
+ * Generated factory for {@link AppRuntimePathCheck} record objects.
+ */
+export const AppRuntimePathCheck = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppRuntimePathCheck, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppRuntimePathCheck>,
+ });
+})();
+
+const FfiConverterTypeAppRuntimePathCheck = (() => {
+ type TypeName = AppRuntimePathCheck;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ path: FfiConverterString.read(from),
+ exists: FfiConverterBool.read(from),
+ executable: FfiConverterBool.read(from),
+ tool: FfiConverterOptionalString.read(from),
+ name: FfiConverterOptionalString.read(from),
+ version: FfiConverterOptionalString.read(from),
+ minVersion: FfiConverterOptionalString.read(from),
+ expected: FfiConverterSequenceString.read(from),
+ guests: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.path, into);
+ FfiConverterBool.write(value.exists, into);
+ FfiConverterBool.write(value.executable, into);
+ FfiConverterOptionalString.write(value.tool, into);
+ FfiConverterOptionalString.write(value.name, into);
+ FfiConverterOptionalString.write(value.version, into);
+ FfiConverterOptionalString.write(value.minVersion, into);
+ FfiConverterSequenceString.write(value.expected, into);
+ FfiConverterOptionalString.write(value.guests, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.path) +
+ FfiConverterBool.allocationSize(value.exists) +
+ FfiConverterBool.allocationSize(value.executable) +
+ FfiConverterOptionalString.allocationSize(value.tool) +
+ FfiConverterOptionalString.allocationSize(value.name) +
+ FfiConverterOptionalString.allocationSize(value.version) +
+ FfiConverterOptionalString.allocationSize(value.minVersion) +
+ FfiConverterSequenceString.allocationSize(value.expected) +
+ FfiConverterOptionalString.allocationSize(value.guests);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type AppRuntimeKindInput = {
+ /**
+ * `container`, `vm` or `microvm`.
+ */
+ kind: string,
+ /**
+ * `runtime.<kind>`: `auto`, `builtin`, `system` (none: auto).
+ */
+ source?: string,
+ /**
+ * `runtime.<kind>_path`, when set.
+ */
+ path?: string,
+ /**
+ * What is installed for the kind, the one used first (none: not
+ * looked for yet).
+ */
+ detected?: Array<AppDetectedRuntime>,
+ /**
+ * The path in use, probed.
+ */
+ check?: AppRuntimePathCheck,
+ /**
+ * The tools the kind takes on this machine (`Docker`, `Podman`).
+ */
+ expected: Array<string>
+}
+
+/**
+ * Generated factory for {@link AppRuntimeKindInput} record objects.
+ */
+export const AppRuntimeKindInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppRuntimeKindInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppRuntimeKindInput>,
+ });
+})();
+
+const FfiConverterTypeAppRuntimeKindInput = (() => {
+ type TypeName = AppRuntimeKindInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ kind: FfiConverterString.read(from),
+ source: FfiConverterOptionalString.read(from),
+ path: FfiConverterOptionalString.read(from),
+ detected: FfiConverterOptionalSequenceTypeAppDetectedRuntime.read(from),
+ check: FfiConverterOptionalTypeAppRuntimePathCheck.read(from),
+ expected: FfiConverterSequenceString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.kind, into);
+ FfiConverterOptionalString.write(value.source, into);
+ FfiConverterOptionalString.write(value.path, into);
+ FfiConverterOptionalSequenceTypeAppDetectedRuntime.write(value.detected, into);
+ FfiConverterOptionalTypeAppRuntimePathCheck.write(value.check, into);
+ FfiConverterSequenceString.write(value.expected, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.kind) +
+ FfiConverterOptionalString.allocationSize(value.source) +
+ FfiConverterOptionalString.allocationSize(value.path) +
+ FfiConverterOptionalSequenceTypeAppDetectedRuntime.allocationSize(value.detected) +
+ FfiConverterOptionalTypeAppRuntimePathCheck.allocationSize(value.check) +
+ FfiConverterSequenceString.allocationSize(value.expected);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type AppRuntimePathVerdict = {
+ ok: boolean,
+ line: string
+}
+
+/**
+ * Generated factory for {@link AppRuntimePathVerdict} record objects.
+ */
+export const AppRuntimePathVerdict = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppRuntimePathVerdict, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppRuntimePathVerdict>,
+ });
+})();
+
+const FfiConverterTypeAppRuntimePathVerdict = (() => {
+ type TypeName = AppRuntimePathVerdict;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ ok: FfiConverterBool.read(from),
+ line: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterBool.write(value.ok, into);
+ FfiConverterString.write(value.line, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterBool.allocationSize(value.ok) +
+ FfiConverterString.allocationSize(value.line);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type AppRuntimeSettingChange = {
+ /**
+ * `runtime.container`, `runtime.vm_path`.
+ */
+ key: string,
+ value?: string
+}
+
+/**
+ * Generated factory for {@link AppRuntimeSettingChange} record objects.
+ */
+export const AppRuntimeSettingChange = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppRuntimeSettingChange, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppRuntimeSettingChange>,
+ });
+})();
+
+const FfiConverterTypeAppRuntimeSettingChange = (() => {
+ type TypeName = AppRuntimeSettingChange;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ key: FfiConverterString.read(from),
+ value: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.key, into);
+ FfiConverterOptionalString.write(value.value, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.key) +
+ FfiConverterOptionalString.allocationSize(value.value);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type AppRuntimeSwitch = {
/**
* The `cua config` setting: `runtime.lume`.
@@ -39841,6 +40143,76 @@ const FfiConverterTypeAppRuntimeSwitch = (() => {
return new FFIConverter();
})();
+export type AppRuntimesInput = {
+ /**
+ * This machine's system (none: not said; every option is offered).
+ */
+ os?: AppSpaceOs,
+ /**
+ * `arm64`, `amd64`.
+ */
+ hostArch?: string,
+ /**
+ * The runtime doctor's ready backends (none: not read yet).
+ */
+ localBackends?: Array<string>,
+ /**
+ * Why each other backend is not ready.
+ */
+ localDetails?: Map<string, string>,
+ /**
+ * Each kind's setting and what is installed for it (none: not read).
+ */
+ kinds?: Array<AppRuntimeKindInput>
+}
+
+/**
+ * Generated factory for {@link AppRuntimesInput} record objects.
+ */
+export const AppRuntimesInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppRuntimesInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppRuntimesInput>,
+ });
+})();
+
+const FfiConverterTypeAppRuntimesInput = (() => {
+ type TypeName = AppRuntimesInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ os: FfiConverterOptionalTypeAppSpaceOs.read(from),
+ hostArch: FfiConverterOptionalString.read(from),
+ localBackends: FfiConverterOptionalSequenceString.read(from),
+ localDetails: FfiConverterOptionalMapStringString.read(from),
+ kinds: FfiConverterOptionalSequenceTypeAppRuntimeKindInput.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalTypeAppSpaceOs.write(value.os, into);
+ FfiConverterOptionalString.write(value.hostArch, into);
+ FfiConverterOptionalSequenceString.write(value.localBackends, into);
+ FfiConverterOptionalMapStringString.write(value.localDetails, into);
+ FfiConverterOptionalSequenceTypeAppRuntimeKindInput.write(value.kinds, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalTypeAppSpaceOs.allocationSize(value.os) +
+ FfiConverterOptionalString.allocationSize(value.hostArch) +
+ FfiConverterOptionalSequenceString.allocationSize(value.localBackends) +
+ FfiConverterOptionalMapStringString.allocationSize(value.localDetails) +
+ FfiConverterOptionalSequenceTypeAppRuntimeKindInput.allocationSize(value.kinds);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type AppScreenFacts = {
/**
* `NSScreen.frame`.
@@ -41110,26 +41482,17 @@ export type AppSettingsInput = {
* without the preview cover leaves it out).
*/
autoConnect?: boolean,
- /**
- * Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,
- * `system`); none: no Runtimes section.
- */
- lumeSource?: string,
- /**
- * Which engine local Linux Spaces run on (`runtime.linux`: `auto`,
- * `builtin`, `system`); none: no Linux row.
- */
- linuxSource?: string,
/**
* Overflow into your clouds when this machine is full
* (`placement.overflow`); none: no row.
*/
overflow?: boolean,
/**
- * What this machine's runtime doctor said, for Runtimes' MicroVM row
- * (whether microVMs run here, and why not); none: no MicroVM row.
+ * Settings, Advanced's runtimes: each kind's setting, what is
+ * installed for it and whether it runs here. None: nothing read yet
+ * (the rows still show, "Checking…").
*/
- microvm?: AppMicrovmInput,
+ runtimes?: AppRuntimesInput,
/**
* Settings, General's Show tips switch: tips are on
* (`!AppSettings.tips.off`). A shell that does not say reads as on.
@@ -41175,10 +41538,8 @@ const FfiConverterTypeAppSettingsInput = (() => {
keyvaultSiteIcons: FfiConverterBool.read(from),
keyvaultProtection: FfiConverterSequenceTypeAppFact.read(from),
autoConnect: FfiConverterOptionalBoolean.read(from),
- lumeSource: FfiConverterOptionalString.read(from),
- linuxSource: FfiConverterOptionalString.read(from),
overflow: FfiConverterOptionalBoolean.read(from),
- microvm: FfiConverterOptionalTypeAppMicrovmInput.read(from),
+ runtimes: FfiConverterOptionalTypeAppRuntimesInput.read(from),
showTips: FfiConverterBool.read(from)
};
}
@@ -41200,10 +41561,8 @@ const FfiConverterTypeAppSettingsInput = (() => {
FfiConverterBool.write(value.keyvaultSiteIcons, into);
FfiConverterSequenceTypeAppFact.write(value.keyvaultProtection, into);
FfiConverterOptionalBoolean.write(value.autoConnect, into);
- FfiConverterOptionalString.write(value.lumeSource, into);
- FfiConverterOptionalString.write(value.linuxSource, into);
FfiConverterOptionalBoolean.write(value.overflow, into);
- FfiConverterOptionalTypeAppMicrovmInput.write(value.microvm, into);
+ FfiConverterOptionalTypeAppRuntimesInput.write(value.runtimes, into);
FfiConverterBool.write(value.showTips, into);
}
allocationSize(value: TypeName): number {
@@ -41224,10 +41583,8 @@ const FfiConverterTypeAppSettingsInput = (() => {
FfiConverterBool.allocationSize(value.keyvaultSiteIcons) +
FfiConverterSequenceTypeAppFact.allocationSize(value.keyvaultProtection) +
FfiConverterOptionalBoolean.allocationSize(value.autoConnect) +
- FfiConverterOptionalString.allocationSize(value.lumeSource) +
- FfiConverterOptionalString.allocationSize(value.linuxSource) +
FfiConverterOptionalBoolean.allocationSize(value.overflow) +
- FfiConverterOptionalTypeAppMicrovmInput.allocationSize(value.microvm) +
+ FfiConverterOptionalTypeAppRuntimesInput.allocationSize(value.runtimes) +
FfiConverterBool.allocationSize(value.showTips);
}
@@ -69568,12 +69925,6 @@ const FfiConverterOptionalTypeAppCloudsInput = new FfiConverterOptional(FfiConve
// FfiConverter for Array<AppMenuPreviewRow>
const FfiConverterSequenceTypeAppMenuPreviewRow = new FfiConverterArray(FfiConverterTypeAppMenuPreviewRow);
-// FfiConverter for AppSpaceOs | undefined
-const FfiConverterOptionalTypeAppSpaceOs = new FfiConverterOptional(FfiConverterTypeAppSpaceOs);
-
-// FfiConverter for Map<string, string> | undefined
-const FfiConverterOptionalMapStringString = new FfiConverterOptional(FfiConverterMapStringString);
-
// FfiConverter for Array<AppNotchButton>
const FfiConverterSequenceTypeAppNotchButton = new FfiConverterArray(FfiConverterTypeAppNotchButton);
@@ -69607,6 +69958,9 @@ const FfiConverterOptionalTypeAppCliInstallPlan = new FfiConverterOptional(FfiCo
// FfiConverter for AppOnboardingMode | undefined
const FfiConverterOptionalTypeAppOnboardingMode = new FfiConverterOptional(FfiConverterTypeAppOnboardingMode);
+// FfiConverter for AppSpaceOs | undefined
+const FfiConverterOptionalTypeAppSpaceOs = new FfiConverterOptional(FfiConverterTypeAppSpaceOs);
+
// FfiConverter for AppDriveStepRequest | undefined
const FfiConverterOptionalTypeAppDriveStepRequest = new FfiConverterOptional(FfiConverterTypeAppDriveStepRequest);
@@ -69733,6 +70087,24 @@ const FfiConverterSequenceTypeAppReviewPassword = new FfiConverterArray(FfiConve
// FfiConverter for AppNotice | undefined
const FfiConverterOptionalTypeAppNotice = new FfiConverterOptional(FfiConverterTypeAppNotice);
+// FfiConverter for Array<AppDetectedRuntime>
+const FfiConverterSequenceTypeAppDetectedRuntime = new FfiConverterArray(FfiConverterTypeAppDetectedRuntime);
+
+// FfiConverter for Array<AppDetectedRuntime> | undefined
+const FfiConverterOptionalSequenceTypeAppDetectedRuntime = new FfiConverterOptional(FfiConverterSequenceTypeAppDetectedRuntime);
+
+// FfiConverter for AppRuntimePathCheck | undefined
+const FfiConverterOptionalTypeAppRuntimePathCheck = new FfiConverterOptional(FfiConverterTypeAppRuntimePathCheck);
+
+// FfiConverter for Map<string, string> | undefined
+const FfiConverterOptionalMapStringString = new FfiConverterOptional(FfiConverterMapStringString);
+
+// FfiConverter for Array<AppRuntimeKindInput>
+const FfiConverterSequenceTypeAppRuntimeKindInput = new FfiConverterArray(FfiConverterTypeAppRuntimeKindInput);
+
+// FfiConverter for Array<AppRuntimeKindInput> | undefined
+const FfiConverterOptionalSequenceTypeAppRuntimeKindInput = new FfiConverterOptional(FfiConverterSequenceTypeAppRuntimeKindInput);
+
// FfiConverter for Array<AppRememberedChoice>
const FfiConverterSequenceTypeAppRememberedChoice = new FfiConverterArray(FfiConverterTypeAppRememberedChoice);
@@ -69754,8 +70126,8 @@ const FfiConverterOptionalTypeAppTeamsInput = new FfiConverterOptional(FfiConver
// FfiConverter for AppLoginItemInput | undefined
const FfiConverterOptionalTypeAppLoginItemInput = new FfiConverterOptional(FfiConverterTypeAppLoginItemInput);
-// FfiConverter for AppMicrovmInput | undefined
-const FfiConverterOptionalTypeAppMicrovmInput = new FfiConverterOptional(FfiConverterTypeAppMicrovmInput);
+// FfiConverter for AppRuntimesInput | undefined
+const FfiConverterOptionalTypeAppRuntimesInput = new FfiConverterOptional(FfiConverterTypeAppRuntimesInput);
// FfiConverter for Array<AppSettingsSection>
const FfiConverterSequenceTypeAppSettingsSection = new FfiConverterArray(FfiConverterTypeAppSettingsSection);
@@ -70075,6 +70447,9 @@ const FfiConverterOptionalTypeAppRelayUsageView = new FfiConverterOptional(FfiCo
// FfiConverter for Array<AppSpaceRow>
const FfiConverterSequenceTypeAppSpaceRow = new FfiConverterArray(FfiConverterTypeAppSpaceRow);
+// FfiConverter for AppRuntimeSettingChange | undefined
+const FfiConverterOptionalTypeAppRuntimeSettingChange = new FfiConverterOptional(FfiConverterTypeAppRuntimeSettingChange);
+
// FfiConverter for AppShareGate | undefined
const FfiConverterOptionalTypeAppShareGate = new FfiConverterOptional(FfiConverterTypeAppShareGate);
@@ -70751,6 +71126,12 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_rows_to_spaces() !== 20688) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_rows_to_spaces");
}
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_runtime_path_verdict() !== 38898) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_runtime_path_verdict");
+ }
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_runtimes_choose() !== 22513) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_runtimes_choose");
+ }
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_sensitive_group_sdk() !== 32734) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_sensitive_group_sdk");
}
@@ -71401,6 +71782,7 @@ export default Object.freeze({
FfiConverterTypeAppDetailAction,
FfiConverterTypeAppDetailActionId,
FfiConverterTypeAppDetailCopy,
+ FfiConverterTypeAppDetectedRuntime,
FfiConverterTypeAppDeviceAction,
FfiConverterTypeAppDeviceBanner,
FfiConverterTypeAppDeviceConfirm,
@@ -71547,7 +71929,6 @@ export default Object.freeze({
FfiConverterTypeAppMenuOption,
FfiConverterTypeAppMenuPreview,
FfiConverterTypeAppMenuPreviewRow,
- FfiConverterTypeAppMicrovmInput,
FfiConverterTypeAppModeChoice,
FfiConverterTypeAppMsg,
FfiConverterTypeAppNewSpaceOn,
@@ -71652,7 +72033,12 @@ export default Object.freeze({
FfiConverterTypeAppRoutineInput,
FfiConverterTypeAppRoutineScheduleKind,
FfiConverterTypeAppRuntime,
+ FfiConverterTypeAppRuntimeKindInput,
+ FfiConverterTypeAppRuntimePathCheck,
+ FfiConverterTypeAppRuntimePathVerdict,
+ FfiConverterTypeAppRuntimeSettingChange,
FfiConverterTypeAppRuntimeSwitch,
+ FfiConverterTypeAppRuntimesInput,
FfiConverterTypeAppSandboxImage,
FfiConverterTypeAppScreenFacts,
FfiConverterTypeAppSendSource,
diff --git a/apps/cua-spaces-desktop/test/agents-fixtures.ts b/apps/cua-spaces-desktop/test/agents-fixtures.ts
index 4da18d0403..e42971cfb5 100644
--- a/apps/cua-spaces-desktop/test/agents-fixtures.ts
+++ b/apps/cua-spaces-desktop/test/agents-fixtures.ts
@@ -190,6 +190,22 @@ export class FixtureAgentSetup implements AgentSetupRunning {
return JSON.stringify({ outcomes: [], removed_sign_ins: [] });
}
+ async disconnectPartsJson(agents: string[], skills: boolean, mcp: boolean, _signIn: boolean) {
+ this.calls.push(`disconnect-parts:${agents.join(",")}:${skills}:${mcp}`);
+ return JSON.stringify({ outcomes: [], removed_sign_ins: [] });
+ }
+
+ /** Codex's device code, approved at once (no browser in a fixture). */
+ async deviceSignInStartJson(agent: string) {
+ this.calls.push(`device-start:${agent}`);
+ return JSON.stringify({ id: `${agent}-1`, url: "https://auth.openai.com/codex/device", code: "ABCD-12345" });
+ }
+
+ async deviceSignInWaitJson(id: string) {
+ this.calls.push(`device-wait:${id}`);
+ return JSON.stringify({ imported: { source: "codex", env: "CODEX_AUTH_JSON", label: "Codex · ChatGPT sign-in", expires_ms: null, added_ms: 1 }, refused: null, line: null });
+ }
+
/** The sign-in finishes at once (no browser in a fixture). */
async signIn(agent: string) {
this.calls.push(`sign-in:${agent}`);
@@ -213,6 +229,6 @@ export const AGENT_METHODS = [
"agents.list", "agents.runs", "agents.events", "agents.start", "agents.message", "agents.pause", "agents.resume", "agents.setup", "agents.configure", "agents.signIn", "agents.setupDriver",
"agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine", "agents.removeRoutine",
"agents.allowComputer", "agents.revokeComputer",
- "agents.status", "agents.connect", "agents.disconnect",
- "agentKeys.list", "agentKeys.set", "agentKeys.remove",
+ "agents.status", "agents.connect", "agents.disconnect", "agents.signInStart", "agents.signInWait",
+ "agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell",
];
diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.ts
index 8a34c67f76..8af3900f9c 100644
--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts
+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts
@@ -194,7 +194,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {
expect(problems).toEqual([]);
// Every ported method has its case (or is checked below).
// (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts; resource numbers: resources.test.ts; presence: presence-bridge.test.ts; the Machines page's rename, remove and health checks: machines-view.test.ts; the Windows runtime fix: below.)
- const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", ...THREAD_OPERATIONS, ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);
+ const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", ...THREAD_OPERATIONS, ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);
const ported = bridge.registry.methods.filter((m) => !NOT_YET.includes(m) && !elsewhere.has(m));
expect(ported.filter((m) => !cases.some(([c]) => c === m))).toEqual([]);
});
@@ -611,7 +611,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {
"spaces.leave": { ids: ["local:nowhere"] },
};
// This machine, Devices, Settings and the rest: host-bridge.test.ts reads them with their arguments (the Machines page's rename and remove: machines-view.test.ts).
- const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", ...(THREAD_OPERATIONS as readonly string[] as OpName[]), ...VAULT_OPS, ...(HOST_OPS as OpName[])]);
+ const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", ...(THREAD_OPERATIONS as readonly string[] as OpName[]), ...VAULT_OPS, ...(HOST_OPS as OpName[])]);
// (The thread: thread.test.ts.)
const problems: string[] = [];
const checked: string[] = [];
diff --git a/apps/cua-spaces-desktop/test/damaged-state.test.ts b/apps/cua-spaces-desktop/test/damaged-state.test.ts
new file mode 100644
index 0000000000..dd790f0bcb
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/damaged-state.test.ts
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// State files that are truncated or garbage must not crash the app or lose
+// what they held: the app starts from the defaults and keeps the file as
+// `<name>.damaged` (the core does the same for settings.json).
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import * as path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { forgetKept, keepDamaged } from "../src/damaged";
+import { ChecklistModel } from "../src/model/checklist";
+import { OnboardingStore } from "../src/model/onboarding";
+import type { Native } from "../src/native/load";
+
+const dirs: string[] = [];
+const dir = () => {
+ const d = mkdtempSync(path.join(tmpdir(), "cua-damaged-"));
+ dirs.push(d);
+ return d;
+};
+beforeEach(forgetKept);
+afterEach(() => dirs.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true })));
+
+/** The steps the checklist's words map to (the real ones come from the native core). */
+const native = { AppChecklistStep: { AddMachine: "AddMachine", CreateSpace: "CreateSpace", Teleport: "Teleport", Share: "Share", RunAgent: "RunAgent" } } as unknown as Native;
+
+const GARBAGE = ["{", '{"completed": tru', "", "null", "[]", "\u0000\u0001garbage", '"a string"'];
+
+describe("keepDamaged", () => {
+ it("copies the file beside itself, once per content, and says so", () => {
+ const d = dir();
+ const file = path.join(d, "x.json");
+ writeFileSync(file, "{ truncated");
+ const said: string[] = [];
+ expect(keepDamaged(file, "is damaged", (m) => said.push(m))).toBe(`${file}.damaged`);
+ expect(readFileSync(`${file}.damaged`, "utf8")).toBe("{ truncated");
+ expect(said).toHaveLength(1);
+ expect(said[0]).toContain(`${file}.damaged`);
+ // Read again (the app reads state files often): not copied or said again.
+ expect(keepDamaged(file, "is damaged", (m) => said.push(m))).toBe(`${file}.damaged`);
+ expect(said).toHaveLength(1);
+ });
+
+ it("keeps the latest damaged file when it changes", () => {
+ const d = dir();
+ const file = path.join(d, "x.json");
+ writeFileSync(file, "first");
+ keepDamaged(file, "is damaged", () => {});
+ writeFileSync(file, "second, longer");
+ keepDamaged(file, "is damaged", () => {});
+ expect(readFileSync(`${file}.damaged`, "utf8")).toBe("second, longer");
+ });
+
+ it("keeps a private file private, and never throws for a missing one", () => {
+ if (process.platform === "win32") return;
+ const d = dir();
+ const file = path.join(d, "secret.json");
+ writeFileSync(file, "{", { mode: 0o600 });
+ keepDamaged(file, "is damaged", () => {});
+ expect(statSync(`${file}.damaged`).mode & 0o777).toBe(0o600);
+ expect(keepDamaged(path.join(d, "missing.json"))).toBeNull();
+ });
+});
+
+describe("the first run's state", () => {
+ it.each(GARBAGE)("starts the first run again for %j, and keeps the file", (text) => {
+ const d = dir();
+ const s = new OnboardingStore(path.join(d, "onboarding.json"));
+ writeFileSync(s.file, text);
+ expect(s.read()).toEqual({ completed: false, mode: "client" });
+ expect(readFileSync(`${s.file}.damaged`, "utf8")).toBe(text);
+ // Finishing writes a good file over it; the damaged copy stays.
+ s.finish("host");
+ expect(s.read()).toEqual({ completed: true, mode: "host" });
+ expect(existsSync(`${s.file}.damaged`)).toBe(true);
+ });
+
+ it("does not keep anything for a missing or a good file", () => {
+ const d = dir();
+ const s = new OnboardingStore(path.join(d, "onboarding.json"));
+ expect(s.read().completed).toBe(false);
+ s.finish("client");
+ expect(s.read().completed).toBe(true);
+ expect(existsSync(`${s.file}.damaged`)).toBe(false);
+ });
+});
+
+describe("the checklist", () => {
+ it.each(GARBAGE)("starts empty for %j, and keeps the file", (text) => {
+ const d = dir();
+ const file = path.join(d, "checklist.json");
+ writeFileSync(file, text);
+ const m = new ChecklistModel(native, file);
+ expect(m.state).toEqual({ done: [], dismissed: false, shown: false, skipped: [] });
+ expect(readFileSync(`${file}.damaged`, "utf8")).toBe(text);
+ });
+
+ it("reads a good file and keeps nothing", () => {
+ const d = dir();
+ const file = path.join(d, "checklist.json");
+ writeFileSync(file, JSON.stringify({ done: ["create_space"], dismissed: true, shown: true, skipped: [] }));
+ const m = new ChecklistModel(native, file);
+ expect(m.state.done).toEqual(["CreateSpace"]);
+ expect(m.state.dismissed).toBe(true);
+ expect(existsSync(`${file}.damaged`)).toBe(false);
+ });
+
+ it("does not copy the Swift app's damaged seed file (it is not ours)", () => {
+ const d = dir();
+ const seed = path.join(d, "seed.json");
+ writeFileSync(seed, "{");
+ const m = new ChecklistModel(native, path.join(d, "checklist.json"), seed);
+ expect(m.state.done).toEqual([]);
+ expect(existsSync(`${seed}.damaged`)).toBe(false);
+ });
+});
diff --git a/apps/cua-spaces-desktop/test/fixtures.ts b/apps/cua-spaces-desktop/test/fixtures.ts
index 664ddf51bd..1e731c6993 100644
--- a/apps/cua-spaces-desktop/test/fixtures.ts
+++ b/apps/cua-spaces-desktop/test/fixtures.ts
@@ -196,6 +196,25 @@ export class FixtureSpacesBackend implements SpacesBackend {
return "auto";
}
async setLinuxSource() {}
+ runtimeSettings = new Map<string, string>();
+ async runtimeKinds() {
+ return ["container", "vm", "microvm"].map((kind) => ({
+ kind,
+ source: this.runtimeSettings.get(`runtime.${kind}`) ?? "auto",
+ path: this.runtimeSettings.get(`runtime.${kind}_path`),
+ detected: kind === "container" ? [{ tool: "docker", name: "Docker", path: "/usr/local/bin/docker", version: "27.3.1", guests: undefined }] : [],
+ check: undefined,
+ expected: kind === "container" ? ["Docker", "Podman"] : [],
+ }));
+ }
+ async runtimeCheckPath(kind: string, path: string) {
+ const docker = kind === "container" && path === "/usr/local/bin/docker";
+ return { path, exists: docker, executable: docker, tool: docker ? "docker" : undefined, name: docker ? "Docker" : undefined, version: docker ? "27.3.1" : undefined, minVersion: undefined, expected: ["Docker", "Podman"], guests: undefined };
+ }
+ async setRuntimeSetting(key: string, value: string | null) {
+ if (value === null) this.runtimeSettings.delete(key);
+ else this.runtimeSettings.set(key, value);
+ }
async localStorage() {
return null;
}
diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.ts
index a15cf42279..99188b0deb 100644
--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts
+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts
@@ -529,7 +529,8 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
};
const rows = s.page.sections.flatMap((x) => x.rows.map((r) => r.id));
expect(rows).toEqual(expect.arrayContaining(["account", "notch", "auto-connect", "welcome", "teams", "teams-manage", "teams-billing", "telemetry", "telemetry-note", "launch-at-login"]));
- expect(rows).toEqual(expect.arrayContaining(["macos-runtime", "linux-runtime"]));
+ // One runtime row per kind, on every system.
+ expect(rows).toEqual(expect.arrayContaining(["runtime:container", "runtime:vm", "runtime:microvm"]));
expect(s.updateChannel).toBe("stable");
// Another app holds ⌘⇧Space: the page says so.
expect(s.globalShortcut).toEqual({ label: "\u2318\u21e7Space", registered: false });
@@ -597,20 +598,25 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
expect(await code("settings.choose", { row: "experiment:classic_ui", option: "on" })).toBe("unsupported");
});
- it("New Space's \u201cUse built-in Lume\u201d and \u201cUse built-in runtime\u201d change the Runtimes rows", async () => {
- const set: string[] = [];
- Object.assign(backend, { setLumeSource: async (v: string) => void set.push(`lume=${v}`) });
- backend.lumeSource = async () => "builtin";
- Object.assign(backend, { setLinuxSource: async (v: string) => void set.push(`linux=${v}`) });
- backend.linuxSource = async () => "builtin";
- // The wizard's switch (`RUNTIME_SWITCH_ROW`): the same choice as Settings, Runtimes.
- const s = (await call("settings.choose", { row: "macos-runtime", option: "builtin" })) as { page: { sections: { rows: { id: string; options: { id: string; active: boolean }[] }[] }[] } };
- await call("settings.choose", { row: "linux-runtime", option: "builtin" });
- expect(set).toEqual(["lume=builtin", "linux=builtin"]);
- expect(model.lumeSource).toBe("builtin");
- expect(model.linuxSource).toBe("builtin");
- const row = s.page.sections.flatMap((x) => x.rows).find((r) => r.id === "macos-runtime")!;
- expect(row.options.find((o) => o.active)?.id).toBe("builtin");
+ it("New Space's \u201cUse built-in Lume\u201d and Settings' kind rows write the per-kind runtime settings", async () => {
+ const fixture = backend as unknown as { runtimeSettings: Map<string, string> };
+ // The wizard's switch (`RUNTIME_SWITCH_ROW`): the same choice as Settings, Advanced.
+ const s = (await call("settings.choose", { row: "runtime:vm", option: "builtin" })) as { page: { sections: { rows: { id: string; label: string; value?: string; options: { id: string; active: boolean }[] }[] }[] } };
+ expect(fixture.runtimeSettings.get("runtime.vm")).toBe("builtin");
+ const rows = () => s.page.sections.flatMap((x) => x.rows);
+ expect(rows().find((r) => r.id === "runtime:vm")!.options.find((o) => o.active)?.id).toBe("builtin");
+ // Already installed: what is installed and the path in use.
+ const t = (await call("settings.choose", { row: "runtime:container", option: "system" })) as typeof s;
+ const path = t.page.sections.flatMap((x) => x.rows).find((r) => r.id === "runtime-path:container")!;
+ expect([path.label, path.value]).toEqual(["Detected", "/usr/local/bin/docker"]);
+ await call("settings.choose", { row: "runtime-path:container", option: "/opt/homebrew/bin/podman" });
+ expect(fixture.runtimeSettings.get("runtime.container_path")).toBe("/opt/homebrew/bin/podman");
+ await call("settings.choose", { row: "runtime-path:container", option: "" });
+ expect(fixture.runtimeSettings.has("runtime.container_path")).toBe(false);
+ // A typed path, checked before it is saved.
+ expect(await call("runtimes.check", { kind: "container", path: "/usr/local/bin/docker" })).toMatchObject({ tool: "docker", version: "27.3.1" });
+ // "Browse…" is the app's file panel (none in this fixture UI).
+ expect(await code("runtimes.browse", { kind: "container" })).toBe("unsupported");
});
it("lists the coding agents under AI agents, and a row's button sets one up", async () => {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
index 382a7b43b2..17214966b4 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
@@ -34,7 +34,8 @@ public final class AgentKeysModel {
func call(_ method: String, _ args: [String: Any] = [:]) async throws -> Any {
guard let tools else { throw AgentsToolError(message: "Agent keys need the cua daemon") }
let r = try await tools.agentsTool(method, args)
- if let r = r as? [String: Any] {
+ // Every method answers the list after it, except agent_keys.shell (names your shell has).
+ if method != "agent_keys.shell", let r = r as? [String: Any] {
report = r
error = nil
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index c2ff22af70..8db2ee4ba3 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -1807,14 +1807,74 @@ public final class AppModel {
experiments: settings.experiments, keyvaultAutoWipe: keyvault.autoWipe,
keyvaultUnlockPrompt: keyvault.unlockPromptShows,
keyvaultSiteIcons: settings.keyvaultSiteIcons, keyvaultProtection: keyvault.page.protection,
- autoConnect: settings.autoConnect, lumeSource: lumeSource, linuxSource: linuxSource,
+ autoConnect: settings.autoConnect,
overflow: placementOverflow,
- // Runtimes' MicroVM row: the runtime doctor New Space's MicroVM tile follows.
- microvm: AppMicrovmInput(os: .macos, localBackends: wizard.env.localBackends,
- localDetails: wizard.env.localDetails, hostArch: wizard.env.hostArch),
+ runtimes: runtimesInput,
showTips: !settings.tips.off))
}
+ // MARK: - Runtimes (Settings, Advanced)
+
+ /// Each kind of Space's runtime setting and what is installed for it,
+ /// once read (`runtime_kinds`).
+ public private(set) var runtimeKinds: [AppRuntimeKindInput]?
+ /// The runtime doctor's answer for Settings (ready backends, why not),
+ /// once read.
+ public private(set) var runtimeDoctor: (ready: [String], details: [String: String])?
+ /// When the runtimes were last read.
+ @ObservationIgnored private var runtimesReadAt: Date?
+ @ObservationIgnored private var runtimesReading = false
+ /// How long a read of the runtimes stands before the page's next
+ /// `settings.get` reads them again.
+ static let runtimesRefreshInterval: TimeInterval = 15
+
+ /// What Settings, Advanced's runtime rows are laid out from
+ /// (`runtimes::section`): every kind, "Checking…" until read.
+ public var runtimesInput: AppRuntimesInput {
+ AppRuntimesInput(os: .macos, hostArch: Self.hostArch,
+ localBackends: runtimeDoctor?.ready, localDetails: runtimeDoctor?.details,
+ kinds: runtimeKinds)
+ }
+
+ /// Reads the runtimes again when the last read is older than
+ /// `runtimesRefreshInterval` (or `force`), in the background: the page
+ /// hears `settings.changed` when they come in.
+ public func refreshRuntimesIfStale(force: Bool = false) {
+ guard servicesIn, !runtimesReading else { return }
+ if !force, let at = runtimesReadAt, Date().timeIntervalSince(at) < Self.runtimesRefreshInterval { return }
+ runtimesReading = true
+ Task { @MainActor in
+ await readRuntimes()
+ runtimesReading = false
+ }
+ }
+
+ /// Reads each kind's setting, what is installed and the doctor.
+ public func readRuntimes() async {
+ async let doctor = backend.localRuntimes()
+ async let kinds = backend.runtimeKinds()
+ let (d, k) = await (doctor, kinds)
+ runtimesReadAt = Date()
+ if let d, runtimeDoctor.map({ $0.ready != d.ready || $0.details != d.details }) ?? true { runtimeDoctor = d }
+ if let k, k != runtimeKinds { runtimeKinds = k }
+ }
+
+ /// A runtime row's choice (`runtime:<kind>`, `runtime-detected:<kind>`,
+ /// `runtime-path:<kind>`): the setting the core names, written; the
+ /// runtimes read again. Whether `row` was one.
+ func chooseRuntime(row: String, option: String) async -> Bool {
+ guard let change = appRuntimesChoose(input: runtimesInput, row: row, option: option) else { return false }
+ do {
+ try await backend.setRuntimeSetting(key: change.key, value: change.value)
+ } catch {
+ show(error: LiveSpacesBackend.words(error))
+ }
+ await readRuntimes()
+ // New Space's "Use built-in" switches read the same settings.
+ await loadRuntimeSettings()
+ return true
+ }
+
/// Teams for Settings: the account's organizations with their people
/// (the Spaces API), and the account app's address for this environment.
var teamsSettingsInput: AppTeamsInput {
@@ -1978,9 +2038,7 @@ public final class AppModel {
/// Reads what Settings shows (telemetry, the coding agents).
public func loadSettings() async {
- lumeSource = await backend.lumeSource()
- linuxSource = await backend.linuxSource()
- placementOverflow = await backend.placementOverflow()
+ await loadRuntimeSettings()
telemetryInput = telemetry?.status()
readLoginItem()
await storage.load()
@@ -1989,6 +2047,21 @@ public final class AppModel {
await keyvault.refresh()
}
+ /// Reads the settings Settings, Advanced shows from the config file
+ /// (`runtime.lume`, `runtime.linux`, `placement.overflow`). The page's
+ /// `settings.get` asks for them each time: without this read the
+ /// runtime choices were missing from the page (only New Space's probe
+ /// read them). Each one changes only when its value does, so the
+ /// `settings.changed` it causes never loops.
+ public func loadRuntimeSettings() async {
+ let lume = await backend.lumeSource()
+ let linux = await backend.linuxSource()
+ let overflow = await backend.placementOverflow()
+ if lume != lumeSource { lumeSource = lume }
+ if linux != linuxSource { linuxSource = linux }
+ if overflow != placementOverflow { placementOverflow = overflow }
+ }
+
/// Opens a website page (the account app's Teams page and billing).
public func openBillingPage(_ raw: String) {
guard let url = URL(string: raw), url.scheme == "https" || url.scheme == "http" else { return }
@@ -2020,20 +2093,8 @@ public final class AppModel {
case "notch":
settings.menuBar = option == "hide"
saveSettings()
- case "macos-runtime":
- do {
- try await backend.setLumeSource(option)
- lumeSource = await backend.lumeSource() ?? option
- } catch {
- show(error: LiveSpacesBackend.words(error))
- }
- case "linux-runtime":
- do {
- try await backend.setLinuxSource(option)
- linuxSource = await backend.linuxSource() ?? option
- } catch {
- show(error: LiveSpacesBackend.words(error))
- }
+ case _ where row.hasPrefix("runtime"):
+ _ = await chooseRuntime(row: row, option: option)
case "placement-overflow":
do {
try await backend.setPlacementOverflow(option == "on")
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
index b7fad44861..8ed419c9ae 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
@@ -35,6 +35,12 @@ public protocol AgentSetupRunning: AnyObject, Sendable {
func connectJson(agents: [String], signIn: Bool, skills: Bool, mcp: Bool) async throws -> String
/// Disconnect: both undone. JSON `{outcomes, removed_sign_ins}`.
func disconnectJson(agents: [String], signIn: Bool) async throws -> String
+ /// Disconnect of some parts only (an app's page's switches).
+ func disconnectPartsJson(agents: [String], skills: Bool, mcp: Bool, signIn: Bool) async throws -> String
+ /// An agent's device-code sign-in made for Cua (Codex): JSON `{id, url, code}`.
+ func deviceSignInStartJson(agent: String) async throws -> String
+ /// Waits for it to be approved and saves it in Keyvault: JSON as Connect's `sign_in`.
+ func deviceSignInWaitJson(id: String) async throws -> String
}
/// The SDK's `AgentSetup`, registering the app's own `cua` as the MCP
@@ -84,6 +90,18 @@ public final class LiveAgentSetup: AgentSetupRunning, @unchecked Sendable {
public func disconnectJson(agents: [String], signIn: Bool) async throws -> String {
try await inner.disconnectJson(agents: agents, signIn: signIn)
}
+
+ public func disconnectPartsJson(agents: [String], skills: Bool, mcp: Bool, signIn: Bool) async throws -> String {
+ try await inner.disconnectPartsJson(agents: agents, skills: skills, mcp: mcp, signIn: signIn)
+ }
+
+ public func deviceSignInStartJson(agent: String) async throws -> String {
+ try await inner.deviceSignInStartJson(agent: agent)
+ }
+
+ public func deviceSignInWaitJson(id: String) async throws -> String {
+ try await inner.deviceSignInWaitJson(id: id)
+ }
}
/// In-memory agents for fixtures and tests: nothing on disk is read or written.
@@ -188,6 +206,22 @@ public final class FixtureAgentSetup: AgentSetupRunning, @unchecked Sendable {
return #"{"outcomes":[],"removed_sign_ins":[]}"#
}
+ public func disconnectPartsJson(agents: [String], skills: Bool, mcp: Bool, signIn: Bool) async throws -> String {
+ calls.append("disconnect-parts:\(agents.joined(separator: ",")):\(skills):\(mcp)")
+ return #"{"outcomes":[],"removed_sign_ins":[]}"#
+ }
+
+ /// Codex's device code, approved at once (no browser in fixtures).
+ public func deviceSignInStartJson(agent: String) async throws -> String {
+ calls.append("device-start:\(agent)")
+ return #"{"id":"\#(agent)-1","url":"https://auth.openai.com/codex/device","code":"ABCD-12345"}"#
+ }
+
+ public func deviceSignInWaitJson(id: String) async throws -> String {
+ calls.append("device-wait:\(id)")
+ return #"{"imported":{"source":"codex","env":"CODEX_AUTH_JSON","label":"Codex · ChatGPT sign-in","expires_ms":null,"added_ms":1},"refused":null,"line":null}"#
+ }
+
public func remove(agents: [String]) async throws -> [AppAgentSetupOutcomeInput] {
calls.append("remove:\(agents.joined(separator: ","))")
for i in current.indices where agents.contains(current[i].id) {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
index 138c9d6942..73ed37bb67 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
@@ -638,6 +638,13 @@ public final class PendingSpacesBackend: SpacesBackend, AgentsToolRunning, Cloud
public func setLinuxSource(_ value: String) async throws { try await b().setLinuxSource(value) }
public func placementOverflow() async -> Bool? { await b().placementOverflow() }
public func setPlacementOverflow(_ on: Bool) async throws { try await b().setPlacementOverflow(on) }
+ public func runtimeKinds() async -> [AppRuntimeKindInput]? { await b().runtimeKinds() }
+ public func runtimeCheckPath(kind: String, path: String) async throws -> AppRuntimePathCheck {
+ try await b().runtimeCheckPath(kind: kind, path: path)
+ }
+ public func setRuntimeSetting(key: String, value: String?) async throws {
+ try await b().setRuntimeSetting(key: key, value: value)
+ }
public func localStorage() async -> LocalStorage? { await b().localStorage() }
public func runningMacosVms() async -> Int? { await b().runningMacosVms() }
// The Machines page: Remove from account and each computer's health
@@ -742,6 +749,15 @@ public final class PendingAgentSetup: AgentSetupRunning, @unchecked Sendable {
public func disconnectJson(agents: [String], signIn: Bool) async throws -> String {
try await s().disconnectJson(agents: agents, signIn: signIn)
}
+ public func disconnectPartsJson(agents: [String], skills: Bool, mcp: Bool, signIn: Bool) async throws -> String {
+ try await s().disconnectPartsJson(agents: agents, skills: skills, mcp: mcp, signIn: signIn)
+ }
+ public func deviceSignInStartJson(agent: String) async throws -> String {
+ try await s().deviceSignInStartJson(agent: agent)
+ }
+ public func deviceSignInWaitJson(id: String) async throws -> String {
+ try await s().deviceSignInWaitJson(id: id)
+ }
}
/// This Mac's relay devices until the SDK is in.
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ChecklistModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ChecklistModel.swift
index d31680ea11..b616b45573 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ChecklistModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/ChecklistModel.swift
@@ -54,8 +54,12 @@ public final class ChecklistModel {
]
private static func read(_ path: String) -> AppChecklistState? {
- guard let data = FileManager.default.contents(atPath: path),
- let s = try? JSONDecoder().decode(Stored.self, from: data) else { return nil }
+ guard let data = FileManager.default.contents(atPath: path) else { return nil }
+ guard let s = try? JSONDecoder().decode(Stored.self, from: data) else {
+ // Truncated or garbage: the defaults, and the file kept as `.damaged`.
+ DamagedFile.keep(path)
+ return nil
+ }
return state(done: s.done, dismissed: s.dismissed, shown: s.shown, skipped: s.skipped ?? [])
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DamagedFile.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DamagedFile.swift
new file mode 100644
index 0000000000..4cad6216c4
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DamagedFile.swift
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import Foundation
+
+/// A state file that is not what it should be (cut short by a crash or a full
+/// disk, or garbage) must not crash the app or lose what it held: the app
+/// starts from the defaults and the file stays beside it as `<name>.damaged`
+/// until the next save writes a good one over the original. The core does the
+/// same for settings.json (`settings::load`).
+enum DamagedFile {
+ /// Keeps `path` as `<path>.damaged` (the latest damaged one replaces an
+ /// older copy; a copy that is already the same is left alone, so a file
+ /// read on every launch step is not copied again). Returns where it went,
+ /// or nil when it could not be kept. Copies keep the file's mode.
+ @discardableResult
+ static func keep(_ path: String) -> String? {
+ let fm = FileManager.default
+ let copy = path + ".damaged"
+ guard let data = fm.contents(atPath: path) else { return nil }
+ if let kept = fm.contents(atPath: copy), kept == data { return copy }
+ do {
+ if fm.fileExists(atPath: copy) { try fm.removeItem(atPath: copy) }
+ try fm.copyItem(atPath: path, toPath: copy)
+ NSLog("cua-spaces: %@ is damaged; starting from the defaults, the file is kept as %@", path, copy)
+ return copy
+ } catch {
+ return nil
+ }
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swift
index 00ab917155..3137f7a0e9 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swift
@@ -51,9 +51,13 @@ public final class OnboardingModel {
static func readCompleted(_ path: String) -> Bool? { read(path)?.completed }
private static func read(_ path: String) -> (completed: Bool, mode: AppOnboardingMode)? {
- guard let data = FileManager.default.contents(atPath: path),
- let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let completed = obj["completed"] as? Bool else { return nil }
+ // No file: the first run is due. A file that is not valid state: due too, and kept as `.damaged`.
+ guard let data = FileManager.default.contents(atPath: path) else { return nil }
+ guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let completed = obj["completed"] as? Bool else {
+ DamagedFile.keep(path)
+ return nil
+ }
return (completed, (obj["mode"] as? String) == "host" ? .host : .client)
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceThumbnails.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceThumbnails.swift
index bf18da2f25..183c828362 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceThumbnails.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceThumbnails.swift
@@ -154,9 +154,15 @@ public final class SpaceThumbnails {
keeping?.cancel()
let interval = TimeInterval(Self.policy.backgroundIntervalMs) / 1000
keeping = Task { @MainActor [weak self] in
+ var cursor = 0
while !Task.isCancelled {
if let self, active() {
- for id in running() {
+ // A sweep refreshes at most `sweepLimit` Spaces, picking up where the last one
+ // stopped: with 256 running Spaces that is a few screenshots a second to each of
+ // the machines, not all of them every interval.
+ let sweep = Self.sweep(running(), from: cursor, limit: Self.sweepLimit)
+ cursor = sweep.next
+ for id in sweep.ids {
_ = await self.refresh(id, maxAge: interval)
}
}
@@ -165,6 +171,20 @@ public final class SpaceThumbnails {
}
}
+ /// The most Spaces one background sweep refreshes.
+ public static let sweepLimit = 32
+
+ /// The Spaces to refresh now: up to `limit` of `ids` from position `from`
+ /// on, wrapping, and where the next sweep starts. A list that fits is all
+ /// of it, every time.
+ public static func sweep(_ ids: [String], from: Int, limit: Int) -> (ids: [String], next: Int) {
+ guard !ids.isEmpty, limit > 0 else { return ([], 0) }
+ if ids.count <= limit { return (ids, 0) }
+ let start = from % ids.count
+ let take = (0..<limit).map { ids[(start + $0) % ids.count] }
+ return (take, (start + limit) % ids.count)
+ }
+
/// Visible and not saving power.
public static func appActive() -> Bool {
!NSApp.isHidden && !ProcessInfo.processInfo.isLowPowerModeEnabled
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift
index 71ad77b19d..16c44ad16b 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift
@@ -88,6 +88,14 @@ public protocol SpacesBackend: AnyObject, Sendable {
func placementOverflow() async -> Bool?
/// Sets `placement.overflow`.
func setPlacementOverflow(_ on: Bool) async throws
+ /// Each kind of Space's runtime setting (`runtime.<kind>`, its path) and
+ /// what is installed on this Mac for it (`runtime_kinds`), when known.
+ func runtimeKinds() async -> [AppRuntimeKindInput]?
+ /// What `path` is for `kind` (`container`, `vm`, `microvm`).
+ func runtimeCheckPath(kind: String, path: String) async throws -> AppRuntimePathCheck
+ /// Writes a runtime setting (`runtime.container`, `runtime.vm_path`), or
+ /// unsets it (`nil`).
+ func setRuntimeSetting(key: String, value: String?) async throws
/// Free space where local Spaces are written and which images are
/// pulled (`local().storage()`), when known.
func localStorage() async -> LocalStorage?
@@ -271,6 +279,11 @@ public extension SpacesBackend {
func setLinuxSource(_ value: String) async throws {}
func placementOverflow() async -> Bool? { nil }
func setPlacementOverflow(_ on: Bool) async throws {}
+ func runtimeKinds() async -> [AppRuntimeKindInput]? { nil }
+ func runtimeCheckPath(kind: String, path: String) async throws -> AppRuntimePathCheck {
+ throw FixtureError(message: "Runtimes can't be checked here")
+ }
+ func setRuntimeSetting(key: String, value: String?) async throws {}
}
/// The wizard's GPU choices from the SDK's `gpu_support`: the first option
@@ -596,6 +609,35 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {
(try? configGet(key: "placement.overflow")).map { $0.value != "off" }
}
+ public func runtimeKinds() async -> [AppRuntimeKindInput]? {
+ let result = await withTimeout(seconds: Self.probeSeconds) { [cua] in try await cua.local().runtimeKinds() }
+ guard case .success(let kinds) = result else { return nil }
+ return kinds.map(Self.runtimeKind)
+ }
+
+ public func runtimeCheckPath(kind: String, path: String) async throws -> AppRuntimePathCheck {
+ Self.pathCheck(try await cua.local().runtimeCheckPath(kind: kind, path: path))
+ }
+
+ public func setRuntimeSetting(key: String, value: String?) async throws {
+ if let value { _ = try configSet(key: key, value: value) } else { _ = try configUnset(key: key) }
+ }
+
+ /// The SDK's kind as the app core's Settings input takes it.
+ static func runtimeKind(_ k: RuntimeKindState) -> AppRuntimeKindInput {
+ AppRuntimeKindInput(
+ kind: k.kind, source: k.source, path: k.path,
+ detected: k.detected.map {
+ AppDetectedRuntime(tool: $0.tool, name: $0.name, path: $0.path, version: $0.version, guests: $0.guests)
+ },
+ check: k.check.map(pathCheck), expected: k.expected)
+ }
+
+ static func pathCheck(_ p: RuntimePathProbe) -> AppRuntimePathCheck {
+ AppRuntimePathCheck(path: p.path, exists: p.exists, executable: p.executable, tool: p.tool, name: p.name,
+ version: p.version, minVersion: p.minVersion, expected: p.expected, guests: p.guests)
+ }
+
public func setPlacementOverflow(_ on: Bool) async throws {
_ = try configSet(key: "placement.overflow", value: on ? "on" : "off")
}
@@ -1240,6 +1282,40 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {
public var fixturePlacementOverflow: Bool? = true
public func placementOverflow() async -> Bool? { await MainActor.run { fixturePlacementOverflow } }
public func setPlacementOverflow(_ on: Bool) async throws { await MainActor.run { fixturePlacementOverflow = on } }
+ /// The fixture Mac's runtime settings (`runtime.<kind>`, `runtime.<kind>_path`).
+ public var fixtureRuntimeSettings: [String: String] = [:]
+ /// What the fixture Mac has installed, per kind (path, version).
+ public var fixtureInstalled: [String: [AppDetectedRuntime]] = [
+ "container": [AppDetectedRuntime(tool: "docker", name: "Docker", path: "/usr/local/bin/docker", version: "27.3.1", guests: nil)],
+ "vm": [AppDetectedRuntime(tool: "lume", name: "Lume", path: "/opt/homebrew/bin/lume", version: "0.6.1", guests: "macOS")],
+ "microvm": [],
+ ]
+ static let fixtureExpected = ["container": ["Docker", "Podman"], "vm": ["Lume"], "microvm": ["Apple container"]]
+ public func runtimeKinds() async -> [AppRuntimeKindInput]? {
+ await MainActor.run {
+ ["container", "vm", "microvm"].map { kind in
+ let found = fixtureInstalled[kind] ?? []
+ let path = fixtureRuntimeSettings["runtime.\(kind)_path"]
+ let inUse = path ?? found.first?.path
+ return AppRuntimeKindInput(kind: kind, source: fixtureRuntimeSettings["runtime.\(kind)"] ?? "auto", path: path,
+ detected: found, check: inUse.map { fixtureCheck(kind: kind, path: $0) },
+ expected: Self.fixtureExpected[kind] ?? [])
+ }
+ }
+ }
+ public func runtimeCheckPath(kind: String, path: String) async throws -> AppRuntimePathCheck {
+ await MainActor.run { fixtureCheck(kind: kind, path: path) }
+ }
+ public func setRuntimeSetting(key: String, value: String?) async throws {
+ await MainActor.run { fixtureRuntimeSettings[key] = value }
+ }
+ func fixtureCheck(kind: String, path: String) -> AppRuntimePathCheck {
+ let known = (fixtureInstalled[kind] ?? []).first { $0.path == path }
+ return AppRuntimePathCheck(path: path, exists: known != nil, executable: known != nil, tool: known?.tool,
+ name: known?.name, version: known?.version,
+ minVersion: known?.tool == "lume" ? "0.6.0" : nil,
+ expected: Self.fixtureExpected[kind] ?? [], guests: known?.guests)
+ }
public func localBackends() async -> [String]? { await MainActor.run { fixtureBackends } }
/// Why each of the fixture Mac's runtimes that is not ready is not.
public var fixtureRuntimeDetails: [String: String] = [:]
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
index feacbb20f3..b971325a7c 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
@@ -86,6 +86,9 @@ extension WebUIBridge {
if let env = args["env"] as? String, !env.isEmpty { keyArgs["env"] = env }
return try await model.agentKeys.call("agent_keys.set", keyArgs)
case "agentKeys.remove": return try await model.agentKeys.call("agent_keys.remove", ["env": try string(args, "env")])
+ // 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": return try await model.agentKeys.call("agent_keys.from_shell", ["env": try string(args, "env")])
// Cua Volume
case "volume.overview": return try await volumeOverview()
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Runtimes.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Runtimes.swift
new file mode 100644
index 0000000000..0e3232a933
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Runtimes.swift
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import CuaSpacesFFI
+
+/// Settings, Advanced's runtime rows: `runtimes.check` (what a typed path
+/// is, before it is saved) and `runtimes.browse` (the file panel). The rows
+/// themselves come with `settings.get` (`runtimes`, laid out by the core)
+/// and change with `settings.choose`.
+extension WebUIBridge {
+ func runtimes(_ method: String, _ args: [String: Any]) async throws -> Any {
+ let kind = try string(args, "kind")
+ switch method {
+ case "runtimes.check":
+ let path = try string(args, "path")
+ do {
+ return BridgeValue.encode(try await model.backend.runtimeCheckPath(kind: kind, path: path))
+ } catch {
+ throw Failure(code: "failed", message: LiveSpacesBackend.words(error))
+ }
+ default:
+ let picked = await pickRuntime(kind)
+ return ["path": picked?.path ?? NSNull()] as [String: Any]
+ }
+ }
+
+ /// A file panel for one program (a binary anywhere, `/usr/local/bin`
+ /// first).
+ static func runtimePanel(_ kind: String) -> URL? {
+ let panel = NSOpenPanel()
+ panel.allowsMultipleSelection = false
+ panel.canChooseDirectories = false
+ panel.canChooseFiles = true
+ panel.treatsFilePackagesAsDirectories = true
+ panel.showsHiddenFiles = true
+ panel.directoryURL = URL(fileURLWithPath: "/usr/local/bin")
+ panel.message = "Choose the program to use"
+ panel.prompt = "Use"
+ return panel.runModal() == .OK ? panel.url : nil
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 9cc97e9b3d..6a4a524e0d 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -74,12 +74,14 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume",
"agents.setup", "agents.configure", "agents.signIn",
"agents.status", "agents.connect", "agents.disconnect",
+ // An agent's device-code sign-in made for Cua (Codex), started and waited in two calls.
+ "agents.signInStart", "agents.signInWait",
// Start a run in a Space and reply to it (the daemon's agent_start, agent_message).
"agents.start", "agents.message",
// 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.set", "agentKeys.remove",
+ "agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell",
// New Space's address form and Connect a cloud, Teleport and Share,
// Cua Volume, Settings and Notifications, a Space's detail and This
// machine (WebUIBridge+Pages.swift).
@@ -102,6 +104,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"spaces.chooseFiles", "spaces.droppedFiles", "spaces.sendFiles",
"host.setUp", "host.joinWithCode", "host.action", "host.openSettings",
"settings.get", "settings.choose", "settings.update",
+ // Settings, Advanced's runtime rows (WebUIBridge+Runtimes.swift).
+ "runtimes.check", "runtimes.browse",
"keyvault.get", "keyvault.lock", "keyvault.unlock",
"keyvault.unlockVault", "keyvault.setup", "keyvault.setDisabled",
"keyvault.approve", "keyvault.deny", "keyvault.revokeGrant",
@@ -180,6 +184,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
var offeredPaths: Set<String> = []
/// "Send file…"'s picker (a test sets its own).
var pickFiles: @MainActor () -> [URL]? = WebUIBridge.openPanel
+ /// Settings, Advanced's "Browse…" for a kind's program (a test sets its own).
+ var pickRuntime: @MainActor (String) async -> URL? = { WebUIBridge.runtimePanel($0) }
/// The "<Space> is ready" notification of a create the onboarding
/// started (a test sets its own).
var notifySpaceReady: @MainActor (SpaceReadyNote) -> Void = { SpaceReadyNotifier.shared.post($0) }
@@ -341,7 +347,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
case "agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume",
"agents.setup", "agents.configure", "agents.signIn",
- "agents.status", "agents.connect", "agents.disconnect", "agents.start", "agents.message":
+ "agents.status", "agents.connect", "agents.disconnect", "agents.start", "agents.message",
+ "agents.signInStart", "agents.signInWait":
return try await agents(method, args)
case "checklist.get": return ["state": model.checklist.stored]
@@ -354,9 +361,23 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
case "settings.get":
model.refreshTelemetry()
+ // Settings, Advanced's runtime choices and overflow come from the
+ // config file; read them here (nothing else does before New Space).
+ // What is installed and the doctor are read in the background:
+ // the rows say "Checking…" until `settings.changed`.
+ if model.servicesIn {
+ await model.loadRuntimeSettings()
+ model.refreshRuntimesIfStale()
+ }
return settings()
+ case "runtimes.check", "runtimes.browse":
+ return try await runtimes(method, args)
case "settings.choose":
- let row = try string(args, "row"), option = try string(args, "option")
+ let row = try string(args, "row")
+ // An empty option only for a runtime path ("Reset to detected").
+ guard let option = args["option"] as? String, !option.isEmpty || row.hasPrefix("runtime-path:") else {
+ throw Failure.badArgs("option: string")
+ }
if row == "update-channel" {
// Settings → About's channel (saved in `AppSettings`).
guard model.updates.updater != nil else { throw Failure.unsupported("Updates are off in this build") }
@@ -584,6 +605,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"accountUrl": appAccountAppUrl(),
// The CLI this app installs and whether it is here (WebUIBridge+Cli.swift).
"cli": cliSetting(),
+ // Settings, Advanced's runtimes as read (`runtimes::RuntimesInput`):
+ // the page's core lays out every kind's row from them.
+ "runtimes": BridgeValue.encode(model.runtimesInput),
// The app core's own settings the page reads and saves (`settings.update`).
"tips": ["off": model.settings.tips.off, "done": model.settings.tips.done] as [String: Any],
]
@@ -816,7 +840,29 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
case "agents.disconnect":
guard let setup = model.agentSetup else { throw Failure.unsupported("Agent setup is not available in this build") }
do {
- let out = try await setup.disconnectJson(agents: try strings(args, "agents"), signIn: (args["signIn"] as? Bool) ?? false)
+ let agents = try strings(args, "agents")
+ let signIn = (args["signIn"] as? Bool) ?? false
+ // Some parts only (an app's page's switches), when the page says which.
+ let out: String
+ if args["skills"] is Bool || args["mcp"] is Bool {
+ out = try await setup.disconnectPartsJson(agents: agents, skills: (args["skills"] as? Bool) ?? false,
+ mcp: (args["mcp"] as? Bool) ?? false, signIn: signIn)
+ } else {
+ out = try await setup.disconnectJson(agents: agents, signIn: signIn)
+ }
+ await model.reloadAgents()
+ return try json(out)
+ } catch let f as Failure { throw f }
+ catch { throw Failure(code: "failed", message: LiveSpacesBackend.words(error)) }
+ case "agents.signInStart":
+ guard let setup = model.agentSetup else { throw Failure.unsupported("Agent setup is not available in this build") }
+ do { return try json(try await setup.deviceSignInStartJson(agent: try string(args, "agent"))) }
+ catch let f as Failure { throw f }
+ catch { throw Failure(code: "failed", message: LiveSpacesBackend.words(error)) }
+ case "agents.signInWait":
+ guard let setup = model.agentSetup else { throw Failure.unsupported("Agent setup is not available in this build") }
+ do {
+ let out = try await setup.deviceSignInWaitJson(id: try string(args, "id"))
await model.reloadAgents()
return try json(out)
} catch let f as Failure { throw f }
@@ -1169,7 +1215,12 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
follow("session.changed") { [model] in
_ = (model.identity, model.signIn, model.cloudConfigured, model.onboarding.completed)
}
- follow("settings.changed") { [model] in _ = model.settings }
+ // The runtime choices too: New Space's probe and its "Use built-in"
+ // switch read and change them.
+ follow("settings.changed") { [model] in
+ _ = (model.settings, model.lumeSource, model.linuxSource, model.placementOverflow,
+ model.runtimeKinds, model.runtimeDoctor?.ready, model.runtimeDoctor?.details)
+ }
// These views are rewritten on every read, so the event goes out
// only when what the page shows differs.
followChanges("machines.changed") { [weak self] in
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift
index c3006500c0..240d8d8c0d 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift
@@ -27,6 +27,13 @@ final class FakeAgentKeysTools: AgentsToolRunning, @unchecked Sendable {
keys.append(["provider": provider, "env": env, "last4": String(value.suffix(4)), "added_ms": 1_790_000_100_000])
case "agent_keys.remove":
keys.removeAll { $0["env"] as? String == args["env"] as? String }
+ // 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":
+ let env = args["env"] as? String ?? ""
+ guard env == "ANTHROPIC_API_KEY" else { throw AgentsToolError(message: "\(env) isn't set in your shell") }
+ keys.removeAll { $0["env"] as? String == env }
+ keys.append(["provider": "anthropic", "env": env, "last4": "a91c", "added_ms": 1_790_000_200_000])
default: throw AgentsToolError(message: "unknown tool \(tool)")
}
var report: [String: Any] = ["keys": keys, "providers": [], "available": available]
@@ -82,8 +89,20 @@ struct AgentKeysTests {
#expect(none.view.notice?.contains("need the cua daemon") == true)
}
+ @Test func aKeyFromYourShellIsSavedAndTheNamesNeverReplaceTheList() async throws {
+ let tools = FakeAgentKeysTools()
+ let m = AgentKeysModel(tools: tools)
+ await m.load()
+ let names = try await m.call("agent_keys.shell") as? [String: Any]
+ #expect(names?["names"] as? [String] == ["ANTHROPIC_API_KEY"])
+ // The names answer is not the key list: the rows stay as they were.
+ #expect(m.view.rows.map(\.status) == ["Not set", "\u{2022}\u{2022}\u{2022}\u{2022} 3f9a"])
+ try await m.call("agent_keys.from_shell", ["env": "ANTHROPIC_API_KEY"])
+ #expect(m.view.rows.first?.status == "\u{2022}\u{2022}\u{2022}\u{2022} a91c")
+ }
+
@Test func theWebBridgeRoutesAgentKeysToTheDaemon() {
- for m in ["agentKeys.list", "agentKeys.set", "agentKeys.remove"] {
+ for m in ["agentKeys.list", "agentKeys.set", "agentKeys.remove", "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.swift
index bbfcbb2898..7aa074af0b 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
@@ -51,6 +51,8 @@ struct BridgeContractTests {
}
// "Send file…" picks this instead of showing the native panel.
bridge.pickFiles = { [URL(fileURLWithPath: "/tmp/cua-contract-notes.txt")] }
+ // Settings, Advanced's "Browse…" picks this instead of the panel.
+ bridge.pickRuntime = { _ in URL(fileURLWithPath: "/opt/homebrew/bin/podman") }
return bridge
}
@@ -148,6 +150,13 @@ struct BridgeContractTests {
func streamProvider(id: String) async throws -> SpaceStreamSourceProviding { try await inner.streamProvider(id: id) }
func localBackends() async -> [String]? { await inner.localBackends() }
func localRuntimes() async -> (ready: [String], details: [String: String])? { await inner.localRuntimes() }
+ func runtimeKinds() async -> [AppRuntimeKindInput]? { await inner.runtimeKinds() }
+ func runtimeCheckPath(kind: String, path: String) async throws -> AppRuntimePathCheck {
+ try await inner.runtimeCheckPath(kind: kind, path: path)
+ }
+ func setRuntimeSetting(key: String, value: String?) async throws {
+ try await inner.setRuntimeSetting(key: key, value: value)
+ }
func lumeSource() async -> String? { await inner.lumeSource() }
func setLumeSource(_ value: String) async throws { try await inner.setLumeSource(value) }
func linuxSource() async -> String? { await inner.linuxSource() }
@@ -205,6 +214,7 @@ struct BridgeContractTests {
}
// "Send file…" picks this instead of showing the native panel.
bridge.pickFiles = { [URL(fileURLWithPath: "/tmp/cua-contract-notes.txt")] }
+ bridge.pickRuntime = { _ in URL(fileURLWithPath: "/opt/homebrew/bin/podman") }
let space = try #require(model.spaces.first?.id)
return (bridge, model, space)
}
@@ -230,6 +240,7 @@ struct BridgeContractTests {
("agents.configure", ["agents": ["claude-code"]]), ("agents.signIn", ["agent": "codex"]),
("agents.status", ["refresh": true]), ("agents.connect", ["agents": ["claude-code"], "signIn": true]),
("agents.disconnect", ["agents": ["claude-code"], "signIn": true]),
+ ("agents.signInStart", ["agent": "codex"]), ("agents.signInWait", ["id": "codex-1"]),
("agents.detail", ["name": "ada"]), ("agents.readFile", ["path": "agents/ada/hermes/MEMORY.md"]),
("agents.restoreFile", ["path": "agents/ada/hermes/MEMORY.md", "version": "v1"]),
("agents.addRoutine", ["agent": "ada", "title": "Inbox", "prompt": "Sort my inbox", "everyMinutes": NSNull(),
@@ -239,6 +250,7 @@ struct BridgeContractTests {
("agents.revokeComputer", ["agent": "ada", "machine": "relay:0123"]),
("agentKeys.list", [:]), ("agentKeys.set", ["provider": "anthropic", "value": "sk-ant-test-0000"]),
("agentKeys.remove", ["env": "ANTHROPIC_API_KEY"]),
+ ("agentKeys.shell", [:]), ("agentKeys.fromShell", ["env": "ANTHROPIC_API_KEY"]),
("clouds.status", [:]), ("clouds.test", ["target": ["provider": "aws", "region": "us-west-2"]]),
("clouds.connect", ["target": ["provider": "aws", "region": "us-west-2"], "makeDefault": false]),
("clouds.disconnect", ["provider": "aws", "deleteResources": false]),
@@ -264,6 +276,7 @@ struct BridgeContractTests {
("spaces.droppedFiles", ["names": ["notes.txt"]]), ("spaces.chooseFiles", [:]),
("spaces.sendFiles", ["spaceId": space, "paths": ["/tmp/cua-contract-notes.txt"]]),
("settings.get", [:]), ("settings.choose", ["row": "telemetry", "option": "off"]),
+ ("runtimes.check", ["kind": "container", "path": "/usr/local/bin/docker"]), ("runtimes.browse", ["kind": "container"]),
("settings.update", ["tips": ["off": false, "done": ["try-agent"]]]),
("keyvault.get", [:]),
("keyvault.lock", ["ids": ["kv-1"]]),
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DamagedStateTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DamagedStateTests.swift
new file mode 100644
index 0000000000..3d280b6405
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DamagedStateTests.swift
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import CuaSpacesFFI
+@testable import CuaSpacesMacKit
+import Foundation
+import Testing
+
+/// Truncated or garbage state files must not crash the app or lose what they
+/// held: the app starts from the defaults and keeps the file as
+/// `<name>.damaged`, the way the core keeps settings.json.
+@MainActor
+@Suite("Damaged state files")
+struct DamagedStateTests {
+ static let garbage = ["{", "{\"completed\": tru", "", "null", "[]", "\u{0}\u{1}garbage", "\"a string\""]
+
+ func temp(_ name: String, _ text: String) throws -> String {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-damaged-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let path = dir.appendingPathComponent(name).path
+ try Data(text.utf8).write(to: URL(fileURLWithPath: path))
+ return path
+ }
+
+ @Test func aDamagedOnboardingFileMakesTheFirstRunDueAndIsKept() throws {
+ for text in Self.garbage {
+ let path = try temp("onboarding.json", text)
+ let m = OnboardingModel(statePath: path)
+ #expect(m.completed == false, "\(text.debugDescription)")
+ #expect(String(data: FileManager.default.contents(atPath: path + ".damaged") ?? Data(), encoding: .utf8) == text)
+ // Finishing writes a good file over it; the copy stays.
+ m.finish(mode: .host)
+ #expect(OnboardingModel(statePath: path).completed)
+ #expect(FileManager.default.fileExists(atPath: path + ".damaged"))
+ }
+ }
+
+ @Test func aDamagedChecklistStartsEmptyAndIsKept() throws {
+ for text in Self.garbage {
+ let path = try temp("checklist.json", text)
+ let m = ChecklistModel(path: path)
+ #expect(m.state.done.isEmpty && !m.state.dismissed, "\(text.debugDescription)")
+ #expect(String(data: FileManager.default.contents(atPath: path + ".damaged") ?? Data(), encoding: .utf8) == text)
+ }
+ }
+
+ @Test func aGoodOrMissingFileKeepsNothing() throws {
+ let good = try temp("onboarding.json", "{\"completed\":true,\"mode\":\"host\"}")
+ #expect(OnboardingModel(statePath: good).completed)
+ #expect(!FileManager.default.fileExists(atPath: good + ".damaged"))
+ let missing = FileManager.default.temporaryDirectory.appendingPathComponent("nope-\(UUID().uuidString)/checklist.json").path
+ _ = ChecklistModel(path: missing)
+ #expect(!FileManager.default.fileExists(atPath: missing + ".damaged"))
+ }
+
+ @Test func theLatestDamagedFileReplacesAnOlderCopyAndAnIdenticalOneIsNotCopiedAgain() throws {
+ let path = try temp("x.json", "first")
+ #expect(DamagedFile.keep(path) == path + ".damaged")
+ try Data("second, longer".utf8).write(to: URL(fileURLWithPath: path))
+ DamagedFile.keep(path)
+ #expect(String(data: FileManager.default.contents(atPath: path + ".damaged") ?? Data(), encoding: .utf8) == "second, longer")
+ #expect(DamagedFile.keep(path + "-missing") == nil)
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/RuntimeSettingsTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/RuntimeSettingsTests.swift
new file mode 100644
index 0000000000..86178205bf
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/RuntimeSettingsTests.swift
@@ -0,0 +1,148 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+@testable import CuaSpacesMacKit
+import CuaSpacesFFI
+import Foundation
+import Testing
+
+/// Settings, Advanced's runtime rows on the Mac: one per kind of Space
+/// (Containers, Virtual machines, MicroVMs), from the page's first
+/// `settings.get` on; Already installed with what is installed, the path
+/// in use and its check; each choice written to the per-kind setting.
+///
+/// The `settings.get` answers here are also the web UI's fixtures
+/// (`apps/cua-spaces-web/src/__tests__/fixtures/mac-host-settings-*.json`):
+/// its Advanced tab is tested on exactly what this host answers.
+/// `UPDATE_WEB_FIXTURES=1` rewrites them; otherwise they must match.
+@Suite("Runtime settings")
+@MainActor
+struct RuntimeSettingsTests {
+ static let fixtures = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("../cua-spaces-web/src/__tests__/fixtures").standardizedFileURL
+
+ init() { _ = NSApplication.shared }
+
+ func bridge(_ backend: FixtureSpacesBackend = FixtureSpacesBackend()) -> (WebUIBridge, AppModel) {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-runtimes-\(UUID().uuidString)")
+ let model = AppModel(backend: backend, keyvault: KeyvaultModel(client: nil),
+ onboarding: OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path),
+ settingsPath: dir.appendingPathComponent("settings.json").path,
+ telemetry: FixtureTelemetry())
+ return (WebUIBridge(model: model, allowedOrigins: []), model)
+ }
+
+ func rows(_ answer: [String: Any]) -> [[String: Any]] {
+ let page = answer["page"] as? [String: Any]
+ let sections = page?["sections"] as? [[String: Any]] ?? []
+ return sections.first { $0["id"] as? String == "runtimes" }?["rows"] as? [[String: Any]] ?? []
+ }
+
+ func ids(_ answer: [String: Any]) -> [String] { rows(answer).compactMap { $0["id"] as? String } }
+
+ func row(_ answer: [String: Any], _ id: String) -> [String: Any]? {
+ rows(answer).first { $0["id"] as? String == id }
+ }
+
+ func get(_ bridge: WebUIBridge) async throws -> [String: Any] {
+ try #require(try await bridge.handle("settings.get", [:]) as? [String: Any])
+ }
+
+ /// The answer the web UI's test reads: the page's General and Runtimes
+ /// sections and the runtimes as read (the rest depends on this Mac).
+ func checkFixture(_ answer: [String: Any], _ name: String) throws {
+ let page = try #require(answer["page"] as? [String: Any])
+ let sections = (page["sections"] as? [[String: Any]] ?? []).filter {
+ ["general", "runtimes"].contains($0["id"] as? String ?? "")
+ }
+ let subset: [String: Any] = [
+ "page": ["title": page["title"] ?? "Settings", "sections": sections] as [String: Any],
+ "runtimes": answer["runtimes"] ?? NSNull(),
+ ]
+ var data = try JSONSerialization.data(withJSONObject: subset, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ data.append(0x0A)
+ let file = Self.fixtures.appendingPathComponent("mac-host-settings-\(name).json")
+ if ProcessInfo.processInfo.environment["UPDATE_WEB_FIXTURES"] == "1" {
+ try FileManager.default.createDirectory(at: Self.fixtures, withIntermediateDirectories: true)
+ try data.write(to: file)
+ }
+ let stored = try Data(contentsOf: file)
+ #expect(String(decoding: stored, as: UTF8.self) == String(decoding: data, as: UTF8.self),
+ "\(file.lastPathComponent) is stale: UPDATE_WEB_FIXTURES=1 scripts/test.sh --filter RuntimeSettingsTests")
+ }
+
+ /// Before anything was read, every kind's row is there, checking.
+ @Test func everyKindHasARowOnTheFirstRead() async throws {
+ let (bridge, model) = bridge()
+ #expect(model.runtimeKinds == nil)
+ let answer = try await get(bridge)
+ #expect(ids(answer) == ["runtime:container", "runtime:vm", "runtime:microvm"])
+ #expect(row(answer, "runtime:microvm")?["help"] as? String == "Checking\u{2026}")
+ let runtimes = try #require(answer["runtimes"] as? [String: Any])
+ #expect(runtimes["kinds"] is NSNull)
+ #expect(runtimes["os"] as? String == "macos")
+ try checkFixture(answer, "unread")
+ }
+
+ /// Read: Already installed lists what is installed, autofills the path
+ /// in use (Detected) and says what it is; a kind that can't run says why.
+ @Test func alreadyInstalledShowsWhatIsInstalledAndThePathInUse() async throws {
+ let backend = FixtureSpacesBackend()
+ backend.fixtureBackends = ["managed", "lume", "vz"]
+ backend.fixtureRuntimeSettings = ["runtime.container": "system", "runtime.vm": "builtin"]
+ let (bridge, model) = bridge(backend)
+ await model.readRuntimes()
+ let answer = try await get(bridge)
+ #expect(ids(answer) == ["runtime:container", "runtime-detected:container", "runtime-path:container",
+ "runtime-check:container", "runtime:vm", "runtime:microvm"])
+ let path = try #require(row(answer, "runtime-path:container"))
+ #expect(path["label"] as? String == "Detected")
+ #expect(path["value"] as? String == "/usr/local/bin/docker")
+ #expect(row(answer, "runtime-check:container")?["label"] as? String == "Docker 27.3 found")
+ let detected = try #require(row(answer, "runtime-detected:container")?["options"] as? [[String: Any]])
+ #expect(detected.first?["label"] as? String == "Docker \u{2014} /usr/local/bin/docker (27.3)")
+ try checkFixture(answer, "read")
+ }
+
+ /// Each choice writes the per-kind setting the core names; a typed path
+ /// is Custom (Reset to detected); an empty one goes back to detection.
+ @Test func choicesWriteThePerKindSettings() async throws {
+ let backend = FixtureSpacesBackend()
+ backend.fixtureBackends = ["managed", "lume", "vz"]
+ let (bridge, model) = bridge(backend)
+ await model.readRuntimes()
+ _ = try await bridge.handle("settings.choose", ["row": "runtime:microvm", "option": "system"])
+ #expect(backend.fixtureRuntimeSettings["runtime.microvm"] == "system")
+ _ = try await bridge.handle("settings.choose", ["row": "runtime:container", "option": "system"])
+ _ = try await bridge.handle("settings.choose", ["row": "runtime-path:container", "option": "/Users/me/bin/docker"])
+ #expect(backend.fixtureRuntimeSettings["runtime.container_path"] == "/Users/me/bin/docker")
+ var answer = try await get(bridge)
+ let path = try #require(row(answer, "runtime-path:container"))
+ #expect(path["label"] as? String == "Custom")
+ #expect(path["button"] as? String == "Reset to detected")
+ #expect(row(answer, "runtime-check:container")?["kind"] as? String == "error")
+ _ = try await bridge.handle("settings.choose", ["row": "runtime-path:container", "option": ""])
+ #expect(backend.fixtureRuntimeSettings["runtime.container_path"] == nil)
+ answer = try await get(bridge)
+ #expect(row(answer, "runtime-path:container")?["value"] as? String == "/usr/local/bin/docker")
+ }
+
+ /// `runtimes.check` says what a typed path is; `runtimes.browse` is the
+ /// file panel.
+ @Test func aTypedPathIsCheckedAndBrowsed() async throws {
+ let (bridge, _) = bridge()
+ let check = try #require(try await bridge.handle("runtimes.check", ["kind": "container", "path": "/usr/local/bin/docker"]) as? [String: Any])
+ #expect(check["tool"] as? String == "docker")
+ #expect(check["version"] as? String == "27.3.1")
+ let missing = try #require(try await bridge.handle("runtimes.check", ["kind": "container", "path": "/nope"]) as? [String: Any])
+ #expect(missing["exists"] as? Bool == false)
+ #expect(missing["expected"] as? [String] == ["Docker", "Podman"])
+ bridge.pickRuntime = { _ in URL(fileURLWithPath: "/opt/homebrew/bin/podman") }
+ let picked = try await bridge.handle("runtimes.browse", ["kind": "container"]) as? [String: Any]
+ #expect(picked?["path"] as? String == "/opt/homebrew/bin/podman")
+ bridge.pickRuntime = { _ in nil }
+ #expect((try await bridge.handle("runtimes.browse", ["kind": "container"]) as? [String: Any])?["path"] is NSNull)
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ThumbnailSweepTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ThumbnailSweepTests.swift
new file mode 100644
index 0000000000..1284ee9863
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ThumbnailSweepTests.swift
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+@testable import CuaSpacesMacKit
+import Testing
+
+/// The background thumbnail sweep refreshes a bounded number of Spaces each
+/// time, rotating through the rest, so 256 running Spaces are not 256
+/// screenshots in one go.
+@MainActor
+@Suite("Thumbnail sweep")
+struct ThumbnailSweepTests {
+ @Test func aListThatFitsIsSweptWhole() {
+ let ids = (0..<10).map { "s\($0)" }
+ let s = SpaceThumbnails.sweep(ids, from: 7, limit: 32)
+ #expect(s.ids == ids)
+ #expect(s.next == 0)
+ #expect(SpaceThumbnails.sweep([], from: 3, limit: 32).ids.isEmpty)
+ }
+
+ @Test func aLongListIsSweptInTurns() {
+ let ids = (0..<100).map { "s\($0)" }
+ var cursor = 0
+ var seen: [String] = []
+ for _ in 0..<4 {
+ let s = SpaceThumbnails.sweep(ids, from: cursor, limit: 32)
+ #expect(s.ids.count == 32)
+ seen += s.ids
+ cursor = s.next
+ }
+ // 4 sweeps of 32 cover all 100 Spaces (and wrap onto the first 28 again).
+ #expect(Set(seen) == Set(ids))
+ #expect(cursor == (4 * 32) % 100)
+ }
+
+ @Test func aListThatShrankStartsInsideIt() {
+ let ids = (0..<50).map { "s\($0)" }
+ let s = SpaceThumbnails.sweep(ids, from: 900, limit: 32)
+ #expect(s.ids.count == 32)
+ #expect(s.ids.allSatisfy { ids.contains($0) })
+ #expect(s.next < ids.count)
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
index 1f1d17c7ac..5f2544fdab 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
@@ -602,23 +602,18 @@ struct ViewModelTests {
await model.loadSettings()
let page = model.settingsPage
#expect(page.sections.map(\.id) == ["account", "teams", "general", "runtimes", "privacy", "agents"])
- // Settings, Runtimes: macOS VMs picks runtime.lume.
- let runtime = page.sections.first { $0.id == "runtimes" }!.rows[0]
- #expect(runtime.options.map(\.id) == ["auto", "builtin", "system"])
- #expect(runtime.options.first(where: \.active)?.id == "auto")
- await model.choose(row: "macos-runtime", option: "builtin")
- #expect(model.lumeSource == "builtin")
- #expect(model.settingsPage.sections.first { $0.id == "runtimes" }!.rows[0]
- .options.first(where: \.active)?.id == "builtin")
- // Linux picks runtime.linux (the built-in Linux runtime).
- let linux = model.settingsPage.sections.first { $0.id == "runtimes" }!.rows
- .first { $0.id == "linux-runtime" }!
- #expect(linux.label == "Linux")
- #expect(linux.options.first(where: \.active)?.id == "auto")
- await model.choose(row: "linux-runtime", option: "system")
- #expect(model.linuxSource == "system")
- #expect(model.settingsPage.sections.first { $0.id == "runtimes" }!.rows
- .first { $0.id == "linux-runtime" }!.options.first(where: \.active)?.id == "system")
+ // Settings, Runtimes: one row per kind; Virtual machines picks runtime.vm.
+ let runtimes = { model.settingsPage.sections.first { $0.id == "runtimes" }!.rows }
+ #expect(runtimes().map(\.id) == ["runtime:container", "runtime:vm", "runtime:microvm"])
+ let vm = runtimes()[1]
+ #expect(vm.label == "Virtual machines")
+ #expect(vm.options.map(\.id) == ["auto", "builtin", "system"])
+ #expect(vm.options.first(where: \.active)?.id == "auto")
+ await model.choose(row: "runtime:vm", option: "builtin")
+ #expect(runtimes()[1].options.first(where: \.active)?.id == "builtin")
+ await model.choose(row: "runtime:container", option: "system")
+ #expect(runtimes().first { $0.id == "runtime:container" }!.options.first(where: \.active)?.id == "system")
+ #expect(runtimes().contains { $0.id == "runtime-path:container" })
#expect(model.chrome.signInLabel == "Sign in")
await model.press(row: "sign-in")
#expect(model.identity == "[email protected]")
@@ -684,10 +679,10 @@ struct ViewModelTests {
#expect(mac.wizard.view.kindTiles.first { $0.id == "microvm" }?.enabled == false)
// No words in New Space; Settings, Advanced, Runtimes says why.
#expect(mac.wizard.view.kindTiles.first { $0.id == "microvm" }?.detail == "")
- let microvm = mac.settingsPage.sections.first { $0.id == "runtimes" }?.rows.filter { $0.id.hasPrefix("microvm-") }
- #expect(microvm?.map(\.id) == ["microvm-runtime", "microvm-runtime-note"])
- #expect(microvm?.first?.value == "Not available")
- #expect(microvm?.last?.label == "MicroVM needs macOS 26.")
+ await mac.readRuntimes()
+ let microvm = mac.settingsPage.sections.first { $0.id == "runtimes" }?.rows.first { $0.id == "runtime:microvm" }
+ #expect(microvm?.value == "Not available")
+ #expect(microvm?.help == "MicroVMs need macOS 26")
#expect(appWizardCreateArgs(plan: mac.wizard.view.plan).kind == .container)
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
index 410ad01c8f..90d75c37d1 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
@@ -401,6 +401,24 @@ struct WebUIHostTests {
#expect(s?["accountUrl"] as? String == appAccountAppUrl())
}
+ /// Settings, Advanced's rows come with the page's first `settings.get`,
+ /// before New Space ever probed: every kind's runtime row, and overflow
+ /// (they were missing: only New Space's probe read the settings).
+ @Test func settingsCarryTheRuntimeChoicesOnTheFirstRead() async throws {
+ let backend = FixtureSpacesBackend()
+ backend.fixtureLumeSource = "system"
+ let (bridge, model) = bridge(backend: backend)
+ #expect(model.lumeSource == nil)
+ let s = try #require(try await bridge.handle("settings.get", [:]) as? [String: Any])
+ let page = try #require(s["page"] as? [String: Any])
+ let sections = try #require(page["sections"] as? [[String: Any]])
+ let ids = sections.flatMap { $0["rows"] as? [[String: Any]] ?? [] }.compactMap { $0["id"] as? String }
+ for kind in ["container", "vm", "microvm"] { #expect(ids.contains("runtime:\(kind)")) }
+ #expect(ids.contains("placement-overflow"))
+ // New Space's "Use built-in Lume" reads the same setting.
+ #expect(model.lumeSource == "system")
+ }
+
@Test func theGlobalShortcutSaysWhetherTheSystemGaveIt() async throws {
let (bridge, _) = bridge()
defer { GlobalShortcut.installed = nil }
diff --git a/apps/cua-spaces-web/e2e/agent-keys.ts b/apps/cua-spaces-web/e2e/agent-keys.ts
index 5ecc28a511..33599be73e 100644
--- a/apps/cua-spaces-web/e2e/agent-keys.ts
+++ b/apps/cua-spaces-web/e2e/agent-keys.ts
@@ -34,8 +34,21 @@ const attrs = (l: Locator, name: string) => l.evaluateAll((els, n) => els.map((e
/** A key the checks type; it must never be drawn. */
const TYPED = "sk-ant-test-0000";
+/**
+ * Account keys are the classic Connectors page (the new design's Providers
+ * are the `connectors` flow): this flow checks them with the new design off
+ * on this device, as a person who hasn't turned it on sees them.
+ */
+async function classicConnectors(page: Page): Promise<void> {
+ await page.evaluate(() => localStorage.setItem("cua.flag.spaces_redesign", "0"));
+ await page.reload();
+ await page.waitForFunction(() => window.__cuaParity !== undefined);
+ expect(await page.evaluate(() => window.__cuaParity!.coreStatus), "the wasm core loaded").toBe("ready");
+}
+
export async function checkAgentKeys(page: Page, checkpoints: ParityCheckpoint[]): Promise<number> {
let checked = 0;
+ await classicConnectors(page);
for (const { input, view } of unique(checkpoints, "agent-keys")) {
await page.evaluate((i) => window.__cuaParity!.showAgentKeys(i), input);
diff --git a/apps/cua-spaces-web/e2e/flows.ts b/apps/cua-spaces-web/e2e/flows.ts
index 31a25e0e89..9275e6db89 100644
--- a/apps/cua-spaces-web/e2e/flows.ts
+++ b/apps/cua-spaces-web/e2e/flows.ts
@@ -78,6 +78,10 @@ export const FLOW_PLAN: Record<string, FlowPlan> = {
notifications: { status: "run", screen: "notifications" },
about: { status: "run", screen: "settings/about" },
"agent-keys": { status: "run", screen: "settings/connected-apps" },
+ connectors: {
+ status: "skip",
+ reason: "The redesign's Connectors page, an app's page, the @ picker and the agent list draw connectors.*, summon.* and agentList.view as is; the webview parity test replays this flow on the wasm core, and src/__tests__/connectors-redesign.test.tsx, ask-first-in-space.test.tsx and home-agents.test.tsx drive the screens",
+ },
"your-cloud": { status: "run", screen: "new-space" },
"telemetry-funnel": { status: "run", screen: "spaces" },
"launch-at-login": { status: "run", screen: "settings/general" },
diff --git a/apps/cua-spaces-web/scale-budget.json b/apps/cua-spaces-web/scale-budget.json
index 58769698df..3e986f1e37 100644
--- a/apps/cua-spaces-web/scale-budget.json
+++ b/apps/cua-spaces-web/scale-budget.json
@@ -1,23 +1,26 @@
{
"100": {
- "firstTile": 1380,
+ "firstTile": 1277,
"filterKey": 50,
"selectAll": 50,
"pickOne": 50,
- "longTasks": 147
+ "longTasks": 50,
+ "drawn": 27
},
"1000": {
- "firstTile": 1479,
- "filterKey": 114,
- "selectAll": 236,
+ "firstTile": 1340,
+ "filterKey": 50,
+ "selectAll": 50,
"pickOne": 50,
- "longTasks": 720
+ "longTasks": 50,
+ "drawn": 27
},
"3000": {
- "firstTile": 2373,
- "filterKey": 407,
- "selectAll": 711,
- "pickOne": 156,
- "longTasks": 1668
+ "firstTile": 1509,
+ "filterKey": 50,
+ "selectAll": 50,
+ "pickOne": 50,
+ "longTasks": 150,
+ "drawn": 27
}
}
diff --git a/apps/cua-spaces-web/scripts/scale-bench.mjs b/apps/cua-spaces-web/scripts/scale-bench.mjs
index a01cbed436..7dbb8718b6 100644
--- a/apps/cua-spaces-web/scripts/scale-bench.mjs
+++ b/apps/cua-spaces-web/scripts/scale-bench.mjs
@@ -9,6 +9,7 @@
// selectAll ⌘A (select every Space shown) to the selection bar drawn
// pickOne one Space's checkbox clicked to the selection bar drawn
// longTasks main-thread tasks over 50 ms while the page settles, total ms
+// drawn tiles in the page: one screen of rows once the list is long (windowing)
// and fails when a number is over its budget in scale-budget.json.
//
// Usage:
@@ -65,29 +66,36 @@ async function once(n) {
// Settled: no long task for a second.
await page.waitForTimeout(1500);
const longTasks = await page.evaluate(() => window.__long);
+ // Tiles drawn: all of them for a short list, one screen of rows for a long one.
const total = await page.locator("[data-space-id]").count();
// One character in the filter, to the grid redrawn with fewer tiles.
const filter = page.locator("[data-spaces-filter]").first();
await filter.click();
+ // One Space's name: the list drops to that one, so the first tile and the count change.
+ const name = `scale-${String(n - 1).padStart(4, "0")}`;
const filterKey = await page.evaluate(
- () =>
+ (name) =>
new Promise((resolve) => {
- const before = document.querySelectorAll("[data-space-id]").length;
+ // The grid draws only what is on screen, so the number of tiles may not change: the
+ // first tile and the "N Spaces" line do.
+ const sig = () => `${document.querySelector("[data-space-id]")?.getAttribute("data-space-id")}|${document.querySelectorAll("[data-space-id]").length}|${document.querySelector("h1")?.parentElement?.textContent}`;
+ const before = sig();
const input = document.activeElement;
const t0 = performance.now();
const obs = new MutationObserver(() => {
- if (document.querySelectorAll("[data-space-id]").length !== before) {
+ if (sig() !== before) {
obs.disconnect();
requestAnimationFrame(() => resolve(performance.now() - t0));
}
});
obs.observe(document.body, { childList: true, subtree: true });
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;
- setter.call(input, "scale-00");
+ setter.call(input, name);
input.dispatchEvent(new Event("input", { bubbles: true }));
setTimeout(() => resolve(-1), 10_000);
}),
+ name,
);
await filter.fill("");
await page.waitForTimeout(500);
@@ -119,14 +127,14 @@ async function once(n) {
}),
);
await page.close();
- return { firstTile, filterKey, selectAll, pickOne, longTasks, total };
+ return { firstTile, filterKey, selectAll, pickOne, longTasks, drawn: total, total };
}
const results = {};
for (const n of SIZES) {
const runs = [];
for (let i = 0; i < RUNS; i++) runs.push(await once(n));
- results[n] = Object.fromEntries(["firstTile", "filterKey", "selectAll", "pickOne", "longTasks"].map((k) => [k, Math.round(median(runs.map((r) => r[k])))]));
+ results[n] = Object.fromEntries(["firstTile", "filterKey", "selectAll", "pickOne", "longTasks", "drawn"].map((k) => [k, Math.round(median(runs.map((r) => r[k])))]));
results[n].tiles = runs[0].total;
console.log(`N=${n}`, JSON.stringify(results[n]));
}
@@ -134,14 +142,18 @@ await browser.close();
stop();
if (has("--update")) {
- const budget = Object.fromEntries(Object.entries(results).map(([n, r]) => [n, Object.fromEntries(Object.entries(r).filter(([k]) => k !== "tiles").map(([k, v]) => [k, Math.max(50, Math.round(v * 1.5))]))]));
+ const budget = Object.fromEntries(Object.entries(results).map(([n, r]) => [n, Object.fromEntries(Object.entries(r).filter(([k]) => k !== "tiles").map(([k, v]) => [k, Math.max(k === "drawn" ? 20 : 50, Math.round(v * 1.5))]))]));
writeFileSync(budgetFile, JSON.stringify(budget, null, 2) + "\n");
console.log(`wrote ${budgetFile}`);
} else if (existsSync(budgetFile)) {
const budget = JSON.parse(readFileSync(budgetFile, "utf8"));
const over = [];
for (const [n, r] of Object.entries(results))
- for (const [k, v] of Object.entries(budget[n] ?? {})) if (r[k] > v) over.push(`N=${n} ${k} ${r[k]} > ${v}`);
+ for (const [k, v] of Object.entries(budget[n] ?? {})) {
+ // -1: the redraw never came (a measurement that timed out is a failure, not a fast run).
+ if (r[k] < 0) over.push(`N=${n} ${k} was not measured`);
+ else if (r[k] > v) over.push(`N=${n} ${k} ${r[k]} > ${v}`);
+ }
if (over.length) {
console.error(`over budget:\n ${over.join("\n ")}`);
process.exit(1);
diff --git a/apps/cua-spaces-web/src/__tests__/agent-identity.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-identity.test.tsx
index 9c58d4a8e4..7bdff79acc 100644
--- a/apps/cua-spaces-web/src/__tests__/agent-identity.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/agent-identity.test.tsx
@@ -65,15 +65,14 @@ async function openCard(handle: string): Promise<HTMLElement> {
return card!;
});
}
-/** Each row's value as read aloud (the owner's initial is decoration). */
-const facts = (card: HTMLElement) =>
- Object.fromEntries(
- [...card.querySelectorAll<HTMLElement>("[data-card-fact]")].map((f) => {
- const v = f.lastElementChild!.cloneNode(true) as HTMLElement;
- v.querySelectorAll("[aria-hidden]").forEach((n) => n.remove());
- return [f.dataset.cardFact!, v.textContent];
- }),
- );
+/** The card's Details, opened: label to value. */
+async function details(card: HTMLElement): Promise<Record<string, string>> {
+ await act(async () => {
+ fireEvent.click(card.querySelector("[data-card-details]")!);
+ });
+ return Object.fromEntries([...card.querySelectorAll<HTMLElement>("[data-card-details-open] dt")].map((dt) => [dt.textContent!, dt.nextElementSibling!.textContent!]));
+}
+const line = (card: HTMLElement) => card.querySelector("[data-card-line='who']")?.textContent;
describe("an agent's identity", () => {
it("draws the harness's mark, the AI tag and the owner's badge in the thread and in In this Space", async () => {
@@ -143,37 +142,38 @@ describe("an agent's identity", () => {
expect(memberIdentity({ handle: "x", owner: ADA, icon: "https://example.com/i.png" })?.icon).toBe("https://example.com/i.png");
});
- it("opens the card from the name: Grace's Claude Code, connected with a prompt", async () => {
+ it("opens the card from the name: Grace's Claude Code, in one line, with the rest under Details", async () => {
await app();
const card = await openCard("claude");
- expect(facts(card)).toEqual({
- Owner: "Grace",
- "Posts from": "Grace's MacBook Pro",
- Joined: "Connected by Grace with a prompt",
- When: expect.stringMatching(/^Yesterday \d\d:\d\d$/),
- Harness: "Claude Code 2.4.1",
- "Can task": "Members",
- "Can stop": "Admins",
- "Can approve": "Grace",
+ expect(card.querySelector("[data-card-title]")?.textContent).toBe("Claude Code");
+ expect(card.querySelector("[data-card-badge]")?.textContent).toBe("Agent");
+ expect(line(card)).toBe("Run by Grace on Grace's MacBook Pro, uses Anthropic");
+ // Details is folded until asked.
+ expect(card.querySelector("[data-card-details-open]")).toBeNull();
+ expect(await details(card)).toMatchObject({
+ Handle: "@claude",
+ Runs: "Claude Code 2.4.1",
+ Joined: expect.stringMatching(/^Connected by Grace with a prompt, \d+ (hour|day)s? ago$/),
+ "Owner's id": "acct_grace",
});
- // Owner and computer carry Cua's check; nothing else does.
- expect(card.querySelectorAll("[data-card-fact='Owner'] [aria-label='Checked by Cua'], [data-card-fact='Posts from'] [aria-label='Checked by Cua']")).toHaveLength(2);
- expect(card.querySelectorAll("[aria-label='Checked by Cua']")).toHaveLength(2);
- expect(card.textContent).toContain("Name, icon and harness are set by the agent. Owner and computer are checked by Cua.");
+ // The owner may change who can task, stop and approve it: the selects, under Details.
+ expect(card.querySelectorAll("[data-agent-right]")).toHaveLength(3);
+ // The old card's facts and fine print are gone.
+ expect(card.textContent).not.toContain("checked by Cua");
});
- it("the card of your own Hermes, started here: you, This Space, the harness Cua started", async () => {
+ it("the card of your own Hermes, started here: run by you in this Space", async () => {
await app();
const card = await openCard("hermes");
- expect(facts(card)).toMatchObject({ Owner: "Ada (you)", "Posts from": "This Space", Joined: "Started in this Space", Harness: "Hermes Agent 0.9.2", "Can task": "Owner" });
- expect(card.textContent).toContain("The name and icon are set by the agent.");
+ expect(line(card)).toBe("Run by you in this Space, uses Anthropic");
+ expect(await details(card)).toMatchObject({ Handle: "@hermes", Runs: "Hermes Agent 0.9.2", Joined: expect.stringMatching(/^Started in this Space/) });
});
- it("a look-alike's card: its own owner, its own handle, Harness not reported", async () => {
+ it("a look-alike's card: its own owner, its own handle, Runs not reported", async () => {
await app({ threadLookalike: true });
const card = await openCard("claude-2");
- expect(card.textContent).toContain("@claude-2");
- expect(facts(card)).toMatchObject({ Owner: "Linus", "Posts from": "linus-thinkpad", Harness: "Not reported", "Can task": "Linus", "Can approve": "Linus" });
+ expect(line(card)).toMatch(/^Run by Linus on linus-thinkpad/);
+ expect(await details(card)).toMatchObject({ Handle: "@claude-2", Runs: "Not reported" });
});
it("Remove from Space: the owner sees it and removing leaves its posts with their mark and owner", async () => {
@@ -213,7 +213,11 @@ describe("an agent's identity", () => {
await app({ threadRole: "member" });
const card = await openCard("claude");
expect(card.querySelector("[data-remove-agent]")).toBeNull();
- expect(facts(card).Owner).toBe("Grace");
+ expect(line(card)).toMatch(/^Run by Grace /);
+ // A member reads who may task it, stop it and approve it; only the owner and admins change it.
+ const d = await details(card);
+ expect(d).toMatchObject({ "Can give it tasks": "Members", "Can stop it": "Admins", "Can approve its steps": "Grace" });
+ expect(card.querySelectorAll("[data-agent-right]")).toHaveLength(0);
});
it("words the harness and when it joined", () => {
diff --git a/apps/cua-spaces-web/src/__tests__/agents-chat.test.tsx b/apps/cua-spaces-web/src/__tests__/agents-chat.test.tsx
index 656bc5e430..636ff7555d 100644
--- a/apps/cua-spaces-web/src/__tests__/agents-chat.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/agents-chat.test.tsx
@@ -10,6 +10,7 @@ import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { chatKey, mergeChats } from "@/bridge/agents-dm";
+import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";
import { demoDmEntries } from "@/bridge/adapters/demo/thread";
import type { AgentMember, MemberIdentity } from "@/bridge/ops/thread";
import { needText } from "@/components/agents/agent-chat";
@@ -133,8 +134,8 @@ describe("the Agents tab", () => {
await waitFor(() => expect(router.state.location.pathname).toBe("/settings/connectors"));
expect((router.state.location.search as { app?: string }).app).toBe(agent);
// The row is there, and still off: opening the page did not connect it.
- const appRow = await found(`[data-connected-app="${agent}"]`);
- expect(appRow.dataset.on).toBe("false");
+ const appRow = await found(`[data-connector-app="${agent}"]`);
+ expect(appRow.dataset.state).toBe("not-connected");
});
it("New agent opens Add an agent with the Space in its title", async () => {
@@ -153,10 +154,11 @@ describe("the Agents tab", () => {
expect(page.querySelector("[data-agent-page-all]")).not.toBeNull();
});
- it("the thread's card links to the agent's DM (Activity)", async () => {
+ it("the thread's card links to the agent's DM (Activity, under Details)", async () => {
await mountApp(`/spaces/${encodeURIComponent("relay:linux-box/ubuntu-build")}`, { failsCreates: false, listsGhost: false });
const name = await found("[data-author-name='claude']");
await click(name);
+ await click(await found("[data-profile-card='agent'] [data-card-details]"));
await click(await found("[data-agent-activity='claude']"));
await found(`[data-dm='${CLAUDE}']`);
});
@@ -179,10 +181,11 @@ describe("the DM and the list, as data", () => {
const member = (name: string, i: MemberIdentity | null, over: Partial<AgentMember> = {}): AgentMember => ({ name, harness: i?.harness.id ?? "", status: "idle", activity: null, sessions: 1, rights: null, youCan: null, heldBy: null, identity: i, ...over });
const space = (id: string) => ({ id, name: id.split(":").pop()!, os: "linux" as const }) as never;
- it("keys one agent across Spaces on owner, harness and name; without an identity, on its Space", () => {
+ it.skipIf(!wasmBuilt)("keys one agent across Spaces on owner, harness and name; without an identity, on its Space", async () => {
+ const core = await testCore();
expect(chatKey("a", member("hermes-2", ident("ada", "hermes", "Hermes")))).toBe("ada/hermes/hermes");
expect(chatKey("local:x", member("bot", null))).toBe("local:x/bot");
- const chats = mergeChats([
+ const chats = mergeChats(core, [
{ space: space("local:a"), role: "owner", members: [member("hermes", ident("ada", "hermes", "Hermes"), { status: "asleep" })] },
{ space: space("local:b"), role: "owner", members: [member("hermes-2", ident("ada", "hermes", "Hermes"), { status: "working", activity: "drafting notes", dm: { unread: 2, last: null }, needsYou: [] })] },
{ space: space("local:b"), role: "owner", members: [member("hermes-3", ident("grace", "hermes", "Hermes"))] },
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.tsx
new file mode 100644
index 0000000000..6e80057d86
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Ask first with the redesign: Start goes straight to the Space being made,
+// and the job is its thread's first message, @mentioning the agent. When the
+// agent can't be woken (Claude Code with no Anthropic sign-in) the message
+// is still posted, with "Claude Code isn't connected yet" and Connect under
+// it; once connected, the message goes again. In any Space, @ offers the
+// agents that can start there and sending adds one. With only one of the two
+// flags, Ask first keeps its own task page (ask-first-start-failed.test.tsx).
+
+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 { DEMO_THREAD_SPACE } from "@/bridge/adapters/demo/thread";
+import { resetWakeNotes } from "@/components/space-thread/summon";
+import { resetConnectedAppsState } from "@/hooks/use-connected-apps";
+import { resetConnectState } from "@/hooks/use-connectors";
+import { askTasks, resetAskTasks } from "@/lib/ask-first";
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+stubBrowserApis();
+beforeEach(() => {
+ localStorage.clear();
+ resetAskTasks();
+ resetWakeNotes();
+ 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 found = (s: string, timeout = 8000) =>
+ waitFor(
+ () => {
+ const el = q(s);
+ expect(el).not.toBeNull();
+ return el!;
+ },
+ { timeout },
+ );
+
+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 () => {
+ 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" } });
+ 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/);
+ 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]")!);
+ });
+ await waitFor(() => expect(q("[data-wake-note=claude]")!.dataset.state).toBe("retried"), { timeout: 15000 });
+ expect(calls.filter((c) => c.op === "agents.connect").map((c) => c.args)).toEqual([{ agents: ["claude-code"], signIn: true }]);
+ 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", {
+ failsCreates: false,
+ listsGhost: false,
+ intercept: (op, args) => {
+ 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" }));
+ });
+ await found("[data-wake-connect]", 15000);
+ await act(async () => {
+ fireEvent.click(q("[data-wake-connect]")!);
+ });
+ await waitFor(() => expect(q("[data-wake-note=claude]")!.textContent).toContain("this Space is full"), { timeout: 15000 });
+ expect(q("[data-wake-note=claude]")!.dataset.state).not.toBe("retried");
+ expect(posts).toEqual(["@claude fix the build"]);
+ });
+});
+
+describe.skipIf(!wasmBuilt)("notes only you see", () => {
+ it("say so, can be dismissed, and never reach the thread or any other member", 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" } });
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Start" }));
+ });
+ // While the Space is made: the queued line says only you see it.
+ const queued = await found("[data-queued-note]");
+ expect(queued.hasAttribute("data-only-you")).toBe(true);
+ 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.
+ 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]")!);
+ });
+ expect(q("[data-wake-note=claude]")).toBeNull();
+ });
+});
+
+describe.skipIf(!wasmBuilt)("@ any agent in a Space (redesign)", () => {
+ it("offers the agents that can start here and adds one on send", async () => {
+ setFlagOverride("spaces_ask_first_home", null);
+ const calls: { op: string; args: Record<string, unknown> }[] = [];
+ await mountApp(`/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`, {
+ failsCreates: false,
+ listsGhost: false,
+ intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined),
+ });
+ const box = await waitFor(() => {
+ const el = q("[data-composer]") as HTMLTextAreaElement | null;
+ expect(el?.disabled).toBe(false);
+ return el!;
+ });
+ fireEvent.change(box, { target: { value: "@", selectionStart: 1 } });
+ await found("[data-mention-picker]");
+ // Codex (OpenAI is connected in the demo) starts here; its row says so.
+ expect(q("[data-mention-option=codex]")!.textContent).toContain("Starts in this Space");
+ fireEvent.change(box, { target: { value: "@codex bump the timeout", selectionStart: 23 } });
+ await act(async () => {
+ fireEvent.keyDown(box, { key: "Enter" });
+ await new Promise((r) => setTimeout(r, 20));
+ });
+ await waitFor(() => expect(calls.some((c) => c.op === "thread.agentAdd" && c.args.name === "codex" && c.args.harness === "openai-codex")).toBe(true));
+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@codex bump the timeout")).toBe(true));
+ // Added before the message, so the message wakes it.
+ const add = calls.findIndex((c) => c.op === "thread.agentAdd");
+ const post = calls.findIndex((c) => c.op === "thread.post" && c.args.text === "@codex bump the timeout");
+ expect(add).toBeLessThan(post);
+ expect(q("[data-wake-note]")).toBeNull();
+ });
+});
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.tsx
index 17cd1c9dc8..ba21dd66e4 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
@@ -9,7 +9,7 @@
// words, with Try again and Change computer in the card.
import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setFlagOverride } from "@/bridge";
import { wasmBuilt } from "@/bridge/__tests__/testCore";
@@ -22,12 +22,17 @@ const CORE_NOT_FOUND = 'Space "this-mac" (use its id, such as local:<name> or cl
const HOST_SPACE = "relay:this-mac";
const HOST = { failsCreates: false, listsGhost: false };
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.unstubAllEnvs();
+});
stubBrowserApis();
beforeEach(() => {
localStorage.clear();
resetAskTasks();
setFlagOverride("spaces_ask_first_home", true);
+ // Ask first on its own: its task page (with the redesign too, see ask-first-in-space.test.tsx).
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");
});
async function pickThisMac() {
diff --git a/apps/cua-spaces-web/src/__tests__/connections.test.tsx b/apps/cua-spaces-web/src/__tests__/connections.test.tsx
index e8a3d44864..fa83972080 100644
--- a/apps/cua-spaces-web/src/__tests__/connections.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/connections.test.tsx
@@ -106,10 +106,11 @@ describe.skipIf(!wasmBuilt)("the Agents page, On This Mac", () => {
await waitFor(() => expect(router.state.location.pathname).toBe("/settings/connectors"));
expect((router.state.location.search as { app?: string }).app).toBe("hermes");
const appRow = await waitFor(() => {
- const r = document.querySelector<HTMLElement>('[data-connected-app="hermes"]');
+ const r = document.querySelector<HTMLElement>('[data-connector-app="hermes"]');
expect(r).not.toBeNull();
return r!;
}, { timeout: 8000 });
- expect(appRow.dataset.on).toBe("false");
+ // The redesign's row: still Connect, nothing connected on the spot.
+ expect(appRow.dataset.state).toBe("not-connected");
});
});
diff --git a/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx
new file mode 100644
index 0000000000..a65ee291da
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Settings, Connectors with the redesign: each coding app has Connect (Cua's
+// tools and its sign-in, once) and a chevron to its own page; Providers has
+// Connect or Sign out. Connect on Claude Code runs only its own token
+// command (`signIn: true` for Claude Code alone) and connects Anthropic too.
+// Off, the page as it was: switches and Account keys.
+
+import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { wasmBuilt } from "@/bridge/__tests__/testCore";
+import { resetConnectedAppsState } from "@/hooks/use-connected-apps";
+import { resetConnectState } from "@/hooks/use-connectors";
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+stubBrowserApis();
+beforeEach(() => {
+ localStorage.clear();
+ resetConnectedAppsState();
+ resetConnectState();
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllEnvs();
+});
+
+const q = (s: string) => document.querySelector<HTMLElement>(s);
+const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];
+const found = (s: string) =>
+ waitFor(() => {
+ const el = q(s);
+ expect(el).not.toBeNull();
+ return el!;
+ });
+const click = (el: Element) =>
+ act(async () => {
+ fireEvent.click(el);
+ });
+
+function host(calls: { op: string; args: unknown }[]) {
+ return { failsCreates: false, listsGhost: false, intercept: (op: string, args: unknown) => (calls.push({ op, args }), undefined) };
+}
+
+describe.skipIf(!wasmBuilt)("Settings, Connectors (redesign)", () => {
+ it("lists apps with Connect and a chevron, then Providers; no switches per app", async () => {
+ await mountApp("/settings/connectors", host([]));
+ const claude = await found("[data-connector-app=claude-code]");
+ expect(claude.getAttribute("role")).toBe("link");
+ expect(claude.className).toContain("hover:bg-accent/50");
+ expect(claude.querySelector("[data-connector-chevron]")).not.toBeNull();
+ expect(claude.querySelector("[data-connector-connect]")?.textContent).toBe("Connect");
+ expect(claude.textContent).toContain("Needs a sign-in to Anthropic.");
+ expect(qa("[data-connectors-apps] [role=switch]").length).toBe(1); // Set up new apps automatically only
+ expect(qa("[data-connector-provider]").map((r) => r.dataset.connectorProvider)).toEqual(["anthropic", "openai", "github"]);
+ expect(q("[data-connector-provider=anthropic]")!.textContent).toContain("Not connected");
+ expect(q("[data-connector-provider=openai]")!.textContent).toContain("Sign out");
+ expect(document.body.textContent).not.toContain("Account keys");
+ });
+
+ it("Connect on Claude Code runs its token command alone, and connects Anthropic", async () => {
+ const calls: { op: string; args: unknown }[] = [];
+ await mountApp("/settings/connectors", host(calls));
+ const btn = await found("[data-connector-app=claude-code] [data-connector-connect]");
+ await click(btn);
+ await waitFor(() => expect(q("[data-connector-app=claude-code]")!.dataset.state).toBe("connected"));
+ await waitFor(() => expect(q("[data-connector-provider=anthropic]")!.dataset.state).toBe("connected"));
+ expect(q("[data-connector-provider=anthropic]")!.textContent).toContain("Claude sign-in, for Claude Code");
+ const connects = calls.filter((c) => c.op === "agents.connect").map((c) => c.args as { agents: string[]; signIn: boolean });
+ expect(connects).toEqual([{ agents: ["claude-code"], signIn: true }]);
+ });
+
+ it("a provider without a sign-in of its own asks for a key; Sign out removes it", async () => {
+ await mountApp("/settings/connectors", host([]));
+ await click(await found("[data-connector-provider=github] [data-connector-provider-action]"));
+ await found("[data-provider-sheet=github]");
+ expect(qa("[data-provider-way]").map((w) => w.dataset.providerWay)).toEqual(["key"]);
+ await click(q("[data-provider-way=key]")!);
+ fireEvent.change(await found("[data-provider-key]"), { target: { value: "github_pat_11ABCDEFG0123456789" } });
+ await click(q("[data-provider-save]")!);
+ await waitFor(() => expect(q("[data-connector-provider=github]")!.dataset.state).toBe("connected"));
+ expect(q("[data-provider-sheet]")).toBeNull();
+ await click(q("[data-connector-provider=github] [data-connector-provider-action]")!);
+ await waitFor(() => expect(q("[data-connector-provider=github]")!.dataset.state).toBe("not-connected"));
+ });
+
+ it("the row opens the app's page: switches, its sign-in, and Remove", async () => {
+ await mountApp("/settings/connectors", host([]));
+ await click(await found("[data-connector-app=claude-code]"));
+ await found("[data-connector-detail=claude-code]");
+ expect(qa("[data-connector-toggle]").map((t) => t.dataset.connectorToggle)).toEqual(["skills", "mcp", "auto"]);
+ expect(q("[data-connector-detail-signin=anthropic]")!.textContent).toContain("Signs in with Anthropic");
+ expect(q("[data-connector-detail-signin-action]")!.textContent).toBe("Sign in");
+ expect(q("[data-connector-remove]")!.textContent).toBe("Remove Cua from Claude Code");
+ });
+
+ it("Codex signs in with its own device code: the code shows, then OpenAI is connected", async () => {
+ const calls: { op: string; args: unknown }[] = [];
+ await mountApp("/settings/connectors", host(calls));
+ // OpenAI starts connected in the demo with a key; sign out first.
+ await click(await found("[data-connector-provider=openai] [data-connector-provider-action='sign-out']"));
+ await waitFor(() => expect(q("[data-connector-app=codex]")!.dataset.state).toBe("not-connected"));
+ await click(q("[data-connector-app=codex] [data-connector-connect]")!);
+ const code = await found("[data-device-code]");
+ expect(code.textContent).toBe("QX7P-4M2KD");
+ expect(q("[data-device-sign-in=codex]")?.textContent).toContain("Open sign-in page");
+ await waitFor(() => expect(q("[data-connector-provider=openai]")!.dataset.state).toBe("connected"), { timeout: 8000 });
+ expect(q("[data-connector-provider=openai]")!.textContent).toContain("ChatGPT sign-in, for Codex");
+ expect(q("[data-device-sign-in]")).toBeNull();
+ // Never Codex's own files: no agents.connect with signIn for Codex.
+ const signIns = calls.filter((c) => c.op === "agents.connect").map((c) => c.args as { agents: string[]; signIn: boolean });
+ expect(signIns.every((a) => !(a.agents.includes("codex") && a.signIn))).toBe(true);
+ expect(calls.some((c) => c.op === "agents.signInStart" && (c.args as { agent: string }).agent === "codex")).toBe(true);
+ });
+
+ it("a key exported in your shell can be used; only its name is read first", async () => {
+ const calls: { op: string; args: unknown }[] = [];
+ await mountApp("/settings/connectors", host(calls));
+ await click(await found("[data-connector-provider=anthropic] [data-connector-provider-action]"));
+ const way = await found("[data-provider-way=shell]");
+ expect(way.textContent).toContain("Use ANTHROPIC_API_KEY from your shell");
+ await click(way);
+ await waitFor(() => expect(q("[data-connector-provider=anthropic]")!.dataset.state).toBe("connected"));
+ expect(calls.filter((c) => c.op.startsWith("agentKeys.") && c.op !== "agentKeys.list").map((c) => c.op)).toEqual(["agentKeys.shell", "agentKeys.fromShell"]);
+ });
+
+ it("an app's page switches one part off and on, leaving the other", async () => {
+ const calls: { op: string; args: unknown }[] = [];
+ await mountApp("/settings/connectors/claude-code", host(calls));
+ await click(await found("[data-connector-toggle=mcp]"));
+ await waitFor(() => expect(calls.some((c) => c.op === "agents.disconnect")).toBe(true));
+ expect(calls.find((c) => c.op === "agents.disconnect")!.args).toEqual({ agents: ["claude-code"], signIn: false, skills: false, mcp: true });
+ await waitFor(() => expect(q("[data-connector-toggle=mcp]")!.getAttribute("aria-checked") ?? q("[data-connector-toggle=mcp]")!.dataset.checked).toMatch(/false|unchecked/));
+ expect(q("[data-connector-toggle=skills]")!.getAttribute("aria-checked") ?? "true").not.toBe("false");
+ });
+
+ it("redesign off: the page as it was, with switches and Account keys", async () => {
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");
+ await mountApp("/settings/connectors", host([]));
+ await found('[data-connected-app="claude-code"]');
+ expect(q("[data-connectors-redesign]")).toBeNull();
+ await found("[data-agent-keys]");
+ });
+});
diff --git a/apps/cua-spaces-web/src/__tests__/fixtures/mac-host-settings-read.json b/apps/cua-spaces-web/src/__tests__/fixtures/mac-host-settings-read.json
new file mode 100644
index 0000000000..09e3bc57be
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/fixtures/mac-host-settings-read.json
@@ -0,0 +1,375 @@
+{
+ "page" : {
+ "sections" : [
+ {
+ "button" : null,
+ "buttonEnabled" : false,
+ "buttonHelp" : null,
+ "id" : "general",
+ "rows" : [
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "notch",
+ "kind" : "choice",
+ "label" : "Spaces tab in the notch",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "show",
+ "label" : "Show"
+ },
+ {
+ "active" : false,
+ "id" : "hide",
+ "label" : "Hide"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : "Opening a running Space shows its live desktop",
+ "id" : "auto-connect",
+ "kind" : "toggle",
+ "label" : "Connect to the desktop automatically",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "on",
+ "label" : "On"
+ },
+ {
+ "active" : false,
+ "id" : "off",
+ "label" : "Off"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : "With a linked cloud and a budget, new Spaces go there when this Mac is full",
+ "id" : "placement-overflow",
+ "kind" : "toggle",
+ "label" : "Overflow into your clouds when this Mac is full",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "on",
+ "label" : "On"
+ },
+ {
+ "active" : false,
+ "id" : "off",
+ "label" : "Off"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : "Show again",
+ "enabled" : true,
+ "help" : null,
+ "id" : "welcome",
+ "kind" : "text",
+ "label" : "Welcome",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "tips",
+ "kind" : "toggle",
+ "label" : "Show tips",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "on",
+ "label" : "On"
+ },
+ {
+ "active" : false,
+ "id" : "off",
+ "label" : "Off"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : "Reset",
+ "enabled" : true,
+ "help" : null,
+ "id" : "reset-tips",
+ "kind" : "text",
+ "label" : "Reset tips",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+
+ ],
+ "placeholder" : null,
+ "value" : null
+ }
+ ],
+ "title" : "General"
+ },
+ {
+ "button" : null,
+ "buttonEnabled" : false,
+ "buttonHelp" : null,
+ "id" : "runtimes",
+ "rows" : [
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "runtime:container",
+ "kind" : "choice",
+ "label" : "Containers",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : false,
+ "id" : "auto",
+ "label" : "Automatic"
+ },
+ {
+ "active" : false,
+ "id" : "builtin",
+ "label" : "Cua’s own"
+ },
+ {
+ "active" : true,
+ "id" : "system",
+ "label" : "Already installed"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "runtime-detected:container",
+ "kind" : "choice",
+ "label" : "Installed",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "/usr/local/bin/docker",
+ "label" : "Docker — /usr/local/bin/docker (27.3)"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "runtime-path:container",
+ "kind" : "field",
+ "label" : "Detected",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+
+ ],
+ "placeholder" : "Full path of the program",
+ "value" : "/usr/local/bin/docker"
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "runtime-check:container",
+ "kind" : "note",
+ "label" : "Docker 27.3 found",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "runtime:vm",
+ "kind" : "choice",
+ "label" : "Virtual machines",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : false,
+ "id" : "auto",
+ "label" : "Automatic"
+ },
+ {
+ "active" : true,
+ "id" : "builtin",
+ "label" : "Cua’s own"
+ },
+ {
+ "active" : false,
+ "id" : "system",
+ "label" : "Already installed"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "runtime:microvm",
+ "kind" : "choice",
+ "label" : "MicroVMs",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "auto",
+ "label" : "Automatic"
+ },
+ {
+ "active" : false,
+ "id" : "builtin",
+ "label" : "Cua’s own"
+ },
+ {
+ "active" : false,
+ "id" : "system",
+ "label" : "Already installed"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ }
+ ],
+ "title" : "Runtimes"
+ }
+ ],
+ "title" : "Settings"
+ },
+ "runtimes" : {
+ "hostArch" : "arm64",
+ "kinds" : [
+ {
+ "check" : {
+ "executable" : true,
+ "exists" : true,
+ "expected" : [
+ "Docker",
+ "Podman"
+ ],
+ "guests" : null,
+ "minVersion" : null,
+ "name" : "Docker",
+ "path" : "/usr/local/bin/docker",
+ "tool" : "docker",
+ "version" : "27.3.1"
+ },
+ "detected" : [
+ {
+ "guests" : null,
+ "name" : "Docker",
+ "path" : "/usr/local/bin/docker",
+ "tool" : "docker",
+ "version" : "27.3.1"
+ }
+ ],
+ "expected" : [
+ "Docker",
+ "Podman"
+ ],
+ "kind" : "container",
+ "path" : null,
+ "source" : "system"
+ },
+ {
+ "check" : {
+ "executable" : true,
+ "exists" : true,
+ "expected" : [
+ "Lume"
+ ],
+ "guests" : "macOS",
+ "minVersion" : "0.6.0",
+ "name" : "Lume",
+ "path" : "/opt/homebrew/bin/lume",
+ "tool" : "lume",
+ "version" : "0.6.1"
+ },
+ "detected" : [
+ {
+ "guests" : "macOS",
+ "name" : "Lume",
+ "path" : "/opt/homebrew/bin/lume",
+ "tool" : "lume",
+ "version" : "0.6.1"
+ }
+ ],
+ "expected" : [
+ "Lume"
+ ],
+ "kind" : "vm",
+ "path" : null,
+ "source" : "builtin"
+ },
+ {
+ "check" : null,
+ "detected" : [
+
+ ],
+ "expected" : [
+ "Apple container"
+ ],
+ "kind" : "microvm",
+ "path" : null,
+ "source" : "auto"
+ }
+ ],
+ "localBackends" : [
+ "managed",
+ "lume",
+ "vz"
+ ],
+ "localDetails" : {
+
+ },
+ "os" : "macos"
+ }
+}
diff --git a/apps/cua-spaces-web/src/__tests__/fixtures/mac-host-settings-unread.json b/apps/cua-spaces-web/src/__tests__/fixtures/mac-host-settings-unread.json
new file mode 100644
index 0000000000..dfb8d3a1e4
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/fixtures/mac-host-settings-unread.json
@@ -0,0 +1,245 @@
+{
+ "page" : {
+ "sections" : [
+ {
+ "button" : null,
+ "buttonEnabled" : false,
+ "buttonHelp" : null,
+ "id" : "general",
+ "rows" : [
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "notch",
+ "kind" : "choice",
+ "label" : "Spaces tab in the notch",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "show",
+ "label" : "Show"
+ },
+ {
+ "active" : false,
+ "id" : "hide",
+ "label" : "Hide"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : "Opening a running Space shows its live desktop",
+ "id" : "auto-connect",
+ "kind" : "toggle",
+ "label" : "Connect to the desktop automatically",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "on",
+ "label" : "On"
+ },
+ {
+ "active" : false,
+ "id" : "off",
+ "label" : "Off"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : "With a linked cloud and a budget, new Spaces go there when this Mac is full",
+ "id" : "placement-overflow",
+ "kind" : "toggle",
+ "label" : "Overflow into your clouds when this Mac is full",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "on",
+ "label" : "On"
+ },
+ {
+ "active" : false,
+ "id" : "off",
+ "label" : "Off"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : "Show again",
+ "enabled" : true,
+ "help" : null,
+ "id" : "welcome",
+ "kind" : "text",
+ "label" : "Welcome",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : null,
+ "id" : "tips",
+ "kind" : "toggle",
+ "label" : "Show tips",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "on",
+ "label" : "On"
+ },
+ {
+ "active" : false,
+ "id" : "off",
+ "label" : "Off"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : "Reset",
+ "enabled" : true,
+ "help" : null,
+ "id" : "reset-tips",
+ "kind" : "text",
+ "label" : "Reset tips",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+
+ ],
+ "placeholder" : null,
+ "value" : null
+ }
+ ],
+ "title" : "General"
+ },
+ {
+ "button" : null,
+ "buttonEnabled" : false,
+ "buttonHelp" : null,
+ "id" : "runtimes",
+ "rows" : [
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : "Checking…",
+ "id" : "runtime:container",
+ "kind" : "choice",
+ "label" : "Containers",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "auto",
+ "label" : "Automatic"
+ },
+ {
+ "active" : false,
+ "id" : "builtin",
+ "label" : "Cua’s own"
+ },
+ {
+ "active" : false,
+ "id" : "system",
+ "label" : "Already installed"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : "Checking…",
+ "id" : "runtime:vm",
+ "kind" : "choice",
+ "label" : "Virtual machines",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "auto",
+ "label" : "Automatic"
+ },
+ {
+ "active" : false,
+ "id" : "builtin",
+ "label" : "Cua’s own"
+ },
+ {
+ "active" : false,
+ "id" : "system",
+ "label" : "Already installed"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ },
+ {
+ "button" : null,
+ "enabled" : true,
+ "help" : "Checking…",
+ "id" : "runtime:microvm",
+ "kind" : "choice",
+ "label" : "MicroVMs",
+ "linkLabel" : null,
+ "linkUrl" : null,
+ "options" : [
+ {
+ "active" : true,
+ "id" : "auto",
+ "label" : "Automatic"
+ },
+ {
+ "active" : false,
+ "id" : "builtin",
+ "label" : "Cua’s own"
+ },
+ {
+ "active" : false,
+ "id" : "system",
+ "label" : "Already installed"
+ }
+ ],
+ "placeholder" : null,
+ "value" : null
+ }
+ ],
+ "title" : "Runtimes"
+ }
+ ],
+ "title" : "Settings"
+ },
+ "runtimes" : {
+ "hostArch" : "arm64",
+ "kinds" : null,
+ "localBackends" : null,
+ "localDetails" : null,
+ "os" : "macos"
+ }
+}
diff --git a/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx b/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx
new file mode 100644
index 0000000000..99984a10ef
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/home-agents.test.tsx
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Home and the Agents page draw ONE list (`agentList.view`): a job whose
+// Space is still being made and an agent that isn't connected show on both,
+// with the same words and the same Connect; a row opens its Space's thread.
+// Home's order: the composer, Your agents, Your Spaces. With the redesign
+// off, Home keeps its Tasks list.
+
+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 { 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 { mountApp, stubBrowserApis } from "./app-harness";
+
+stubBrowserApis();
+beforeEach(() => {
+ localStorage.clear();
+ resetAskTasks();
+ resetWakeNotes();
+ 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 found = (s: string, timeout = 8000) =>
+ waitFor(
+ () => {
+ const el = q(s);
+ expect(el).toBeTruthy();
+ return el!;
+ },
+ { timeout },
+ );
+
+async function start(job: string) {
+ fireEvent.change(await screen.findByLabelText("What do you want to do?"), { target: { value: job } });
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Start" }));
+ });
+}
+
+describe.skipIf(!wasmBuilt)("Your agents and the Agents page: one list", () => {
+ it("a creating run and a not-connected run show on both, the same way", async () => {
+ let release!: () => void;
+ const hold = new Promise<void>((r) => (release = r));
+ const { router } = await mountApp("/home", { failsCreates: false, listsGhost: false, hold });
+ await start("fix the build");
+ // While its Space is being made: on the Agents page, waiting for its Space…
+ await act(async () => void router.navigate({ to: "/agents" }));
+ 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.
+ await act(async () => void router.navigate({ to: "/home" }));
+ expect((await found("[data-home-see-all='/agents']")).textContent?.trim()).toBe(`See all ${total}`);
+ await act(async () => void router.navigate({ to: "/agents" }));
+ release();
+
+ // Ready, and Claude Code isn't connected: both say so, with Connect.
+ 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();
+ await act(async () => void router.navigate({ to: "/home" }));
+ const home = await found("[data-home-agent][data-chat-tone='not-connected']");
+ expect(home.querySelector("[data-home-agent-line]")?.textContent).toBe("Claude Code isn't connected yet");
+ expect(home.querySelector("[data-home-agent-action='connect']")?.textContent).toBe("Connect Claude Code");
+
+ // A row opens its Space's thread.
+ await act(async () => {
+ fireEvent.click(home);
+ });
+ await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\//));
+ await found("[data-call-layout] [data-wake-note=claude]", 15000);
+ });
+
+ it("Home: the composer, then Your agents, then Your Spaces; See all links; Spaces say running", async () => {
+ await mountApp("/home", { failsCreates: false, listsGhost: false });
+ await start("tidy the repo");
+ // Back on Home.
+ 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");
+ 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+$/);
+ expect(q("[data-home-spaces] h2")?.textContent).toMatch(/running/);
+ 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");
+ expect(q("[data-ask-where]")?.textContent).toBe("New SpaceLinux on This Mac");
+ });
+
+ it("a task whose Space is gone leaves nothing to list: Home is the welcome, not a bare box", async () => {
+ addAskTask({ prompt: "an old job", agent: "claude-code", os: "linux", spaceId: "gone-space" });
+ await mountApp("/home", { failsCreates: false, listsGhost: false, answer: (op, out) => (op === "spaces.list" ? [] : out) });
+ expect(await screen.findByRole("heading", { name: "What do you want to do?" })).toBeTruthy();
+ expect(q("[data-home-agents]")).toBeNull();
+ expect(q("[data-home-spaces]")).toBeNull();
+ });
+
+ it("redesign off: Home keeps its Tasks list", async () => {
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");
+ await mountApp("/home", { failsCreates: false, listsGhost: false });
+ await start("tidy the repo");
+ fireEvent.click(await found("a[href='/home']"));
+ await found("[data-task-row]");
+ expect(q("[data-home-agents]")).toBeNull();
+ });
+});
diff --git a/apps/cua-spaces-web/src/__tests__/new-space-microvm-settings.test.tsx b/apps/cua-spaces-web/src/__tests__/new-space-microvm-settings.test.tsx
index ffbad249a8..4dc1ee5ef6 100644
--- a/apps/cua-spaces-web/src/__tests__/new-space-microvm-settings.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/new-space-microvm-settings.test.tsx
@@ -3,7 +3,7 @@
// New Space's Kind row has no line under it: a MicroVM this computer can't
// run is greyed out with no words there. Why it can't is told in Settings,
-// Advanced, beside the runtimes (`settings::microvm_rows`), from the same
+// Advanced, on the MicroVMs row (`runtimes::section`), from the same
// runtime doctor the tile follows.
import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
@@ -44,7 +44,7 @@ describe.skipIf(!wasmBuilt)("MicroVM: greyed out in New Space, explained in Sett
await mountApp("/settings/advanced", { failsCreates: false, listsGhost: false });
const row = await waitFor(
() => {
- const r = document.querySelector<HTMLElement>("[data-microvm-runtime]");
+ const r = document.querySelector<HTMLElement>("[data-setting-row='runtime:microvm']");
expect(r).not.toBeNull();
return r!;
},
@@ -52,7 +52,7 @@ describe.skipIf(!wasmBuilt)("MicroVM: greyed out in New Space, explained in Sett
);
expect(row.querySelector("[data-row-label]")?.textContent).toBe("MicroVMs");
expect(row.querySelector("[data-row-value]")?.textContent).toBe("Not available");
- expect(row.querySelector("[data-row-description]")?.textContent).toBe("MicroVM needs macOS 26.");
- expect(row.getAttribute("data-microvm-problem")).toBe("true");
+ expect(row.querySelector("[data-row-description]")?.textContent).toBe("MicroVMs need macOS 26");
+ expect(row.getAttribute("data-enabled")).toBe("false");
});
});
diff --git a/apps/cua-spaces-web/src/__tests__/profile-cards.test.tsx b/apps/cua-spaces-web/src/__tests__/profile-cards.test.tsx
new file mode 100644
index 0000000000..4773eb42fe
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/profile-cards.test.tsx
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The cards people and agents open to on the redesigned Space page: a
+// person's (email, access, Active now; Change access and Remove for the
+// owner), your own, and an agent of yours with no sign-in (Not
+// connected, with Connect). Mentions open the same cards. With the redesign
+// off, the page as it was has none.
+
+import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { wasmBuilt } from "@/bridge/__tests__/testCore";
+import { DEMO_THREAD_SPACE } from "@/bridge/adapters/demo/thread";
+import { resetConnectState } from "@/hooks/use-connectors";
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+stubBrowserApis();
+beforeEach(() => {
+ localStorage.clear();
+ resetConnectState();
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllEnvs();
+});
+
+const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;
+const q = (s: string) => document.querySelector<HTMLElement>(s);
+const found = (s: string) =>
+ waitFor(() => {
+ const el = q(s);
+ expect(el).toBeTruthy();
+ return el!;
+ });
+/** The page has settled (the thread read, the composer on): its triggers stay put. */
+const ready = () => waitFor(() => expect((q("[data-composer]") as HTMLTextAreaElement | null)?.disabled).toBe(false));
+const click = (el: Element) =>
+ act(async () => {
+ fireEvent.click(el);
+ await new Promise((r) => setTimeout(r, 10));
+ });
+
+describe.skipIf(!wasmBuilt)("profile cards (redesign)", () => {
+ it("the owner opens an editor's card: email, Can edit, Active now, Change access, Remove; no Copy email", async () => {
+ const calls: { op: string; args: unknown }[] = [];
+ await mountApp(path, { failsCreates: false, listsGhost: false, intercept: (op, args) => (calls.push({ op, args }), undefined) });
+ await ready();
+ await click(await found("[data-profile-trigger='Grace']"));
+ const card = await found("[data-profile-card='person'][data-profile='Grace']");
+ expect(card.textContent).toContain("[email protected]");
+ expect(card.querySelector("[data-card-access]")?.textContent).toContain("Can edit");
+ expect(card.querySelector("[data-card-presence]")?.textContent).toBe("Active now");
+ expect(card.textContent).not.toContain("Copy email");
+ const remove = card.querySelector<HTMLElement>("[data-card-remove]")!;
+ expect(remove.textContent).toBe("Remove from Space");
+ await click(remove);
+ await waitFor(() => expect(calls.some((c) => c.op === "sharing.unshare" && (c.args as { who: string }).who === "[email protected]")).toBe(true));
+ });
+
+ it("your own card: (you), Owner, no access actions", async () => {
+ await mountApp(path, { failsCreates: false, listsGhost: false });
+ await ready();
+ await click(await found("[data-profile-trigger='Ada']"));
+ const card = await found("[data-profile-card='person'][data-profile='Ada']");
+ expect(card.textContent).toContain("(you)");
+ expect(card.querySelector("[data-card-access]")?.textContent).toContain("Owner");
+ expect(card.querySelector("[data-card-remove]")).toBeNull();
+ expect(card.querySelector("[role=combobox]")).toBeNull();
+ });
+
+ it("your agent with no sign-in it can use: Not connected, with Connect", async () => {
+ await mountApp(path, { failsCreates: false, listsGhost: false, answer: (op, out) => (op === "agentKeys.list" ? { ...(out as object), keys: [] } : out) });
+ await ready();
+ await click(await found("[data-profile-trigger='hermes']"));
+ const card = await found("[data-profile-card='agent'][data-profile='hermes']");
+ await waitFor(() => expect(card.querySelector("[data-card-status]")?.getAttribute("data-card-status")).toBe("not-connected"));
+ expect(card.querySelector("[data-card-status]")?.textContent).toBe("Not connected");
+ expect(card.querySelector("[data-card-connect]")?.textContent).toBe("Connect Hermes");
+ expect(card.querySelector("[data-card-line='who']")?.textContent).toBe("Run by you in this Space, uses Anthropic");
+ });
+
+ it("a mention chip opens its member's card", async () => {
+ await mountApp(path, { failsCreates: false, listsGhost: false });
+ await ready();
+ const chip = await found("[data-profile-trigger] [data-mention='hermes']");
+ await click(chip.closest("[data-profile-trigger]")!);
+ await found("[data-profile-card='agent'][data-profile='hermes']");
+ });
+
+ it("redesign off: the page as it was, no cards", async () => {
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");
+ await mountApp(path, { failsCreates: false, listsGhost: false });
+ await waitFor(() => expect(document.body.textContent).toContain("ubuntu-build"));
+ expect(q("[data-profile-trigger]")).toBeNull();
+ });
+});
diff --git a/apps/cua-spaces-web/src/__tests__/redesign-flag.test.tsx b/apps/cua-spaces-web/src/__tests__/redesign-flag.test.tsx
index dcad0f66c1..b9f775a4eb 100644
--- a/apps/cua-spaces-web/src/__tests__/redesign-flag.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/redesign-flag.test.tsx
@@ -1,9 +1,9 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-// `spaces_redesign` (Settings → Advanced → Labs) switches whole pages: off,
-// the default, each gated route draws the page as it was (src/legacy/); on,
-// the redesign. Both states render, so neither can quietly break.
+// `spaces_redesign` (Settings → Advanced → Labs) switches whole pages: on,
+// the default, the redesign; off, each gated route draws the classic page
+// (src/legacy/). Both states render, so neither can quietly break.
import { cleanup, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -23,10 +23,25 @@ const q = (sel: string) => document.querySelector(sel);
const flag = (on: boolean) => vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", on ? "1" : "0");
describe.skipIf(!wasmBuilt)("the redesign flag", () => {
- it("is off by default outside the test suite's own default", async () => {
- const { flagOn } = await import("@/bridge/flags");
+ it("is on by default, and an override or the build's env turns it off", async () => {
+ const { flagOn, setFlagOverride } = await import("@/bridge/flags");
+ setFlagOverride("spaces_redesign", null);
vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "");
+ expect(flagOn("spaces_redesign")).toBe(true);
+ // The build's env.
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");
expect(flagOn("spaces_redesign")).toBe(false);
+ // This device's explicit choice wins over the env, both ways.
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "");
+ setFlagOverride("spaces_redesign", false);
+ expect(flagOn("spaces_redesign")).toBe(false);
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");
+ setFlagOverride("spaces_redesign", true);
+ expect(flagOn("spaces_redesign")).toBe(true);
+ setFlagOverride("spaces_redesign", null);
+ // The Ask first Home stays off by default.
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_ASK_FIRST_HOME", "");
+ expect(flagOn("spaces_ask_first_home")).toBe(false);
});
it("Spaces page: the toolbar and the new sidebar on; the page and the getting-started checklist as they were off", async () => {
diff --git a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx
index f3b44ef749..2f50b400ad 100644
--- a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx
@@ -8,7 +8,7 @@
import { createMemoryHistory, createRootRoute, createRouter, RouterProvider } from "@tanstack/react-router";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BridgeProvider } from "@/bridge";
import { createDemoAdapter } from "@/bridge/adapters/demo";
import { noCore, wasmBuilt } from "@/bridge/__tests__/testCore";
@@ -17,7 +17,10 @@ import { RunAgentDialog } from "@/components/agents/run-agent-dialog";
import { connectedAppsState, resetConnectedAppsState, setConnectedAppsState } from "@/hooks/use-connected-apps";
import { mountApp, stubBrowserApis } from "./app-harness";
+// The Connectors page as it was (`spaces_redesign` off); the redesign's is connectors-redesign.test.tsx.
+beforeEach(() => vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0"));
afterEach(() => {
+ vi.unstubAllEnvs();
cleanup();
localStorage.clear();
resetConnectedAppsState();
diff --git a/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsx
index 87417cb48b..fd09d3d2eb 100644
--- a/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/settings-host-rows.test.tsx
@@ -1,17 +1,24 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-// Settings on a host with settings of its own (the SwiftUI app): Runtimes,
-// "Connect to the desktop automatically" and the Keyvault's auto-wipe, as
-// the core lays them out, changed with `settings.choose`. Elsewhere the
-// rows are left out.
+// Settings, Advanced on a host with settings of its own: one row per kind
+// of Space (Containers, Virtual machines, MicroVMs) as the core lays them
+// out, "Already installed" with what is installed, the path in use and a
+// live check of a typed one; "Open a Space's screen right away". Rendered
+// from the demo host and from the SwiftUI host's own `settings.get`
+// answers (fixtures the Mac app's tests write), through the WebKit
+// adapter's conversion, as the real app draws them.
import { createMemoryHistory, createRouter, RouterProvider } from "@tanstack/react-router";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { BridgeProvider, type HostSettings } from "@/bridge";
+import { BridgeProvider } from "@/bridge";
import type { DataAdapter } from "@/bridge/adapter";
import { createDemoAdapter } from "@/bridge/adapters/demo";
+import { toSettingsSnapshot } from "@/bridge/adapters/webkit";
+import type { WkSettings } from "@/bridge/webkit-protocol";
import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";
import { ToastProvider } from "@/components/ui/toast";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -21,24 +28,17 @@ import { stubBrowserApis } from "./app-harness";
afterEach(cleanup);
stubBrowserApis();
-/** The demo host, with these host settings (none: the demo's own answer). */
-async function mountSettings(own: HostSettings | null) {
+/** Settings, Advanced on `adapter` (the demo host by default), with what it was asked. */
+async function mountAdvanced(wrap?: (demo: DataAdapter) => DataAdapter) {
const demo = createDemoAdapter({ latencyMs: 1, stepMs: 4 });
- const chosen: [string, string][] = [];
- const settings = { ...own };
- const ROW: Record<string, keyof HostSettings> = { "macos-runtime": "lumeSource", "linux-runtime": "linuxSource", "auto-connect": "autoConnect", "keyvault-auto-wipe": "keyvaultAutoWipe" };
+ const calls: [string, unknown][] = [];
+ const base = wrap ? wrap(demo) : demo;
const adapter: DataAdapter = {
- mode: demo.mode,
- subscribe: (l) => demo.subscribe(l),
- call: (async (op: string, args: { row: string; option: string }) => {
- if (op === "settings.choose") {
- chosen.push([args.row, args.option]);
- const key = ROW[args.row]!;
- (settings as Record<string, unknown>)[key] = key === "autoConnect" || key === "keyvaultAutoWipe" ? args.option === "on" : args.option;
- op = "settings.get";
- }
- const out = await demo.call(op as never, args as never);
- return op === "settings.get" && own ? { ...(out as object), hostSettings: { ...settings } } : out;
+ mode: base.mode,
+ subscribe: (l) => base.subscribe(l),
+ call: (async (op: string, args: unknown) => {
+ calls.push([op, args]);
+ return base.call(op as never, args as never);
}) as DataAdapter["call"],
};
const router = createRouter({ routeTree, history: createMemoryHistory({ initialEntries: ["/settings/advanced"] }) });
@@ -51,46 +51,119 @@ async function mountSettings(own: HostSettings | null) {
</TooltipProvider>
</BridgeProvider>,
);
- return { chosen };
+ const chosen = () => calls.filter(([op]) => op === "settings.choose").map(([, a]) => a as { row: string; option: string });
+ return { calls, chosen };
}
const row = (id: string) => document.querySelector<HTMLElement>(`[data-setting-row="${id}"]`);
+/** The row once it is there. */
+const rowSoon = (id: string) =>
+ waitFor(() => {
+ const r = row(id);
+ if (!r) throw new Error(`no ${id} row`);
+ return r;
+ });
+const kindRow = (kind: string) => document.querySelector<HTMLElement>(`[data-runtime-kind="${kind}"]`);
+const KINDS: [string, string][] = [
+ ["container", "Containers"],
+ ["vm", "Virtual machines"],
+ ["microvm", "MicroVMs"],
+];
-describe.skipIf(!wasmBuilt)("the host's own settings (real routes, wasm core)", () => {
- it("lays out which software runs Spaces and auto-connect in Advanced, in plain words, and picks their options", async () => {
- const { chosen } = await mountSettings({ lumeSource: "system", linuxSource: "auto", autoConnect: true, keyvaultAutoWipe: false });
- const macos = await waitFor(() => {
- const r = row("macos-runtime");
- if (!r) throw new Error("no runtime row");
- return r;
- });
- expect(within(macos).getByText("Mac computers")).toBeTruthy();
- expect(macos.textContent).toContain("Already installed");
- expect(document.body.textContent).toContain("Which software runs Spaces on this Mac");
- expect(document.body.textContent).not.toMatch(/Lume|gVisor|Runtimes/);
- expect(within(row("linux-runtime")!).getByText("Linux computers")).toBeTruthy();
- expect(within(row("auto-connect")!).getByText("Open a Space\u2019s screen right away")).toBeTruthy();
- // The Keyvault's switches live on the Keyvault page now.
- expect(row("keyvault-auto-wipe")).toBeNull();
+async function pick(scope: HTMLElement, name: string) {
+ const trigger = within(scope).getByRole("combobox");
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: "ArrowDown" });
+ const option = await screen.findByRole("option", { name });
+ fireEvent.pointerMove(option, { pointerType: "mouse" });
+ fireEvent.mouseMove(option);
+ fireEvent.keyDown(option, { key: "Enter" });
+ fireEvent.keyUp(option, { key: "Enter" });
+}
- fireEvent.click(within(row("auto-connect")!).getByRole("switch"));
- await waitFor(() => expect(chosen).toContainEqual(["auto-connect", "off"]));
- const trigger = within(macos).getByRole("combobox");
- trigger.focus();
- fireEvent.keyDown(trigger, { key: "ArrowDown" });
- const option = await screen.findByRole("option", { name: "Cua\u2019s own" });
- fireEvent.pointerMove(option, { pointerType: "mouse" });
- fireEvent.mouseMove(option);
- fireEvent.keyDown(option, { key: "Enter" });
- fireEvent.keyUp(option, { key: "Enter" });
- await waitFor(() => expect(chosen).toContainEqual(["macos-runtime", "builtin"]));
- });
+/** The SwiftUI host's `settings.get` answer, as its tests wrote it. */
+const macHostAnswer = (name: string): WkSettings =>
+ JSON.parse(readFileSync(join(__dirname, "fixtures", `mac-host-settings-${name}.json`), "utf8")) as WkSettings;
+
+/** The demo host, but `settings.get` answers what the SwiftUI host answered, through the WebKit adapter. */
+const asMacHost = (name: string) => (demo: DataAdapter): DataAdapter => ({
+ ...demo,
+ call: (async (op: string, args: unknown) => {
+ if (op === "settings.get") return toSettingsSnapshot(macHostAnswer(name), { theme: "system", hotkey: "⌘⇧Space" });
+ return demo.call(op as never, args as never);
+ }) as DataAdapter["call"],
+});
- it("leaves the rows out on a host without them", async () => {
- await mountSettings(null);
- await waitFor(() => expect(document.querySelector("[data-setting-row]")).toBeTruthy());
+describe.skipIf(!wasmBuilt)("Settings, Advanced: which software runs Spaces (real routes, wasm core)", () => {
+ it("has one row per kind, in plain words, and none of the old per-OS rows", async () => {
+ await mountAdvanced();
+ await waitFor(() => expect(kindRow("microvm")).toBeTruthy());
+ expect(document.body.textContent).toContain("Which software runs Spaces on this computer");
+ for (const [kind, label] of KINDS) {
+ const r = row(`runtime:${kind}`)!;
+ expect(within(r).getByText(label)).toBeTruthy();
+ }
+ expect(row("runtime:container")!.textContent).toContain("Automatic");
+ // The demo Mac (macOS 15) can't run microVMs: it says so, and why.
+ expect(row("runtime:microvm")!.textContent).toContain("Not available");
+ expect(row("runtime:microvm")!.textContent).toContain("MicroVMs need macOS 26");
expect(row("macos-runtime")).toBeNull();
- expect(row("auto-connect")).toBeNull();
- expect(row("keyvault-auto-wipe")).toBeNull();
+ expect(row("linux-runtime")).toBeNull();
+ expect(document.body.textContent).not.toMatch(/Mac computers|Linux computers|Built-in|gVisor/);
+ // Automatic shows nothing more.
+ expect(document.querySelector("[data-runtime-installed]")).toBeNull();
+ });
+
+ it("Already installed lists what is installed, autofills the path in use and checks a typed one", async () => {
+ const { chosen } = await mountAdvanced();
+ const containers = await rowSoon("runtime:container");
+ await pick(containers, "Already installed");
+ await waitFor(() => expect(chosen()).toContainEqual({ row: "runtime:container", option: "system" }));
+ const path = await rowSoon("runtime-path:container");
+ const field = within(path).getByRole("textbox") as HTMLInputElement;
+ // Autofilled with the binary that will be used, Detected, and what it is.
+ expect(field.value).toBe("/usr/local/bin/docker");
+ expect(path.dataset.runtimeState).toBe("detected");
+ await waitFor(() => expect(path.querySelector("[data-runtime-check]")?.textContent).toBe("Docker 27.3 found"));
+ // The drop-down names what is installed.
+ const detected = row("runtime-detected:container")!;
+ expect(detected.textContent).toContain("Docker — /usr/local/bin/docker (27.3)");
+
+ // Something that is not Docker: checked while typed, not saved.
+ fireEvent.change(field, { target: { value: "/bin/ls" } });
+ await waitFor(() => expect(path.querySelector("[data-runtime-check='bad']")?.textContent).toBe("Not a Docker or Podman binary"));
+ expect(path.dataset.runtimeState).toBe("custom");
+ expect(chosen().some((c) => c.row === "runtime-path:container")).toBe(false);
+
+ // Another Docker: saved on Enter, Custom, with Reset to detected.
+ fireEvent.change(field, { target: { value: "/Users/demo/bin/docker" } });
+ await waitFor(() => expect(path.querySelector("[data-runtime-check='ok']")?.textContent).toBe("Docker 28.0 found"));
+ fireEvent.keyDown(field, { key: "Enter" });
+ await waitFor(() => expect(chosen()).toContainEqual({ row: "runtime-path:container", option: "/Users/demo/bin/docker" }));
+ await waitFor(() => expect(row("runtime-path:container")!.dataset.runtimeState).toBe("custom"));
+ const reset = await waitFor(() => within(row("runtime-path:container")!).getByText("Reset to detected"));
+ fireEvent.click(reset);
+ await waitFor(() => expect(chosen()).toContainEqual({ row: "runtime-path:container", option: "" }));
+ await waitFor(() => expect((within(row("runtime-path:container")!).getByRole("textbox") as HTMLInputElement).value).toBe("/usr/local/bin/docker"));
+ });
+
+ it("an older Lume is named too old", async () => {
+ const { chosen } = await mountAdvanced();
+ await pick(await rowSoon("runtime:vm"), "Already installed");
+ const path = await rowSoon("runtime-path:vm");
+ fireEvent.click(within(path).getByText("Browse…"));
+ await waitFor(() => expect(chosen()).toContainEqual({ row: "runtime-path:vm", option: "/opt/homebrew/Cellar/lume/0.5.3/bin/lume" }));
+ await waitFor(() => expect(row("runtime-path:vm")!.querySelector("[data-runtime-check='bad']")?.textContent).toBe("Lume 0.5.3 is too old (needs 0.6.0)"));
});
+
+ for (const answer of ["unread", "read"]) {
+ it(`draws all three kinds from the Mac app's own settings.get (${answer})`, async () => {
+ await mountAdvanced(asMacHost(answer));
+ await waitFor(() => expect(kindRow("microvm")).toBeTruthy());
+ for (const [kind, label] of KINDS) {
+ expect(kindRow(kind), kind).toBeTruthy();
+ expect(within(row(`runtime:${kind}`)!).getByText(label)).toBeTruthy();
+ }
+ });
+ }
});
diff --git a/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx
index 84472e96db..335ce103da 100644
--- a/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/settings-tabs.test.tsx
@@ -7,13 +7,14 @@
// the audit put it.
import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { useUiStore } from "@/stores/ui";
import { wasmBuilt } from "@/bridge/__tests__/testCore";
import { mountApp, stubBrowserApis, type TestHost } from "./app-harness";
afterEach(() => {
+ vi.unstubAllEnvs();
cleanup();
localStorage.clear();
});
@@ -65,6 +66,8 @@ describe.skipIf(!wasmBuilt)("Settings tabs (real routes, wasm core)", () => {
});
it("puts Connectors where Agents was, with the account keys and Terminal", async () => {
+ // The page as it was (the redesign's Providers: connectors-redesign.test.tsx).
+ vi.stubEnv("VITE_CUA_FLAG_SPACES_REDESIGN", "0");
await mountApp("/settings/connectors", host);
await waitFor(() => expect(document.querySelector("[data-agent-keys]")).not.toBeNull(), { timeout: 8000 });
const text = tab("connectors")!.textContent!;
diff --git a/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx b/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx
index e7f2bd87ab..1bc7736853 100644
--- a/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx
@@ -18,6 +18,26 @@ const q = (s: string) => document.querySelector<HTMLElement>(s);
const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];
const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;
+/** Opens an agent's card from its row in In this space, with Details open. */
+async function openRailCard(handle: string) {
+ const row = await waitFor(() => {
+ const el = q(`[data-profile-trigger='${handle}'] [data-member='agent:${handle}']`)?.closest<HTMLElement>("[data-profile-trigger]");
+ expect(el).toBeTruthy();
+ return el!;
+ });
+ await act(async () => {
+ fireEvent.click(row);
+ });
+ const details = await waitFor(() => {
+ const el = q(`[data-profile-card='agent'][data-profile='${handle}'] [data-card-details]`);
+ expect(el).not.toBeNull();
+ return el!;
+ });
+ await act(async () => {
+ fireEvent.click(details);
+ });
+}
+
describe("a Space's thread", () => {
it("draws the call layout: tasks with their state, a reply under its task, notes, an approval, the divider and the members", async () => {
await mountApp(path, { failsCreates: false, listsGhost: false });
@@ -48,7 +68,7 @@ describe("a Space's thread", () => {
});
fireEvent.change(box, { target: { value: "@", selectionStart: 1 } });
await waitFor(() => expect(q("[data-mention-picker]")).not.toBeNull());
- expect(qa("[data-mention-option]").map((o) => o.dataset.mentionOption)).toEqual(["claude", "hermes", "cursor", "grace", "linus"]);
+ expect(qa("[data-mention-option]").map((o) => o.dataset.mentionOption)).toEqual(["claude", "hermes", "cursor", "codex", "openclaw", "grace", "linus"]);
fireEvent.keyDown(box, { key: "ArrowDown" });
fireEvent.keyDown(box, { key: "Enter" });
expect(box.value).toBe("@hermes ");
@@ -171,7 +191,7 @@ describe("a Space's thread", () => {
});
// Grace's Claude Code: its approvals go to Grace (CUA-2262).
expect(card.textContent).toBe("Waiting for Grace");
- expect(qa('[data-approval-state="open"] button:not([data-author-name])')).toHaveLength(0);
+ expect(qa('[data-approval-state="open"] button:not([data-author-name]):not([data-profile-trigger])')).toHaveLength(0);
});
it("says whose keys a task runs on, and shows rights read-only to a member", async () => {
@@ -179,25 +199,17 @@ describe("a Space's thread", () => {
await waitFor(() => expect(qa("[data-entry-footnote]").length).toBeGreaterThan(0), { timeout: 4000 });
// Grace owns the Space here: Linus's task runs on her keys, hers on nobody else's.
expect(qa("[data-entry-footnote]").map((f) => f.textContent)).toContain("Runs on Grace's keys");
- const hermes = await waitFor(() => {
- const el = q("[data-member='agent:hermes'] [data-member-toggle]");
- expect(el).not.toBeNull();
- return el!;
- });
- fireEvent.click(hermes);
- await waitFor(() => expect(q("[data-agent-rights='hermes']")).not.toBeNull());
- expect(qa("[data-agent-rights='hermes'] [data-agent-right]").map((r) => r.textContent)).toEqual(["Can taskOwner", "Can stopAdmins", "Can approveAdmins"]);
- expect(q("[data-agent-rights='hermes'] button")).toBeNull();
+ // Its row in In this space opens its card; who may task, stop and approve it is under Details, read-only.
+ await openRailCard("hermes");
+ expect(qa("[data-card-details-open] dt").map((d) => `${d.textContent}: ${d.nextElementSibling?.textContent}`)).toEqual(
+ expect.arrayContaining(["Can give it tasks: Owner", "Can stop it: Admins", "Can approve its steps: Admins"]),
+ );
+ expect(q("[data-agent-right]")).toBeNull();
});
it("lets the owner change who can task an agent", async () => {
await mountApp(path, { failsCreates: false, listsGhost: false });
- const hermes = await waitFor(() => {
- const el = q("[data-member='agent:hermes'] [data-member-toggle]");
- expect(el).not.toBeNull();
- return el!;
- });
- fireEvent.click(hermes);
+ await openRailCard("hermes");
await waitFor(() => expect(q("[data-agent-rights='hermes'] [data-agent-right='task'] button")).not.toBeNull());
expect(q("[data-agent-rights='hermes'] [data-agent-right='task']")?.textContent).toContain("Owner");
expect(qa("[data-agent-rights='hermes'] [data-agent-right] button")).toHaveLength(3);
diff --git a/apps/cua-spaces-web/src/__tests__/spaces-grid-redraws.test.tsx b/apps/cua-spaces-web/src/__tests__/spaces-grid-redraws.test.tsx
index d3bfa8b017..b112632811 100644
--- a/apps/cua-spaces-web/src/__tests__/spaces-grid-redraws.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/spaces-grid-redraws.test.tsx
@@ -41,4 +41,13 @@ describe.skipIf(!wasmBuilt)("the Spaces grid", () => {
expect(redrawn).toContain("local:scale-7");
expect(redrawn.length, `redrew ${redrawn.length} tiles: ${redrawn.slice(0, 8).join(", ")}…`).toBeLessThanOrEqual(3);
});
+
+ it("draws one screen of a long grid, not every Space (jsdom has no width, so the grid draws its first rows)", { timeout: 30_000 }, async () => {
+ await mountApp("/spaces", { failsCreates: false, listsGhost: false, demo: { extraSpaces: 400 } });
+ await waitFor(() => expect(document.querySelectorAll("[data-space-id]").length).toBeGreaterThan(0));
+ const drawn = document.querySelectorAll("[data-space-id]").length;
+ expect(drawn, `${drawn} of 410 tiles drawn`).toBeLessThanOrEqual(24);
+ // The page still counts all of them.
+ expect(document.body.textContent).toMatch(/4\d\d Spaces/);
+ });
});
diff --git a/apps/cua-spaces-web/src/__tests__/thread-follow-growth.test.ts b/apps/cua-spaces-web/src/__tests__/thread-follow-growth.test.ts
new file mode 100644
index 0000000000..a897d63499
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/thread-follow-growth.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// A note drawn under the last message (one only you see, a "woke up" line)
+// grows the thread without a new item: the thread stays at its end when you
+// were there, and leaves you where you were when you had scrolled up.
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { followGrowth } from "@/components/space-thread/thread-view";
+
+let grow: (() => void) | null = null;
+class FakeResizeObserver {
+ constructor(cb: () => void) {
+ grow = cb;
+ }
+ observe() {}
+ disconnect() {
+ grow = null;
+ }
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+function scroller(height: number) {
+ const el = document.createElement("div");
+ let h = height;
+ Object.defineProperty(el, "scrollHeight", { get: () => h });
+ return { el, setHeight: (n: number) => (h = n) };
+}
+
+describe("the thread follows a note added under the last message", () => {
+ it("stays at the end when you were there", () => {
+ vi.stubGlobal("ResizeObserver", FakeResizeObserver);
+ const { el, setHeight } = scroller(500);
+ el.scrollTop = 500;
+ const stop = followGrowth(el, document.createElement("div"), () => true);
+ setHeight(640);
+ grow!();
+ expect(el.scrollTop).toBe(640);
+ stop();
+ expect(grow).toBeNull();
+ });
+
+ it("leaves you where you were when you had scrolled up", () => {
+ vi.stubGlobal("ResizeObserver", FakeResizeObserver);
+ const { el, setHeight } = scroller(500);
+ el.scrollTop = 120;
+ followGrowth(el, document.createElement("div"), () => false);
+ setHeight(640);
+ grow!();
+ expect(el.scrollTop).toBe(120);
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
index 0f93e45623..f123b820c6 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
@@ -56,6 +56,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"agents.status": { refresh: true },
"agents.connect": { agents: ["codex"], signIn: true },
"agents.disconnect": { agents: ["codex"], signIn: true },
+ "agents.signInStart": { agent: "codex" },
+ "agents.signInWait": { id: "codex-1" },
"agents.detail": { name: "ada" },
"agents.readFile": { path: "agents/ada/MEMORY.md" },
"agents.restoreFile": { path: "agents/ada/MEMORY.md", version: "agents/ada/MEMORY.md@1" },
@@ -95,6 +97,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"agentKeys.list": {},
"agentKeys.set": { provider: "anthropic", value: "sk-ant-test-0000" },
"agentKeys.remove": { env: "ANTHROPIC_API_KEY" },
+ "agentKeys.shell": {},
+ "agentKeys.fromShell": { env: "ANTHROPIC_API_KEY" },
"volume.overview": {},
"volume.storage": {},
"volume.storageSet": { update: { backend: "fs", s3: null, access_key_id: null, secret_access_key: null, dry_run: true } },
@@ -145,6 +149,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"loginItem.get": {},
"loginItem.set": { on: true },
"loginItem.openSettings": {},
+ "runtimes.check": { kind: "container", path: "/usr/local/bin/docker" },
+ "runtimes.browse": { kind: "container" },
"devices.get": {},
"devices.enroll": {},
"devices.checkEnrolled": {},
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
index 4831ff8e17..a087c3275c 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
@@ -71,6 +71,8 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {
"agents.status": { refresh: true },
"agents.connect": { agents: ["codex"], signIn: true },
"agents.disconnect": { agents: ["codex"], signIn: true },
+ "agents.signInStart": { agent: "codex" },
+ "agents.signInWait": { id: "codex-1" },
...AGENT_DETAIL_ARGS,
...NEW_SPACE_ARGS,
...AGENT_KEYS_ARGS,
@@ -113,6 +115,8 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {
"loginItem.get": {},
"loginItem.set": { on: true },
"loginItem.openSettings": {},
+ "runtimes.check": { kind: "container", path: "/usr/local/bin/docker" },
+ "runtimes.browse": { kind: "container" },
"devices.get": {},
"devices.enroll": {},
"devices.checkEnrolled": {},
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts
index ee24d06b30..43df2ae9da 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts
@@ -856,12 +856,21 @@ describe("webkit adapter", () => {
it("reads the host's own settings rows and picks their options with settings.choose", async () => {
const choice = (id: string, active: string) => ({ id, kind: "choice", label: "", enabled: true, options: ["auto", "builtin", "system"].map((o) => ({ id: o, label: o, active: o === active })) });
const toggle = (id: string, on: boolean) => ({ id, kind: "toggle", label: "", enabled: true, options: [{ id: "on", label: "On", active: on }, { id: "off", label: "Off", active: !on }] });
+ // The host's runtimes, as read (`runtimes::RuntimesInput`): passed through for the core.
+ const runtimes = {
+ os: "macos",
+ hostArch: "arm64",
+ localBackends: ["lume", "managed"],
+ localDetails: {},
+ kinds: [{ kind: "container", source: "system", path: null, detected: [{ tool: "docker", name: "Docker", path: "/usr/local/bin/docker", version: "27.3.1" }], check: null, expected: ["Docker", "Podman"] }],
+ };
const page = {
+ runtimes,
page: {
title: "Settings",
sections: [
- { id: "general", rows: [toggle("auto-connect", false)] },
- { id: "runtimes", rows: [choice("macos-runtime", "builtin"), choice("linux-runtime", "system")] },
+ { id: "general", rows: [toggle("auto-connect", false), toggle("placement-overflow", true)] },
+ { id: "runtimes", rows: [choice("runtime:container", "system"), choice("runtime:vm", "builtin"), choice("runtime:microvm", "auto")] },
{
id: "keyvault",
rows: [
@@ -877,25 +886,25 @@ describe("webkit adapter", () => {
const { win, sent } = webkitHost(() => ok(page));
const a = createWebkitAdapter(win);
expect((await a.call("settings.get", {})).hostSettings).toEqual({
- lumeSource: "builtin",
- linuxSource: "system",
+ runtimes: runtimes,
autoConnect: false,
+ overflow: true,
keyvaultAutoWipe: true,
keyvaultUnlockPrompt: false,
keyvaultSiteIcons: true,
keyvaultProtection: [{ label: "Unlock", value: "Mac login" }],
});
- await a.call("settings.choose", { row: "macos-runtime", option: "system" });
+ await a.call("settings.choose", { row: "runtime:vm", option: "system" });
expect(sent.slice(-2).map((r) => [r.method, r.args])).toEqual([
- ["settings.choose", { row: "macos-runtime", option: "system" }],
+ ["settings.choose", { row: "runtime:vm", option: "system" }],
["settings.get", {}],
]);
// A host without these rows has none of them.
const { win: bare } = webkitHost(() => ok(settingsPage));
expect((await createWebkitAdapter(bare).call("settings.get", {})).hostSettings).toEqual({
- lumeSource: null,
- linuxSource: null,
+ runtimes: null,
autoConnect: null,
+ overflow: null,
keyvaultAutoWipe: null,
keyvaultUnlockPrompt: null,
keyvaultSiteIcons: null,
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/new-space.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/new-space.test.tsx
index beab4d2690..2ce3e16f9f 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/new-space.test.tsx
+++ b/apps/cua-spaces-web/src/bridge/__tests__/new-space.test.tsx
@@ -453,7 +453,7 @@ describe.skipIf(!wasmBuilt)("On the SwiftUI host's answer (wasm core)", () => {
await act(() => hooks.wizard.applyRuntimeSwitch(change));
// Settings, Runtimes' own row, then this Mac's runtimes read again.
- expect(chosen).toEqual([{ row: "macos-runtime", option: "builtin" }]);
+ expect(chosen).toEqual([{ row: "runtime:vm", option: "builtin" }]);
await waitFor(() => expect(hooks.wizard.view?.runtimeSwitch ?? null).toBeNull());
expect(hooks.wizard.view?.placementError ?? null).toBeNull();
});
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index fcccdc2fc3..8b3c90e124 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -39,7 +39,7 @@ import { demoNewSpaceState, newSpaceDemoHandlers, type DemoClouds, type DemoNewS
import { demoShareHandlers } from "./demo/share";
import { demoThreadHandlers } from "./demo/thread";
import { demoAgentDetailHandlers } from "./demo/agent-detail";
-import { demoAgentKeysHandlers } from "./demo/agent-keys";
+import { 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";
@@ -49,6 +49,7 @@ import type { CliInstallPlan } from "../contracts/first-run";
import { unsupportedChecklistOps } from "../ops/checklist";
import { demoTeleportHandlers } from "./demo/teleport";
import { createDemoSettings } from "./demo/settings";
+import { demoChooseRuntime, demoRuntimesInput, demoRuntimesState, type DemoRuntimes } from "./demo/runtimes";
import { demoAgentSetup, demoConnections, demoPersistentAgents, demoReply, demoRunRecords, demoStartedRun, runAt, writtenEvents, type DemoRunRecord } from "./demo-agents";
import { demoVolumeHandlers, demoVolumeState, type DemoVolumeState } from "./demo/volume";
import { demoHostSetupHandlers, demoHostSetupState, type DemoHostSetupState } from "./demo/host-setup";
@@ -310,6 +311,7 @@ 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),
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,
@@ -317,6 +319,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
renamed: {},
removed: [],
hostSettings: options.macHost ? DEMO_MAC_HOST_SETTINGS : undefined,
+ runtimes: demoRuntimesState(),
volume: demoVolumeState(now(), options.onboarded !== false, options.platform),
...demoTelemetryState(),
...demoRelayUsageState(),
@@ -389,7 +392,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
values: { ...state.settings },
defaultLocation: { value: state.settings.defaultLocation, source: "config", path: "~/.cua/config.toml" },
telemetry: demoTelemetry(state.settings.telemetry),
- ...(state.hostSettings ? { hostSettings: { ...state.hostSettings } } : {}),
+ hostSettings: { ...state.hostSettings, runtimes: demoRuntimesInput(state.runtimes) },
// The macOS hosts register ⌘⇧Space; the Windows and Linux shells have none.
globalShortcut: state.platform.os === "macos" ? { label: state.settings.hotkey, registered: true } : null,
// What a host's CLI install plan names (`CuaChannel::cli_name`): Local's is `cua-local`.
@@ -609,6 +612,8 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
"settings.choose": async ({ row, option }) => {
const key = DEMO_KEYVAULT_ROWS[row];
if (key && state.hostSettings) state.hostSettings = { ...state.hostSettings, [key]: option === "on" };
+ // Settings, Advanced's runtime rows: the kind's source or its path.
+ if (demoChooseRuntime(state.runtimes, row, option)) await wait(step);
// An AI agents row's button (the SwiftUI host's `press`): set it up, or remove what cua added.
const agent = row.startsWith("agent:") ? state.agentSetup.find((r) => `agent:${r.agent}` === row && r.installed) : undefined;
if (agent) {
@@ -770,16 +775,29 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
},
"agents.setup": () => state.agentSetup.map((r) => ({ ...r })),
"agents.status": () => options.connections ?? demoConnections(state.agentSetup, state.imported, now()),
- "agents.connect": async ({ agents, signIn }) => {
+ "agents.connect": async ({ agents, signIn, skills, mcp }) => {
await wait(step);
+ // Only Cua's skills or only its MCP server (an app's page's switches).
+ const part = skills === false || mcp === false;
// `?demo=agents-readonly`: an app whose config Cua can't write fails, as with `agents.configure`.
state.agentSetup = state.agentSetup.map((r) =>
r.installed && agents.includes(r.agent)
? state.readOnlyAgents.includes(r.agent)
? { ...r, configured: false, skillsInstalled: 0, detail: "Permission denied (os error 13)" }
- : { ...r, configured: true, skillsInstalled: r.skillsTotal, detail: "Skills and MCP server set up" }
+ : part
+ ? { ...r, configured: false, skillsInstalled: skills === false ? 0 : r.skillsTotal, detail: skills === false ? "MCP server set up" : "Skills set up" }
+ : { ...r, configured: true, skillsInstalled: r.skillsTotal, detail: "Skills and MCP server set up" }
: r,
);
+ // Claude Code's own token command: one browser approval, then its token is saved with the keys.
+ if (signIn && agents.includes("claude-code")) {
+ await wait(step * 14);
+ state.keyStore.keys = [
+ ...state.keyStore.keys.filter((k) => k.env !== "CLAUDE_CODE_OAUTH_TOKEN"),
+ { provider: "other", env: "CLAUDE_CODE_OAUTH_TOKEN", last4: "", addedMs: now() },
+ ];
+ emit({ type: "agents.changed" });
+ }
return agents.map((agent) => {
const row = state.agentSetup.find((r) => r.agent === agent);
if (row && state.readOnlyAgents.includes(agent)) {
@@ -799,10 +817,31 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
};
});
},
- "agents.disconnect": async ({ agents, signIn }) => {
+ // Codex's device-code sign-in made for Cua: a code to show, then approved a moment later.
+ "agents.signInStart": async ({ agent }) => {
+ await wait(step);
+ if (agent !== "codex") throw new HostError(`${agent} has no device sign-in`);
+ return { id: `codex-${now()}`, url: "https://auth.openai.com/codex/device", code: "QX7P-4M2KD" };
+ },
+ "agents.signInWait": async () => {
+ await wait(step * 20);
+ state.keyStore.keys = [...state.keyStore.keys.filter((k) => k.env !== "CODEX_AUTH_JSON"), { provider: "other", env: "CODEX_AUTH_JSON", last4: "", addedMs: now() }];
+ emit({ type: "agents.changed" });
+ return { imported: { source: "codex", env: "CODEX_AUTH_JSON", label: "Codex · ChatGPT sign-in", expires_ms: null, added_ms: now() }, refused: null, line: null };
+ },
+ "agents.disconnect": async ({ agents, signIn, skills, mcp }) => {
await wait(step);
- state.agentSetup = state.agentSetup.map((r) => (agents.includes(r.agent) ? { ...r, configured: false, skillsInstalled: 0, detail: "Not set up" } : r));
+ // Some parts only (an app's page's switches): what stays keeps its state.
+ const part = skills !== undefined || mcp !== undefined;
+ state.agentSetup = state.agentSetup.map((r) => {
+ if (!agents.includes(r.agent)) return r;
+ if (!part) return { ...r, configured: false, skillsInstalled: 0, detail: "Not set up" };
+ const hasSkills = skills ? false : r.skillsInstalled > 0;
+ const hasMcp = mcp ? false : r.configured || /MCP/.test(r.detail);
+ return { ...r, configured: false, skillsInstalled: hasSkills ? r.skillsTotal : 0, detail: hasSkills && hasMcp ? "Skills and MCP server set up" : hasSkills ? "Skills set up" : hasMcp ? "MCP server set up" : "Not set up" };
+ });
const removed = signIn ? state.imported.filter((a) => agents.includes(a)) : [];
+ if (signIn && agents.includes("claude-code")) state.keyStore.keys = state.keyStore.keys.filter((k) => k.env !== "CLAUDE_CODE_OAUTH_TOKEN");
state.imported = state.imported.filter((a) => !removed.includes(a));
return { removed_sign_ins: removed };
},
@@ -840,7 +879,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
...demoTeleportHandlers({ wait, emit, now, stepMs: step }),
...demoShareHandlers({ wait, stepMs: step, teamFull: options.teamFull }),
...demoAgentDetailHandlers({ wait, stepMs: step, now }),
- ...demoAgentKeysHandlers({ wait, stepMs: step, now }),
+ ...demoAgentKeysHandlers({ wait, stepMs: step, now, store: state.keyStore }),
...demoVolumeHandlers({ state: state.volume, now, wait, step, emit, platform: state.platform }),
...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, unenrolled: options.unenrolled, update: options.update, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })), addMachine: (m) => ((state.paired = [...state.paired, m]), emit({ type: "machines.changed" })) }),
...demoTelemetryHandlers(ctx),
@@ -914,6 +953,8 @@ export interface DemoState extends DemoLinksStateField, DemoTelemetryState, Demo
agentSetup: AgentSetupRow[];
/** Agents whose sign-in the demo "copied" to Keyvault. */
imported: string[];
+ /** Saved keys and sign-ins (Settings, Connectors; Claude Code's Connect adds its token here). */
+ keyStore: DemoKeyStore;
readOnlyAgents: string[];
volume: DemoVolumeState;
platform: DemoPlatform;
@@ -925,4 +966,6 @@ export interface DemoState extends DemoLinksStateField, DemoTelemetryState, Demo
removed: string[];
/** `?demo=mac-host`: the Keyvault's switches the SwiftUI host lays out in Settings. */
hostSettings?: HostSettings;
+ /** Settings, Advanced's runtimes (every demo host has them). */
+ runtimes: DemoRuntimes;
}
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.ts
index d0af926eaf..0e22c01cb5 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
@@ -17,11 +17,28 @@ const PROVIDERS = [
const providerOf = (env: string): AgentKeyProvider => PROVIDERS.find((p) => p.env === env)?.id ?? "other";
-export function demoAgentKeysHandlers({ wait, stepMs, now }: { wait(ms: number): Promise<void>; stepMs: number; now: () => number }): DemoHandlers<
- "agentKeys.list" | "agentKeys.set" | "agentKeys.remove"
-> {
- let keys: AgentKeyInfo[] = [{ provider: "openai", env: "OPENAI_API_KEY", last4: "3f9a", addedMs: now() - 6 * 24 * 3600_000 }];
- const report = (): AgentKeysReport => ({ keys: keys.map((k) => ({ ...k })), providers: PROVIDERS, available: true, unavailable: null });
+/** The demo's saved keys, shared with Connect (a sign-in Connect copies lands here, as in the daemon's store). */
+export interface DemoKeyStore {
+ keys: AgentKeyInfo[];
+}
+
+export const demoKeyStore = (now: () => number): DemoKeyStore => ({
+ keys: [{ provider: "openai", env: "OPENAI_API_KEY", last4: "3f9a", addedMs: now() - 6 * 24 * 3600_000 }],
+});
+
+export function demoAgentKeysHandlers({
+ wait,
+ stepMs,
+ now,
+ store = demoKeyStore(now),
+}: {
+ wait(ms: number): Promise<void>;
+ stepMs: number;
+ now: () => number;
+ store?: DemoKeyStore;
+}): DemoHandlers<"agentKeys.list" | "agentKeys.set" | "agentKeys.remove" | "agentKeys.shell" | "agentKeys.fromShell"> {
+ const keys = () => store.keys;
+ const report = (): AgentKeysReport => ({ keys: keys().map((k) => ({ ...k })), providers: PROVIDERS, available: true, unavailable: null });
return {
"agentKeys.list": () => report(),
"agentKeys.set": async ({ provider, env, value }) => {
@@ -33,14 +50,25 @@ export function demoAgentKeysHandlers({ wait, stepMs, now }: { wait(ms: number):
if (!v) throw new HostError("the key is empty");
// The Keychain write.
await wait(stepMs / 2);
- keys = [...keys.filter((k) => k.env !== name), { provider: providerOf(name), env: name, last4: v.length >= 12 ? v.slice(-4) : "", addedMs: now() }].sort(
+ store.keys = [...keys().filter((k) => k.env !== name), { provider: providerOf(name), env: name, last4: v.length >= 12 ? v.slice(-4) : "", addedMs: now() }].sort(
(a, b) => a.env.localeCompare(b.env),
);
return report();
},
+ // The demo's shell exports an Anthropic key (`?demo=…` none needed): Use it saves a copy.
+ "agentKeys.shell": async () => {
+ await wait(stepMs);
+ return { names: ["ANTHROPIC_API_KEY"] };
+ },
+ "agentKeys.fromShell": async ({ env }) => {
+ if (env !== "ANTHROPIC_API_KEY") throw new HostError(`${env} isn't set in your shell`);
+ await wait(stepMs / 2);
+ store.keys = [...keys().filter((k) => k.env !== env), { provider: "anthropic", env, last4: "a91c", addedMs: now() }];
+ return report();
+ },
"agentKeys.remove": async ({ env }) => {
await wait(stepMs / 2);
- keys = keys.filter((k) => k.env !== env);
+ store.keys = keys().filter((k) => k.env !== env);
return report();
},
};
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/runtimes.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/runtimes.ts
new file mode 100644
index 0000000000..7e6546ae50
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/runtimes.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The demo host's runtimes for Settings, Advanced: an Apple silicon Mac
+ * with Docker and Podman, Homebrew's Lume and Apple's container installed,
+ * shaped like the SwiftUI host's `settings.get` `runtimes`
+ * (`runtimes::RuntimesInput`), and its `runtimes.check` / `runtimes.browse`.
+ */
+
+import type { DetectedRuntime, RuntimeKindInput, RuntimePathCheck, RuntimesInput } from "../../contracts/host";
+
+/** What the demo Mac has, per tool: its path and `--version`. */
+const INSTALLED: Record<string, { tool: string; name: string; version: string; guests?: string; kind: string; minVersion?: string }> = {
+ "/usr/local/bin/docker": { tool: "docker", name: "Docker", version: "27.3.1", kind: "container" },
+ "/opt/homebrew/bin/podman": { tool: "podman", name: "Podman", version: "5.2.1", kind: "container" },
+ "/opt/homebrew/bin/lume": { tool: "lume", name: "Lume", version: "0.6.1", guests: "macOS", kind: "vm", minVersion: "0.6.0" },
+ "/usr/local/bin/container": { tool: "container", name: "Apple container", version: "0.6.0", guests: "Linux", kind: "microvm" },
+};
+
+/** Another binary someone might type or browse to. */
+const OTHER: Record<string, (typeof INSTALLED)[string]> = {
+ "/Users/demo/bin/docker": { tool: "docker", name: "Docker", version: "28.0.1", kind: "container" },
+ "/opt/homebrew/Cellar/lume/0.5.3/bin/lume": { tool: "lume", name: "Lume", version: "0.5.3", guests: "macOS", kind: "vm", minVersion: "0.6.0" },
+};
+
+const EXPECTED: Record<string, string[]> = { container: ["Docker", "Podman"], vm: ["Lume"], microvm: ["Apple container"] };
+
+/** `runtimes.check`: what `path` is for `kind` on the demo Mac. */
+export function demoProbe(kind: string, path: string): RuntimePathCheck {
+ const p = path.trim();
+ const known = INSTALLED[p] ?? OTHER[p];
+ const expected = EXPECTED[kind] ?? [];
+ const base: RuntimePathCheck = { path: p, exists: false, executable: false, expected };
+ if (known && known.kind === kind) {
+ return { ...base, exists: true, executable: true, tool: known.tool, name: known.name, version: known.version, minVersion: known.minVersion ?? null, guests: known.guests ?? null };
+ }
+ // Something else that runs (`/bin/ls`), a file that doesn't (`/etc/hosts`), or nothing.
+ if (known || p.startsWith("/bin/") || p.startsWith("/usr/bin/")) return { ...base, exists: true, executable: true };
+ if (p.startsWith("/etc/")) return { ...base, exists: true };
+ return base;
+}
+
+function detected(kind: string): DetectedRuntime[] {
+ return Object.entries(INSTALLED)
+ .filter(([, t]) => t.kind === kind)
+ .map(([path, t]) => ({ tool: t.tool, name: t.name, path, version: t.version, guests: t.guests ?? null }));
+}
+
+export interface DemoRuntimes {
+ sources: Record<string, string>;
+ paths: Record<string, string | null>;
+}
+
+export const demoRuntimesState = (): DemoRuntimes => ({
+ sources: { container: "auto", vm: "auto", microvm: "auto" },
+ paths: { container: null, vm: null, microvm: null },
+});
+
+/** The demo host's `runtimes` for `settings.get`. */
+export function demoRuntimesInput(r: DemoRuntimes): RuntimesInput {
+ const kinds: RuntimeKindInput[] = ["container", "vm", "microvm"].map((kind) => {
+ const found = detected(kind);
+ const inUse = r.paths[kind] ?? found[0]?.path ?? null;
+ return {
+ kind,
+ source: r.sources[kind] ?? "auto",
+ path: r.paths[kind] ?? null,
+ detected: found,
+ check: inUse ? demoProbe(kind, inUse) : null,
+ expected: EXPECTED[kind] ?? [],
+ };
+ });
+ // The demo Mac's doctor, as New Space's (`demoMacHostOptions`): no microVMs (macOS 15).
+ return { os: "macos", hostArch: "arm64", localBackends: ["lume", "qemu", "container"], localDetails: { managed: "not used: this Mac's own container engine runs Linux Spaces" }, kinds };
+}
+
+/** A runtime row's choice (`settings.choose`), as the SwiftUI host saves it
+ * (`runtimes::choose`): the kind's source, or its path. */
+export function demoChooseRuntime(r: DemoRuntimes, row: string, option: string): boolean {
+ const [prefix, kind] = row.split(":");
+ if (!kind || !(kind in r.sources)) return false;
+ if (prefix === "runtime") r.sources[kind] = ["auto", "builtin", "system"].includes(option) ? option : "auto";
+ else if (prefix === "runtime-path") r.paths[kind] = option.trim() || null;
+ else if (prefix === "runtime-detected") r.paths[kind] = detected(kind)[0]?.path === option ? null : option;
+ else return false;
+ return true;
+}
+
+/** `runtimes.browse`: the file the demo's panel "picks". */
+export const DEMO_BROWSED: Record<string, string> = {
+ container: "/Users/demo/bin/docker",
+ vm: "/opt/homebrew/Cellar/lume/0.5.3/bin/lume",
+ microvm: "/usr/local/bin/container",
+};
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
index 3f0f541c65..2d22662b1f 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
@@ -14,6 +14,7 @@ import type { NotificationInput } from "../../contracts/notifications";
import type { AboutInput, DriveCheckInput, Experiments, LoginItemReport, StorageInput, UpdateState } from "../../contracts/settings";
import { NO_EXPERIMENTS } from "../../contracts/volume";
import { demoMachine, MAC_DEMO_PLATFORM, type DemoPlatform } from "./platform";
+import { DEMO_BROWSED, demoProbe } from "./runtimes";
import type { NotificationsOperations } from "../../ops/notifications";
import type { SettingsOperations } from "../../ops/settings";
import type { HostEvent, SettingsValues } from "../../protocol";
@@ -235,6 +236,12 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {
},
"loginItem.openSettings": () => null,
+ "runtimes.check": async ({ kind, path }) => {
+ await wait(stepMs);
+ return demoProbe(kind, path);
+ },
+ "runtimes.browse": ({ kind }) => ({ path: DEMO_BROWSED[kind] ?? null }),
+
"devices.get": () => {
if (!ctx.signedIn()) throw new HostError("Sign in to Cua to see your devices", "signed_out");
return structuredClone(devices);
diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
index 6e82a68dbb..06915bf77d 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
@@ -101,6 +101,8 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [
"agents.status",
"agents.connect",
"agents.disconnect",
+ "agents.signInStart",
+ "agents.signInWait",
"host.joinWithCode",
...TELEPORT_TAURI_UNSUPPORTED,
...KEYVAULT_MANAGE_TAURI_UNSUPPORTED,
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index af07d3d15c..66715a0d50 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -300,7 +300,6 @@ export function toSettingsSnapshot(s: WkSettings, page: Pick<SettingsValues, "th
const telemetryOn = telemetry ? active(telemetry) === "on" : DEFAULT_SETTINGS.telemetry;
// The rows only this host lays out: what they show now, so the core lays
// them out again on the page (null: the host has none).
- const source = (id: string) => (rows.has(id) ? (active(rows.get(id)) ?? "auto") : null);
const on = (id: string) => (rows.has(id) ? active(rows.get(id)) === "on" : null);
const protection = [...rows.values()]
.filter((r) => r.id.startsWith("keyvault-protection:"))
@@ -332,9 +331,9 @@ export function toSettingsSnapshot(s: WkSettings, page: Pick<SettingsValues, "th
}
: null,
hostSettings: {
- lumeSource: source("macos-runtime"),
- linuxSource: source("linux-runtime"),
+ runtimes: s.runtimes ?? null,
autoConnect: on("auto-connect"),
+ overflow: on("placement-overflow"),
keyvaultAutoWipe: on("keyvault-auto-wipe"),
keyvaultUnlockPrompt: on("keyvault-unlock-prompt"),
keyvaultSiteIcons: on("keyvault-site-icons"),
@@ -710,7 +709,10 @@ export function createWebkitAdapter(
"agents.connect": async ({ agents, signIn, skills, mcp }) =>
// No timeout: Claude Code's sign-in waits for its one browser approval.
list(await request("agents.connect", { agents, signIn, skills: skills ?? true, mcp: mcp ?? true }, null)) as ConnectResult[],
- "agents.disconnect": ({ agents, signIn }) => request<{ removed_sign_ins: string[] }>("agents.disconnect", { agents, signIn }),
+ "agents.disconnect": ({ agents, signIn, skills, mcp }) =>
+ request<{ removed_sign_ins: string[] }>("agents.disconnect", { agents, signIn, ...(skills === undefined ? {} : { skills }), ...(mcp === undefined ? {} : { mcp }) }),
+ "agents.signInStart": ({ agent }) => request<OpResult<"agents.signInStart">>("agents.signInStart", { agent }),
+ "agents.signInWait": ({ id }) => request<OpResult<"agents.signInWait">>("agents.signInWait", { id }),
"session.openExternal": async ({ url }) => {
win.open?.(url, "_blank", "noopener");
return null;
diff --git a/apps/cua-spaces-web/src/bridge/agents-dm.ts b/apps/cua-spaces-web/src/bridge/agents-dm.ts
index fd19252f87..7f3666f8e4 100644
--- a/apps/cua-spaces-web/src/bridge/agents-dm.ts
+++ b/apps/cua-spaces-web/src/bridge/agents-dm.ts
@@ -16,8 +16,10 @@
* answers approvals.
*/
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { CoreClient } from "./core";
+import { chatsPollMs, jittered, mapLimit, MissCache } from "../lib/poll-plan";
import { useBridge, useSpaces } from "./hooks";
import type { Space } from "./contracts/spaces";
import { foldThread, readSeqFrom, type ThreadItem } from "./thread";
@@ -41,7 +43,22 @@ export interface ChatNeed extends NeedsYou {
spaceName: string;
}
-export type ChatTone = "you" | "working" | "idle" | "asleep" | "failed";
+export type ChatTone = "you" | "working" | "idle" | "asleep" | "failed" | "not-connected" | "creating" | "stopped";
+
+/** A run of this device's that isn't an agent in a Space (yet): its job waiting for a Space being made, an agent not connected, a start that failed. */
+export interface ChatAttempt {
+ id: string;
+ spaceId: string;
+ spaceName: string;
+ harness: string;
+ label: string;
+ job: string;
+ atMs: number;
+ state: "creating" | "not-connected" | "failed" | "stopped";
+ note: string | null;
+ connectLabel: string | null;
+ app: string | null;
+}
/** One agent, across its Spaces. */
export interface AgentChat {
@@ -59,6 +76,16 @@ export interface AgentChat {
line: string;
/** The last thing said in its DM, for ordering and the age. */
lastMs: number;
+ /** `agent` (in a Space's thread) or `attempt` (a run of this device's). */
+ kind: "agent" | "attempt";
+ /** What it was asked to do, or is doing. */
+ job: string | null;
+ /** Where it is (an attempt has no member there yet). */
+ places: { spaceId: string; spaceName: string }[];
+ /** The step that moves it on: Connect or Try again. */
+ action: { id: "connect" | "retry"; label: string } | null;
+ app: string | null;
+ attempt: string | null;
}
/** One agent across Spaces: the same owner, harness and name. Without an identity, its handle in its Space. */
@@ -69,62 +96,89 @@ export function chatKey(spaceId: string, m: AgentMember): string {
return `${i.owner.id}/${i.harness.id || "other"}/${i.displayName.trim().toLowerCase()}`;
}
-const WORKING = new Set(["working", "claimed"]);
+/**
+ * Each Space's members (with `overview`) and this device's unfinished runs as
+ * one list: the app core's `agentList.view` (`agent_list.rs`) decides the
+ * rows, their order and every word; this only hangs each Space's member
+ * records back on the rows. The Agents page and Home both use it.
+ */
+export function mergeChats(core: CoreClient, perSpace: readonly { space: Space; role: ThreadRole | null; members: readonly AgentMember[] }[], attempts: readonly ChatAttempt[] = []): AgentChat[] {
+ const input = {
+ spaces: perSpace.map(({ space, members }) => ({
+ spaceId: space.id,
+ spaceName: space.name,
+ members: members.map((m) => ({
+ handle: m.name,
+ harness: m.identity?.harness.id || m.harness,
+ displayName: m.identity?.displayName ?? "",
+ ownerId: m.identity?.owner.id ?? "",
+ status: m.status,
+ activity: m.activity,
+ unread: m.dm?.unread ?? 0,
+ lastMs: m.dm?.last?.tsMs ?? 0,
+ needsMs: (m.needsYou ?? []).map((n) => n.tsMs),
+ pending: m.identity?.state === "pending",
+ })),
+ })),
+ attempts,
+ };
+ const view = core.tryCall<{ rows: AgentListRow[] }>("agentList.view", { input: input as unknown as Record<string, unknown> });
+ if (!view) return [];
-/** Merges each Space's members (with `overview`) into one row per agent. */
-export function mergeChats(perSpace: readonly { space: Space; role: ThreadRole | null; members: readonly AgentMember[] }[]): AgentChat[] {
- const by = new Map<string, AgentChat>();
- for (const { space, role, members } of perSpace) {
- for (const m of members) {
- if (m.identity?.state === "pending") continue;
- const key = chatKey(space.id, m);
- let c = by.get(key);
- if (!c) {
- c = { key, label: m.identity?.displayName || m.name, identity: m.identity, harness: m.identity?.harness.id || m.harness, spaces: [], unread: 0, needsYou: [], tone: "idle", line: "", lastMs: 0 };
- by.set(key, c);
- }
- c.spaces.push({ spaceId: space.id, spaceName: space.name, os: space.os, handle: m.name, member: m, role });
- c.unread += m.dm?.unread ?? 0;
- c.lastMs = Math.max(c.lastMs, m.dm?.last?.tsMs ?? 0);
- for (const n of m.needsYou ?? []) c.needsYou.push({ ...n, spaceId: space.id, spaceName: space.name });
- }
- }
- const out = [...by.values()];
- for (const c of out) {
- c.needsYou.sort((a, b) => b.tsMs - a.tsMs);
- c.lastMs = Math.max(c.lastMs, ...c.needsYou.map((n) => n.tsMs));
- const working = c.spaces.find((s) => WORKING.has(s.member.status));
- const failed = c.spaces.find((s) => s.member.status === "failed");
- if (c.needsYou.length) {
- c.tone = "you";
- c.line = `Waiting for you in ${c.needsYou[0]!.spaceName}`;
- } else if (working) {
- c.tone = "working";
- c.line = `${sentence(working.member.activity) ?? "Working"} in ${working.spaceName}`;
- } else if (failed) {
- c.tone = "failed";
- c.line = `Failed in ${failed.spaceName}`;
- } else if (c.spaces.every((s) => s.member.status === "asleep" || s.member.status === "paused")) {
- c.tone = "asleep";
- c.line = c.spaces.length > 1 ? `Asleep in ${c.spaces.length} Spaces` : `Asleep in ${c.spaces[0]!.spaceName}`;
- } else {
- c.tone = "idle";
- c.line = c.spaces.length > 1 ? `In ${c.spaces.length} Spaces` : `In ${c.spaces[0]!.spaceName}`;
- }
- }
- // Waiting for you, then working, then the most recent.
- const rank = (c: AgentChat) => (c.tone === "you" ? 0 : c.tone === "working" ? 1 : 2);
- return out.sort((a, b) => rank(a) - rank(b) || b.lastMs - a.lastMs || a.label.localeCompare(b.label));
+ return view.rows.map((r) => {
+ const spaces: AgentChatSpace[] = r.kind === "agent"
+ ? r.places.flatMap((pl) => {
+ // A Space may come in more than one part: the one that has this member.
+ const p = perSpace.find((x) => x.space.id === pl.spaceId && x.members.some((m) => m.name === pl.handle));
+ const member = p?.members.find((m) => m.name === pl.handle);
+ return p && member ? [{ spaceId: p.space.id, spaceName: p.space.name, os: p.space.os, handle: pl.handle, member, role: p.role }] : [];
+ })
+ : [];
+ const needsYou: ChatNeed[] = spaces.flatMap((sp) => (sp.member.needsYou ?? []).map((n) => ({ ...n, spaceId: sp.spaceId, spaceName: sp.spaceName }))).sort((a, b) => b.tsMs - a.tsMs);
+ return {
+ key: r.key,
+ label: r.label,
+ identity: spaces[0]?.member.identity ?? null,
+ harness: r.harness,
+ spaces,
+ unread: r.unread,
+ needsYou,
+ tone: r.tone,
+ line: r.line,
+ lastMs: r.lastMs,
+ kind: r.kind,
+ job: r.job,
+ places: r.places.map((p) => ({ spaceId: p.spaceId, spaceName: p.spaceName })),
+ action: r.action,
+ app: r.app,
+ attempt: r.attempt,
+ };
+ });
}
-/** "bumping the retry timeout" reads "Bumping the retry timeout"; a line that names its own Space keeps only the action. */
-function sentence(s: string | null): string | null {
- if (!s) return null;
- const t = s.replace(/\s+in\s+\S+$/i, "").replace(/^waiting for you$/i, "Waiting");
- return t.charAt(0).toUpperCase() + t.slice(1);
+/** A row of the core's list (`agent_list::AgentListRow`). */
+interface AgentListRow {
+ key: string;
+ kind: "agent" | "attempt";
+ label: string;
+ harness: string;
+ tone: ChatTone;
+ line: string;
+ job: string | null;
+ lastMs: number;
+ unread: number;
+ places: { spaceId: string; spaceName: string; handle: string }[];
+ action: { id: "connect" | "retry"; label: string } | null;
+ app: string | null;
+ attempt: string | null;
}
+/** The Agents tab's base poll; it slows as the account's Spaces grow (`chatsPollMs`). */
export const CHATS_POLL_MS = 5_000;
+/** Spaces' threads read at once, at most. */
+const CHATS_PARALLEL = 8;
+/** How long a Space with no thread is left alone. */
+const MISS_TTL_MS = 60_000;
export interface AgentChats {
/** null while the first read is under way. */
@@ -138,46 +192,65 @@ export interface AgentChats {
}
/** Every agent in every Space you can see, as the Agents tab's list. */
-export function useAgentChats(): AgentChats {
- const { data } = useBridge();
+export function useAgentChats(attempts: readonly ChatAttempt[] = []): AgentChats {
+ const { data, core } = useBridge();
const { data: spaces } = useSpaces();
- const [chats, setChats] = useState<AgentChat[] | null>(null);
+ const [read, setRead] = useState<{ space: Space; role: ThreadRole | null; members: AgentMember[] }[] | null>(null);
const [withThread, setWithThread] = useState<Space[]>([]);
const [me, setMe] = useState<string | null>(null);
const [round, setRound] = useState(0);
const list = (spaces ?? []).filter((s) => !s.id.startsWith("pending:"));
const ids = list.map((s) => s.id).join("\n");
+ // Not asked again for a minute: a Space with no thread (a stopped machine, an old daemon) stays that way.
+ const misses = useRef(new MissCache(MISS_TTL_MS));
useEffect(() => {
if (!data || spaces === undefined) return;
let alive = true;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ misses.current.prune(new Set(list.map((s) => s.id)));
const read = async () => {
- const got = await Promise.all(
- list.map(async (space) => {
- try {
- const [{ members }, page] = await Promise.all([data.call("thread.members", { spaceId: space.id, overview: true }), data.call("thread.read", { spaceId: space.id, limit: 1 })]);
- return { space, role: page.role, members, me: page.me };
- } catch (e) {
- // No thread there (an old daemon, a stopped machine): not in the list.
- if (!isMissingThreadTool(e)) console.debug("agents: couldn't read", space.id, e);
- return null;
- }
- }),
- );
+ const asked = list.filter((s) => !misses.current.has(s.id));
+ const got = await mapLimit(asked, CHATS_PARALLEL, async (space) => {
+ try {
+ const [{ members }, page] = await Promise.all([data.call("thread.members", { spaceId: space.id, overview: true }), data.call("thread.read", { spaceId: space.id, limit: 1 })]);
+ return { space, role: page.role, members, me: page.me };
+ } catch (e) {
+ // No thread there (an old daemon, a stopped machine): not in the list, and not asked again for a while.
+ if (isMissingThreadTool(e)) misses.current.add(space.id);
+ else console.debug("agents: couldn't read", space.id, e);
+ return null;
+ }
+ });
if (!alive) return;
const ok = got.filter((g): g is NonNullable<typeof g> => g !== null);
setWithThread(ok.map((g) => g.space));
setMe(ok.find((g) => g.me)?.me ?? null);
- setChats(mergeChats(ok));
+ setRead(ok);
+ };
+ // One read at a time, the next after the last one ends: slower as the
+ // account grows (`chatsPollMs`), spread so pages don't ask together, and
+ // paused while the page is hidden (it reads at once on coming back).
+ const loop = async () => {
+ if (visible()) await read();
+ if (alive) timer = setTimeout(() => void loop(), jittered(chatsPollMs(list.length)));
+ };
+ const onVisible = () => {
+ if (!visible() || !alive) return;
+ clearTimeout(timer);
+ void loop();
};
- void read();
- const t = setInterval(() => void read(), CHATS_POLL_MS);
+ document.addEventListener("visibilitychange", onVisible);
+ void loop();
return () => {
alive = false;
- clearInterval(t);
+ clearTimeout(timer);
+ document.removeEventListener("visibilitychange", onVisible);
};
// `list` follows `ids`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data, ids, round, spaces === undefined]);
+ // One list, with this device's unfinished runs (the core's order and words).
+ const chats = read === null ? null : mergeChats(core, read, attempts);
return { chats, spaces: withThread, me, refresh: useCallback(() => setRound((r) => r + 1), []) };
}
diff --git a/apps/cua-spaces-web/src/bridge/connectors.ts b/apps/cua-spaces-web/src/bridge/connectors.ts
new file mode 100644
index 0000000000..7479709917
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/connectors.ts
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Settings → Connectors (redesign) and summoning agents in a Space: the
+ * app core's `connectors.*` and `summon.*` (`connectors.rs`, `summon.rs`)
+ * over what the host already answers (`agents.setup`, `agentKeys.list`).
+ * Every word, state and rule is the core's; this file only shapes inputs
+ * and calls it.
+ */
+
+import type { CoreClient } from "./core";
+import type { AgentSetupRow } from "./contracts/agents";
+import { hostOs, type HostOs } from "./host-os";
+import type { AgentKeysInput, AgentKeyRowView } from "./agent-keys";
+
+type Json = Record<string, unknown>;
+
+/* ---- Connectors ---------------------------------------------------------------- */
+
+export interface ConnectorAppInput {
+ agent: string;
+ name: string;
+ installed: boolean;
+ configured: boolean;
+ skills: boolean;
+ mcp: boolean | null;
+ mcpConfig: string | null;
+}
+
+export interface ConnectorsInput {
+ apps: ConnectorAppInput[];
+ keys: AgentKeysInput;
+ shellKeys: string[];
+ auto: boolean;
+ off: string[];
+ busy: { id: string; step: "connecting" | "signing-in" | "signing-out" }[];
+ failures: { id: string; line: string }[];
+}
+
+export interface ConnectorButton {
+ id: "connect" | "sign-out" | "sign-in" | "try-again";
+ label: string;
+ enabled: boolean;
+}
+
+export interface ConnectorAppRow {
+ agent: string;
+ name: string;
+ state: "connected" | "not-connected" | "connecting" | "failed";
+ line: string | null;
+ button: ConnectorButton | null;
+ connectedLabel: string | null;
+ openLabel: string;
+}
+
+export interface ConnectorProviderRow {
+ id: string;
+ label: string;
+ state: "connected" | "not-connected" | "connecting" | "failed";
+ status: string;
+ detail: string;
+ button: ConnectorButton;
+ addedMs: number | null;
+ signOutEnvs: string[];
+}
+
+export interface ConnectorsView {
+ appsTitle: string;
+ apps: ConnectorAppRow[];
+ appsEmpty: string | null;
+ autoLabel: string;
+ autoHelp: string;
+ auto: boolean;
+ providersTitle: string;
+ providersFooter: string;
+ providers: ConnectorProviderRow[];
+ others: AgentKeyRowView[];
+ addOtherLabel: string;
+ otherHelp: string;
+ notice: string | null;
+ canEdit: boolean;
+ addedLabel: string;
+}
+
+export interface ConnectPlan {
+ tools: boolean;
+ appToken: boolean;
+ device: boolean;
+ provider: string | null;
+ tokenProvider: string | null;
+}
+
+export interface ProviderWay {
+ id: "app-token" | "app-device" | "key" | "shell";
+ label: string;
+ help: string;
+ button: string;
+ app: string | null;
+ env: string | null;
+}
+
+export interface ProviderSheetView {
+ provider: string;
+ title: string;
+ lede: string;
+ ways: ProviderWay[];
+ cancelLabel: string;
+ keyLabel: string;
+ keyPlaceholder: string;
+ keyHelp: string;
+ saveLabel: string;
+ keyProvider: "anthropic" | "openai" | "other";
+ keyEnv: string | null;
+}
+
+export interface ConnectorToggle {
+ id: "skills" | "mcp" | "auto";
+ label: string;
+ help: string;
+ on: boolean;
+ enabled: boolean;
+}
+
+export interface AppDetailView {
+ agent: string;
+ name: string;
+ backLabel: string;
+ status: string;
+ connected: boolean;
+ connect: ConnectorButton | null;
+ toolsTitle: string;
+ toggles: ConnectorToggle[];
+ signInTitle: string;
+ signIn: { title: string; status: string; connected: boolean; way: string; provider: string; button: ConnectorButton } | null;
+ signInNote: string | null;
+ settingsFileLabel: string;
+ settingsFile: string | null;
+ removeLabel: string | null;
+}
+
+export interface SetupCardView {
+ title: string;
+ body: string;
+ connectLabel: string;
+ connectingLabel: string;
+ connectedLabel: string;
+ retryLabel: string;
+ changeLabel: string;
+ detailsLabel: string;
+}
+
+/** The connectors input from the host's answers and the page's own state. */
+export function connectorsInputOf(
+ rows: readonly AgentSetupRow[] | null,
+ keys: AgentKeysInput,
+ extra: Partial<Omit<ConnectorsInput, "apps" | "keys">> = {},
+): ConnectorsInput {
+ return {
+ apps: (rows ?? []).map((r) => ({
+ agent: r.agent,
+ name: r.name,
+ installed: r.installed,
+ configured: r.configured,
+ skills: r.skillsTotal > 0 ? r.skillsInstalled >= r.skillsTotal : r.configured,
+ mcp: r.mcpConfig ? r.configured || /MCP/i.test(r.detail) : null,
+ mcpConfig: r.mcpConfig,
+ })),
+ keys,
+ shellKeys: extra.shellKeys ?? [],
+ auto: extra.auto ?? false,
+ off: extra.off ?? [],
+ busy: extra.busy ?? [],
+ failures: extra.failures ?? [],
+ };
+}
+
+export const connectorsView = (core: CoreClient, input: ConnectorsInput, os: HostOs = hostOs()): ConnectorsView | null =>
+ core.tryCall<ConnectorsView>("connectors.view", { input: input as unknown as Json, hostOs: os }) ?? null;
+
+export const connectPlan = (core: CoreClient, input: ConnectorsInput, agent: string): ConnectPlan | null =>
+ core.tryCall<ConnectPlan>("connectors.connectPlan", { input: input as unknown as Json, agent }) ?? null;
+
+export const providerSheet = (core: CoreClient, input: ConnectorsInput, provider: string, os: HostOs = hostOs()): ProviderSheetView | null =>
+ core.tryCall<ProviderSheetView | null>("connectors.providerSheet", { input: input as unknown as Json, provider, hostOs: os }) ?? 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;
+
+export const setupCard = (core: CoreClient, input: ConnectorsInput, agent: string, name: string): SetupCardView | null =>
+ core.tryCall<SetupCardView>("connectors.setupCard", { input: input as unknown as Json, agent, name }) ?? null;
+
+/* ---- Summoning agents in a Space ---------------------------------------------------- */
+
+export interface SummonMember {
+ handle: string;
+ harness: string;
+ label: string;
+}
+
+export interface SummonInput {
+ members: SummonMember[];
+ people: string[];
+ canAdd: boolean;
+ connectors: ConnectorsInput;
+}
+
+export interface SummonCandidate {
+ handle: string;
+ label: string;
+ harness: string;
+ member: boolean;
+ detail: string;
+}
+
+export interface CantWake {
+ reason: "not-connected" | "cant-add" | "failed";
+ handle: string;
+ harness: string;
+ name: string;
+ app: string;
+ text: string;
+ detail: string;
+ connectLabel: string | null;
+ connectingLabel: string;
+ openLabel: string | null;
+ retryLabel: string;
+ retriedText: string;
+ /** Only you see it: never posted to the thread. */
+ onlyYou: boolean;
+ onlyYouLabel: string;
+ dismissLabel: string;
+}
+
+/** A line only this device shows in a thread (never posted). */
+export interface LocalNote {
+ text: string;
+ onlyYou: boolean;
+ onlyYouLabel: string;
+ dismissLabel: string | null;
+}
+
+export const queuedNote = (core: CoreClient, creating: boolean): LocalNote | null => core.tryCall<LocalNote>("summon.queuedNote", { creating }) ?? null;
+
+export interface SummonStep {
+ handle: string;
+ harness: string;
+ action: "wake" | "add" | "blocked";
+ cantWake: CantWake | null;
+}
+
+export interface FirstMessage {
+ text: string;
+ handle: string | null;
+ harness: string;
+}
+
+export const summonCandidates = (core: CoreClient, input: SummonInput): SummonCandidate[] | null =>
+ core.tryCall<SummonCandidate[]>("summon.candidates", { input: input as unknown as Json }) ?? null;
+
+export const summonPlan = (core: CoreClient, input: SummonInput, text: string): SummonStep[] | null =>
+ core.tryCall<{ steps: SummonStep[] }>("summon.plan", { input: input as unknown as Json, text })?.steps ?? null;
+
+export const summonFailed = (core: CoreClient, input: SummonInput, harness: string, handle: string, error: string): CantWake | null =>
+ core.tryCall<CantWake | null>("summon.failed", { input: input as unknown as Json, harness, handle, error }) ?? null;
+
+export const firstMessage = (core: CoreClient, input: SummonInput, agent: string, prompt: string): FirstMessage | null =>
+ core.tryCall<FirstMessage>("summon.firstMessage", { input: input as unknown as Json, agent, prompt }) ?? null;
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index 12be79debc..7cb55dc848 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -3911,6 +3911,181 @@
"termsUrl"
]
},
+ "RuntimePathCheck": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string"
+ },
+ "exists": {
+ "type": "boolean"
+ },
+ "executable": {
+ "type": "boolean"
+ },
+ "tool": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "version": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "minVersion": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "expected": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "guests": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "path",
+ "exists",
+ "executable",
+ "expected"
+ ]
+ },
+ "RuntimesInput": {
+ "type": "object",
+ "properties": {
+ "os": {
+ "enum": [
+ "macos",
+ "windows",
+ "linux",
+ "unknown",
+ null
+ ]
+ },
+ "hostArch": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "localBackends": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "type": "string"
+ }
+ },
+ "localDetails": {
+ "anyOf": [
+ {},
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "kinds": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string"
+ },
+ "source": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "path": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "detected": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "type": "object",
+ "properties": {
+ "tool": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "version": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "guests": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "tool",
+ "name",
+ "path"
+ ]
+ }
+ },
+ "check": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/RuntimePathCheck"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "expected": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "kind"
+ ]
+ }
+ }
+ }
+ },
"SessionSnapshot": {
"type": "object",
"properties": {
@@ -4186,19 +4361,23 @@
"hostSettings": {
"type": "object",
"properties": {
- "lumeSource": {
- "type": [
- "string",
- "null"
+ "runtimes": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/RuntimesInput"
+ },
+ {
+ "type": "null"
+ }
]
},
- "linuxSource": {
+ "autoConnect": {
"type": [
- "string",
+ "boolean",
"null"
]
},
- "autoConnect": {
+ "overflow": {
"type": [
"boolean",
"null"
@@ -6582,6 +6761,16 @@
"off",
"done"
]
+ },
+ "runtimes": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/RuntimesInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
}
},
"required": [
@@ -6874,6 +7063,9 @@
"about.set": {
"$ref": "#/$defs/AboutInput"
},
+ "agentKeys.fromShell": {
+ "$ref": "#/$defs/AgentKeysReport"
+ },
"agentKeys.list": {
"$ref": "#/$defs/AgentKeysReport"
},
@@ -6883,6 +7075,20 @@
"agentKeys.set": {
"$ref": "#/$defs/AgentKeysReport"
},
+ "agentKeys.shell": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "names"
+ ]
+ },
"agents.addRoutine": {
"type": "null"
},
@@ -7197,6 +7403,38 @@
"$ref": "#/$defs/AgentSetupRow"
}
},
+ "agents.signInStart": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ },
+ "code": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "url",
+ "code"
+ ]
+ },
+ "agents.signInWait": {
+ "type": "object",
+ "properties": {
+ "imported": {},
+ "refused": {},
+ "line": {}
+ },
+ "required": [
+ "imported",
+ "refused",
+ "line"
+ ]
+ },
"agents.start": {
"type": "object",
"properties": {
@@ -7922,6 +8160,23 @@
"warning"
]
},
+ "runtimes.browse": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "path"
+ ]
+ },
+ "runtimes.check": {
+ "$ref": "#/$defs/RuntimePathCheck"
+ },
"session.completeOnboarding": {
"type": "null"
},
@@ -8814,6 +9069,72 @@
"about.set": {
"$ref": "#/$defs/AboutInput"
},
+ "agentKeys.fromShell": {
+ "type": "object",
+ "properties": {
+ "keys": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "provider": {
+ "type": "string"
+ },
+ "env": {
+ "type": "string"
+ },
+ "last4": {
+ "type": "string"
+ },
+ "added_ms": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "provider",
+ "env",
+ "last4",
+ "added_ms"
+ ]
+ }
+ },
+ "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.list": {
"type": "object",
"properties": {
@@ -9012,6 +9333,20 @@
"available"
]
},
+ "agentKeys.shell": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "names"
+ ]
+ },
"agents.addRoutine": {
"type": "null"
},
@@ -9322,6 +9657,38 @@
"$ref": "#/$defs/AgentSetupRow"
}
},
+ "agents.signInStart": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ },
+ "code": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "url",
+ "code"
+ ]
+ },
+ "agents.signInWait": {
+ "type": "object",
+ "properties": {
+ "imported": {},
+ "refused": {},
+ "line": {}
+ },
+ "required": [
+ "imported",
+ "refused",
+ "line"
+ ]
+ },
"agents.start": {
"type": "object",
"properties": {
@@ -10063,6 +10430,23 @@
"warning"
]
},
+ "runtimes.browse": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "path"
+ ]
+ },
+ "runtimes.check": {
+ "$ref": "#/$defs/RuntimePathCheck"
+ },
"session.get": {
"$ref": "#/$defs/WkSession"
},
diff --git a/apps/cua-spaces-web/src/bridge/contracts/host.ts b/apps/cua-spaces-web/src/bridge/contracts/host.ts
index b735388e49..eb14f21667 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/host.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/host.ts
@@ -740,10 +740,12 @@ export interface SettingsInput {
keyvaultProtection?: { label: string; value: string }[];
/** "Connect to the desktop automatically" (none: no row). */
autoConnect?: boolean | null;
- /** Which Lume macOS Spaces run on (none: no Runtimes section). */
- lumeSource?: string | null;
- /** Which engine local Linux Spaces run on (none: no Linux row). */
- linuxSource?: string | null;
+ /** Overflow into your clouds when this machine is full (`placement.overflow`; none: no row). */
+ overflow?: boolean | null;
+ /** Settings, Advanced's runtimes: each kind's setting, what is installed
+ * for it and whether it runs here (`runtimes::RuntimesInput`). None: not
+ * read yet (the rows still show, "Checking…"). */
+ runtimes?: RuntimesInput | null;
/** The coding agents (Settings, AI agents; none while detecting). */
agents?: AgentSetupRow[] | null;
/** "Configure all detected agents" is running. */
@@ -798,3 +800,61 @@ export interface SettingsPage {
title: string;
sections: SettingsSection[];
}
+
+/** A runtime the host found for one kind (`runtimes::DetectedRuntime`). */
+export interface DetectedRuntime {
+ /** `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`. */
+ tool: string;
+ /** As people know it (`Docker`, `Apple container`). */
+ name: string;
+ path: string;
+ version?: string | null;
+ /** The one guest system it runs, when only one (`macOS`, `Linux`). */
+ guests?: string | null;
+}
+
+/** What a binary is for one kind (`runtimes::RuntimePathCheck`; the host's `runtimes.check`). */
+export interface RuntimePathCheck {
+ path: string;
+ exists: boolean;
+ executable: boolean;
+ tool?: string | null;
+ name?: string | null;
+ version?: string | null;
+ minVersion?: string | null;
+ /** The tools the kind takes here (`Docker`, `Podman`). */
+ expected: string[];
+ guests?: string | null;
+}
+
+/** One kind as the host read it (`runtimes::RuntimeKindInput`). */
+export interface RuntimeKindInput {
+ /** `container`, `vm`, `microvm`. */
+ kind: string;
+ /** `runtime.<kind>`: `auto`, `builtin`, `system`. */
+ source?: string | null;
+ /** `runtime.<kind>_path`, when set. */
+ path?: string | null;
+ /** What is installed for the kind, the one used first (null: not looked for yet). */
+ detected?: DetectedRuntime[] | null;
+ /** The path in use, probed. */
+ check?: RuntimePathCheck | null;
+ /** The tools the kind takes here. */
+ expected?: string[];
+}
+
+/** What Settings knows about this machine's runtimes (`runtimes::RuntimesInput`). */
+export interface RuntimesInput {
+ os?: "macos" | "windows" | "linux" | "unknown" | null;
+ hostArch?: string | null;
+ /** The runtime doctor's ready backends (null: not read yet). */
+ localBackends?: string[] | null;
+ localDetails?: Record<string, string> | null;
+ kinds?: RuntimeKindInput[] | null;
+}
+
+/** A path's one line (`settings.runtimePathVerdict`). */
+export interface RuntimePathVerdict {
+ ok: boolean;
+ line: string;
+}
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index 8611318446..e9fe15c65d 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -36,6 +36,10 @@ import type {
SpacePowerReport,
TelemetryView,
CrashReportingConfig,
+ DetectedRuntime,
+ RuntimeKindInput,
+ RuntimePathCheck,
+ RuntimesInput,
} from "./host";
import type { KeyvaultOverview, KvGrant } from "./keyvault";
import type {
@@ -318,6 +322,45 @@ const SessionShape = ref(
/** `AppSettings.tips` (`tips::TipsState`). */
const TipsStateShape = obj<TipsState>()({ off: bool, done: strings });
+const RuntimePathCheckShape = ref(
+ "RuntimePathCheck",
+ obj<RuntimePathCheck>()({
+ path: str,
+ exists: bool,
+ executable: bool,
+ tool: optNull(str),
+ name: optNull(str),
+ version: optNull(str),
+ minVersion: optNull(str),
+ expected: strings,
+ guests: optNull(str),
+ }),
+);
+
+const RuntimesInputShape = ref(
+ "RuntimesInput",
+ obj<RuntimesInput>()({
+ os: optNull(os),
+ hostArch: optNull(str),
+ localBackends: optNull(strings),
+ localDetails: optNull(any),
+ kinds: optNull(
+ list(
+ obj<RuntimeKindInput>()({
+ kind: str,
+ source: optNull(str),
+ path: optNull(str),
+ detected: optNull(
+ list(obj<DetectedRuntime>()({ tool: str, name: str, path: str, version: optNull(str), guests: optNull(str) })),
+ ),
+ check: optNull(RuntimePathCheckShape),
+ expected: opt(strings),
+ }),
+ ),
+ ),
+ }),
+);
+
const SettingsShape = ref(
"SettingsSnapshot",
obj<SettingsSnapshot>()({
@@ -338,9 +381,9 @@ const SettingsShape = ref(
),
hostSettings: opt(
obj<HostSettings>()({
- lumeSource: optNull(str),
- linuxSource: optNull(str),
+ runtimes: optNull(RuntimesInputShape),
autoConnect: optNull(bool),
+ overflow: optNull(bool),
keyvaultAutoWipe: optNull(bool),
keyvaultUnlockPrompt: optNull(bool),
keyvaultSiteIcons: optNull(bool),
@@ -805,6 +848,8 @@ const ConnectResultsShape = list(
),
);
const DisconnectShape = object({ removed_sign_ins: list(str) });
+const SignInStartShape = object({ id: str, url: str, code: str });
+const SignInWaitShape = object({ imported: any, refused: any, line: any });
const AgentDetailShape = ref(
"AgentDetailInput",
obj<AgentDetailInput>()({
@@ -1187,6 +1232,8 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"agents.status": ConnectionReportShape,
"agents.connect": ConnectResultsShape,
"agents.disconnect": DisconnectShape,
+ "agents.signInStart": SignInStartShape,
+ "agents.signInWait": SignInWaitShape,
"agents.detail": AgentDetailShape,
"agents.readFile": AgentOpenFileShape,
"agents.restoreFile": nul,
@@ -1268,6 +1315,8 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"agentKeys.list": AgentKeysShape,
"agentKeys.set": AgentKeysShape,
"agentKeys.remove": AgentKeysShape,
+ "agentKeys.shell": object({ names: list(str) }),
+ "agentKeys.fromShell": AgentKeysShape,
"volume.overview": VolumeShape,
"volume.storage": nullable(DriveStorageShape),
@@ -1377,6 +1426,8 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"loginItem.get": LoginItemShape,
"loginItem.set": LoginItemShape,
"loginItem.openSettings": nul,
+ "runtimes.check": RuntimePathCheckShape,
+ "runtimes.browse": object({ path: nullable(str) }),
"devices.get": DevicesShape,
"devices.enroll": obj<EnrollResult>()({ enrolled: bool, code: nullable(str) }),
"devices.checkEnrolled": bool,
@@ -1533,6 +1584,7 @@ const WkSettingsShape = ref(
accountUrl: optNull(str),
cli: optNull(object({ name: str, installed: bool })),
tips: opt(TipsStateShape),
+ runtimes: optNull(RuntimesInputShape),
}),
);
@@ -1673,6 +1725,8 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"agents.status": ConnectionReportShape,
"agents.connect": ConnectResultsShape,
"agents.disconnect": DisconnectShape,
+ "agents.signInStart": SignInStartShape,
+ "agents.signInWait": SignInWaitShape,
"agents.setupDriver": OP_SHAPES["agents.setupDriver"],
"agents.detail": AgentDetailShape,
"agents.readFile": AgentOpenFileShape,
@@ -1685,6 +1739,8 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"agentKeys.list": AgentKeysWire,
"agentKeys.set": AgentKeysWire,
"agentKeys.remove": AgentKeysWire,
+ "agentKeys.shell": object({ names: list(str) }),
+ "agentKeys.fromShell": AgentKeysWire,
"clouds.status": nullable(OP_SHAPES["clouds.status"]),
"clouds.test": OP_SHAPES["clouds.test"],
"clouds.connect": OP_SHAPES["clouds.connect"],
@@ -1724,6 +1780,8 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"loginItem.get": LoginItemShape,
"loginItem.set": LoginItemShape,
"loginItem.openSettings": nul,
+ "runtimes.check": RuntimePathCheckShape,
+ "runtimes.browse": object({ path: nullable(str) }),
"devices.get": DevicesShape,
"devices.enroll": OP_SHAPES["devices.enroll"],
"devices.checkEnrolled": bool,
diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.ts
index 6b6e8886fb..a71e298a04 100644
--- a/apps/cua-spaces-web/src/bridge/coverage.ts
+++ b/apps/cua-spaces-web/src/bridge/coverage.ts
@@ -157,6 +157,8 @@ export const HOST_COVERAGE = {
"agents.status": { webkit: { methods: ["agents.status"] }, tauri: [], unsupported: { tauri: "the Tauri shell has no connection status command (cua connect status --json)" } },
"agents.connect": { webkit: { methods: ["agents.connect"] }, tauri: [], unsupported: { tauri: "the Tauri shell can't copy an agent's sign-in to Keyvault" } },
"agents.disconnect": { webkit: { methods: ["agents.disconnect"] }, tauri: [], unsupported: { tauri: "the Tauri shell can't delete a copied sign-in" } },
+ "agents.signInStart": { webkit: { methods: ["agents.signInStart"] }, tauri: [], unsupported: { tauri: "the Tauri shell can't start a device sign-in" } },
+ "agents.signInWait": { webkit: { methods: ["agents.signInWait"] }, tauri: [], unsupported: { tauri: "the Tauri shell can't start a device sign-in" } },
...AGENT_DETAIL_COVERAGE,
...NEW_SPACE_COVERAGE,
...TELEPORT_COVERAGE,
@@ -177,6 +179,8 @@ export const HOST_COVERAGE = {
"loginItem.get": { webkit: { methods: ["loginItem.get"] }, tauri: ST["loginItem.get"] },
"loginItem.set": { webkit: { methods: ["loginItem.set"] }, tauri: ST["loginItem.set"] },
"loginItem.openSettings": { webkit: { methods: ["loginItem.openSettings"] }, tauri: ST["loginItem.openSettings"] },
+ "runtimes.check": { webkit: { methods: ["runtimes.check"] }, tauri: ST["runtimes.check"], unsupported: { tauri: "the Tauri app has no per-kind runtime settings" } },
+ "runtimes.browse": { webkit: { methods: ["runtimes.browse"] }, tauri: ST["runtimes.browse"], unsupported: { tauri: "the Tauri app has no per-kind runtime settings" } },
"devices.get": { webkit: { methods: ["devices.get"] }, tauri: ST["devices.get"] },
"devices.enroll": { webkit: { methods: ["devices.enroll"] }, tauri: ST["devices.enroll"] },
"devices.checkEnrolled": { webkit: { methods: ["devices.checkEnrolled"] }, tauri: ST["devices.checkEnrolled"] },
diff --git a/apps/cua-spaces-web/src/bridge/derive.ts b/apps/cua-spaces-web/src/bridge/derive.ts
index 65014662f7..7b125e8752 100644
--- a/apps/cua-spaces-web/src/bridge/derive.ts
+++ b/apps/cua-spaces-web/src/bridge/derive.ts
@@ -690,8 +690,9 @@ export function settingsPage(
keyvaultSiteIcons: settings.hostSettings?.keyvaultSiteIcons ?? true,
keyvaultProtection: settings.hostSettings?.keyvaultProtection ?? [],
autoConnect: settings.hostSettings?.autoConnect ?? null,
- lumeSource: settings.hostSettings?.lumeSource ?? null,
- linuxSource: settings.hostSettings?.linuxSource ?? null,
+ overflow: settings.hostSettings?.overflow ?? null,
+ // Every host's runtimes section; what the host read fills it in.
+ runtimes: settings.hostSettings?.runtimes ?? null,
agents: agents?.agents ?? null,
agentsBusy: agents?.agentsBusy ?? false,
agentsPending: agents?.agentsPending ?? [],
diff --git a/apps/cua-spaces-web/src/bridge/flags.ts b/apps/cua-spaces-web/src/bridge/flags.ts
index 45120933de..228b21e936 100644
--- a/apps/cua-spaces-web/src/bridge/flags.ts
+++ b/apps/cua-spaces-web/src/bridge/flags.ts
@@ -2,15 +2,15 @@
// Copyright (c) 2026 Cua AI, Inc.
/**
- * Feature flags for the web UI. A flag is off unless something turns it on,
- * in this order:
+ * Feature flags for the web UI. A flag takes its default (off, except
+ * `spaces_redesign`, which is on) unless something sets it, in this order:
*
* 1. this device's override (`localStorage` `cua.flag.<name>` = `1` or `0`),
* which is how a dev build or a tester forces one;
* 2. the build's default (`VITE_CUA_FLAG_<NAME>` = `1`);
* 3. the remote value, when a source has set one (`setRemoteFlags`: the
* PostHog feature-flag payload, once the shells pass it in);
- * 4. off.
+ * 4. the flag's default.
*
* A flag only decides what the UI draws. Plans and limits are enforced by the
* relay and the control plane, never by a flag.
@@ -26,14 +26,15 @@ import { useSyncExternalStore } from "react";
* this device.
* - `spaces_redesign`: the redesigned Spaces page, Space page (thread, stream
* switching), Agents tab (chat), Add a computer, sidebar and page
- * language. Off (the default), each of those routes draws the page as it
- * was (`src/legacy/`); the core, daemon, CLI, SDK, MCP, Settings and
- * Connect a cloud are the same either way. Settings → Advanced → Labs
- * turns it on for this device.
+ * language. On (the default), the redesign is drawn. Off, each of those
+ * routes draws the classic page (`src/legacy/`); the core, daemon, CLI,
+ * SDK, MCP, Settings and Connect a cloud are the same either way.
+ * Settings → Advanced → Labs → "New design" switches back to the classic
+ * design for this device.
*/
export type FlagName = "upsell_cards" | "spaces_ask_first_home" | "spaces_redesign";
-const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false, spaces_redesign: false };
+const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false, spaces_redesign: true };
const key = (name: FlagName) => `cua.flag.${name}`;
let remote: Partial<Record<FlagName, boolean>> = {};
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index d55cd94492..58ac315ea4 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -104,7 +104,6 @@ export {
useCloudActions,
useConnectCloud,
useFirstSpaceOffers,
- useMicrovmRows,
useNewSpaceRequests,
useNewSpaceWizard,
useRuntimeFix,
@@ -158,7 +157,7 @@ export {
} from "./relay-usage";
export { linkEnds, needsRelaySetup, useLinks, type LinksHook } from "./links";
-export { chatKey, mergeChats, useAgentChats, useAgentDm, type AgentChat, type AgentChats, type AgentChatSpace, type AgentDm, type ChatNeed, type ChatTone, type DmItem } from "./agents-dm";
+export { chatKey, mergeChats, useAgentChats, useAgentDm, type AgentChat, type AgentChats, type AgentChatSpace, type AgentDm, type ChatAttempt, type ChatNeed, type ChatTone, type DmItem } from "./agents-dm";
export { foldThread, readSeqFrom, useSpaceThread, type SpaceThread, type SpaceThreadStatus, type ThreadAnswer, type ThreadItem } from "./thread";
export {
DEFAULT_AGENT_RIGHTS,
@@ -263,3 +262,5 @@ export {
tipsView,
} from "./spaces-page";
export type * from "./contracts/spaces-page";
+export * from "./connectors";
+export * from "./profile-card";
diff --git a/apps/cua-spaces-web/src/bridge/new-space-hooks.ts b/apps/cua-spaces-web/src/bridge/new-space-hooks.ts
index de2875dc47..6d3b714cc7 100644
--- a/apps/cua-spaces-web/src/bridge/new-space-hooks.ts
+++ b/apps/cua-spaces-web/src/bridge/new-space-hooks.ts
@@ -9,8 +9,6 @@ import { BridgeContext } from "./BridgeProvider";
import type { CoreClient } from "./core";
import type { CloudConnectWire, CloudSheetAction, CloudSheetView, CloudTarget, RuntimeFix, RuntimeSwitch, WizardAction, WizardEnv, WizardView } from "./contracts/new-space";
import type { Space, SpaceOs } from "./contracts/spaces";
-import type { SettingsPage, SettingsRow } from "./contracts/host";
-import { hostOs } from "./host-os";
import { useMachines, useSettings, useSpaces } from "./hooks";
import { newPendingId } from "./store";
import {
@@ -87,7 +85,7 @@ export interface NewSpaceWizardHook {
}
/** The Settings, Runtimes row a New Space runtime switch changes. */
-export const RUNTIME_SWITCH_ROW: Record<string, string> = { "runtime.lume": "macos-runtime", "runtime.linux": "linux-runtime" };
+export const RUNTIME_SWITCH_ROW: Record<string, string> = { "runtime.lume": "runtime:vm", "runtime.linux": "runtime:container" };
/** New Space: the core's wizard over the bridge's data. */
export function useNewSpaceWizard(): NewSpaceWizardHook {
@@ -432,23 +430,3 @@ export function useRuntimeFix(): RuntimeFixHook {
};
}
-/**
- * Settings, Advanced, Runtimes' MicroVM row (`settings::microvm_rows`):
- * whether this computer runs microVMs and on what, or why not, from the
- * same runtime doctor New Space's MicroVM tile follows. New Space only
- * greys MicroVM out; the reason is told here. Empty until the host's
- * options are in (asked for here when not yet).
- */
-export function useMicrovmRows(): SettingsRow[] {
- const ctx = useContext(BridgeContext)!;
- const { core, env, s } = useNewSpaceEnv();
- const needsOptions = optionsPending(s.options);
- useEffect(() => {
- if (needsOptions && core.status === "ready") void ctx.ready.then(loadHostData);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [needsOptions, core.status, ctx.ready]);
- if (!s.options || core.status !== "ready") return [];
- const microvm = { os: hostOs(), localBackends: env.localBackends ?? null, localDetails: env.localDetails ?? null, hostArch: env.hostArch ?? null };
- const page = core.tryCall<SettingsPage>("settings.page", { input: { microvm } });
- return page?.sections.find((x) => x.id === "runtimes")?.rows.filter((r) => r.id.startsWith("microvm-")) ?? [];
-}
diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
index 96dac8cd1a..7959ea5fde 100644
--- a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
@@ -65,10 +65,14 @@ declare module "../protocol" {
"agentKeys.set": { args: { provider: AgentKeyProvider; env?: string | null; value: string }; result: AgentKeysReport };
/** Removes the key named `env`. Answers the list after. */
"agentKeys.remove": { args: { env: 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. */
+ "agentKeys.fromShell": { args: { env: string }; result: AgentKeysReport };
}
}
-export const AGENT_KEYS_OPERATIONS = ["agentKeys.list", "agentKeys.set", "agentKeys.remove"] as const;
+export const AGENT_KEYS_OPERATIONS = ["agentKeys.list", "agentKeys.set", "agentKeys.remove", "agentKeys.shell", "agentKeys.fromShell"] as const;
export type AgentKeysOp = (typeof AGENT_KEYS_OPERATIONS)[number];
/** The SwiftUI host routes each under its own name. */
@@ -79,12 +83,16 @@ export const AGENT_KEYS_METHODS = {
"agentKeys.list": "agent_keys.list",
"agentKeys.set": "agent_keys.set",
"agentKeys.remove": "agent_keys.remove",
+ "agentKeys.shell": "agent_keys.shell",
+ "agentKeys.fromShell": "agent_keys.from_shell",
} as const satisfies { [K in AgentKeysOp]: string };
export const AGENT_KEYS_COVERAGE = {
"agentKeys.list": { webkit: { methods: ["agentKeys.list"] }, tauri: ["agents_tool"] },
"agentKeys.set": { webkit: { methods: ["agentKeys.set"] }, tauri: ["agents_tool"] },
"agentKeys.remove": { webkit: { methods: ["agentKeys.remove"] }, 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>;
/** Arguments that take each operation down its usual path (the coverage test). */
@@ -92,6 +100,8 @@ export const AGENT_KEYS_ARGS: { [K in AgentKeysOp]: OpArgs<K> } = {
"agentKeys.list": {},
"agentKeys.set": { provider: "anthropic", value: "sk-ant-test-0000" },
"agentKeys.remove": { env: "ANTHROPIC_API_KEY" },
+ "agentKeys.shell": {},
+ "agentKeys.fromShell": { env: "ANTHROPIC_API_KEY" },
};
/* ---- The daemon's answer ---------------------------------------------------------- */
@@ -135,7 +145,13 @@ const setArgs = ({ provider, env, value }: OpArgs<"agentKeys.set">) =>
type Handlers = { [K in AgentKeysOp]: (args: OpArgs<K>) => Promise<OpResult<K>> };
type Invoke = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>;
-type Request = <T>(method: "agentKeys.list" | "agentKeys.set" | "agentKeys.remove", args?: Record<string, unknown>) => Promise<T>;
+type Request = <T>(method: AgentKeysOp, args?: Record<string, unknown>) => Promise<T>;
+
+/** `agent_keys.shell`'s answer: names only. */
+const shellNamesFromWire = (raw: unknown): { names: string[] } => {
+ const o = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
+ return { names: (Array.isArray(o.names) ? o.names : []).filter((n): n is string => typeof n === "string") };
+};
/** Tauri: the daemon's methods through `agents_tool` (the shell allows them). */
export function tauriAgentKeysOps(invoke: Invoke): Handlers {
@@ -145,6 +161,8 @@ export function tauriAgentKeysOps(invoke: Invoke): Handlers {
"agentKeys.list": () => tool("agentKeys.list"),
"agentKeys.set": (args) => tool("agentKeys.set", setArgs(args)),
"agentKeys.remove": ({ env }) => tool("agentKeys.remove", { env }),
+ "agentKeys.shell": async () => shellNamesFromWire(await invoke<unknown>("agents_tool", { tool: AGENT_KEYS_METHODS["agentKeys.shell"], args: {} })),
+ "agentKeys.fromShell": ({ env }) => tool("agentKeys.fromShell", { env }),
};
}
@@ -155,5 +173,7 @@ export function webkitAgentKeysOps(request: Request): Handlers {
"agentKeys.list": () => call("agentKeys.list"),
"agentKeys.set": (args) => call("agentKeys.set", setArgs(args)),
"agentKeys.remove": ({ env }) => call("agentKeys.remove", { env }),
+ "agentKeys.shell": async () => shellNamesFromWire(await request<unknown>("agentKeys.shell", {})),
+ "agentKeys.fromShell": ({ env }) => call("agentKeys.fromShell", { env }),
};
}
diff --git a/apps/cua-spaces-web/src/bridge/ops/settings.ts b/apps/cua-spaces-web/src/bridge/ops/settings.ts
index b068368122..ee10188f82 100644
--- a/apps/cua-spaces-web/src/bridge/ops/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/settings.ts
@@ -10,7 +10,7 @@
*/
import { UnsupportedOperationError } from "../adapter";
-import type { LoginItemStatus } from "../contracts/host";
+import type { LoginItemStatus, RuntimePathCheck } from "../contracts/host";
import type { DevicesInput, EnrollResult, PairingCode, TeamsList } from "../contracts/devices";
import type {
AboutInput,
@@ -53,6 +53,12 @@ export interface SettingsOperations {
/** System Settings, Login Items (to approve it). */
"loginItem.openSettings": { args: Empty; result: null };
+ /** What a binary is for one kind of Space (`container`, `vm`, `microvm`):
+ * Settings, Advanced checks a typed path with it before it is saved. */
+ "runtimes.check": { args: { kind: string; path: string }; result: RuntimePathCheck };
+ /** The host's file panel, to pick a kind's binary (null: cancelled). */
+ "runtimes.browse": { args: { kind: string }; result: { path: string | null } };
+
/** The account's devices and access log (`devices_snapshot`). */
"devices.get": { args: Empty; result: DevicesInput };
/** Registers this device: enrolled at once, or a one-time code. */
@@ -96,6 +102,8 @@ export const SETTINGS_OPERATIONS = [
"loginItem.get",
"loginItem.set",
"loginItem.openSettings",
+ "runtimes.check",
+ "runtimes.browse",
"devices.get",
"devices.enroll",
"devices.checkEnrolled",
@@ -168,6 +176,8 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): string
"about.checkNow": () => Promise.reject(new UnsupportedOperationError("tauri", "about.checkNow")),
"update.get": () => Promise.reject(new UnsupportedOperationError("tauri", "update.get")),
"update.install": () => Promise.reject(new UnsupportedOperationError("tauri", "update.install")),
+ "runtimes.check": () => Promise.reject(new UnsupportedOperationError("tauri", "runtimes.check")),
+ "runtimes.browse": () => Promise.reject(new UnsupportedOperationError("tauri", "runtimes.browse")),
// The Tauri app keeps the switches in its UI storage, as its own Settings does.
"experiments.get": async () => readExperiments(),
@@ -244,7 +254,7 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): string
}
/** The Tauri updater has one feed and no controls. */
-export const TAURI_SETTINGS_UNSUPPORTED = ["about.set", "about.checkNow", "update.get", "update.install"] as const satisfies readonly SettingsOpName[];
+export const TAURI_SETTINGS_UNSUPPORTED = ["about.set", "about.checkNow", "update.get", "update.install", "runtimes.check", "runtimes.browse"] as const satisfies readonly SettingsOpName[];
/** The Tauri commands each operation calls (`coverage.ts`). */
export const SETTINGS_TAURI_COMMANDS = {
@@ -258,6 +268,8 @@ export const SETTINGS_TAURI_COMMANDS = {
"loginItem.get": ["login_item_status", "host_status", "agents_tool"],
"loginItem.set": ["login_item_set", "login_item_status", "host_status", "agents_tool"],
"loginItem.openSettings": ["host_open_settings"],
+ "runtimes.check": [],
+ "runtimes.browse": [],
"devices.get": ["devices_snapshot"],
"devices.enroll": ["devices_enroll"],
"devices.checkEnrolled": ["devices_check_enrolled"],
diff --git a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
index 62f52d0684..c841ff1c16 100644
--- a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
@@ -75,6 +75,8 @@ export const WEBKIT_PAGE_OPS = [
"loginItem.get",
"loginItem.set",
"loginItem.openSettings",
+ "runtimes.check",
+ "runtimes.browse",
"devices.get",
"devices.enroll",
"devices.checkEnrolled",
@@ -255,6 +257,9 @@ export function webkitPageOps(request: Request, toHostStatus: (h: WkHostState) =
"loginItem.get": call("loginItem.get"),
"loginItem.set": call("loginItem.set"),
"loginItem.openSettings": none("loginItem.openSettings"),
+ "runtimes.check": call("runtimes.check"),
+ // The file panel waits for the person: no timeout.
+ "runtimes.browse": async (args) => (await request("runtimes.browse", { ...args }, null)) as { path: string | null },
"devices.get": call("devices.get"),
"devices.enroll": call("devices.enroll"),
"devices.checkEnrolled": async () => Boolean(await request("devices.checkEnrolled")),
diff --git a/apps/cua-spaces-web/src/bridge/profile-card.ts b/apps/cua-spaces-web/src/bridge/profile-card.ts
new file mode 100644
index 0000000000..6a0691a0d5
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/profile-card.ts
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/** The card a person or an agent opens to in a Space: the app core's `profileCard.*` (`profile_card.rs`). */
+
+import type { CoreClient } from "./core";
+import type { ConnectorsInput } from "./connectors";
+
+type Json = Record<string, unknown>;
+
+export interface CardDetail {
+ label: string;
+ value: string;
+ copy: boolean;
+}
+
+export interface PersonCardInput {
+ name: string;
+ who: string | null;
+ me: boolean;
+ access: string | null;
+ team: string | null;
+ active: boolean;
+ lastSeenMs: number | null;
+ nowMs: number;
+ canManage: boolean;
+}
+
+export interface PersonCardView {
+ name: string;
+ youLabel: string | null;
+ email: string | null;
+ access: string | null;
+ team: string | null;
+ presence: string | null;
+ active: boolean;
+ changeAccessLabel: string | null;
+ accessChoices: { value: string; label: string }[];
+ accessValue: string | null;
+ removeLabel: string | null;
+}
+
+export interface AgentCardInput {
+ displayName: string;
+ handle: string;
+ harness: string;
+ harnessReported: string | null;
+ ownerName: string;
+ ownerId: string;
+ ownerIsMe: boolean;
+ device: string | null;
+ origin: string;
+ status: string;
+ activity: string | null;
+ joinedHow: string;
+ joinedAtMs: number | null;
+ nowMs: number;
+ rights: { label: string; holders: string }[];
+ canRemove: boolean;
+ connectors: ConnectorsInput;
+}
+
+export interface AgentCardView {
+ name: string;
+ badge: string;
+ line: string;
+ status: "working" | "idle" | "not-connected" | "pending";
+ statusText: string;
+ connectLabel: string | null;
+ app: string | null;
+ settingsLabel: string | null;
+ removeLabel: string | null;
+ detailsLabel: string;
+ details: CardDetail[];
+}
+
+export const personCard = (core: CoreClient, input: PersonCardInput): PersonCardView | null =>
+ core.tryCall<PersonCardView>("profileCard.person", { input: input as unknown as Json }) ?? null;
+
+export const agentCard = (core: CoreClient, input: AgentCardInput): AgentCardView | null =>
+ core.tryCall<AgentCardView>("profileCard.agent", { input: input as unknown as Json }) ?? null;
diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.ts
index 78b4cb0bac..041bd37f6e 100644
--- a/apps/cua-spaces-web/src/bridge/protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/protocol.ts
@@ -27,6 +27,7 @@ import type {
CancelOutcome,
CreateProgress,
TelemetryView,
+ RuntimesInput,
} from "./contracts/host";
import type { AgentEventsPage, AgentMessageSent, AgentSetupRow, AgentStarted, AgentStartRequest, ConnectionReport, ConnectResult, PersistentAgent, SpaceAgentRun } from "./contracts/agents";
import type { KeyvaultOverview, KvGrant, KvItem } from "./contracts/keyvault";
@@ -143,12 +144,12 @@ export interface GlobalShortcut {
/** `settings::SettingsInput`'s host-only fields: the core lays out their rows. */
export interface HostSettings {
- /** Which Lume macOS Spaces run on (`auto`, `builtin`, `system`). */
- lumeSource?: string | null;
- /** Which engine local Linux Spaces run on (`auto`, `builtin`, `system`). */
- linuxSource?: string | null;
+ /** Settings, Advanced's runtimes, as the host read them (`runtimes::RuntimesInput`). */
+ runtimes?: RuntimesInput | null;
/** "Connect to the desktop automatically". */
autoConnect?: boolean | null;
+ /** New Spaces overflow into your linked cloud when this machine is full (`placement.overflow`). */
+ overflow?: boolean | null;
/** The Keyvault wipes access from Spaces automatically. */
keyvaultAutoWipe?: boolean | null;
/** The Keyvault explains unattended access before allowing it (off after "Never ask again"). */
@@ -264,7 +265,8 @@ export interface HostOperations
"settings.get": { args: Record<string, never>; result: SettingsSnapshot };
"settings.set": { args: { key: SettingKey; value: SettingsValues[SettingKey] }; result: SettingsSnapshot };
/** Picks an option on one of the host's own rows (`SettingsSnapshot.hostSettings`:
- * `macos-runtime`, `linux-runtime`, `auto-connect`, `keyvault-auto-wipe`),
+ * `runtime:<kind>`, `runtime-detected:<kind>`, `runtime-path:<kind>`,
+ * `auto-connect`, `keyvault-auto-wipe`),
* as the core's Settings page names them. The SwiftUI host also takes
* `welcome` (General's "Show again": its welcome window). */
"settings.choose": { args: { row: string; option: string }; result: SettingsSnapshot };
@@ -310,7 +312,11 @@ export interface HostOperations
/** Connect and Reconnect: Cua's tools and, with `signIn`, the agent's sign-in copied to Keyvault on This Mac (`cua connect setup --sign-in`). */
"agents.connect": { args: { agents: string[]; signIn: boolean; skills?: boolean; mcp?: boolean }; result: ConnectResult[] };
/** Disconnect: Cua's entry out of the agent's config (the previous one back) and, with `signIn`, the copy in Keyvault (`cua connect remove --sign-in`). */
- "agents.disconnect": { args: { agents: string[]; signIn: boolean }; result: { removed_sign_ins: string[] } };
+ "agents.disconnect": { args: { agents: string[]; signIn: boolean; skills?: boolean; mcp?: boolean }; result: { removed_sign_ins: string[] } };
+ /** Starts an agent's device-code sign-in made for Cua (Codex: `codex login --device-auth` in a folder Cua owns): the link and the code to show. */
+ "agents.signInStart": { args: { agent: string }; result: { id: string; url: string; code: string } };
+ /** Waits for that sign-in to be approved and saves it in Keyvault on This Mac (as Connect's `sign_in`). */
+ "agents.signInWait": { args: { id: string }; result: { imported: { source: string; env: string; label: string; expires_ms: number | null; added_ms: number } | null; refused: string | null; line: string | null } };
}
export type OpName = keyof HostOperations;
@@ -358,6 +364,8 @@ export const OPERATIONS = [
"agents.status",
"agents.connect",
"agents.disconnect",
+ "agents.signInStart",
+ "agents.signInWait",
...AGENT_DETAIL_OPERATIONS,
...NEW_SPACE_OPERATIONS,
...TELEPORT_OPERATIONS,
diff --git a/apps/cua-spaces-web/src/bridge/thread.ts b/apps/cua-spaces-web/src/bridge/thread.ts
index 1f280775c0..a94bbbc9d8 100644
--- a/apps/cua-spaces-web/src/bridge/thread.ts
+++ b/apps/cua-spaces-web/src/bridge/thread.ts
@@ -180,7 +180,7 @@ export interface SpaceThread {
/** Reads the page before the oldest entry shown. */
loadEarlier(): Promise<void>;
/** Posts `text`; `view` says what the person is looking at in the Space (the main view's window). */
- post(text: string, view?: ThreadView | null): Promise<void>;
+ post(text: string, view?: ThreadView | null): Promise<ThreadEntry | null>;
answer(approval: number, approve: boolean): Promise<void>;
/** Changes who can task, control and approve an agent (owners and admins). */
setRights(name: string, rights: Partial<AgentRights>): Promise<void>;
@@ -334,11 +334,12 @@ export function useSpaceThread(spaceId: string | null): SpaceThread {
const post = useCallback(
async (text: string, view?: ThreadView | null) => {
- if (!spaceId || !data || !text.trim()) return;
+ if (!spaceId || !data || !text.trim()) return null;
const entry = await data.call("thread.post", { spaceId, text: text.trim(), ...(view ? { view } : {}) });
if (entry) merge([entry]);
// Your own message: everything above it is read; the divider goes.
setReadSeq(null);
+ return entry ?? null;
},
[data, spaceId, merge],
);
diff --git a/apps/cua-spaces-web/src/bridge/thumbnails.ts b/apps/cua-spaces-web/src/bridge/thumbnails.ts
index 9549f4e020..49e32cf8e4 100644
--- a/apps/cua-spaces-web/src/bridge/thumbnails.ts
+++ b/apps/cua-spaces-web/src/bridge/thumbnails.ts
@@ -19,12 +19,17 @@ import { BridgeContext } from "./BridgeProvider";
import type { Space } from "./contracts/spaces";
import type { SpaceThumbnail } from "./ops/space-detail";
import type { BridgeStore } from "./store";
+import { JobQueue } from "../lib/poll-plan";
/** The most images held (thumbnails are about 320 px on the long edge). */
export const THUMBNAIL_CAP = 32;
/** How fresh a shown thumbnail is kept: the core's `thumbnail_policy`
* background interval (a Space is asked again no sooner). */
export const THUMBNAIL_REFRESH_MS = 90_000;
+/** Thumbnails asked of the host at once, at most: a screenful of tiles drawing
+ * together (a scroll through a long grid) is a few calls at a time, not one
+ * per tile. */
+export const THUMBNAIL_PARALLEL = 4;
export class ThumbnailStore {
/** By Space id, least recently used first. */
@@ -32,6 +37,7 @@ export class ThumbnailStore {
private asked = new Map<string, number>();
private inflight = new Set<string>();
private unsupported = false;
+ private readonly queue = new JobQueue(THUMBNAIL_PARALLEL);
private listeners = new Set<() => void>();
constructor(
@@ -84,7 +90,7 @@ export class ThumbnailStore {
this.asked.set(spaceId, this.now());
this.inflight.add(spaceId);
try {
- const t = await this.adapter.call("spaces.thumbnail", { spaceId });
+ const t = await this.queue.run(() => this.adapter.call("spaces.thumbnail", { spaceId }));
if (t?.url) this.set(spaceId, t);
} catch (e) {
if (isUnsupported(e)) this.unsupported = true;
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index 939b34b1c0..1602e1f61c 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -30,7 +30,7 @@
*/
import type { MachineAccessNotice } from "./contracts/devices";
-import type { MachinePageRow, MachinesView } from "./contracts/host";
+import type { MachinePageRow, MachinesView, RuntimesInput } from "./contracts/host";
import { AGENT_DETAIL_WEBKIT_METHODS } from "./ops/agent-detail";
import { AGENT_KEYS_WEBKIT_METHODS } from "./ops/agent-keys";
import { KEYVAULT_MANAGE_WEBKIT_METHODS } from "./ops/keyvault-manage";
@@ -78,6 +78,8 @@ export const WEBKIT_METHODS = [
"agents.status",
"agents.connect",
"agents.disconnect",
+ "agents.signInStart",
+ "agents.signInWait",
...AGENT_DETAIL_WEBKIT_METHODS,
...AGENT_KEYS_WEBKIT_METHODS,
...KEYVAULT_SETUP_WEBKIT_METHODS,
@@ -124,6 +126,8 @@ export const WEBKIT_METHODS = [
"loginItem.get",
"loginItem.set",
"loginItem.openSettings",
+ "runtimes.check",
+ "runtimes.browse",
"devices.get",
"devices.enroll",
"devices.checkEnrolled",
@@ -372,6 +376,8 @@ export interface WkSettings {
cli?: { name: string; installed: boolean } | null;
/** `AppSettings.tips`; absent: an older host that keeps none. Saved with `settings.update`. */
tips?: { off: boolean; done: string[] };
+ /** Settings, Advanced's runtimes as the host read them (`runtimes::RuntimesInput`); absent: not read. */
+ runtimes?: RuntimesInput | null;
}
/** `keyvault.*`: the core's page views, plus the overview (camelCase records). */
diff --git a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx b/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
index ec9e40e70f..6a905f8fe4 100644
--- a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
+++ b/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
@@ -36,6 +36,9 @@ const TONE: Record<AgentChat["tone"], string> = {
failed: "bg-destructive",
idle: "bg-muted-foreground/40",
asleep: "bg-muted-foreground/40",
+ "not-connected": "bg-warning",
+ creating: "bg-brand",
+ stopped: "bg-muted-foreground/40",
};
/** The owner as the list says it: nothing for your own agents, "Grace's" for a teammate's. */
@@ -66,6 +69,8 @@ export function AgentList({
me,
selected,
onSelect,
+ onOpenRun,
+ onAction,
onNew,
now,
}: {
@@ -73,12 +78,18 @@ export function AgentList({
me: string | null;
selected: string | null;
onSelect: (key: string, space?: string) => void;
+ /** A run that hasn't started: its Space's thread. */
+ onOpenRun?: (chat: AgentChat) => void;
+ /** Its Connect or Try again. */
+ onAction?: (chat: AgentChat) => void;
onNew: () => void;
now: number;
}) {
const needs = chats.flatMap((c) => c.needsYou.map((n) => ({ n, c }))).sort((a, b) => b.n.tsMs - a.n.tsMs);
- const running = chats.filter((c) => c.tone === "you" || c.tone === "working");
- const others = chats.filter((c) => c.tone !== "you" && c.tone !== "working");
+ // Runs that haven't started (being made, not connected, failed): their own section, in the core's order.
+ const runs = chats.filter((c) => c.kind === "attempt");
+ const running = chats.filter((c) => c.kind === "agent" && (c.tone === "you" || c.tone === "working"));
+ const others = chats.filter((c) => c.kind === "agent" && c.tone !== "you" && c.tone !== "working");
return (
<aside data-agent-list="" className="flex w-72 shrink-0 flex-col bg-chrome">
<div className="flex h-14 items-center justify-between pr-3 pl-5">
@@ -110,17 +121,24 @@ export function AgentList({
))}
</Section>
) : null}
+ {runs.length ? (
+ <Section title="Not started" count={runs.length}>
+ {runs.map((c) => (
+ <AgentRow key={c.key} chat={c} me={me} selected={false} onSelect={() => onOpenRun?.(c)} onAction={onAction ? () => onAction(c) : undefined} now={now} />
+ ))}
+ </Section>
+ ) : null}
{running.length ? (
<Section title="Running" count={running.length}>
{running.map((c) => (
- <AgentRow key={c.key} chat={c} me={me} selected={selected === c.key} onSelect={() => onSelect(c.key)} now={now} />
+ <AgentRow key={c.key} chat={c} me={me} selected={selected === c.key} onSelect={() => (c.kind === "attempt" ? onOpenRun?.(c) : onSelect(c.key))} onAction={onAction ? () => onAction(c) : undefined} now={now} />
))}
</Section>
) : null}
{others.length ? (
<Section title={running.length ? "Others" : "Agents"} count={others.length}>
{others.map((c) => (
- <AgentRow key={c.key} chat={c} me={me} selected={selected === c.key} onSelect={() => onSelect(c.key)} now={now} />
+ <AgentRow key={c.key} chat={c} me={me} selected={selected === c.key} onSelect={() => (c.kind === "attempt" ? onOpenRun?.(c) : onSelect(c.key))} onAction={onAction ? () => onAction(c) : undefined} now={now} />
))}
</Section>
) : null}
@@ -145,8 +163,35 @@ function Section({ title, count, children }: { title: string; count: number; chi
);
}
-function AgentRow({ chat: c, me, selected, onSelect, now }: { chat: AgentChat; me: string | null; selected: boolean; onSelect: () => void; now: number }) {
+function AgentRow({ chat: c, me, selected, onSelect, onAction, now }: { chat: AgentChat; me: string | null; selected: boolean; onSelect: () => void; onAction?: () => void; now: number }) {
const owner = ownerWord(c, me);
+ if (c.kind === "attempt") {
+ // A run that hasn't started: its job and why, the step that moves it on, and its Space's thread on click.
+ return (
+ <div data-chat={c.key} data-chat-tone={c.tone} data-chat-run="" className="flex w-full items-center gap-2 rounded-lg px-2 py-2 hover:bg-accent">
+ <button type="button" onClick={onSelect} className="flex min-w-0 flex-1 cursor-default items-center gap-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/60">
+ <AgentTile harness={c.harness} name={c.label} px={28} surface="chrome" />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-1.5">
+ <span className="truncate text-[13px] font-semibold">{c.job ?? c.label}</span>
+ <span className="ml-auto shrink-0 text-[11px] text-muted-foreground tabular-nums">{ago(c.lastMs, now)}</span>
+ </span>
+ <span className="flex items-center gap-1.5">
+ <span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", TONE[c.tone])} />
+ <span data-chat-line="" className="min-w-0 flex-1 truncate text-[11.5px] text-muted-foreground">
+ {c.line}
+ </span>
+ </span>
+ </span>
+ </button>
+ {c.action && onAction ? (
+ <Button size="sm" variant="outline" className="h-7 shrink-0 px-2 text-xs" data-chat-action={c.action.id} onClick={onAction}>
+ {c.action.id === "connect" ? "Connect" : c.action.label}
+ </Button>
+ ) : null}
+ </div>
+ );
+ }
return (
<button
type="button"
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.tsx
index 9242e695cb..1f14bb03b0 100644
--- a/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx
+++ b/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx
@@ -5,7 +5,7 @@ import { Menu as MenuPrimitive } from "@base-ui/react/menu";
import { ArrowUpIcon, CheckIcon, ChevronDownIcon, LaptopIcon, MonitorIcon } from "lucide-react";
import { useEffect, useRef, type ReactElement, type ReactNode } from "react";
-import type { Space, SpaceOs } from "@/bridge";
+import { firstMessage, useBridge, useFlag, type Space, type SpaceOs } from "@/bridge";
import { AppMarkImage } from "@/components/agents/harness-mark";
import { OsIcon } from "@/components/os-icon";
import type { NewKind, TaskWhere } from "@/lib/ask-first";
@@ -27,6 +27,12 @@ export const agentName = (id: string) => TASK_AGENTS.find((a) => a.id === id)?.n
const OS_WORD: Record<SpaceOs, string> = { linux: "Linux", macos: "Mac", windows: "Windows", unknown: "" };
+/** With the redesign, 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 === "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 };
+}
+
export function whereLabel(where: TaskWhere): string {
return where.kind === "new" ? `A new ${OS_WORD[where.os]} computer · this Mac` : where.kind === "this-mac" ? "This Mac" : where.space.name;
}
@@ -139,6 +145,10 @@ export function AskBox({
if (autoFocus) ref.current?.focus();
}, [autoFocus]);
const ready = text.trim().length > 0 && !busy;
+ // With the redesign the agent reads as the @mention the thread will show, and where as a Space.
+ const redesign = useFlag("spaces_redesign");
+ const { core } = useBridge();
+ const handle = redesign ? (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" : installed.has(id) ? "On this Mac" : "Runs on the new computer with your saved key");
return (
<div data-ask-box="" className="rounded-2xl border bg-card shadow-xs dark:bg-white/[0.03]">
@@ -163,7 +173,13 @@ export function AskBox({
trigger={
<button type="button" className={pickerButton} data-picker="who">
<AppMark agent={agent} size={24} />
- <span>{agentName(agent)}</span>
+ {handle ? (
+ <span data-ask-mention={handle} className="font-medium text-brand-strong">
+ @{handle}
+ </span>
+ ) : (
+ <span>{agentName(agent)}</span>
+ )}
<ChevronDownIcon className="size-4 text-muted-foreground" />
</button>
}
@@ -173,7 +189,7 @@ export function AskBox({
<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)} />
))}
</Picker>
- <span className="px-1 text-[14px] text-muted-foreground">on</span>
+ <span className="px-1 text-[14px] text-muted-foreground">{redesign ? "in" : "on"}</span>
<WherePicker
where={where}
onWhere={onWhere}
@@ -190,7 +206,14 @@ export function AskBox({
) : (
<MonitorIcon className="size-4 text-muted-foreground" />
)}
- <span className="max-w-72 truncate">{whereLabel(where)}</span>
+ {redesign ? (
+ <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>
+ ) : (
+ <span className="max-w-72 truncate">{whereLabel(where)}</span>
+ )}
<ChevronDownIcon className="size-4 text-muted-foreground" />
</button>
}
diff --git a/apps/cua-spaces-web/src/components/ask-first/home-sections.tsx b/apps/cua-spaces-web/src/components/ask-first/home-sections.tsx
new file mode 100644
index 0000000000..c4b922e998
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/ask-first/home-sections.tsx
@@ -0,0 +1,160 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Home's sections with the redesign: "Your agents" (the Agents page's own
+ * list, `agentList.view`: agents in your Spaces and this device's runs that
+ * haven't started, with Connect or Try again) and "Your Spaces" (the Spaces
+ * page's tiles). One row each, and See all.
+ */
+
+import { Link, useNavigate } from "@tanstack/react-router";
+import { ChevronRightIcon } from "lucide-react";
+import { useMemo, type KeyboardEvent, type MouseEvent } from "react";
+
+import { spaceDiskBytes, useMachines, useResources, useSpaces, useSpaceThumbnail, type AgentChat } from "@/bridge";
+import { BulkConfirmDialog, useBulkRemove } from "@/components/spaces/bulk-remove";
+import type { SpaceItem } from "@/components/spaces/model";
+import { SpaceMoreMenu, type MenuActions } from "@/components/spaces/space-menu";
+import { SpaceTile } from "@/components/spaces/space-tile";
+import { AgentTile } from "@/components/space-thread/avatar";
+import { Button } from "@/components/ui/button";
+import { GroupedSection } from "@/components/ui/grouped";
+import { toastError } from "@/components/ui/toast";
+import { useAttemptAction } from "@/hooks/use-agent-attempts";
+import { accessOf, isMine } from "@/lib/space-access";
+import { machineName, realSpaces, spaceState } from "@/lib/spaces";
+import { cn } from "@/lib/utils";
+
+/** Agents shown on Home before See all. */
+const HOME_AGENTS = 3;
+/** Spaces shown on Home before See all: one row of tiles. */
+const HOME_SPACES = 4;
+
+const TONE: Record<AgentChat["tone"], string> = {
+ you: "bg-warning",
+ working: "bg-success",
+ failed: "bg-destructive",
+ idle: "bg-muted-foreground/40",
+ asleep: "bg-muted-foreground/40",
+ "not-connected": "bg-warning",
+ creating: "bg-brand",
+ stopped: "bg-muted-foreground/40",
+};
+
+function ago(ms: number, now: number): string {
+ if (!ms) return "";
+ const m = Math.max(0, Math.round((now - ms) / 60_000));
+ if (m < 1) return "Now";
+ if (m < 60) return `${m}m`;
+ const h = Math.round(m / 60);
+ return h < 24 ? `${h}h` : `${Math.round(h / 24)}d`;
+}
+
+function SectionHead({ title, note, to, all }: { title: string; note?: string | null; to: "/agents" | "/spaces"; all: string }) {
+ return (
+ <div className="mb-3 flex items-center justify-between">
+ <h2 className="flex items-baseline gap-2 text-[17px] font-semibold">
+ {title} {note ? <span className="text-[14px] font-normal text-muted-foreground">{note}</span> : null}
+ </h2>
+ <Link to={to} data-home-see-all={to} className="flex items-center gap-1 text-[13px] text-muted-foreground hover:text-foreground">
+ {all} <ChevronRightIcon className="size-4" />
+ </Link>
+ </div>
+ );
+}
+
+/** "Your agents": the first rows of the one agent list; a row opens its Space's thread. */
+export function YourAgents({ chats }: { chats: AgentChat[] | null | undefined }) {
+ const act = useAttemptAction();
+ if (!chats || chats.length === 0) return null;
+ const working = chats.filter((c) => c.tone === "working").length;
+ return (
+ <section data-home-agents="">
+ <SectionHead title="Your agents" note={working ? `${working} working` : null} to="/agents" all={`See all ${chats.length}`} />
+ <GroupedSection>
+ {chats.slice(0, HOME_AGENTS).map((c) => (
+ <AgentRunRow key={c.key} chat={c} onAction={() => act(c)} />
+ ))}
+ </GroupedSection>
+ </section>
+ );
+}
+
+function AgentRunRow({ chat: c, onAction }: { chat: AgentChat; onAction: () => void }) {
+ const navigate = useNavigate();
+ const { data: spaces } = useSpaces();
+ const place = c.places[0];
+ const space = spaces?.find((s) => s.id === place?.spaceId);
+ const thumb = useSpaceThumbnail(place?.spaceId ?? "", Boolean(space) && spaceState(space!) === "running");
+ const open = () => place && void navigate({ to: "/spaces/$spaceId", params: { spaceId: place.spaceId } });
+ const stop = (e: MouseEvent | KeyboardEvent) => e.stopPropagation();
+ return (
+ <div
+ role="link"
+ tabIndex={0}
+ data-home-agent={c.key}
+ data-chat-tone={c.tone}
+ onClick={open}
+ onKeyDown={(e) => (e.key === "Enter" ? open() : undefined)}
+ className="flex min-h-[64px] cursor-default items-center gap-4 px-4 py-3 outline-none hover:bg-accent/50 focus-visible:bg-accent/50"
+ >
+ <AgentTile harness={c.harness} icon={c.identity?.icon} owner={c.identity?.owner} name={c.label} px={32} dim={c.tone === "asleep"} surface="background" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13px] font-medium">{c.job ?? c.label}</div>
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", TONE[c.tone])} />
+ <span className="truncate" data-home-agent-line="">
+ {c.line}
+ </span>
+ </div>
+ </div>
+ {c.action ? (
+ <Button size="sm" variant="outline" data-home-agent-action={c.action.id} onClick={(e) => (stop(e), onAction())} onKeyDown={stop}>
+ {c.action.label}
+ </Button>
+ ) : null}
+ <span className="hidden w-36 truncate text-right text-xs text-muted-foreground md:block">{place?.spaceName}</span>
+ <span className="w-10 text-right text-xs text-muted-foreground tabular-nums">{ago(c.lastMs, Date.now())}</span>
+ <span className="hidden w-20 lg:block">{thumb ? <img src={thumb} alt="" className="aspect-[16/10] w-20 rounded-lg object-cover" /> : <span className="block aspect-[16/10] w-20 rounded-lg bg-muted" />}</span>
+ </div>
+ );
+}
+
+/** "Your Spaces": the Spaces page's tiles, one row, with power and ⋯ on hover. */
+export function YourSpaces() {
+ const { data, startSpace, stopSpace } = useSpaces();
+ const { data: machines = [] } = useMachines();
+ const resources = useResources();
+ const spaces = realSpaces(data ?? []);
+ const items = useMemo(
+ () =>
+ spaces.map((space): SpaceItem => {
+ const machine = machineName(machines, space);
+ const mine = isMine(space);
+ return { space, state: spaceState(space), access: accessOf(space, machine), mine, bytes: mine ? spaceDiskBytes(resources, space.id) : null, machine };
+ }),
+ [spaces, machines, resources],
+ );
+ const present = useMemo(() => new Set(spaces.map((s) => s.id)), [spaces]);
+ const bulk = useBulkRemove(present, () => {});
+ if (spaces.length === 0) return null;
+ const running = items.filter((it) => it.state === "running").length;
+ const actions: MenuActions = {
+ power: (it, on) => void (on ? startSpace : stopSpace)(it.space.id).catch(toastError(`Couldn't turn ${on ? "on" : "off"} ${it.space.name}`)),
+ remove: (it) => bulk.ask([it]),
+ };
+ return (
+ <section data-home-spaces="">
+ <SectionHead title="Your Spaces" note={running ? `${running} running` : null} to="/spaces" all={`See all ${spaces.length}`} />
+ <ul className="grid grid-cols-2 gap-5 md:grid-cols-4">
+ {items.slice(0, HOME_SPACES).map((it) => (
+ <li key={it.space.id}>
+ <SpaceTile item={it} more={<SpaceMoreMenu item={it} actions={actions} />} />
+ </li>
+ ))}
+ </ul>
+ {bulk.view ? <BulkConfirmDialog view={bulk.view} items={bulk.asked} onCancel={bulk.cancel} onConfirm={() => void bulk.confirm()} /> : null}
+ </section>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/ask-first/home.tsx b/apps/cua-spaces-web/src/components/ask-first/home.tsx
index cc8679736d..77092bff74 100644
--- a/apps/cua-spaces-web/src/components/ask-first/home.tsx
+++ b/apps/cua-spaces-web/src/components/ask-first/home.tsx
@@ -5,8 +5,9 @@ import { Link } from "@tanstack/react-router";
import { ChevronRightIcon } from "lucide-react";
import { useEffect, useState } from "react";
-import { useAgents, useSpaces, useSpaceThumbnail, type AgentRunSummary, type Space } from "@/bridge";
+import { useAgentChats, useAgents, useFlag, useSpaces, useSpaceThumbnail, type AgentRunSummary, type Space } from "@/bridge";
import { CuaKey } from "@/components/cua-key";
+import { useAgentAttempts } from "@/hooks/use-agent-attempts";
import { OsIcon } from "@/components/os-icon";
import { SpaceCanvas } from "@/components/space-canvas";
import { Button } from "@/components/ui/button";
@@ -15,6 +16,7 @@ import { realSpaces, spaceState } from "@/lib/spaces";
import { cn } from "@/lib/utils";
import { agentName, AppMark, AskBox, TASK_AGENTS, type TaskWhere } from "./ask-box";
+import { YourAgents, YourSpaces as YourSpacesRow } from "./home-sections";
import { useWherePick } from "./this-mac-confirm";
import { useStartTask } from "./use-start-task";
import { useWhereOptions } from "./where-options";
@@ -81,7 +83,12 @@ export function AskFirstHome() {
return { task, run, state: taskState(task, run ? { status: run.status, needsYou: Boolean(run.needsYou), lastEventMs: null } : null) };
}),
);
- const first = tasks.length === 0;
+ const redesign = useFlag("spaces_redesign");
+ // The redesign lists agents and Spaces, not tasks: with neither (a first run,
+ // or tasks whose Spaces are gone), Home is the welcome again.
+ const attempts = useAgentAttempts();
+ const { chats } = useAgentChats(attempts);
+ const first = redesign ? !chats?.length && realSpaces(spaces ?? []).length === 0 : tasks.length === 0;
return (
<div className="h-full overflow-y-auto [scrollbar-gutter:stable]" data-ask-first-home="">
@@ -128,10 +135,18 @@ export function AskFirstHome() {
<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.
</p>
</>
- ) : (
+ ) : redesign ? null : (
<TaskList rows={rows} spaces={spaces ?? []} />
)}
- {!first && realSpaces(spaces ?? []).length > 0 ? <YourSpaces spaces={realSpaces(spaces ?? [])} /> : null}
+ {redesign ? (
+ // The redesign: the Agents page's own list, then the Spaces page's tiles.
+ <>
+ <YourAgents chats={chats} />
+ <YourSpacesRow />
+ </>
+ ) : !first && realSpaces(spaces ?? []).length > 0 ? (
+ <YourSpaces spaces={realSpaces(spaces ?? [])} />
+ ) : null}
</div>
{pick.dialog}
</div>
diff --git a/apps/cua-spaces-web/src/components/ask-first/task-view.tsx b/apps/cua-spaces-web/src/components/ask-first/task-view.tsx
index ae58cd37ad..d10f449e36 100644
--- a/apps/cua-spaces-web/src/components/ask-first/task-view.tsx
+++ b/apps/cua-spaces-web/src/components/ask-first/task-view.tsx
@@ -5,7 +5,7 @@ import { Link } from "@tanstack/react-router";
import { ArrowLeftIcon, ArrowUpIcon, CheckIcon, ChevronDownIcon, EyeIcon, HandIcon, Loader2Icon, Maximize2Icon, Minimize2Icon, RotateCwIcon, Trash2Icon, TriangleAlertIcon, UserPlusIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
-import { useAgents, useAgentTimeline, useBridge, useSession, useShareSheet, useSpaceDetail, useSpaces, type AgentTimeline, type Space } from "@/bridge";
+import { setupCard, useAgents, useAgentTimeline, useBridge, useSession, useShareSheet, useSpaceDetail, useSpaces, type AgentTimeline, type Space } from "@/bridge";
import { Timeline } from "@/components/agents/timeline";
import { CuaKey } from "@/components/cua-key";
import { OsIcon } from "@/components/os-icon";
@@ -13,11 +13,12 @@ import { StreamSurface } from "@/components/space-detail/stream-surface";
import { ConfirmDialog } from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { toastError } from "@/components/ui/toast";
+import { useConnectors } from "@/hooks/use-connectors";
import { keepTranscript, postToSpaceThread, retryTarget, startErrorView, taskState, TASK_STATE_TEXT, taskTitle, updateAskTask, useAskTasks, type AskTask, type TaskState, type TaskWhere } from "@/lib/ask-first";
import { createProgress, spaceState } from "@/lib/spaces";
import { cn } from "@/lib/utils";
-import { agentName, AppMark, WherePicker } from "./ask-box";
+import { agentName, AppMark, TASK_AGENTS, WherePicker } from "./ask-box";
import { StateDot, taskRun } from "./home";
import { useWherePick } from "./this-mac-confirm";
import { useStartTask } from "./use-start-task";
@@ -283,8 +284,20 @@ function Starting({ pending, space, name, onHost }: { pending: Space | undefined
* Change computer right in the card, and the core's own words under
* Details.
*/
-export function StartFailed({ error, name, host, onRetry }: { error: string; name: string; host: boolean; onRetry: (where?: TaskWhere) => void }) {
+export function StartFailed({ error, name, agent, host, onRetry }: { error: string; name: string; agent?: string; host: boolean; onRetry: (where?: TaskWhere) => void }) {
const view = startErrorView(error, name);
+ const { core } = useBridge();
+ const connectors = useConnectors();
+ // "Connect <app>" in place of Add your key: Settings, Connectors' Connect, here; then it starts again by itself.
+ const setupId = TASK_AGENTS.find((a) => a.id === agent)?.setupId ?? agent ?? "";
+ const card = view.action === "add-key" ? setupCard(core, connectors.input, setupId, name) : null;
+ const [connecting, setConnecting] = useState(false);
+ const connect = async () => {
+ setConnecting(true);
+ const outcome = await connectors.connectApp(setupId);
+ setConnecting(false);
+ if (outcome === "connected") onRetry();
+ };
const { kinds, spaces } = useWhereOptions();
const [open, setOpen] = useState(false);
const pick = useWherePick(name);
@@ -292,9 +305,9 @@ export function StartFailed({ error, name, host, onRetry }: { error: string; nam
<CuaLine>
<div data-ask-start-failed={view.action}>
<div className="mb-1 flex items-center gap-2 text-[15px] font-semibold text-foreground">
- <TriangleAlertIcon className="size-4 text-destructive" /> {view.title}
+ <TriangleAlertIcon className="size-4 text-destructive" /> {card?.title ?? view.title}
</div>
- <p>{view.body}</p>
+ <p>{card?.body ?? view.body}</p>
<div className="mt-3 flex flex-wrap items-center gap-2">
{view.action === "set-up-host" ? (
<Button className="h-10 px-4" render={<Link to="/machines" />}>
@@ -302,8 +315,9 @@ export function StartFailed({ error, name, host, onRetry }: { error: string; nam
</Button>
) : null}
{view.action === "add-key" ? (
- <Button className="h-10 px-4" render={<Link to="/settings/connectors" />}>
- Add your key
+ <Button className="h-10 px-4" disabled={connecting} onClick={() => void connect()} data-ask-connect="">
+ {connecting ? <Loader2Icon className="animate-spin" /> : null}
+ {connecting ? (card?.connectingLabel ?? "Connecting…") : (card?.connectLabel ?? `Connect ${name}`)}
</Button>
) : null}
{view.retry ? (
@@ -360,7 +374,7 @@ function ThreadFooter({
}) {
return (
<div className="flex flex-col gap-5" data-ask-footer="">
- {task.error ? <StartFailed error={task.error} name={name} host={retryTarget(task).kind === "host"} onRetry={onRetry} /> : null}
+ {task.error ? <StartFailed error={task.error} name={name} agent={task.agent} host={retryTarget(task).kind === "host"} onRetry={onRetry} /> : null}
{state === "working" ? (
<p className="flex items-center gap-2 text-xs text-muted-foreground" role="status">
<StateDot state="working" />
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.ts
index ff0053bfac..79583b9647 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
@@ -1,9 +1,12 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { useNavigate } from "@tanstack/react-router";
+import { useNavigate, useRouter } from "@tanstack/react-router";
-import { newPendingId, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useSpaces, type HostStatus } from "@/bridge";
+import { firstMessage, newPendingId, threadOpAvailable, useAgents, useBridge, useFeatureRecorder, useFirstSpaceOffers, useFlag, useSpaces, type AgentMember, type HostStatus } from "@/bridge";
+import { enqueue, flushQueue, resolveQueue } from "@/components/space-thread/queued";
+import { sendWithSummon } from "@/components/space-thread/summon";
+import { useConnectors } from "@/hooks/use-connectors";
import { addAskTask, askTask, HOST_NOT_SHARED, hostSpaceId, postToSpaceThread, retryTarget, taskTarget, updateAskTask, whereOs, type AskTask, type TaskTarget, type TaskWhere } from "@/lib/ask-first";
/** Task and Space pairs whose thread already has the task's job. */
@@ -22,13 +25,38 @@ export function useStartTask(): {
retry: (task: AskTask, where?: TaskWhere) => void;
} {
const navigate = useNavigate();
+ const router = useRouter();
const { createSpace } = useSpaces();
const { data: host } = useBridge();
const { startRun } = useAgents();
const { offers } = useFirstSpaceOffers();
const record = useFeatureRecorder();
+ const { core } = useBridge();
+ // With the redesign, the job goes straight to its Space: the page is the Space's, and
+ // the job is its first message, @mentioning the agent (the same summon as the composer's).
+ const inSpace = useFlag("spaces_redesign");
+ const { input: connectors } = useConnectors();
- const run = (id: string, target: TaskTarget) =>
+ /** What summoning reads for `spaceId`: its agents now and this device's connectors. */
+ const summonInput = async (spaceId: string) => {
+ const members = ((await host!.call("thread.members", { spaceId }).catch(() => null))?.members ?? []) as AgentMember[];
+ return { members: members.map((m) => ({ handle: m.name, harness: m.harness, label: m.name })), people: [], canAdd: true, connectors };
+ };
+ const send = (spaceId: string, input: Awaited<ReturnType<typeof summonInput>>) => (text: string) =>
+ sendWithSummon({ core, data: host!, spaceId, input, text, post: (t) => host!.call("thread.post", { spaceId, text: t }) });
+ const canSummon = () => !!host && threadOpAvailable(host.mode, "thread.agentAdd");
+
+ /** The job as the Space's first message, through the summon; false when this agent can't join a Space. */
+ const summonIn = async (spaceId: string, agent: string, prompt: string): Promise<boolean> => {
+ if (!canSummon()) return false;
+ const input = await summonInput(spaceId);
+ const first = firstMessage(core, input, agent, prompt);
+ if (!first?.handle) return false;
+ await send(spaceId, input)(first.text);
+ return true;
+ };
+
+ const run = (id: string, target: TaskTarget, place?: { pendingId?: string; queued?: boolean; onSpace?: (spaceId: string) => void; onCreated?: (spaceId: string) => void; onNoSpace?: () => void }) =>
void (async () => {
try {
let spaceId = target.kind === "space" ? target.spaceId : null;
@@ -37,17 +65,30 @@ export function useStartTask(): {
spaceId = hostSpaceId(status);
if (!spaceId) throw new Error(HOST_NOT_SHARED);
updateAskTask(id, { spaceId, onHost: true });
+ place?.onSpace?.(spaceId);
}
if (!spaceId) {
const os = target.kind === "create" ? target.os : "linux";
- const pendingId = newPendingId();
+ 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);
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);
+ 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))) {
+ updateAskTask(id, { inSpace: true });
+ return;
+ }
// The job is the first line of the Space's thread, so the conversation lives with the Space
// (once per Space: Try again on the same Space does not post it twice).
if (!posted.has(`${id}\u0000${spaceId}`)) {
@@ -58,6 +99,8 @@ export function useStartTask(): {
updateAskTask(id, { runId: started.run_id });
} catch (e) {
updateAskTask(id, { error: e instanceof Error ? e.message : String(e), pendingId: null });
+ // No Space to show it in (this Mac isn't shared): its conversation page says why.
+ if (!askTask(id)?.spaceId) place?.onNoSpace?.();
}
})();
@@ -66,8 +109,30 @@ export function useStartTask(): {
const target = taskTarget(where);
const task = addAskTask({ prompt: prompt.trim(), agent, os: whereOs(where), spaceId: target.kind === "space" ? target.spaceId : null, onHost: target.kind === "host" });
record("ask_first_task_started");
- void navigate({ to: "/home/$taskId", params: { taskId: task.id } });
- run(task.id, target);
+ if (!inSpace) {
+ void navigate({ to: "/home/$taskId", params: { taskId: task.id } });
+ run(task.id, target);
+ return;
+ }
+ // Straight to the Space: the one picked, the one being made (its page follows the create), or this Mac's.
+ const go = (spaceId: string) => void navigate({ to: "/spaces/$spaceId", params: { spaceId } });
+ if (target.kind === "space") {
+ run(task.id, target, {});
+ go(target.spaceId);
+ } else if (target.kind === "create") {
+ 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;
+ if (first?.handle) enqueue(pendingId, first.text);
+ run(task.id, target, { pendingId, onCreated, queued: Boolean(first?.handle) });
+ go(pendingId);
+ } else {
+ run(task.id, target, { onSpace: go, onNoSpace: () => void navigate({ to: "/home/$taskId", params: { taskId: task.id } }) });
+ }
},
retry: (task, where) => {
const target = where ? taskTarget(where) : retryTarget(task);
diff --git a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
index 9836434226..49ae02d0ae 100644
--- a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
+++ b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
@@ -1,11 +1,12 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { setFlagOverride, useAbout, useBridge, useExperiments, useFlag, useMachines, useMicrovmRows, useSession, useSettings, useThisMachine, type SettingsOption, type SettingsRow as CoreRow } from "@/bridge";
+import { setFlagOverride, useAbout, useBridge, useExperiments, useFlag, useMachines, useSession, useSettings, useThisMachine, type SettingsRow as CoreRow } from "@/bridge";
import { aboutView } from "@/bridge/settings-derive";
import { SettingsGroup } from "@/components/settings-group";
import { SettingRow } from "@/components/ui/grouped";
import { CoreSettingsRow } from "@/components/settings/core-section";
+import { RuntimeKindRows } from "@/components/settings/runtime-rows";
import { HostSetupForm } from "@/components/this-machine";
import { Button } from "@/components/ui/button";
import { toastError } from "@/components/ui/toast";
@@ -19,46 +20,34 @@ const BETA_HELP = "New features sooner, with rough edges. Back on Stable, this v
/** Experiments that stay as Labs. "Your cloud" and "Sharing" have no switch any more: the plan decides on the server. */
const LABS = new Set(["experiment:cua_volume"]);
-/** The software choices in plain words (the core says Built-in and System). */
-const RUNTIME_LABEL: Record<string, string> = { "macos-runtime": "Mac computers", "linux-runtime": "Linux computers" };
-const RUNTIME_OPTION: Record<string, string> = { auto: "Automatic", builtin: "Cua’s own", system: "Already installed" };
-
-const runtimeRow = (row: CoreRow): CoreRow => ({
- ...row,
- label: RUNTIME_LABEL[row.id] ?? row.label,
- options: row.options.map((o: SettingsOption) => ({ ...o, label: RUNTIME_OPTION[o.id] ?? o.label })),
-});
-
/**
* Settings, Advanced: early releases, Labs, which software runs Spaces on
* this Mac, and your own connection server. For options most people never
* touch; each says what it does in a line.
*/
export function AdvancedTab() {
- const { data: settings, chooseSetting } = useSettings();
+ const { data: settings, chooseSetting, isLoading: settingsLoading } = useSettings();
+ const { isLoading: aboutLoading } = useAbout();
+ const { isLoading: experimentsLoading } = useExperiments();
const page = settings?.page;
const general = page?.sections.find((s) => s.id === "general");
const runtimes = page?.sections.find((s) => s.id === "runtimes");
const autoConnect = general?.rows.find((r) => r.id === "auto-connect");
const overflow = general?.rows.find((r) => r.id === "placement-overflow");
- // Whether this computer runs microVMs, and why not (New Space only greys MicroVM out).
- const microvm = useMicrovmRows();
- const microvmStatus = microvm.find((r) => r.id === "microvm-runtime");
- const microvmNote = microvm.find((r) => r.id === "microvm-runtime-note");
const choose = (row: CoreRow, option: string) => void chooseSetting(row.id, option).catch(toastError(`Couldn't change ${row.label}`));
+ // Nothing is drawn until the host has answered for every group, so none of them pushes
+ // another down as it arrives (a layout shift of the whole tab).
+ if (settingsLoading || aboutLoading || experimentsLoading) return <div data-settings-tab="advanced" aria-busy="true" />;
+
return (
<div data-settings-tab="advanced">
<EarlyReleases />
<Labs />
- {runtimes || autoConnect || overflow || microvmStatus ? (
- <SettingsGroup title="Which software runs Spaces on this Mac">
- {runtimes?.rows.filter((r) => r.kind === "choice").map((r) => <CoreSettingsRow key={r.id} row={runtimeRow(r)} asSelect onChoose={choose} />)}
- {microvmStatus ? (
- <div data-microvm-runtime="" data-microvm-problem={microvmNote?.kind === "error" || undefined}>
- <CoreSettingsRow row={{ ...microvmStatus, label: "MicroVMs" }} description={microvmNote?.label} />
- </div>
- ) : null}
+ {runtimes || autoConnect || overflow ? (
+ <SettingsGroup title="Which software runs Spaces on this computer">
+ {/* One row per kind of Space, as the core lays them out (always there, "Checking…" until the host read them). */}
+ {runtimes ? <RuntimeKindRows section={runtimes} onChoose={choose} /> : null}
{autoConnect ? <CoreSettingsRow row={{ ...autoConnect, label: "Open a Space’s screen right away" }} onChoose={choose} /> : null}
{overflow ? (
<CoreSettingsRow
@@ -153,8 +142,8 @@ function Labs() {
return (
<SettingsGroup title="Labs">
<CoreSettingsRow
- row={flagRow("spaces_redesign", "Try the new design", redesign)}
- description="The new Spaces page, Space page and Agents tab. On this device only."
+ row={flagRow("spaces_redesign", "New design", redesign)}
+ description="The new Spaces page, Space page and Agents tab. Turn off to use the classic design. On this device only."
onChoose={(_, option) => setFlagOverride("spaces_redesign", option === "on")}
/>
<CoreSettingsRow
diff --git a/apps/cua-spaces-web/src/components/settings/connectors/app-detail.tsx b/apps/cua-spaces-web/src/components/settings/connectors/app-detail.tsx
new file mode 100644
index 0000000000..f83bf1cfb1
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/settings/connectors/app-detail.tsx
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { Link } from "@tanstack/react-router";
+import { CheckIcon, ChevronLeftIcon, Loader2Icon } from "lucide-react";
+
+import { HarnessMark } from "@/components/agents/harness-mark";
+import { SettingsGroup, SettingsRow } from "@/components/settings-group";
+import { Snippet } from "@/components/settings/snippet";
+import { Button } from "@/components/ui/button";
+import { DetailsDisclosure, GroupedRow, SettingRow } from "@/components/ui/grouped";
+import { Switch } from "@/components/ui/switch";
+import { useConnectors } from "@/hooks/use-connectors";
+import { BY_HAND } from "@/lib/connected-apps";
+import { cn } from "@/lib/utils";
+
+/**
+ * One coding app's page (Settings, Connectors, the row's chevron): Connect
+ * while it isn't, the separate switches (Cua skills, Cua tools, Keep it set
+ * up), which provider it signs in with and how, Sign in or Sign out, the
+ * settings file, adding Cua by hand, and Remove. The core's
+ * `connectors.appDetail`.
+ */
+export function ConnectorAppPage({ agent }: { agent: string }) {
+ const c = useConnectors();
+ const d = c.detail(agent);
+ const back = (
+ <Link to="/settings/connectors" className="-ml-1 mb-4 inline-flex items-center gap-0.5 rounded-lg px-1 py-0.5 text-[13px] text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60" data-connector-back="">
+ <ChevronLeftIcon className="size-4" /> {d?.backLabel ?? "Connectors"}
+ </Link>
+ );
+ if (c.apps.rows === null) return <div className="h-96" aria-busy="true" />;
+ if (!d) {
+ return (
+ <div>
+ {back}
+ <p className="text-[13px] text-muted-foreground">This app isn't on this computer.</p>
+ </div>
+ );
+ }
+ const busy = c.input.busy.some((b) => b.id === `app:${agent}`);
+ const failure = c.input.failures.find((f) => f.id === `app:${agent}`)?.line;
+ const snippet = BY_HAND[agent];
+ return (
+ <div data-connector-detail={agent}>
+ {back}
+ <header className="mb-6 flex items-center gap-3">
+ <HarnessMark agent={d.agent} name={d.name} large />
+ <div className="min-w-0 flex-1">
+ {/* design-ok: the app's own page needs its name as its title; groups below use SettingsGroup */}
+ <h2 className="truncate text-[17px] font-semibold">{d.name}</h2>
+ <p className={cn("flex items-center gap-1 text-[13px]", d.connected ? "text-foreground" : "text-muted-foreground")} data-connector-detail-status="">
+ {busy ? <Loader2Icon className="size-3.5 animate-spin" /> : d.connected ? <CheckIcon className="size-3.5 text-success" /> : null}
+ {d.status}
+ </p>
+ {failure ? <p className="text-[13px] text-destructive">{failure}</p> : null}
+ </div>
+ {d.connect ? (
+ <Button variant="outline" disabled={!d.connect.enabled || busy} onClick={() => void c.connectApp(agent)} data-connector-detail-connect="">
+ {d.connect.label}
+ </Button>
+ ) : null}
+ </header>
+
+ <SettingsGroup title={d.toolsTitle}>
+ {d.toggles.map((t) => (
+ <SettingsRow
+ key={t.id}
+ label={t.label}
+ description={t.help}
+ htmlFor={`connector-${t.id}`}
+ control={<Switch id={`connector-${t.id}`} data-connector-toggle={t.id} checked={t.on} disabled={!t.enabled} onCheckedChange={(on) => void c.setToggle(agent, t.id, on)} />}
+ />
+ ))}
+ </SettingsGroup>
+
+ <SettingsGroup title={d.signInTitle} footer={d.signIn?.way}>
+ {d.signIn ? (
+ <GroupedRow className="min-h-12" data-connector-detail-signin={d.signIn.provider}>
+ <div className="min-w-0 flex-1">
+ <div>{d.signIn.title}</div>
+ <div className={cn("flex items-center gap-1 text-xs", d.signIn.connected ? "text-foreground" : "text-muted-foreground")}>
+ {d.signIn.connected ? <CheckIcon className="size-3 text-success" /> : null}
+ {d.signIn.status}
+ </div>
+ </div>
+ <Button
+ size="sm"
+ variant={d.signIn.connected ? "ghost" : "outline"}
+ disabled={!d.signIn.button.enabled}
+ data-connector-detail-signin-action={d.signIn.button.id}
+ onClick={() => (d.signIn!.button.id === "sign-out" ? void c.signOut(d.signIn!.provider) : c.openProvider(d.signIn!.provider, agent))}
+ >
+ {d.signIn.button.label}
+ </Button>
+ </GroupedRow>
+ ) : (
+ <GroupedRow className="text-muted-foreground">{d.signInNote}</GroupedRow>
+ )}
+ </SettingsGroup>
+
+ {d.settingsFile || snippet ? (
+ <DetailsDisclosure title="Advanced" className="mb-8">
+ <div className="mt-4">
+ {d.settingsFile ? (
+ <SettingsGroup title={d.settingsFileLabel}>
+ <SettingRow label={<code className="font-mono text-xs text-muted-foreground select-text">{d.settingsFile}</code>} />
+ </SettingsGroup>
+ ) : null}
+ {snippet ? (
+ <SettingsGroup title="Add it by hand" className="mb-0">
+ <div className="px-4 py-4">
+ <Snippet file={snippet.file} text={snippet.snippet} />
+ <p className="mt-2 text-xs text-muted-foreground">Paste this into the file, then restart {d.name}.</p>
+ </div>
+ </SettingsGroup>
+ ) : null}
+ </div>
+ </DetailsDisclosure>
+ ) : null}
+
+ {d.removeLabel ? (
+ <Button variant="ghost" className="text-destructive" disabled={busy} onClick={() => void c.removeFromApp(agent)} data-connector-remove="">
+ {d.removeLabel}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/settings/connectors/connectors-page.tsx b/apps/cua-spaces-web/src/components/settings/connectors/connectors-page.tsx
new file mode 100644
index 0000000000..0c3cadbeed
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/settings/connectors/connectors-page.tsx
@@ -0,0 +1,228 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { useNavigate } from "@tanstack/react-router";
+import { CheckIcon, ChevronDownIcon, ChevronRightIcon, ChevronUpIcon, Loader2Icon, TriangleAlertIcon } from "lucide-react";
+import { lazy, Suspense, useEffect, useState, type KeyboardEvent, type MouseEvent } from "react";
+
+import { useAgentKeys, useBridge, type ConnectorAppRow, type ConnectorProviderRow } from "@/bridge";
+import { HarnessMark } from "@/components/agents/harness-mark";
+import { KeySheet } from "@/components/agents/key-sheet";
+import { SettingsGroup, SettingsRow } from "@/components/settings-group";
+import { ConfirmDialog } from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { GroupedAction, GroupedRow } from "@/components/ui/grouped";
+import { Switch } from "@/components/ui/switch";
+import { toastError } from "@/components/ui/toast";
+import { useConnectors, type Connectors } from "@/hooks/use-connectors";
+import { addedText } from "@/lib/agent-keys";
+import { getItUrl, missingApps } from "@/lib/connected-apps";
+import { cn } from "@/lib/utils";
+
+const DriverSettingsCard = lazy(() => import("@/components/volume/driver-card").then((m) => ({ default: m.DriverSettingsCard })));
+
+/**
+ * Settings, Connectors (redesign): Coding apps, each with Connect (Cua's
+ * tools and the app's sign-in, once) and a chevron to its own page; then
+ * Providers, each with Connect (the provider's sign-in where there is one
+ * for this, else a key) or Sign out. Every word and state is the core's
+ * (`connectors.view`).
+ */
+export function ConnectorsRedesign({ focusApp }: { focusApp?: string }) {
+ const c = useConnectors();
+ const { view } = c;
+ const navigate = useNavigate();
+ const { data } = useBridge();
+ const keys = useAgentKeys();
+ const [all, setAll] = useState(false);
+ const [lit, setLit] = useState<string | null>(null);
+ const missing = missingApps(c.apps.rows ?? []);
+
+ useEffect(() => {
+ if (!view || !focusApp) return;
+ document.querySelector<HTMLElement>(`[data-connector-app="${focusApp}"]`)?.scrollIntoView?.({ block: "center" });
+ setLit(focusApp);
+ const t = setTimeout(() => setLit(null), 2000);
+ return () => clearTimeout(t);
+ }, [Boolean(view), focusApp]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ if (!view || c.apps.rows === null) return <div className="mb-8 h-48" aria-busy="true" />;
+ const open = (agent: string) => void navigate({ to: "/settings/connectors/$app", params: { app: agent } });
+ const confirm = keys.removing ? keys.removeConfirmOf(keys.removing) : null;
+
+ return (
+ <div data-connectors-redesign="">
+ {view.notice ? (
+ <div data-connectors-notice="" className="mb-4 flex items-start gap-2.5 rounded-lg bg-warning/10 px-4 py-2.5 text-[13px]">
+ <TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-warning" />
+ <span className="min-w-0 flex-1">{view.notice}</span>
+ </div>
+ ) : null}
+
+ <SettingsGroup title={view.appsTitle} data-connectors-apps="">
+ {view.appsEmpty ? <GroupedRow className="text-muted-foreground">{view.appsEmpty}</GroupedRow> : null}
+ {view.apps.map((row) => (
+ <AppRow key={row.agent} row={row} lit={lit === row.agent} onOpen={() => open(row.agent)} onConnect={() => void c.connectApp(row.agent)} />
+ ))}
+ <SettingsRow
+ label={view.autoLabel}
+ description={view.autoHelp}
+ htmlFor="connectors-auto"
+ control={<Switch id="connectors-auto" data-connected-auto="" checked={view.auto} onCheckedChange={c.apps.setAuto} />}
+ />
+ {all && missing.length > 0 ? (
+ <>
+ <GroupedRow className="min-h-9 bg-muted/40 py-2 text-xs text-muted-foreground">Not installed</GroupedRow>
+ {missing.map((row) => {
+ const url = getItUrl(row.agent);
+ return (
+ <GroupedRow key={row.agent} data-connected-missing={row.agent} className="text-muted-foreground">
+ <HarnessMark agent={row.agent} name={row.name} />
+ <span className="min-w-0 flex-1 text-[13px]">{row.name}</span>
+ {url ? (
+ <button type="button" className="text-xs hover:text-foreground hover:underline" onClick={() => void data?.call("session.openExternal", { url }).catch(() => {})}>
+ Get it
+ </button>
+ ) : null}
+ </GroupedRow>
+ );
+ })}
+ </>
+ ) : null}
+ <GroupedAction data-connected-show-all="" aria-expanded={all} onClick={() => setAll(!all)}>
+ {all ? "Show fewer" : "Show all"} {all ? <ChevronUpIcon className="size-3.5" /> : <ChevronDownIcon className="size-3.5" />}
+ </GroupedAction>
+ </SettingsGroup>
+ {all ? (
+ <SettingsGroup title="Background computer use">
+ <Suspense fallback={<div className="h-48" />}>
+ <DriverSettingsCard />
+ </Suspense>
+ </SettingsGroup>
+ ) : null}
+
+ <SettingsGroup title={view.providersTitle} footer={view.providersFooter} data-connectors-providers="">
+ {view.providers.map((p) => (
+ <ProviderRow key={p.id} row={p} addedLabel={view.addedLabel} c={c} />
+ ))}
+ {view.others.map((r) => (
+ <GroupedRow key={r.env} data-agent-key-row={r.env}>
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-mono text-[12px]">{r.title}</div>
+ <div className="truncate text-xs text-muted-foreground">{r.detail}</div>
+ </div>
+ <span className="font-mono text-[12px] text-muted-foreground">{r.status}</span>
+ <Button size="sm" variant="outline" disabled={!view.canEdit} onClick={() => keys.openSheet("other", r.env)}>
+ {r.actionLabel}
+ </Button>
+ {r.removeLabel ? (
+ <Button size="sm" variant="ghost" disabled={!view.canEdit} onClick={() => keys.askRemove(r.env)}>
+ {r.removeLabel}
+ </Button>
+ ) : null}
+ </GroupedRow>
+ ))}
+ <SettingsRow
+ label={view.addOtherLabel}
+ description={view.otherHelp}
+ control={
+ <Button size="sm" variant="outline" disabled={!view.canEdit} onClick={() => keys.openSheet("other")} data-agent-key-add-other="">
+ Add key
+ </Button>
+ }
+ />
+ </SettingsGroup>
+
+ {keys.sheet ? <KeySheet key={`${keys.sheet.provider}:${keys.sheet.env ?? ""}`} keys={keys} provider={keys.sheet.provider} env={keys.sheet.env} /> : null}
+ <ConfirmDialog
+ open={confirm !== null}
+ onOpenChange={(o) => !o && keys.askRemove(null)}
+ title={confirm?.title ?? ""}
+ description={confirm?.message ?? ""}
+ confirmLabel={confirm?.confirmLabel ?? "Remove"}
+ cancelLabel={confirm?.cancelLabel}
+ destructive
+ onConfirm={() => {
+ const env = keys.removing;
+ if (env) void keys.remove(env).catch(toastError("Couldn't remove the key"));
+ }}
+ />
+ </div>
+ );
+}
+
+/** A coding app: the whole row opens its page (hover, chevron); Connect works on its own. */
+function AppRow({ row, lit, onOpen, onConnect }: { row: ConnectorAppRow; lit: boolean; onOpen: () => void; onConnect: () => void }) {
+ const stop = (e: MouseEvent | KeyboardEvent) => e.stopPropagation();
+ return (
+ <div
+ role="link"
+ tabIndex={0}
+ aria-label={row.openLabel}
+ data-connector-app={row.agent}
+ data-state={row.state}
+ onClick={onOpen}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onOpen();
+ }
+ }}
+ className={cn(
+ "flex min-h-12 cursor-default items-center gap-3 px-4 py-2.5 text-[13px] outline-none transition-colors hover:bg-accent/50 focus-visible:bg-accent/50",
+ row.state === "failed" && "bg-destructive/5",
+ lit && "bg-accent",
+ )}
+ >
+ <HarnessMark agent={row.agent} name={row.name} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate">{row.name}</div>
+ {row.line ? (
+ <p className={cn("mt-px truncate text-xs", row.state === "failed" ? "text-destructive" : "text-muted-foreground")} data-connector-line="">
+ {row.line}
+ </p>
+ ) : null}
+ </div>
+ {row.connectedLabel ? (
+ <span className="flex items-center gap-1 text-[13px] text-muted-foreground" data-connector-connected="">
+ <CheckIcon className="size-3.5 text-success" /> {row.connectedLabel}
+ </span>
+ ) : null}
+ {row.button ? (
+ <Button size="sm" variant="outline" disabled={!row.button.enabled} data-connector-connect={row.button.id} onClick={(e) => (stop(e), onConnect())} onKeyDown={stop}>
+ {row.state === "connecting" ? <Loader2Icon className="animate-spin" /> : null}
+ {row.button.label}
+ </Button>
+ ) : null}
+ <ChevronRightIcon aria-hidden className="size-4 shrink-0 text-muted-foreground/70" data-connector-chevron="" />
+ </div>
+ );
+}
+
+function ProviderRow({ row, addedLabel, c }: { row: ConnectorProviderRow; addedLabel: string; c: Connectors }) {
+ const connected = row.state === "connected";
+ return (
+ <GroupedRow data-connector-provider={row.id} data-state={row.state} className="min-h-12">
+ <div className="min-w-0 flex-1">
+ <div className="truncate">{row.label}</div>
+ <div className="truncate text-xs text-muted-foreground">{row.detail}</div>
+ </div>
+ <div className="flex shrink-0 flex-col items-end">
+ <span className={cn("flex items-center gap-1.5 text-[13px]", connected ? "" : row.state === "failed" ? "text-destructive" : "text-muted-foreground")} data-connector-status="">
+ {row.state === "connecting" ? <Loader2Icon className="size-3.5 animate-spin" /> : connected ? <CheckIcon className="size-3.5 text-success" /> : null}
+ {row.status}
+ </span>
+ {row.addedMs !== null ? <span className="text-[11px] text-muted-foreground">{addedText(addedLabel, row.addedMs)}</span> : null}
+ </div>
+ <Button
+ size="sm"
+ variant={connected ? "ghost" : "outline"}
+ disabled={!row.button.enabled}
+ data-connector-provider-action={row.button.id}
+ onClick={() => (row.button.id === "sign-out" ? void c.signOut(row.id) : c.openProvider(row.id))}
+ >
+ {row.button.label}
+ </Button>
+ </GroupedRow>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/settings/connectors/provider-sheet.tsx b/apps/cua-spaces-web/src/components/settings/connectors/provider-sheet.tsx
new file mode 100644
index 0000000000..1564fa29b5
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/settings/connectors/provider-sheet.tsx
@@ -0,0 +1,189 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { CheckIcon, ChevronLeftIcon, ChevronRightIcon, CopyIcon, KeyRoundIcon, Loader2Icon, LogInIcon, SmartphoneIcon, TerminalIcon } from "lucide-react";
+import { useState } from "react";
+
+import type { ProviderWay } from "@/bridge";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { useSession } from "@/bridge";
+import { closeDeviceSignIn, useConnectors, useDeviceSignIn, useProviderSheetOpen } from "@/hooks/use-connectors";
+
+const ICON = { "app-token": LogInIcon, "app-device": SmartphoneIcon, key: KeyRoundIcon, shell: TerminalIcon } as const;
+
+/**
+ * "Connect <provider>": the ways the core offers (`connectors.providerSheet`),
+ * one row each, then the key field when Paste an API key is picked. Opened
+ * from Providers, from an app's page, and from an app's Connect when the app
+ * has no sign-in command of its own. Mounted once, beside Share.
+ */
+export function ProviderSheetHost() {
+ const device = useDeviceSignIn();
+ const open = useProviderSheetOpen();
+ if (device) return <DeviceCodeSheet />;
+ return open ? <ProviderSheet /> : null;
+}
+
+/**
+ * A device-code sign-in (Codex with ChatGPT): the one-time code, Copy, and
+ * the page to enter it on. The sheet closes by itself once it's approved;
+ * the sign-in was made for Cua in a folder Cua owns.
+ */
+function DeviceCodeSheet() {
+ const device = useDeviceSignIn();
+ const { openExternal } = useSession();
+ const [copied, setCopied] = useState(false);
+ if (!device) return null;
+ return (
+ <Dialog open onOpenChange={(o) => !o && closeDeviceSignIn()}>
+ <DialogPopup data-device-sign-in={device.app} className="top-[12vh] w-[min(440px,calc(100vw-2rem))]">
+ <div className="px-6 pt-5 pb-5">
+ <DialogTitle className="text-[15px] font-semibold">Sign in with ChatGPT</DialogTitle>
+ <DialogDescription className="mt-1 text-[13px] text-muted-foreground">Enter this code on the sign-in page. It works once and expires in 15 minutes.</DialogDescription>
+ <div className="mt-4 flex items-center justify-between gap-3 rounded-lg bg-muted px-4 py-3">
+ <span data-device-code="" className="font-mono text-[20px] font-semibold tracking-[0.12em] select-all">
+ {device.code}
+ </span>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => {
+ void navigator.clipboard?.writeText(device.code).catch(() => undefined);
+ setCopied(true);
+ }}
+ >
+ {copied ? <CheckIcon /> : <CopyIcon />}
+ {copied ? "Copied" : "Copy"}
+ </Button>
+ </div>
+ <p className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
+ <Loader2Icon className="size-3.5 animate-spin" /> Waiting for you to enter it…
+ </p>
+ <div className="mt-4 flex justify-end gap-2">
+ <Button variant="outline" onClick={() => closeDeviceSignIn()}>
+ Close
+ </Button>
+ <Button data-device-open="" onClick={() => void openExternal(device.url).catch(() => {})}>
+ Open sign-in page
+ </Button>
+ </div>
+ </div>
+ </DialogPopup>
+ </Dialog>
+ );
+}
+
+function ProviderSheet() {
+ const c = useConnectors();
+ const v = c.sheet;
+ const [keyWay, setKeyWay] = useState<ProviderWay | null>(null);
+ const [value, setValue] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const close = () => {
+ setKeyWay(null);
+ setValue("");
+ setError(null);
+ c.closeProvider();
+ };
+ if (!v) return null;
+ const run = async (way: ProviderWay, typed?: string) => {
+ setBusy(true);
+ setError(null);
+ const ok = await c.runWay(way, typed);
+ setBusy(false);
+ if (ok) close();
+ else if (way.id === "key") setError("Couldn't save the key. Check it and try again.");
+ };
+ return (
+ <Dialog open onOpenChange={(o) => !o && close()}>
+ <DialogPopup data-provider-sheet={v.provider} className="top-[12vh] w-[min(520px,calc(100vw-2rem))]">
+ <div className="px-6 pt-5 pb-5">
+ {keyWay ? (
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (value.trim()) void run(keyWay, value);
+ }}
+ >
+ <DialogTitle className="flex items-center gap-1.5 text-[15px] font-semibold">
+ <button
+ type="button"
+ aria-label="Back"
+ onClick={() => setKeyWay(null)}
+ className="-ml-1.5 inline-flex size-6 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"
+ >
+ <ChevronLeftIcon className="size-4" />
+ </button>
+ {v.title}
+ </DialogTitle>
+ <DialogDescription className="mt-1 text-[13px] text-muted-foreground">{keyWay.help}</DialogDescription>
+ <label className="mt-4 block">
+ <span className="mb-1 block text-xs font-medium">{v.keyLabel}</span>
+ <Input
+ type="password"
+ autoFocus
+ data-provider-key=""
+ value={value}
+ placeholder={v.keyPlaceholder}
+ autoComplete="off"
+ spellCheck={false}
+ className="font-mono"
+ onChange={(e) => setValue(e.currentTarget.value)}
+ />
+ </label>
+ <p className="mt-1.5 text-xs text-muted-foreground">{v.keyHelp}</p>
+ {error ? <p className="mt-2 text-[13px] text-destructive">{error}</p> : null}
+ <div className="mt-4 flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={close}>
+ {v.cancelLabel}
+ </Button>
+ <Button type="submit" disabled={busy || !value.trim()} data-provider-save="">
+ {v.saveLabel}
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <>
+ <DialogTitle className="text-[15px] font-semibold" data-provider-sheet-title="">
+ {v.title}
+ </DialogTitle>
+ <DialogDescription className="mt-1 text-[13px] text-muted-foreground">{v.lede}</DialogDescription>
+ <div className="mt-3">
+ {v.ways.map((w) => {
+ const Icon = ICON[w.id];
+ return (
+ <button
+ key={w.id}
+ type="button"
+ data-provider-way={w.id}
+ disabled={busy}
+ onClick={() => (w.id === "key" ? setKeyWay(w) : void run(w))}
+ className="-mx-2 flex w-[calc(100%+1rem)] cursor-default items-center gap-3 rounded-lg px-2 py-2.5 text-left outline-none hover:bg-accent focus-visible:bg-accent disabled:opacity-50"
+ >
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
+ <Icon className="size-3.5" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-[13px]">{w.label}</span>
+ <span className="block text-xs text-muted-foreground">{w.help}</span>
+ </span>
+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground/60" />
+ </button>
+ );
+ })}
+ </div>
+ <div className="mt-4 flex justify-end">
+ <Button variant="outline" onClick={close}>
+ {v.cancelLabel}
+ </Button>
+ </div>
+ </>
+ )}
+ </div>
+ </DialogPopup>
+ </Dialog>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/settings/runtime-rows.tsx b/apps/cua-spaces-web/src/components/settings/runtime-rows.tsx
new file mode 100644
index 0000000000..52e762f058
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/settings/runtime-rows.tsx
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { useEffect, useRef, useState } from "react";
+
+import { useBridge, type RuntimePathCheck, type RuntimePathVerdict, type SettingsRow, type SettingsSection } from "@/bridge";
+import { Button } from "@/components/ui/button";
+import { GroupedRow } from "@/components/ui/grouped";
+import { Input } from "@/components/ui/input";
+import { Select } from "@/components/ui/select";
+import { CoreSettingsRow } from "@/components/settings/core-section";
+import { cn } from "@/lib/utils";
+
+/** How long typing pauses before the path is checked. */
+const CHECK_DELAY_MS = 300;
+
+/**
+ * Settings, Advanced: one row per kind of Space (Containers, Virtual
+ * machines, MicroVMs), as the app core lays them out
+ * (`settings::runtimes_section`). The core decides the labels, the options,
+ * "Not available" and its reason, the runtimes found on this computer and
+ * whether the path in use is the detected one or a custom one; this draws
+ * them, and checks a path while it is typed (the host probes it, the core
+ * words the result).
+ */
+export function RuntimeKindRows({ section, onChoose }: { section: SettingsSection; onChoose: (row: SettingsRow, option: string) => void }) {
+ const byId = new Map(section.rows.map((r) => [r.id, r]));
+ const kinds = section.rows.filter((r) => r.id.startsWith("runtime:")).map((r) => r.id.slice("runtime:".length));
+ return (
+ <>
+ {kinds.map((kind) => (
+ <RuntimeKind key={kind} kind={kind} rows={byId} onChoose={onChoose} />
+ ))}
+ </>
+ );
+}
+
+function RuntimeKind({ kind, rows, onChoose }: { kind: string; rows: Map<string, SettingsRow>; onChoose: (row: SettingsRow, option: string) => void }) {
+ const main = rows.get(`runtime:${kind}`)!;
+ const detected = rows.get(`runtime-detected:${kind}`);
+ const path = rows.get(`runtime-path:${kind}`);
+ const check = rows.get(`runtime-check:${kind}`);
+ return (
+ <div data-runtime-kind={kind}>
+ {main.kind === "choice" ? (
+ <CoreSettingsRow row={main} asSelect description={main.help ?? undefined} onChoose={onChoose} />
+ ) : (
+ <CoreSettingsRow row={{ ...main, help: null }} description={main.help ?? undefined} />
+ )}
+ {detected || path ? (
+ <div data-runtime-installed={kind} className="pb-2">
+ {detected ? <DetectedRow row={detected} onChoose={onChoose} /> : null}
+ {path ? <PathRow kind={kind} row={path} check={check} onChoose={onChoose} /> : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+/** The runtimes found for this kind (name, path, version), or why none is listed. */
+function DetectedRow({ row, onChoose }: { row: SettingsRow; onChoose: (row: SettingsRow, option: string) => void }) {
+ const attrs = { "data-setting-row": row.id, "data-kind": row.kind };
+ if (row.kind !== "choice") {
+ return (
+ <div {...attrs} className="px-4 pl-8 pt-0.5 pb-1.5 text-xs text-muted-foreground">
+ <span data-row-label>{row.label}</span>
+ </div>
+ );
+ }
+ // A custom path matches none of them: the drop-down then says Custom.
+ const value = row.options.find((o) => o.active)?.id ?? "";
+ const options = [...(value ? [] : [{ value: "", label: "Custom" }]), ...row.options.map((o) => ({ value: o.id, label: o.label }))];
+ return (
+ <GroupedRow {...attrs} className="justify-between gap-6 py-1.5 pl-8">
+ <span className="text-[13px] text-muted-foreground" data-row-label>
+ {row.label}
+ </span>
+ <Select aria-label={row.label} className="max-w-[26rem] min-w-64" value={value} options={options} disabled={!row.enabled} onValueChange={(v) => v && onChoose(row, v)} />
+ </GroupedRow>
+ );
+}
+
+/**
+ * The binary that will be used, autofilled from detection: type or browse
+ * to another one (checked as it is typed, saved on Enter or when the field
+ * is left); "Reset to detected" goes back to the detected one.
+ */
+function PathRow({ kind, row, check, onChoose }: { kind: string; row: SettingsRow; check?: SettingsRow; onChoose: (row: SettingsRow, option: string) => void }) {
+ const { core, data } = useBridge();
+ const saved = row.value ?? "";
+ const [draft, setDraft] = useState(saved);
+ const [live, setLive] = useState<RuntimePathVerdict | null>(null);
+ const savedRef = useRef(saved);
+ useEffect(() => {
+ savedRef.current = saved;
+ setDraft(saved);
+ setLive(null);
+ }, [saved]);
+ const editing = draft.trim() !== saved;
+ useEffect(() => {
+ if (!editing || !data) return;
+ const path = draft.trim();
+ if (!path) {
+ setLive(null);
+ return;
+ }
+ let stale = false;
+ const t = setTimeout(() => {
+ void data
+ .call("runtimes.check", { kind, path })
+ .then((probe: RuntimePathCheck) => {
+ if (stale) return;
+ setLive(core.tryCall<RuntimePathVerdict>("settings.runtimePathVerdict", { kind, check: probe }) ?? null);
+ })
+ .catch(() => {
+ if (!stale) setLive(null);
+ });
+ }, CHECK_DELAY_MS);
+ return () => {
+ stale = true;
+ clearTimeout(t);
+ };
+ }, [draft, editing, kind, data, core]);
+ const commit = (value: string) => {
+ if (value.trim() !== savedRef.current) onChoose(row, value.trim());
+ };
+ const browse = async () => {
+ if (!data) return;
+ const picked = await data.call("runtimes.browse", { kind }).catch(() => null);
+ if (picked?.path) {
+ setDraft(picked.path);
+ commit(picked.path);
+ }
+ };
+ // The state badge: what the core says of the saved path, or Custom while another is typed.
+ const state = editing ? "Custom" : row.label;
+ const verdict = editing ? live : check ? { ok: check.kind !== "error", line: check.label } : null;
+ const id = `setting-${row.id.replace(/[^a-z0-9-]/gi, "-")}`;
+ return (
+ <div data-setting-row={row.id} data-kind={row.kind} data-runtime-state={state.toLowerCase()} className="px-4 pl-8 pt-1">
+ <div className="flex items-center gap-2">
+ <label htmlFor={id} className="w-16 shrink-0 text-[13px] text-muted-foreground" data-row-label>
+ {state}
+ </label>
+ <Input
+ id={id}
+ className="h-7 min-w-0 flex-1 font-mono text-xs"
+ autoComplete="off"
+ spellCheck={false}
+ value={draft}
+ placeholder={row.placeholder ?? undefined}
+ disabled={!row.enabled}
+ onChange={(e) => setDraft(e.currentTarget.value)}
+ onBlur={() => commit(draft)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") commit(draft);
+ if (e.key === "Escape") setDraft(saved);
+ }}
+ />
+ <Button size="sm" variant="outline" disabled={!row.enabled || !data} onClick={() => void browse()} data-runtime-browse>
+ Browse…
+ </Button>
+ </div>
+ <div className="flex min-h-6 items-center justify-between gap-3 pl-[4.5rem]">
+ {verdict ? (
+ <span data-runtime-check={verdict.ok ? "ok" : "bad"} className={cn("text-xs", verdict.ok ? "text-muted-foreground" : "text-destructive")}>
+ {verdict.line}
+ </span>
+ ) : (
+ <span />
+ )}
+ {row.button && !editing ? (
+ <button type="button" className="shrink-0 text-xs text-brand-strong hover:underline" onClick={() => onChoose(row, "")} data-row-button>
+ {row.button}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/space-sheets.tsx b/apps/cua-spaces-web/src/components/space-sheets.tsx
index 79b5f320d4..ba3316ecd3 100644
--- a/apps/cua-spaces-web/src/components/space-sheets.tsx
+++ b/apps/cua-spaces-web/src/components/space-sheets.tsx
@@ -4,11 +4,13 @@
import { lazy, Suspense } from "react";
import { useShareSheet, useTeleport } from "@/bridge";
+import { ProviderSheetHost } from "@/components/settings/connectors/provider-sheet";
const TeleportDialog = lazy(() => import("./teleport/teleport-dialog"));
const ShareSheet = lazy(() => import("./share-sheet"));
-/** The sheets a Space opens from anywhere: "Teleport an app" and "Share".
+/** The sheets a Space opens from anywhere: "Teleport an app", "Share" and
+ * a provider's Connect (Settings, an app's page, or a Space's "isn't connected yet").
* Each loads when first opened. */
export function SpaceSheets() {
const teleport = useTeleport();
@@ -17,6 +19,7 @@ export function SpaceSheets() {
<Suspense fallback={null}>
{teleport.session ? <TeleportDialog /> : null}
{share.session ? <ShareSheet /> : null}
+ <ProviderSheetHost />
</Suspense>
);
}
diff --git a/apps/cua-spaces-web/src/components/space-thread/composer.tsx b/apps/cua-spaces-web/src/components/space-thread/composer.tsx
index 98e6a78b7d..3ebe38cd19 100644
--- a/apps/cua-spaces-web/src/components/space-thread/composer.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/composer.tsx
@@ -149,9 +149,11 @@ export function Composer({
onMouseEnter={() => setPicked(i)}
className={cn("flex h-9 cursor-default items-center gap-2.5 rounded-lg px-2 text-[13px]", i === index && "bg-accent")}
>
- <MemberAvatar kind={c.kind} name={c.label} harness={c.kind === "agent" ? agentHarness(c.handle) : ""} size={24} />
+ <MemberAvatar kind={c.kind} name={c.label} harness={c.kind === "agent" ? (c.harness ?? agentHarness(c.handle)) : ""} size={24} />
<span className="min-w-0 flex-1 truncate">{c.label}</span>
- <span className="text-xs text-muted-foreground">@{c.handle}</span>
+ <span className="text-xs text-muted-foreground" data-mention-detail={c.detail ? "" : undefined}>
+ {c.detail ?? `@${c.handle}`}
+ </span>
</div>
))}
</div>
diff --git a/apps/cua-spaces-web/src/components/space-thread/identity.tsx b/apps/cua-spaces-web/src/components/space-thread/identity.tsx
index 6774d5f0bb..f9fb581ed6 100644
--- a/apps/cua-spaces-web/src/components/space-thread/identity.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/identity.tsx
@@ -10,8 +10,6 @@
* those two as checked by Cua.
*/
-import { Popover } from "@base-ui/react/popover";
-import { useNavigate } from "@tanstack/react-router";
import { ShieldCheckIcon } from "lucide-react";
import { useState, type ReactNode } from "react";
@@ -22,6 +20,7 @@ import { cn } from "@/lib/utils";
import { AgentTile, PersonDot, type AvatarSurface } from "./avatar";
import { harnessLabel } from "./harness-marks";
+import { ProfileTrigger } from "./profile-card";
import { RIGHT_ROWS } from "./rights";
import type { Roster, RosterAgent, RosterAuthor } from "./roster";
@@ -214,38 +213,12 @@ export function ProvenanceCard({
export function AgentName({ who, roster, onRemove, size = "md" }: { who: RosterAuthor; roster: Roster; onRemove?: (handle: string) => Promise<void>; size?: "md" | "sm" }) {
const i = who.identity;
const text = cn("min-w-0 truncate font-semibold", size === "md" ? "text-[13px]" : "text-[12.5px]");
- const may = !!onRemove && !!i && !!who.agent && roster.canRemove(i);
- const [open, setOpen] = useState(false);
- const navigate = useNavigate();
return (
<span className="flex min-w-0 items-center gap-1.5">
{i ? (
- <Popover.Root open={open} onOpenChange={setOpen}>
- <Popover.Trigger
- openOnHover
- delay={350}
- data-author-name={who.handle}
- className={cn(text, "cursor-default rounded-[4px] outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring/60")}
- >
- {who.label}
- </Popover.Trigger>
- <Popover.Portal>
- <Popover.Positioner side="bottom" align="start" sideOffset={6} className="z-[70]">
- <Popover.Popup data-video-occluder="" className="w-[300px] rounded-lg bg-popover text-popover-foreground shadow-float outline-none">
- <ProvenanceCard
- identity={i}
- agent={who.agent}
- roster={roster}
- onRemove={may ? () => onRemove(i.handle).then(() => setOpen(false)) : undefined}
- onActivity={() => {
- setOpen(false);
- void navigate({ to: "/agents", search: { agent: identityKey(i) } });
- }}
- />
- </Popover.Popup>
- </Popover.Positioner>
- </Popover.Portal>
- </Popover.Root>
+ <ProfileTrigger identity={i} agent={who.agent} roster={roster} onRemove={onRemove} className={cn(text, "hover:underline")} data={{ "data-author-name": who.handle ?? i.handle }}>
+ {who.label}
+ </ProfileTrigger>
) : (
<span className={text}>{who.label}</span>
)}
diff --git a/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx b/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx
index 624afdcb1f..64c99d1374 100644
--- a/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx
@@ -13,9 +13,10 @@ import { cn } from "@/lib/utils";
import { MemberAvatar } from "./avatar";
import { AiTag, OwnerSuffix } from "./identity";
+import { ProfileTrigger } from "./profile-card";
import { RAIL_WINDOWS, railStreams } from "./rail";
import { holderChoice, holdersLabel, RIGHT_ROWS, type HolderChoice } from "./rights";
-import type { Roster, RosterAgent } from "./roster";
+import type { Roster, RosterAgent, RosterPerson } from "./roster";
/** Who is here right now (P2: relay presence and session states). Without
* it no dot is drawn: P1 never guesses. */
@@ -38,17 +39,11 @@ export function MembersPanel({
onStream,
folded,
onFold,
- onSetRights,
- onRemoveAgent,
onAddAgent,
}: {
roster: Roster;
/** Opens Add an agent (absent for guests). */
onAddAgent?: () => void;
- /** Removes an agent member (absent: the host can't); shown only to who may. */
- onRemoveAgent?: (name: string) => Promise<void>;
- /** Changes an agent's rights; absent when you can't (only the owner and admins can). */
- onSetRights?: (name: string, rights: Partial<AgentRights>) => Promise<void>;
presence?: MemberPresence;
/** The first few of the core's facts; More opens the rest. */
facts: SpaceFact[];
@@ -66,7 +61,6 @@ export function MembersPanel({
folded: boolean;
onFold: (folded: boolean) => void;
}) {
- const [opened, setOpened] = useState<string | null>(null);
if (folded) {
return (
<aside data-members-panel="folded" className="flex w-12 shrink-0 flex-col items-center gap-2.5 bg-chrome py-3">
@@ -111,11 +105,13 @@ export function MembersPanel({
</div>
<ul className="min-h-0 flex-1 overflow-y-auto px-3 pb-3" data-members="">
{roster.people.map((p) => (
- <Row key={p.id} member={p.id} mark={<MemberAvatar kind="person" name={p.label} size={24} presence={presence?.[p.id] ?? null} />} label={p.label} caption={p.me ? "You" : null} />
+ <ProfileRow key={p.id} person={p}>
+ <Row member={p.id} mark={<MemberAvatar kind="person" name={p.label} size={24} presence={presence?.[p.id] ?? null} />} label={p.label} caption={p.me ? "You" : null} />
+ </ProfileRow>
))}
{roster.agents.map((a) => (
+ <ProfileRow key={a.id} agent={a}>
<Row
- key={a.id}
member={a.id}
mark={<MemberAvatar kind="agent" name={a.name} harness={a.harness} identity={a.identity} surface="chrome" size={24} dim={a.dim} presence={presence?.[a.id] ?? null} />}
label={
@@ -128,11 +124,9 @@ export function MembersPanel({
caption={a.caption}
dim={a.dim}
status={a.status}
- open={opened === a.id}
- onToggle={() => setOpened(opened === a.id ? null : a.id)}
- >
- {opened === a.id ? <AgentRightsRows agent={a} onSetRights={onSetRights} onRemove={onRemoveAgent && roster.canRemove(a) ? () => onRemoveAgent(a.name) : undefined} /> : null}
- </Row>
+ chevron
+ />
+ </ProfileRow>
))}
</ul>
{windows.length || desktop ? (
@@ -245,6 +239,7 @@ function Row({
open,
onToggle,
children,
+ chevron,
}: {
member: string;
mark: ReactNode;
@@ -256,6 +251,8 @@ function Row({
open?: boolean;
onToggle?: () => void;
children?: ReactNode;
+ /** Opens a card (the row is inside its trigger). */
+ chevron?: boolean;
}) {
const body = (
<>
@@ -268,9 +265,10 @@ function Row({
);
if (!onToggle) {
return (
- <li data-member={member} data-member-status={status} className="flex min-h-10 items-center gap-2.5 rounded-lg px-2 py-1.5">
+ <span data-member={member} data-member-status={status} className="flex min-h-10 w-full items-center gap-2.5 rounded-lg px-2 py-1.5 hover:bg-accent">
{body}
- </li>
+ {chevron ? <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" /> : null}
+ </span>
);
}
return (
@@ -290,6 +288,22 @@ function Row({
);
}
+/** A row in "In this space" that opens its person's or agent's card. */
+function ProfileRow({ person, agent, children }: { person?: RosterPerson; agent?: RosterAgent; children: ReactNode }) {
+ return (
+ <li>
+ <ProfileTrigger person={person} agent={agent} side="left" className="block w-full rounded-lg">
+ {children}
+ </ProfileTrigger>
+ </li>
+ );
+}
+
+/** Who can task, stop and approve: the selects alone, for the agent card's Details. */
+export function RightsEditor({ agent, onSetRights }: { agent: RosterAgent; onSetRights: (name: string, rights: Partial<AgentRights>) => Promise<void> }) {
+ return <AgentRightsRows agent={agent} onSetRights={onSetRights} bare />;
+}
+
const CHOICES: readonly { value: HolderChoice; label: string }[] = [
{ value: "owner", label: "Owner" },
{ value: "admins", label: "Admins" },
@@ -298,7 +312,7 @@ const CHOICES: readonly { value: HolderChoice; label: string }[] = [
/** Who can task, stop and approve an agent: three plain rows under its name.
* The owner and admins change them; everyone else reads them. */
-function AgentRightsRows({ agent, onSetRights, onRemove }: { agent: RosterAgent; onSetRights?: (name: string, rights: Partial<AgentRights>) => Promise<void>; onRemove?: () => Promise<void> }) {
+function AgentRightsRows({ agent, onSetRights, onRemove, bare }: { agent: RosterAgent; onSetRights?: (name: string, rights: Partial<AgentRights>) => Promise<void>; onRemove?: () => Promise<void>; bare?: boolean }) {
const [busy, setBusy] = useState(false);
const remove = () => {
if (!onRemove) return;
@@ -312,7 +326,7 @@ function AgentRightsRows({ agent, onSetRights, onRemove }: { agent: RosterAgent;
);
};
return (
- <div data-agent-rights={agent.name} className="mb-1 ml-9 divide-y divide-border/60 border-y border-border/60">
+ <div data-agent-rights={agent.name} className={bare ? "" : "mb-1 ml-9 divide-y divide-border/60 border-y border-border/60"}>
{RIGHT_ROWS.map(({ right, label }) => {
const value = agent.rights[right];
const choice = holderChoice(value);
diff --git a/apps/cua-spaces-web/src/components/space-thread/profile-card.tsx b/apps/cua-spaces-web/src/components/space-thread/profile-card.tsx
new file mode 100644
index 0000000000..d304530c8e
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/space-thread/profile-card.tsx
@@ -0,0 +1,421 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The card a person or an agent opens to in a Space (redesign): their name
+ * or avatar in the thread, an @mention, a row in "In this space". One calm
+ * shape for both, like a chat app's profile card: who, their access or what
+ * runs them, their status, the few actions that apply, and for an agent the
+ * rest folded under Details. Every word is the core's (`profileCard.*`).
+ */
+
+import { Popover } from "@base-ui/react/popover";
+import { Link, useNavigate } from "@tanstack/react-router";
+import { CheckIcon, ChevronRightIcon, CopyIcon, Loader2Icon, PlugIcon } from "lucide-react";
+import { createContext, useContext, useState, type ReactNode } from "react";
+
+import { agentCard, personCard, useBridge, type AgentMember, type AgentRights, type MemberIdentity, type ShareEntry, type ThreadRole } from "@/bridge";
+import { Button } from "@/components/ui/button";
+import { Select } from "@/components/ui/select";
+import { toast } from "@/components/ui/toast";
+import { useConnectors } from "@/hooks/use-connectors";
+import { cn } from "@/lib/utils";
+
+import { AgentTile, PersonDot } from "./avatar";
+import { holdersName, identityKey, joinedHow, reportedHarness } from "./identity";
+import { RightsEditor } from "./members-panel";
+import { RIGHT_ROWS } from "./rights";
+import { personLabel, type Roster, type RosterAgent, type RosterPerson } from "./roster";
+
+/** What a Space's cards read: who it's shared with, your role, its agents, and what you may change. */
+export interface ProfileScope {
+ spaceId: string;
+ roster: Roster;
+ shares: readonly ShareEntry[];
+ members: readonly AgentMember[];
+ role: ThreadRole | null;
+ /** Your sign-in (`[email protected]`), for your own card's email. */
+ identity: string | null;
+ onRemoveAgent?: (name: string) => Promise<void>;
+ /** Changes who may task, stop and approve an agent (owners and admins). */
+ onSetRights?: (name: string, rights: Partial<AgentRights>) => Promise<void>;
+}
+
+const Scope = createContext<ProfileScope | null>(null);
+export const ProfileScopeProvider = Scope.Provider;
+export const useProfileScope = () => useContext(Scope);
+
+const canManage = (role: ThreadRole | null) => role === null || role === "owner" || role === "admin";
+
+/* ---- The shape both share ---------------------------------------------------- */
+
+function CardShell({
+ mark,
+ title,
+ badge,
+ sub,
+ children,
+ actions,
+ data,
+}: {
+ mark: ReactNode;
+ title: ReactNode;
+ badge?: ReactNode;
+ sub?: ReactNode;
+ children?: ReactNode;
+ actions?: ReactNode;
+ data: Record<string, string>;
+}) {
+ return (
+ <div className="w-[300px] p-4" {...data}>
+ <div className="flex items-center gap-3">
+ {mark}
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span className="truncate text-[14px] font-semibold" data-card-title="">
+ {title}
+ </span>
+ {badge}
+ </div>
+ {sub ? <div className="truncate text-xs text-muted-foreground">{sub}</div> : null}
+ </div>
+ </div>
+ {children ? <div className="mt-3 space-y-1.5 text-[12.5px]">{children}</div> : null}
+ {actions ? <div className="-mx-2 mt-3 flex flex-wrap items-center gap-1">{actions}</div> : null}
+ </div>
+ );
+}
+
+const Line = ({ children, muted, data }: { children: ReactNode; muted?: boolean; data?: string }) => (
+ <p data-card-line={data} className={cn("leading-snug", muted && "text-muted-foreground")}>
+ {children}
+ </p>
+);
+
+/* ---- People ------------------------------------------------------------------ */
+
+export function PersonCard({ person, onDone }: { person: RosterPerson; onDone?: () => void }) {
+ const { core, data } = useBridge();
+ const scope = useProfileScope();
+ const share = scope?.shares.find((s) => !s.who.startsWith("team:") && personLabel(s.who).toLowerCase() === person.label.toLowerCase());
+ const myRole = scope?.role ?? null;
+ const v = personCard(core, {
+ name: person.label,
+ who: person.me ? (scope?.identity ?? null) : (share?.who ?? null),
+ me: person.me,
+ access: person.me ? (myRole === null || myRole === "owner" ? "owner" : myRole === "admin" ? "editor" : myRole === "guest" ? "viewer" : "editor") : (share?.role ?? null),
+ // Which team someone is on isn't known to this device yet (only that a team is shared with): none shown.
+ team: null,
+ active: person.me || Boolean(share?.connected),
+ lastSeenMs: null,
+ nowMs: Date.now(),
+ canManage: canManage(myRole),
+ });
+ const [busy, setBusy] = useState(false);
+ if (!v) return null;
+ const act = (op: () => Promise<unknown>, failed: string) => {
+ setBusy(true);
+ op().then(
+ () => (setBusy(false), onDone?.()),
+ (e: unknown) => (setBusy(false), toast(failed, { description: e instanceof Error ? e.message : String(e), type: "error" })),
+ );
+ };
+ return (
+ <CardShell
+ data={{ "data-profile-card": "person", "data-profile": person.label }}
+ mark={<PersonDot name={person.label} px={40} />}
+ title={v.name}
+ badge={v.youLabel ? <span className="text-xs text-muted-foreground">{v.youLabel}</span> : null}
+ sub={v.email}
+ actions={
+ v.removeLabel ? (
+ <>
+ <span className="flex-1" />
+ {v.removeLabel && share && scope && data ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="text-destructive hover:text-destructive"
+ disabled={busy}
+ data-card-remove=""
+ onClick={() => act(() => data.call("sharing.unshare", { spaceId: scope.spaceId, who: share.who }), `Couldn't remove ${v.name}`)}
+ >
+ {v.removeLabel}
+ </Button>
+ ) : null}
+ </>
+ ) : null
+ }
+ >
+ {v.access ? (
+ <div className="flex min-h-7 items-center justify-between gap-3" data-card-access="">
+ <span className="text-muted-foreground">Access</span>
+ {v.changeAccessLabel && share && scope && data ? (
+ <Select<string>
+ aria-label={v.changeAccessLabel}
+ value={v.accessValue ?? "viewer"}
+ disabled={busy}
+ options={v.accessChoices}
+ onValueChange={(role) => act(() => data.call("sharing.share", { spaceId: scope.spaceId, who: share.who, role }), `Couldn't change ${v.name}'s access`)}
+ className="h-7 min-w-0 border-0 bg-muted px-2 text-[12.5px] shadow-none dark:bg-muted"
+ />
+ ) : (
+ <span>{v.access}</span>
+ )}
+ </div>
+ ) : null}
+ {v.team ? <Line muted>{v.team}</Line> : null}
+ {v.presence ? (
+ <p className="flex items-center gap-1.5" data-card-presence="">
+ <span className={cn("size-1.5 rounded-full", v.active ? "bg-success" : "bg-muted-foreground/40")} />
+ <span className={v.active ? "" : "text-muted-foreground"}>{v.presence}</span>
+ </p>
+ ) : null}
+ </CardShell>
+ );
+}
+
+/* ---- Agents ------------------------------------------------------------------ */
+
+export function AgentCard({ identity: i, agent, roster, onRemove, onDone }: { identity: MemberIdentity; agent?: RosterAgent; roster: Roster; onRemove?: () => Promise<void>; onDone?: () => void }) {
+ const { core } = useBridge();
+ const scope = useProfileScope();
+ const c = useConnectors();
+ const navigate = useNavigate();
+ const [open, setOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const member = scope?.members.find((m) => m.name === i.handle);
+ const harness = reportedHarness(i);
+ const v = agentCard(core, {
+ displayName: i.displayName,
+ handle: i.handle,
+ harness: i.harness.id,
+ harnessReported: harness,
+ ownerName: i.owner.name,
+ ownerId: i.owner.id,
+ ownerIsMe: roster.me !== null && i.owner.id === roster.me,
+ device: i.device?.name ?? null,
+ origin: i.origin,
+ status: member?.status ?? agent?.status ?? "",
+ activity: member?.activity ?? null,
+ joinedHow: joinedHow(i),
+ joinedAtMs: i.joined.atMs,
+ nowMs: Date.now(),
+ rights: agent
+ ? RIGHT_ROWS.map(({ right, label }) => ({
+ label: RIGHT_WORDS[right] ?? label,
+ holders: holdersName(agent.rights[right], i, roster),
+ }))
+ : [],
+ canRemove: Boolean(onRemove),
+ connectors: c.input,
+ });
+ if (!v) return null;
+ const connecting = v.app ? c.input.busy.some((b) => b.id === `app:${v.app}`) : false;
+ const remove = () => {
+ if (!onRemove) return;
+ setBusy(true);
+ onRemove().then(
+ () => (setBusy(false), onDone?.()),
+ (e: unknown) => (
+ setBusy(false),
+ toast(`Couldn't remove ${v.name}`, {
+ description: e instanceof Error ? e.message : String(e),
+ type: "error",
+ })
+ ),
+ );
+ };
+ return (
+ <CardShell
+ data={{ "data-profile-card": "agent", "data-profile": i.handle, "data-provenance": i.handle }}
+ mark={<AgentTile harness={i.harness.id} icon={i.icon} owner={i.owner} name={i.handle} px={40} surface="popover" />}
+ title={v.name}
+ badge={
+ <span data-card-badge="" className="rounded-lg bg-muted px-1.5 py-px text-[10.5px] font-medium text-muted-foreground">
+ {v.badge}
+ </span>
+ }
+ actions={
+ <>
+ {v.connectLabel && v.app ? (
+ <Button size="sm" variant="outline" className="ml-2" disabled={connecting} data-card-connect="" onClick={() => void c.connectApp(v.app!)}>
+ {connecting ? <Loader2Icon className="animate-spin" /> : <PlugIcon />}
+ {v.connectLabel}
+ </Button>
+ ) : null}
+ {v.settingsLabel && v.app ? (
+ <Button size="sm" variant="ghost" data-card-settings="" render={<Link to="/settings/connectors/$app" params={{ app: v.app }} />}>
+ {v.settingsLabel}
+ </Button>
+ ) : null}
+ <span className="flex-1" />
+ {v.removeLabel ? (
+ <Button size="sm" variant="ghost" className="text-destructive hover:text-destructive" disabled={busy} data-remove-agent={i.handle} onClick={remove}>
+ {busy ? "Removing…" : v.removeLabel}
+ </Button>
+ ) : null}
+ </>
+ }
+ >
+ <Line data="who">{v.line}</Line>
+ <p className="flex items-center gap-1.5" data-card-status={v.status}>
+ <span className={cn("size-1.5 shrink-0 rounded-full", v.status === "working" ? "bg-success" : v.status === "not-connected" ? "bg-warning" : "bg-muted-foreground/40")} />
+ <span className={cn("truncate", v.status === "idle" && "text-muted-foreground")}>{v.statusText}</span>
+ </p>
+ <div className="pt-1">
+ <button
+ type="button"
+ aria-expanded={open}
+ data-card-details=""
+ onClick={() => setOpen(!open)}
+ className="-ml-1 flex cursor-default items-center gap-1 rounded-lg px-1 py-0.5 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <ChevronRightIcon className={cn("size-3 transition-transform", open && "rotate-90")} /> {v.detailsLabel}
+ </button>
+ {open ? (
+ <dl className="mt-1.5 space-y-1" data-card-details-open="">
+ {v.details
+ .filter((d) => !(scope?.onSetRights && agent && canManage(scope.role) && RIGHT_LABELS.has(d.label)))
+ .map((d) => (
+ <div key={d.label} className="flex min-h-6 items-center justify-between gap-3 text-xs">
+ <dt className="shrink-0 text-muted-foreground">{d.label}</dt>
+ <dd className="flex min-w-0 items-center gap-1">
+ <span className={cn("truncate", d.copy && "font-mono text-[11px]")} title={d.value}>
+ {d.value}
+ </span>
+ {d.copy ? <IdCopy value={d.value} /> : null}
+ </dd>
+ </div>
+ ))}
+ {scope?.onSetRights && agent && canManage(scope.role) ? <RightsEditor agent={agent} onSetRights={scope.onSetRights} /> : null}
+ {/* Its tasks and posts with you, in the Agents tab. */}
+ <Button
+ size="sm"
+ variant="ghost"
+ className="-ml-2"
+ data-agent-activity={i.handle}
+ onClick={() => {
+ onDone?.();
+ void navigate({ to: "/agents", search: { agent: identityKey(i) } });
+ }}
+ >
+ Activity
+ </Button>
+ </dl>
+ ) : null}
+ </div>
+ </CardShell>
+ );
+}
+
+/** The rights, in the plain words the card's Details uses. */
+const RIGHT_WORDS: Record<string, string> = {
+ task: "Can give it tasks",
+ control: "Can stop it",
+ approve: "Can approve its steps",
+};
+const RIGHT_LABELS = new Set(Object.values(RIGHT_WORDS));
+
+function IdCopy({ value }: { value: string }) {
+ const [done, setDone] = useState(false);
+ return (
+ <button
+ type="button"
+ aria-label={done ? "Copied" : `Copy ${value}`}
+ data-card-id-copy=""
+ onClick={() => {
+ void navigator.clipboard?.writeText(value.replace(/^@/, "")).catch(() => undefined);
+ setDone(true);
+ setTimeout(() => setDone(false), 1200);
+ }}
+ className="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"
+ >
+ {done ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
+ </button>
+ );
+}
+
+/* ---- Where the cards open ------------------------------------------------------ */
+
+/**
+ * Opens the card of `person` or `agent` on click. Without a Space's scope
+ * (outside the redesigned Space page) a person has no card: the children
+ * draw as they are.
+ */
+export function ProfileTrigger({
+ person,
+ agent,
+ identity,
+ children,
+ className,
+ side = "bottom",
+ data,
+ roster: ownRoster,
+ onRemove,
+}: {
+ /** Where the page has no Space scope (the Agents tab): its roster and Remove. */
+ roster?: Roster;
+ onRemove?: (handle: string) => Promise<void>;
+ person?: RosterPerson;
+ agent?: RosterAgent;
+ identity?: MemberIdentity | null;
+ children: ReactNode;
+ className?: string;
+ side?: "bottom" | "left" | "top";
+ data?: Record<string, string>;
+}) {
+ const scope = useProfileScope();
+ const [open, setOpen] = useState(false);
+ const who = identity ?? agent?.identity ?? null;
+ if ((person && !scope) || (!person && !who)) return <>{children}</>;
+ const roster = scope?.roster ?? ownRoster;
+ const removeFn = scope?.onRemoveAgent ?? onRemove;
+ return (
+ <Popover.Root open={open} onOpenChange={setOpen}>
+ <Popover.Trigger
+ data-profile-trigger={person ? person.label : who!.handle}
+ className={cn("cursor-default rounded-lg text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/60", className)}
+ {...data}
+ >
+ {children}
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Positioner side={side} align="start" sideOffset={6} className="z-[70]">
+ <Popover.Popup data-video-occluder="" className="rounded-lg bg-popover text-popover-foreground shadow-float outline-none">
+ {person ? (
+ <PersonCard person={person} onDone={() => setOpen(false)} />
+ ) : roster ? (
+ <AgentCard
+ identity={who!}
+ agent={agent ?? roster.agents.find((a) => a.name === who!.handle)}
+ roster={roster}
+ onRemove={removeFn && roster.canRemove(who!) ? () => removeFn(who!.handle) : undefined}
+ onDone={() => setOpen(false)}
+ />
+ ) : null}
+ </Popover.Popup>
+ </Popover.Positioner>
+ </Popover.Portal>
+ </Popover.Root>
+ );
+}
+
+/** An @mention chip that opens its member's card (a plain chip when it is nobody here yet). */
+export function MentionChip({ handle, children }: { handle: string; children: ReactNode }) {
+ const scope = useProfileScope();
+ const chip = (
+ <span data-mention={handle} className="font-medium text-brand-strong">
+ {children}
+ </span>
+ );
+ if (!scope) return chip;
+ const agent = scope.roster.agents.find((a) => a.name.toLowerCase() === handle);
+ const person = agent ? undefined : scope.roster.people.find((p) => p.label.toLowerCase().replace(/\s+/g, "") === handle);
+ if (!agent?.identity && !person) return chip;
+ return (
+ <ProfileTrigger agent={agent} person={person} className="hover:underline">
+ {chip}
+ </ProfileTrigger>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/space-thread/queued.ts b/apps/cua-spaces-web/src/components/space-thread/queued.ts
new file mode 100644
index 0000000000..fd6615c1f3
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/space-thread/queued.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Messages written to a Space that is still being made: Ask first's job
+ * (`@claude <job>`) and anything typed in its composer meanwhile. They show
+ * in the thread as ordinary messages that "send when the Space is ready";
+ * once the Space exists they are sent in order, through the same summon as
+ * any message, and each leaves the queue as it is posted.
+ */
+
+import { useMemo } from "react";
+import { create } from "zustand";
+
+import type { SpaceThread, ThreadEntry, ThreadItem } from "@/bridge";
+
+interface Queued {
+ id: string;
+ text: string;
+ tsMs: number;
+}
+
+const useQueue = create<{ byPending: Record<string, Queued[]>; resolved: Record<string, string> }>(() => ({ byPending: {}, resolved: {} }));
+
+let n = 0;
+
+/** Queues `text` for the Space being made under `pendingId`. */
+export function enqueue(pendingId: string, text: string): void {
+ const q: Queued = { id: `q${++n}`, text: text.trim(), tsMs: Date.now() };
+ if (!q.text) return;
+ useQueue.setState((s) => ({ byPending: { ...s.byPending, [pendingId]: [...(s.byPending[pendingId] ?? []), q] } }));
+}
+
+/** The create finished: `pendingId` is `spaceId` now (its queue shows there until sent). */
+export function resolveQueue(pendingId: string, spaceId: string): void {
+ useQueue.setState((s) => ({ resolved: { ...s.resolved, [pendingId]: spaceId } }));
+}
+
+/** Sends the queue of `pendingId` in order; each message leaves it once posted. Safe to call twice. */
+export async function flushQueue(pendingId: string, send: (text: string) => Promise<void>): Promise<void> {
+ for (;;) {
+ const next = useQueue.getState().byPending[pendingId]?.[0];
+ if (!next) return;
+ // Taken before sending, so a second flusher never sends it again.
+ useQueue.setState((s) => ({ byPending: { ...s.byPending, [pendingId]: (s.byPending[pendingId] ?? []).filter((q) => q.id !== next.id) } }));
+ await send(next.text);
+ }
+}
+
+/** Tests start clean. */
+export function resetQueued(): void {
+ useQueue.setState({ byPending: {}, resolved: {} });
+}
+
+/** A queued message as a thread message from you (negative seqs: never a real entry's). */
+function entryOf(q: Queued, i: number, me: string, name = ""): ThreadEntry {
+ return {
+ seq: -1 - i,
+ id: q.id,
+ tsMs: q.tsMs,
+ author: { kind: "person", id: me, name },
+ kind: "message",
+ text: q.text,
+ mentions: [],
+ replyTo: null,
+ task: null,
+ attachments: [],
+ approval: null,
+ answer: null,
+ noteFor: null,
+ update: null,
+ runsOnKeysOf: null,
+ event: null,
+ } as ThreadEntry;
+}
+
+/** The queued messages that belong to `spaceId` (its own pending id, or a pending id that became it). */
+export function useQueued(spaceId: string): Queued[] {
+ const { byPending, resolved } = useQueue();
+ return useMemo(() => Object.entries(byPending).flatMap(([pending, qs]) => (pending === spaceId || resolved[pending] === spaceId ? qs : [])), [byPending, resolved, spaceId]);
+}
+
+/** Queued messages as thread items. */
+export const queuedItems = (qs: readonly Queued[], me: string, name: string): ThreadItem[] =>
+ qs.map((q, i) => ({ type: "message" as const, key: `queued:${q.id}`, entry: entryOf(q, i, me, name) }));
+
+/**
+ * The thread of a Space still being made: empty (its queued messages are
+ * drawn by the page, `useQueued`), and a composer that queues more. No
+ * members, shares or agents until it exists.
+ */
+export function creatingThread(pendingId: string): SpaceThread {
+ return {
+ status: "ready",
+ items: [],
+ entries: [],
+ members: [],
+ shares: [],
+ me: "me",
+ role: null,
+ error: null,
+ hasMoreBefore: false,
+ loadEarlier: async () => {},
+ post: async (text) => (enqueue(pendingId, text), null),
+ answer: async () => {},
+ setRights: async () => {},
+ removeAgent: null,
+ };
+}
diff --git a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx b/apps/cua-spaces-web/src/components/space-thread/space-call.tsx
index 761a122f5c..cdcf2b3b6e 100644
--- a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/space-call.tsx
@@ -9,7 +9,7 @@ import { Minimize2Icon } from "lucide-react";
import { Tooltip } from "@/components/ui/tooltip";
import { isMacPlatform } from "@/lib/utils";
-import { harnessName, useBridge, type SpaceFact, type SpaceThread, type StreamRow, type ThreadAttachment, type ThreadView as PostView } from "@/bridge";
+import { harnessName, queuedNote, summonPlan, useBridge, type SpaceFact, type SpaceThread, type StreamRow, type ThreadAttachment, type ThreadView as PostView } from "@/bridge";
import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";
import { toast } from "@/components/ui/toast";
@@ -24,6 +24,9 @@ import type { SpaceLayout } from "./layout-mode";
import { MiniPlayer } from "./mini-player";
import { GUEST_COMPOSER } from "./rights";
import { buildRoster } from "./roster";
+import { dismissWakeNote, OnlyYou, useSummon, useWakeNotes, WakeNoteView } from "./summon";
+import { ProfileScopeProvider } from "./profile-card";
+import { queuedItems, useQueued } from "./queued";
import { ThreadView } from "./thread-view";
@@ -56,6 +59,7 @@ export function SpaceCall({
smallStage,
aspect = 16 / 10,
stageLabel = "Desktop",
+ creating = false,
}: {
/** Call mode (the desktop is the main area) or thread mode (the thread is, and the desktop shrinks). */
layout?: SpaceLayout;
@@ -93,6 +97,8 @@ export function SpaceCall({
presence?: MemberPresence;
/** Opens Share for this Space (Add an agent offers it; absent: sharing isn't offered here). */
onShare?: () => void;
+ /** The Space is still being made: the composer queues, nothing joins yet (`thread` is `creatingThread`). */
+ creating?: boolean;
}) {
const { core, data } = useBridge();
const [folded, setFolded] = useState(false);
@@ -103,9 +109,9 @@ export function SpaceCall({
[thread.members, thread.shares, thread.entries, thread.me, thread.role, identity, core],
);
// Anyone who can post can add an agent; a guest only reads.
- const canAddAgent = thread.status === "ready" && thread.role !== "guest";
+ const canAdd = !creating && thread.status === "ready" && thread.role !== "guest";
// Share's "Add an agent" opens this page's sheet for this Space.
- useEffect(() => (canAddAgent ? registerAddAgent(spaceId, () => setAddOpen(true)) : undefined), [canAddAgent, spaceId]);
+ useEffect(() => (canAdd ? registerAddAgent(spaceId, () => setAddOpen(true)) : undefined), [canAdd, spaceId]);
const [reserve, setReserve] = useState(0);
const threadMode = layout === "thread" && Boolean(smallStage);
// ⌘⇧T (Ctrl+Shift+T): thread view and back.
@@ -121,7 +127,47 @@ export function SpaceCall({
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [layout, onLayout]);
- const harnessOf = (handle: string) => roster.agents.find((a) => a.name === handle)?.harness ?? "";
+ // @ any agent: those in the Space and those that can start in it; sending summons them (`summon.*`).
+ const summon = useSummon({ spaceId, thread, roster, canAdd: canAdd || creating });
+ const notes = useWakeNotes(spaceId);
+ const shown = useMemo(() => ({ ...roster, handles: summon.handles }), [roster, summon.handles]);
+ const noteView = (n: NonNullable<typeof notes>[number]) => (
+ <WakeNoteView
+ key={n.id}
+ note={n}
+ connected={(summonPlan(core, { members: [], people: [], canAdd: true, connectors: summon.connectors.input }, `@${n.cant.handle}`) ?? []).every((s) => s.action !== "blocked")}
+ onConnect={() => void summon.connectAndRetry(n, summon.connectors)}
+ onRetry={() => void summon.retry(n)}
+ onDismiss={() => dismissWakeNote(spaceId, n.id)}
+ />
+ );
+ // Messages written while the Space was being made: queued until it's ready, then sent in order.
+ const queued = useQueued(spaceId);
+ const myName = roster.people.find((p) => p.me)?.label ?? "";
+ const queuedLine = queuedNote(core, creating);
+ const items = useMemo(() => [...thread.items, ...queuedItems(queued, thread.me ?? "me", myName)], [thread.items, thread.me, queued, myName]);
+ const after = (seq: number) =>
+ seq < 0 ? (
+ <div data-queued-note="" data-only-you="" className="-mt-0.5 mb-1 ml-11 w-fit rounded-lg bg-brand-surface px-2.5 py-1.5">
+ <OnlyYou label={queuedLine?.onlyYouLabel ?? ""} />
+ <p className="text-xs text-muted-foreground">{queuedLine?.text}</p>
+ </div>
+ ) : (
+ notes?.filter((n) => n.seq === seq).map(noteView)
+ );
+ // The person and agent cards read the Space from here (names, avatars, mentions, the rail).
+ // The owner and admins change agents' rights (a daemon that does not say your role: you are its owner).
+ const scope = {
+ spaceId,
+ roster: shown,
+ shares: thread.shares,
+ members: thread.members,
+ role: thread.role,
+ identity,
+ onRemoveAgent: thread.removeAgent ?? undefined,
+ onSetRights: thread.role === null || thread.role === "owner" || thread.role === "admin" ? thread.setRights : undefined,
+ };
+ const harnessOf = (handle: string) => roster.agents.find((a) => a.name === handle)?.harness ?? summon.candidates.find((c) => c.handle === handle)?.harness ?? "";
// Attachments are Cua Volume paths: show the file where the Volume is mounted.
const openAttachment = (a: ThreadAttachment) => {
if (!data) return;
@@ -133,8 +179,10 @@ export function SpaceCall({
<ThreadView
className="min-h-0 flex-1"
endInset={endInset}
- items={thread.items}
- roster={roster}
+ items={items}
+ roster={shown}
+ after={after}
+ tail={notes?.filter((n) => n.seq === null).map(noteView)}
onAnswer={thread.answer}
onOpenAttachment={openAttachment}
onRemoveAgent={thread.removeAgent ?? undefined}
@@ -154,10 +202,10 @@ export function SpaceCall({
<div className="px-5 pb-4">
<Composer
placeholder={`Message ${spaceName}`}
- candidates={roster.candidates}
- handles={roster.handles}
+ candidates={summon.candidates}
+ handles={summon.handles}
agentHarness={harnessOf}
- onSend={(text) => thread.post(text, view ?? null)}
+ onSend={(text) => (creating ? thread.post(text).then(() => undefined) : summon.send(text, view ?? null))}
disabled={thread.status !== "ready"}
disabledReason={thread.role === "guest" ? GUEST_COMPOSER : null}
/>
@@ -165,6 +213,7 @@ export function SpaceCall({
</>
);
return (
+ <ProfileScopeProvider value={scope}>
<div data-call-layout="" className="flex h-full flex-col">
{header}
{notice}
@@ -219,10 +268,7 @@ export function SpaceCall({
onStream={onStream}
folded={folded}
onFold={setFolded}
- // The owner and admins change agents' rights (a daemon that does not say your role: you are its owner).
- onSetRights={thread.role === null || thread.role === "owner" || thread.role === "admin" ? thread.setRights : undefined}
- onRemoveAgent={thread.removeAgent ?? undefined}
- onAddAgent={canAddAgent ? () => setAddOpen(true) : undefined}
+ onAddAgent={canAdd ? () => setAddOpen(true) : undefined}
/>
</div>
<AddAgentSheet open={addOpen} onOpenChange={setAddOpen} space={{ id: spaceId, name: spaceName }} role={thread.role} taken={roster.agents.map((a) => a.name)}
@@ -254,5 +300,6 @@ export function SpaceCall({
</DialogPopup>
</Dialog>
</div>
+ </ProfileScopeProvider>
);
}
diff --git a/apps/cua-spaces-web/src/components/space-thread/summon.tsx b/apps/cua-spaces-web/src/components/space-thread/summon.tsx
new file mode 100644
index 0000000000..4fbee550a1
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/space-thread/summon.tsx
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * @mentioning agents in a Space (redesign): the composer's picker offers the
+ * agents in the Space and those that can start in it; sending posts the
+ * message, adds an @mentioned agent that isn't in the Space yet (asleep, so
+ * the message wakes it), and, when one can't be woken, shows why under the
+ * message with Connect. Once Connect finishes the message goes again by
+ * itself. Which agents, what each step is and every word are the core's
+ * (`summon.*`); Connect is Settings, Connectors' (`useConnectors`).
+ *
+ * The notes are this device's: they are about its own sign-ins, so they
+ * aren't posted to the thread for everyone.
+ */
+
+import { Link } from "@tanstack/react-router";
+import { CheckIcon, EyeIcon, Loader2Icon, PlugIcon, TriangleAlertIcon } from "lucide-react";
+import { useCallback, useMemo, type ReactNode } from "react";
+import { create } from "zustand";
+
+import {
+ summonCandidates,
+ summonFailed,
+ summonPlan,
+ threadOpAvailable,
+ useBridge,
+ type CantWake,
+ type DataAdapter,
+ type SpaceThread,
+ type SummonInput,
+ type ThreadView as PostView,
+} from "@/bridge";
+import type { CoreClient } from "@/bridge/core";
+import { Button } from "@/components/ui/button";
+import { useConnectors, type Connectors } from "@/hooks/use-connectors";
+import type { MentionCandidate } from "@/lib/mentions";
+
+import type { Roster } from "./roster";
+
+export interface WakeNote {
+ id: string;
+ /** The posted message it sits under (null: not posted, the host has no thread). */
+ seq: number | null;
+ /** The message, to send again. */
+ text: string;
+ cant: CantWake;
+ state: "blocked" | "connecting" | "retried" | "failed";
+ /** When it was noted (the Agents list's age). */
+ atMs?: number;
+}
+
+/** Kept on this device only (never posted or synced), so a run that couldn't start is still listed after a reload. */
+const NOTES_KEY = "cua.thread.wakeNotes";
+const loadNotes = (): Record<string, WakeNote[]> => {
+ try {
+ const raw = globalThis.localStorage?.getItem(NOTES_KEY);
+ return raw ? (JSON.parse(raw) as Record<string, WakeNote[]>) : {};
+ } catch {
+ return {};
+ }
+};
+const useNotes = create<{ bySpace: Record<string, WakeNote[]> }>(() => ({ bySpace: loadNotes() }));
+useNotes.subscribe((s) => {
+ try {
+ globalThis.localStorage?.setItem(NOTES_KEY, JSON.stringify(s.bySpace));
+ } catch {
+ // Not kept past this session.
+ }
+});
+
+const put = (spaceId: string, note: WakeNote) =>
+ useNotes.setState((s) => ({ bySpace: { ...s.bySpace, [spaceId]: [...(s.bySpace[spaceId] ?? []).filter((n) => n.id !== note.id), note] } }));
+const patch = (spaceId: string, id: string, p: Partial<WakeNote>) =>
+ useNotes.setState((s) => ({ bySpace: { ...s.bySpace, [spaceId]: (s.bySpace[spaceId] ?? []).map((n) => (n.id === id ? { ...n, ...p } : n)) } }));
+
+/** Dismiss: the note goes from this device (it was never anywhere else). */
+export const dismissWakeNote = (spaceId: string, id: string) =>
+ useNotes.setState((s) => ({ bySpace: { ...s.bySpace, [spaceId]: (s.bySpace[spaceId] ?? []).filter((n) => n.id !== id) } }));
+
+/** Tests start clean. */
+export function resetWakeNotes(): void {
+ useNotes.setState({ bySpace: {} });
+}
+
+/** Every Space's notes (the Agents list's runs that couldn't start). */
+export const useAllWakeNotes = () => useNotes((s) => s.bySpace);
+
+/** A note's move to the Space id its create became. */
+export function moveWakeNotes(from: string, to: string): void {
+ useNotes.setState((s) => {
+ const moved = s.bySpace[from];
+ if (!moved?.length) return s;
+ const { [from]: _gone, ...rest } = s.bySpace;
+ return { bySpace: { ...rest, [to]: [...(rest[to] ?? []), ...moved] } };
+ });
+}
+
+/**
+ * Connect for a note from anywhere (Home, the Agents page), then the message
+ * again in its Space: the same as the note's own Connect in the thread.
+ */
+export async function connectNote(spaceId: string, note: WakeNote, c: { connectApp(agent: string): Promise<"connected" | "sheet" | "failed"> }, data: DataAdapter): Promise<void> {
+ patch(spaceId, note.id, { state: "connecting" });
+ const outcome = await c.connectApp(note.cant.app);
+ if (outcome === "failed") return patch(spaceId, note.id, { state: "failed" });
+ if (outcome === "sheet") return patch(spaceId, note.id, { state: "blocked" });
+ await sendAgain(spaceId, note, data, async (text) => void (await data.call("thread.post", { spaceId, text })));
+}
+
+/**
+ * The note's message again: its agent joins the Space first, then the
+ * message is posted. When the agent can't be added, the note says why and
+ * nothing is posted (a message no agent reads would look sent).
+ */
+async function sendAgain(spaceId: string, note: WakeNote, data: DataAdapter, post: (text: string) => Promise<void>, why?: (error: string) => CantWake | null): Promise<void> {
+ try {
+ await data.call("thread.agentAdd", { spaceId, name: note.cant.handle, harness: note.cant.harness });
+ } catch (e) {
+ const cant = why?.(e instanceof Error ? e.message : String(e));
+ patch(spaceId, note.id, cant ? { state: "blocked", cant } : { state: "failed" });
+ return;
+ }
+ patch(spaceId, note.id, { state: "retried" });
+ try {
+ await post(note.text);
+ } catch {
+ patch(spaceId, note.id, { state: "failed" });
+ }
+}
+
+/** The notes under `spaceId`'s messages. */
+export const useWakeNotes = (spaceId: string) => useNotes((s) => s.bySpace[spaceId]);
+
+/**
+ * Sends `text` to `spaceId`: adds each @mentioned agent the plan says to,
+ * posts, and notes each one that can't be woken. Used by the composer and
+ * by Ask first's first message.
+ */
+export async function sendWithSummon({
+ core,
+ data,
+ spaceId,
+ input,
+ text,
+ post,
+}: {
+ core: CoreClient;
+ data: DataAdapter;
+ spaceId: string;
+ input: SummonInput;
+ text: string;
+ post: (text: string) => Promise<{ seq: number } | null>;
+}): Promise<void> {
+ const steps = summonPlan(core, input, text) ?? [];
+ const blocked: CantWake[] = steps.flatMap((s) => (s.cantWake ? [s.cantWake] : []));
+ for (const s of steps) {
+ if (s.action !== "add") continue;
+ try {
+ await data.call("thread.agentAdd", { spaceId, name: s.handle, harness: s.harness });
+ } catch (e) {
+ const c = summonFailed(core, input, s.harness, s.handle, e instanceof Error ? e.message : String(e));
+ if (c) blocked.push(c);
+ }
+ }
+ const entry = await post(text);
+ for (const c of blocked) {
+ put(spaceId, { id: `${entry?.seq ?? Date.now()}:${c.handle}`, seq: entry?.seq ?? null, text, cant: c, state: "blocked", atMs: Date.now() });
+ }
+}
+
+/** The Space's summon: the picker's candidates, the handles that draw as chips, and send. */
+export function useSummon({ spaceId, thread, roster, canAdd }: { spaceId: string; thread: SpaceThread; roster: Roster; canAdd: boolean }) {
+ const { core, data } = useBridge();
+ const connectors = useConnectors();
+ const input: SummonInput = useMemo(
+ () => ({
+ members: thread.members.map((m) => ({ handle: m.name, harness: m.harness, label: roster.agents.find((a) => a.name === m.name)?.label ?? m.name })),
+ people: roster.people.map((p) => p.label.toLowerCase().replace(/\s+/g, "")),
+ canAdd: canAdd && !!data && threadOpAvailable(data.mode, "thread.agentAdd"),
+ connectors: connectors.input,
+ }),
+ [thread.members, roster, canAdd, data, connectors.input],
+ );
+ const extra = useMemo<MentionCandidate[]>(
+ () =>
+ (summonCandidates(core, input) ?? [])
+ .filter((c) => !c.member)
+ .map((c) => ({ handle: c.handle, label: c.label, kind: "agent" as const, harness: c.harness, detail: c.detail })),
+ [core, input],
+ );
+ const candidates = useMemo(() => {
+ const agents = roster.candidates.filter((c) => c.kind === "agent");
+ const people = roster.candidates.filter((c) => c.kind !== "agent");
+ return [...agents, ...extra, ...people];
+ }, [roster.candidates, extra]);
+ const handles = useMemo(() => new Set([...roster.handles, ...extra.map((c) => c.handle.toLowerCase())]), [roster.handles, extra]);
+
+ const send = useCallback(
+ async (text: string, view: PostView | null) => {
+ if (!data) return;
+ await sendWithSummon({ core, data, spaceId, input, text, post: (t) => thread.post(t, view) });
+ },
+ [core, data, spaceId, input, thread],
+ );
+
+ /** Connect for a note, then the message again. */
+ const connectAndRetry = useCallback(
+ async (note: WakeNote, c: Connectors) => {
+ patch(spaceId, note.id, { state: "connecting" });
+ const outcome = await c.connectApp(note.cant.app);
+ if (outcome === "failed") return patch(spaceId, note.id, { state: "failed" });
+ // A provider sheet asks for a key first: the note waits; Send again is the next step.
+ if (outcome === "sheet") return patch(spaceId, note.id, { state: "blocked" });
+ await retry(note);
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [spaceId],
+ );
+
+ const retry = async (note: WakeNote) => {
+ if (!data) return;
+ await sendAgain(
+ spaceId,
+ note,
+ data,
+ async (text) => void (await thread.post(text, null)),
+ (error) => summonFailed(core, input, note.cant.harness, note.cant.handle, error),
+ );
+ };
+
+ return { candidates, handles, send, connectors, connectAndRetry, retry };
+}
+
+/** One "can't be woken" line under its message: why, Connect, the app's page; then "Sent again". */
+export function WakeNoteView({
+ note,
+ connected,
+ onConnect,
+ onRetry,
+ onDismiss,
+}: {
+ note: WakeNote;
+ onDismiss: () => void;
+ /** The app has a sign-in now (connected elsewhere, or a key just pasted). */
+ connected: boolean;
+ onConnect: () => void;
+ onRetry: () => void;
+}) {
+ const c = note.cant;
+ let body: ReactNode;
+ if (note.state === "retried") {
+ body = (
+ <p className="flex items-center gap-1.5 text-[12.5px] text-muted-foreground" data-wake-note-retried="">
+ <CheckIcon className="size-3.5 text-success" /> {c.retriedText}
+ </p>
+ );
+ } else {
+ body = (
+ <>
+ <p className="flex items-center gap-1.5 text-[13px] font-medium">
+ <TriangleAlertIcon className="size-3.5 shrink-0 text-warning" /> {c.text}
+ </p>
+ <p className="mt-0.5 text-[12.5px] text-muted-foreground">{c.detail}</p>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {connected && note.state !== "connecting" ? (
+ <Button size="sm" variant="outline" onClick={onRetry} data-wake-retry="">
+ {c.retryLabel}
+ </Button>
+ ) : c.connectLabel ? (
+ <Button size="sm" variant="outline" disabled={note.state === "connecting"} onClick={onConnect} data-wake-connect="">
+ {note.state === "connecting" ? <Loader2Icon className="animate-spin" /> : <PlugIcon />}
+ {note.state === "connecting" ? c.connectingLabel : c.connectLabel}
+ </Button>
+ ) : null}
+ {c.openLabel ? (
+ <Button size="sm" variant="ghost" className="text-muted-foreground" render={<Link to="/settings/connectors/$app" params={{ app: c.app }} />} data-wake-open="">
+ {c.openLabel}
+ </Button>
+ ) : null}
+ </div>
+ </>
+ );
+ }
+ return (
+ <div role="status" data-wake-note={c.handle} data-state={note.state} data-only-you={c.onlyYou ? "" : undefined} className="my-1.5 ml-11 rounded-lg bg-brand-surface px-3.5 py-2.5">
+ <OnlyYou label={c.onlyYouLabel} dismiss={note.state === "connecting" ? null : c.dismissLabel} onDismiss={onDismiss} />
+ {body}
+ </div>
+ );
+}
+
+/** "Only visible to you" with its eye, and Dismiss where it applies: on every line only this device shows. */
+export function OnlyYou({ label, dismiss, onDismiss }: { label: string; dismiss?: string | null; onDismiss?: () => void }) {
+ return (
+ <div className="mb-1 flex items-center gap-1.5 text-[11px] text-muted-foreground" data-only-you-label="">
+ <EyeIcon aria-hidden className="size-3" />
+ <span className="flex-1">{label}</span>
+ {dismiss && onDismiss ? (
+ <button type="button" data-wake-dismiss="" onClick={onDismiss} className="cursor-default rounded-lg px-1 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60">
+ {dismiss}
+ </button>
+ ) : null}
+ </div>
+ );
+}
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.tsx
index 0f1b3a55ff..e3c0b1d224 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
@@ -2,7 +2,7 @@
// Copyright (c) 2026 Cua AI, Inc.
import { CheckIcon, FileTextIcon, ImageIcon, XIcon } from "lucide-react";
-import { memo, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { Fragment, memo, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { useBridge, type TaskState, type ThreadAttachment, type ThreadEntry, type ThreadItem, type ThreadView } from "@/bridge";
import { Inlines } from "@/components/markdown";
@@ -13,9 +13,23 @@ import { cn } from "@/lib/utils";
import { AgentTile, MemberAvatar } from "./avatar";
import { AgentName, AiTag, holderNames, MemberEventNote } from "./identity";
+import { MentionChip, ProfileTrigger } from "./profile-card";
import { waitingFor } from "./rights";
import type { Roster } from "./roster";
+/**
+ * Keeps `scroller` at its end while `content` grows, as long as `atEnd()`
+ * (you hadn't scrolled up). Returns the stop.
+ */
+export function followGrowth(scroller: HTMLElement, content: HTMLElement, atEnd: () => boolean): () => void {
+ if (typeof ResizeObserver === "undefined") return () => {};
+ const ro = new ResizeObserver(() => {
+ if (atEnd()) scroller.scrollTop = scroller.scrollHeight;
+ });
+ ro.observe(content);
+ return () => ro.disconnect();
+}
+
/**
* The Space thread under the desktop: messages, tasks with their status and
* the agent's replies nested under them, approvals, one-line notes and the
@@ -32,10 +46,16 @@ export function ThreadView({
empty,
className,
endInset = 0,
+ after,
+ tail,
}: {
items: ThreadItem[];
/** Room kept clear at the end (px): thread mode's mini-player sits there, never over the newest message. */
endInset?: number;
+ /** Drawn under the item that posted entry `seq` (a summon's "can't be woken" note). */
+ after?: (seq: number) => ReactNode;
+ /** Drawn after the last item. */
+ tail?: ReactNode;
/** Removes an agent member from its card (absent: the host can't). */
onRemoveAgent?: (handle: string) => Promise<void>;
/** Scrolled to the top: read the page before (when there is one). */
@@ -82,6 +102,16 @@ export function ThreadView({
const el = ref.current;
if (el && atEnd.current) el.scrollTop = el.scrollHeight;
}, [endInset]);
+ // Something under the last entry grew (a note only you see, a status line):
+ // when you were at the end, stay there.
+ const body = useRef<HTMLDivElement | null>(null);
+ const hasItems = items.length > 0;
+ useEffect(() => {
+ const el = ref.current;
+ const inner = body.current;
+ if (!el || !inner) return;
+ return followGrowth(el, inner, () => atEnd.current && keep.current === null);
+ }, [hasItems]);
return (
<div
ref={ref}
@@ -105,10 +135,14 @@ export function ThreadView({
{items.length === 0 ? (
<div className="flex h-full items-end px-8 pb-4">{empty}</div>
) : (
- <div className="flex min-h-full flex-col justify-end gap-1 px-8 pt-5 pb-4" style={endInset ? { paddingBottom: endInset + 16 } : undefined}>
+ <div ref={body} className="flex min-h-full flex-col justify-end gap-1 px-8 pt-5 pb-4" style={endInset ? { paddingBottom: endInset + 16 } : undefined}>
{items.map((item) => (
- <ThreadItemView key={item.key} item={item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} />
+ <Fragment key={item.key}>
+ <ThreadItemView item={item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} />
+ {after && "entry" in item ? after(item.entry.seq) : null}
+ </Fragment>
))}
+ {tail}
</div>
)}
</div>
@@ -230,20 +264,41 @@ function Message({
nested?: boolean;
}) {
const who = roster.author(entry.author);
+ // A person's card: the roster's entry for this author (by id, else by name).
+ const person = who.kind === "person" ? (roster.people.find((p) => p.id === entry.author.id) ?? roster.people.find((p) => p.label === who.label)) : undefined;
+ const avatar = (
+ <MemberAvatar
+ kind={who.kind === "agent" ? "agent" : "person"}
+ name={who.kind === "agent" ? (who.handle ?? who.label) : who.label}
+ harness={who.harness}
+ identity={who.identity}
+ surface={surface}
+ size={nested ? 24 : 28}
+ className="mt-0.5"
+ />
+ );
return (
<div data-entry={entry.seq} className={cn("flex gap-3", nested ? "py-1.5" : "py-2")}>
- <MemberAvatar
- kind={who.kind === "agent" ? "agent" : "person"}
- name={who.kind === "agent" ? (who.handle ?? who.label) : who.label}
- harness={who.harness}
- identity={who.identity}
- surface={surface}
- size={nested ? 24 : 28}
- className="mt-0.5"
- />
+ {who.kind === "agent" && who.identity ? (
+ <ProfileTrigger identity={who.identity} agent={who.agent} roster={roster} onRemove={onRemoveAgent} className="self-start rounded-full">
+ {avatar}
+ </ProfileTrigger>
+ ) : person ? (
+ <ProfileTrigger person={person} className="self-start rounded-full">
+ {avatar}
+ </ProfileTrigger>
+ ) : (
+ avatar
+ )}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
- {who.kind === "agent" ? <AgentName who={who} roster={roster} onRemove={onRemoveAgent} /> : <span className="truncate text-[13px] font-semibold">{who.label}</span>}
+ {who.kind === "agent" ? <AgentName who={who} roster={roster} onRemove={onRemoveAgent} /> : person ? (
+ <ProfileTrigger person={person} className="truncate text-[13px] font-semibold hover:underline" data={{ "data-person-name": person.label }}>
+ {who.label}
+ </ProfileTrigger>
+ ) : (
+ <span className="truncate text-[13px] font-semibold">{who.label}</span>
+ )}
<time className="shrink-0 text-[11px] text-muted-foreground tabular-nums" dateTime={new Date(entry.tsMs).toISOString()} title={new Date(entry.tsMs).toLocaleString()}>
{clock(entry.tsMs)}
</time>
@@ -286,9 +341,9 @@ export function ThreadText({ text, handles }: { text: string; handles: ReadonlyS
const chips = (t: string, key: number) =>
mentionSegments(t, handles).map((s, i) =>
s.mention ? (
- <span key={`${key}-${i}`} data-mention={s.handle} className="font-medium text-brand-strong">
+ <MentionChip key={`${key}-${i}`} handle={s.handle}>
{s.text}
- </span>
+ </MentionChip>
) : (
s.text
),
diff --git a/apps/cua-spaces-web/src/components/spaces/space-list.tsx b/apps/cua-spaces-web/src/components/spaces/space-list.tsx
index 65f6e90ba1..0a8cf81fa7 100644
--- a/apps/cua-spaces-web/src/components/spaces/space-list.tsx
+++ b/apps/cua-spaces-web/src/components/spaces/space-list.tsx
@@ -10,11 +10,13 @@
import { Link, useNavigate } from "@tanstack/react-router";
import { ArrowDownIcon, ArrowUpIcon, LoaderCircleIcon } from "lucide-react";
-import type { MouseEvent, ReactNode } from "react";
+import type { MouseEvent, ReactNode, RefObject } from "react";
import { OsIcon } from "@/components/os-icon";
import { StateLabel } from "@/components/state-dot";
+import { useWindowedRows } from "@/hooks/use-windowed-rows";
import { lastUsedText, sizeCell, type SpacesSort } from "@/lib/spaces-page";
+import { WINDOW_FROM } from "@/lib/windowing";
import { cn } from "@/lib/utils";
import { PeopleStack, SpaceMark } from "./avatars";
@@ -39,7 +41,13 @@ export interface SpaceListProps {
more?: (item: SpaceItem) => ReactNode;
}
+/** A list row's height (`h-10`), and nothing between rows. */
+const ROW_PITCH = 40;
+
export function SpaceList({ items, sort, onSort, now, selection, menu, more }: SpaceListProps) {
+ // 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 { 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) =>
key ? (
@@ -66,10 +74,12 @@ export function SpaceList({ items, sort, onSort, now, selection, menu, more }: S
<span role="columnheader">{head("used", "Last used")}</span>
<span />
</div>
- {items.map((item) => {
- const row = <ListRow key={item.space.id} item={item} cols={cols} now={now} selection={selection} more={more?.(item)} />;
- return menu ? <div key={item.space.id}>{menu(item, row)}</div> : row;
- })}
+ <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={more?.(item)} />;
+ return menu ? <div key={item.space.id}>{menu(item, row)}</div> : row;
+ })}
+ </div>
</div>
);
}
diff --git a/apps/cua-spaces-web/src/components/spaces/windowed-grid.tsx b/apps/cua-spaces-web/src/components/spaces/windowed-grid.tsx
new file mode 100644
index 0000000000..b3066c9c3b
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/spaces/windowed-grid.tsx
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The Spaces grid, drawing only the rows on screen once it is long
+ * (`WINDOW_FROM` tiles): with thousands of Spaces, select-all and each
+ * filter keystroke redrew them all. Shorter grids are drawn whole, as
+ * before. The columns are the browser's own (`auto-fill, minmax`), counted
+ * from the grid's width so the rows here are the rows it lays out.
+ *
+ * `scrollToIndex` brings one tile into view even when it is not drawn yet.
+ */
+
+import { forwardRef, useCallback, useImperativeHandle, useLayoutEffect, useState, type ReactNode } from "react";
+
+import { useWindowedRows } from "@/hooks/use-windowed-rows";
+import { columnsFor, columnWidth, estimateTileRow, itemRange, rowOf, WINDOW_FROM } from "@/lib/windowing";
+
+const MIN_COLUMN = 232;
+const GAP_X = 20;
+const GAP_Y = 28;
+
+export interface WindowedGridHandle {
+ /** Scrolls so the tile at `index` (counting the leading tiles first) is on screen. */
+ scrollToIndex(index: number): void;
+}
+
+export const WindowedGrid = forwardRef<WindowedGridHandle, { count: number; renderAt: (index: number) => ReactNode; picking?: boolean }>(function WindowedGrid(
+ { count, renderAt, picking },
+ handle,
+) {
+ const [width, setWidth] = useState(0);
+ const columns = columnsFor(width, MIN_COLUMN, GAP_X);
+ const enabled = count >= WINDOW_FROM && width > 0;
+ const rows = Math.ceil(count / columns);
+ const { ref, window: win, style, scrollToRow } = useWindowedRows({
+ enabled,
+ rows,
+ perRow: columns,
+ gap: GAP_Y,
+ estimatePitch: () => estimateTileRow(columnWidth(width, columns, GAP_X)) + GAP_Y,
+ });
+
+ // The grid's own width, for the columns (the element has no horizontal padding).
+ const measure = useCallback(
+ (el: HTMLUListElement | null) => {
+ ref.current = el;
+ },
+ [ref],
+ );
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ setWidth(el.clientWidth);
+ if (typeof ResizeObserver === "undefined") return;
+ const ro = new ResizeObserver(() => setWidth(el.clientWidth));
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [ref]);
+
+ useImperativeHandle(handle, () => ({ scrollToIndex: (index) => scrollToRow(rowOf(index, columns)) }), [scrollToRow, columns]);
+
+ // Before the width is known (the first render) a long grid draws one screen, not all of it.
+ const unmeasured = count >= WINDOW_FROM && width === 0;
+ const [from, to] = enabled ? itemRange(win.start, win.end, columns, count) : unmeasured ? [0, 24] : [0, count];
+ const tiles: ReactNode[] = [];
+ for (let i = from; i < to; i++) tiles.push(renderAt(i));
+ return (
+ <ul
+ ref={measure}
+ style={style}
+ data-picking={picking || undefined}
+ data-windowed={enabled ? `${from}-${to}` : undefined}
+ className="group/grid grid grid-cols-[repeat(auto-fill,minmax(232px,1fr))] gap-x-5 gap-y-7"
+ >
+ {tiles}
+ </ul>
+ );
+});
diff --git a/apps/cua-spaces-web/src/hooks/use-agent-attempts.ts b/apps/cua-spaces-web/src/hooks/use-agent-attempts.ts
new file mode 100644
index 0000000000..9578b8037f
--- /dev/null
+++ b/apps/cua-spaces-web/src/hooks/use-agent-attempts.ts
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * This device's runs that aren't an agent in a Space (yet), for the one
+ * agent list (`agentList.view`): an Ask-first job whose Space is still being
+ * made, an @mention of an agent that isn't connected (the thread's note), a
+ * start that failed. Only gathers what is on this device; the core decides
+ * the rows, their words and their order.
+ */
+
+import { useMemo } from "react";
+
+import { useBridge, useSpaces, type AgentChat, type ChatAttempt } from "@/bridge";
+import { useStartTask } from "@/components/ask-first/use-start-task";
+import { connectNote, useAllWakeNotes } from "@/components/space-thread/summon";
+import { useConnectors } from "@/hooks/use-connectors";
+import { taskTitle, useAskTasks } from "@/lib/ask-first";
+import { agentName } from "@/components/ask-first/ask-box";
+
+const HARNESS: Record<string, string> = { "openai-codex": "codex" };
+
+export function useAgentAttempts(): ChatAttempt[] {
+ const tasks = useAskTasks();
+ const notes = useAllWakeNotes();
+ const { data: spaces } = useSpaces();
+ return useMemo(() => {
+ const nameOf = (id: string | null) => (id ? (spaces?.find((s) => s.id === id)?.name ?? "") : "");
+ const out: ChatAttempt[] = [];
+ for (const t of tasks) {
+ if (t.inSpace === undefined && !t.pendingId) continue;
+ const harness = HARNESS[t.agent] ?? t.agent;
+ const base = { harness, label: agentName(t.agent), job: taskTitle(t.prompt), atMs: t.createdMs, note: null, connectLabel: null, app: null };
+ if (t.pendingId && !t.spaceId && !t.error) out.push({ ...base, id: `task:${t.id}`, spaceId: t.pendingId, spaceName: nameOf(t.pendingId) || "a new Space", state: "creating" });
+ else if (t.error && t.inSpace !== true) out.push({ ...base, id: `task:${t.id}`, spaceId: t.spaceId ?? "", spaceName: nameOf(t.spaceId), state: "failed" });
+ }
+ for (const [spaceId, list] of Object.entries(notes)) {
+ for (const n of list ?? []) {
+ if (n.state === "retried") continue;
+ out.push({
+ id: `note:${spaceId}:${n.id}`,
+ spaceId,
+ spaceName: nameOf(spaceId),
+ harness: n.cant.harness,
+ label: n.cant.name,
+ job: taskTitle(n.text.replace(/^@[\w.-]+\s+/, "")),
+ atMs: n.atMs ?? 0,
+ state: n.cant.reason === "not-connected" ? "not-connected" : "failed",
+ note: n.cant.text,
+ connectLabel: n.cant.connectLabel,
+ app: n.cant.app,
+ });
+ }
+ }
+ return out;
+ }, [tasks, notes, spaces]);
+}
+
+/** Connect or Try again on a run in the list (Home, the Agents page): the same steps as in its thread. */
+export function useAttemptAction(): (chat: AgentChat) => void {
+ const { data } = useBridge();
+ const c = useConnectors();
+ const notes = useAllWakeNotes();
+ const tasks = useAskTasks();
+ const { retry } = useStartTask();
+ return (chat) => {
+ const id = chat.attempt ?? "";
+ if (id.startsWith("note:") && data) {
+ for (const [spaceId, list] of Object.entries(notes)) {
+ const note = list?.find((n) => `note:${spaceId}:${n.id}` === id);
+ if (note) return void connectNote(spaceId, note, c, data);
+ }
+ }
+ if (id.startsWith("task:")) {
+ const task = tasks.find((t) => `task:${t.id}` === id);
+ if (task) retry(task);
+ }
+ };
+}
diff --git a/apps/cua-spaces-web/src/hooks/use-connectors.ts b/apps/cua-spaces-web/src/hooks/use-connectors.ts
new file mode 100644
index 0000000000..46135ad76f
--- /dev/null
+++ b/apps/cua-spaces-web/src/hooks/use-connectors.ts
@@ -0,0 +1,321 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Connect, as Settings → Connectors (redesign), an app's page, a Space's
+ * "isn't connected yet" note and Ask first share it: one place that knows
+ * which connects are running, what failed, and which provider sheet is
+ * open. The steps and words are the core's (`connectors.*`); the host
+ * calls are the ones Settings already makes:
+ *
+ * - Cua's tools in an app: `agents.connect {signIn: false}` (and
+ * Background computer use, best effort);
+ * - the app's own token command (`claude setup-token`, one browser
+ * approval): `agents.connect {signIn: true}`, only where the core's plan
+ * says so. Other apps never get `signIn: true` here, so Cua doesn't read
+ * their own sign-in files;
+ * - a pasted key: `agentKeys.set`; Sign out: `agentKeys.remove`.
+ */
+
+import { useCallback, useEffect } from "react";
+import { create } from "zustand";
+
+import {
+ appDetail,
+ connectorsInputOf,
+ connectorsView,
+ connectPlan,
+ providerSheet,
+ useAgentKeys,
+ useBridge,
+ type AppDetailView,
+ type ConnectorsInput,
+ type ConnectorsView,
+ type ProviderSheetView,
+ type ProviderWay,
+} from "@/bridge";
+import { connectedAppsState, setConnectedAppsState, useConnectedApps, useConnectedAppsState, type ConnectedApps } from "@/hooks/use-connected-apps";
+import { withSwitch } from "@/lib/connected-apps";
+
+type Step = ConnectorsInput["busy"][number]["step"];
+
+interface ConnectState {
+ busy: ConnectorsInput["busy"];
+ failures: ConnectorsInput["failures"];
+ /** The provider sheet open now, and what opened it (an app's Connect continues there). */
+ sheet: { provider: string; forApp: string | null } | null;
+ /** Provider keys your login shell has set (names), read when a sheet opens. */
+ shellKeys: string[];
+ /** A device-code sign-in waiting for its code to be entered. */
+ device: { app: string; provider: string; url: string; code: string } | null;
+}
+
+const useConnectState = create<ConnectState>(() => ({ busy: [], failures: [], sheet: null, shellKeys: [], device: null }));
+const set = useConnectState.setState;
+
+const start = (id: string, step: Step) =>
+ set((s) => ({ busy: [...s.busy.filter((b) => b.id !== id), { id, step }], failures: s.failures.filter((f) => f.id !== id) }));
+const stop = (id: string) => set((s) => ({ busy: s.busy.filter((b) => b.id !== id) }));
+const fail = (id: string, line: string) => set((s) => ({ failures: [...s.failures.filter((f) => f.id !== id), { id, line }] }));
+
+/** Whether a provider sheet is open (cheap: the host mounts the sheet only then). */
+export const useProviderSheetOpen = () => useConnectState((s) => s.sheet !== null || s.device !== null);
+
+/** The device-code sign-in waiting now (its code and page), for its sheet. */
+export const useDeviceSignIn = () => useConnectState((s) => s.device);
+export const closeDeviceSignIn = () => set({ device: null });
+
+/** Tests start clean. */
+export function resetConnectState(): void {
+ set({ busy: [], failures: [], sheet: null, shellKeys: [], device: null });
+}
+
+const message = (e: unknown) => (e instanceof Error ? e.message : String(e));
+
+/** How a connect ended: `connected`, waiting on the provider sheet (`sheet`), or `failed`. */
+export type ConnectOutcome = "connected" | "sheet" | "failed";
+
+export interface Connectors {
+ apps: ConnectedApps;
+ input: ConnectorsInput;
+ view: ConnectorsView | null;
+ detail(agent: string): AppDetailView | null;
+ /** The provider sheet open now. */
+ sheet: ProviderSheetView | null;
+ /** One Connect for an app: Cua's tools, then its sign-in (its token command, or the provider's sheet). */
+ connectApp(agent: string): Promise<ConnectOutcome>;
+ openProvider(provider: string, forApp?: string | null): void;
+ closeProvider(): void;
+ /** Runs one of the sheet's ways (`key` with the pasted value). */
+ runWay(way: ProviderWay, value?: string): Promise<boolean>;
+ signOut(provider: string): Promise<void>;
+ /** An app page's switch: Cua's skills, its MCP server, or keeping it set up. */
+ setToggle(agent: string, id: "skills" | "mcp" | "auto", on: boolean): Promise<void>;
+ /** Takes Cua out of the app (and turns Keep it set up off). */
+ removeFromApp(agent: string): Promise<void>;
+ reload(): Promise<void>;
+}
+
+export function useConnectors(): Connectors {
+ const { core, data } = useBridge();
+ const apps = useConnectedApps();
+ const keys = useAgentKeys({ watch: true });
+ const app = useConnectedAppsState();
+ const st = useConnectState();
+ const input = connectorsInputOf(apps.rows, keys.input, { auto: app.auto === true, off: app.off, busy: st.busy, failures: st.failures, shellKeys: st.shellKeys });
+ const view = connectorsView(core, input);
+ const sheet = st.sheet ? providerSheet(core, input, st.sheet.provider) : null;
+
+ const reload = useCallback(async () => {
+ await Promise.all([apps.reload(), keys.refresh()]);
+ }, [apps, keys]);
+
+ /** An app's device-code sign-in: the code shows in its sheet while the host waits for it to be entered. */
+ const runDevice = useCallback(
+ async (app: string, provider: string): Promise<boolean> => {
+ if (!data) return false;
+ const id = `provider:${provider}`;
+ start(id, "signing-in");
+ start(`app:${app}`, "signing-in");
+ try {
+ const started = await data.call("agents.signInStart", { agent: app });
+ set({ device: { app, provider, url: started.url, code: started.code } });
+ const r = await data.call("agents.signInWait", { id: started.id });
+ if (!r.imported) {
+ fail(id, r.line ?? "The sign-in didn't finish. Try again.");
+ return false;
+ }
+ await reload();
+ return true;
+ } catch (e) {
+ fail(id, message(e));
+ return false;
+ } finally {
+ set({ device: null });
+ stop(id);
+ stop(`app:${app}`);
+ }
+ },
+ [data, reload],
+ );
+
+ const connectApp = useCallback(
+ async (agent: string): Promise<ConnectOutcome> => {
+ if (!data) return "failed";
+ const id = `app:${agent}`;
+ const plan = connectPlan(core, input, agent);
+ if (!plan) return "failed";
+ try {
+ if (plan.device) {
+ if (plan.tools) {
+ start(id, "connecting");
+ await data.call("agents.connect", { agents: [agent], signIn: false });
+ await data.call("agents.setupDriver", { agents: [agent] }).catch(() => undefined);
+ setConnectedAppsState(withSwitch(connectedAppsState(), agent, true));
+ }
+ return (await runDevice(agent, plan.tokenProvider ?? "openai")) ? "connected" : "failed";
+ }
+ if (plan.tools || plan.appToken) {
+ start(id, plan.appToken ? "signing-in" : "connecting");
+ if (plan.tokenProvider) start(`provider:${plan.tokenProvider}`, "signing-in");
+ const [result] = await data.call("agents.connect", { agents: [agent], signIn: plan.appToken });
+ if (plan.tools) await data.call("agents.setupDriver", { agents: [agent] }).catch(() => undefined);
+ setConnectedAppsState(withSwitch(connectedAppsState(), agent, true));
+ await reload();
+ if (result && plan.tools && !result.tools_ok) {
+ fail(id, result.tools_line ?? "Couldn't add Cua to it.");
+ return "failed";
+ }
+ if (plan.appToken && !result?.sign_in?.imported) {
+ fail(id, result?.sign_in?.line ?? "The sign-in didn't finish. Try again.");
+ return "failed";
+ }
+ }
+ if (plan.provider) {
+ set({ sheet: { provider: plan.provider, forApp: agent } });
+ return "sheet";
+ }
+ return "connected";
+ } catch (e) {
+ fail(id, message(e));
+ return "failed";
+ } finally {
+ stop(id);
+ if (plan.tokenProvider) stop(`provider:${plan.tokenProvider}`);
+ }
+ },
+ [core, data, input, reload, runDevice],
+ );
+
+ const runWay = useCallback(
+ async (way: ProviderWay, value?: string): Promise<boolean> => {
+ const open = useConnectState.getState().sheet;
+ if (!data || !open || !sheet) return false;
+ const id = `provider:${open.provider}`;
+ try {
+ if (way.id === "app-token" && way.app) {
+ set({ sheet: null });
+ start(id, "signing-in");
+ const [r] = await data.call("agents.connect", { agents: [way.app], signIn: true });
+ if (!r?.sign_in?.imported) {
+ fail(id, r?.sign_in?.line ?? "The sign-in didn't finish. Try again.");
+ return false;
+ }
+ } else if (way.id === "app-device" && way.app) {
+ set({ sheet: null });
+ return await runDevice(way.app, open.provider);
+ } else if (way.id === "shell" && way.env) {
+ start(id, "connecting");
+ await data.call("agentKeys.fromShell", { env: way.env });
+ await keys.refresh();
+ set({ sheet: null });
+ } else if (way.id === "key" && value?.trim()) {
+ start(id, "connecting");
+ await keys.save(sheet.keyProvider, value.trim(), sheet.keyEnv);
+ set({ sheet: null });
+ } else {
+ return false;
+ }
+ await reload();
+ return true;
+ } catch (e) {
+ fail(id, message(e));
+ return false;
+ } finally {
+ stop(id);
+ }
+ },
+ [data, sheet, keys, reload, runDevice],
+ );
+
+ const signOut = useCallback(
+ async (provider: string) => {
+ const row = view?.providers.find((p) => p.id === provider);
+ if (!row) return;
+ const id = `provider:${provider}`;
+ start(id, "signing-out");
+ try {
+ for (const env of row.signOutEnvs) await keys.remove(env);
+ } catch (e) {
+ fail(id, message(e));
+ } finally {
+ stop(id);
+ }
+ },
+ [view, keys],
+ );
+
+ const setToggle = useCallback(
+ async (agent: string, which: "skills" | "mcp" | "auto", on: boolean) => {
+ if (which === "auto") {
+ setConnectedAppsState(withSwitch(connectedAppsState(), agent, on));
+ return;
+ }
+ if (!data) return;
+ const id = `app:${agent}`;
+ start(id, "connecting");
+ try {
+ // Only that part: in, or out (the other stays as it is).
+ const part = { skills: which === "skills", mcp: which === "mcp" };
+ if (on) await data.call("agents.connect", { agents: [agent], signIn: false, ...part });
+ else await data.call("agents.disconnect", { agents: [agent], signIn: false, ...part });
+ await reload();
+ } catch (e) {
+ fail(id, message(e));
+ } finally {
+ stop(id);
+ }
+ },
+ [data, reload],
+ );
+
+ const removeFromApp = useCallback(
+ async (agent: string) => {
+ if (!data) return;
+ const id = `app:${agent}`;
+ start(id, "connecting");
+ try {
+ await data.call("agents.disconnect", { agents: [agent], signIn: false });
+ setConnectedAppsState(withSwitch(connectedAppsState(), agent, false));
+ await reload();
+ } catch (e) {
+ fail(id, message(e));
+ } finally {
+ stop(id);
+ }
+ },
+ [data, reload],
+ );
+
+ return {
+ apps,
+ input,
+ view,
+ detail: (agent) => appDetail(core, input, agent),
+ sheet,
+ connectApp,
+ openProvider: (provider, forApp = null) => {
+ set({ sheet: { provider, forApp } });
+ // Which keys your shell has (names only), for "Use … from your shell".
+ void data
+ ?.call("agentKeys.shell", {})
+ .then((r) => set({ shellKeys: r.names }))
+ .catch(() => set({ shellKeys: [] }));
+ },
+ closeProvider: () => set({ sheet: null }),
+ runWay,
+ signOut,
+ setToggle,
+ removeFromApp,
+ reload,
+ };
+}
+
+/** Re-reads once when a page that connects mounts (the keys may have changed in the CLI). */
+export function useConnectorsFresh(c: Connectors): void {
+ useEffect(() => {
+ void c.reload();
+ // Once per mount.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+}
diff --git a/apps/cua-spaces-web/src/hooks/use-windowed-rows.ts b/apps/cua-spaces-web/src/hooks/use-windowed-rows.ts
new file mode 100644
index 0000000000..55c0e3960d
--- /dev/null
+++ b/apps/cua-spaces-web/src/hooks/use-windowed-rows.ts
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Which rows of a long grid or list to draw (`lib/windowing.ts` has the
+ * maths). The element `ref` goes on is the one holding the rows: the hook
+ * keeps the room of the rows before and after the window as its own top and
+ * bottom padding (`style`), so the scrollbar is the full list's and the rows
+ * drawn sit where they would with all of them there.
+ *
+ * It follows the nearest scrolling ancestor and the element's own width, and
+ * measures the real row pitch from the rows it drew. Off (`enabled` false) it
+ * draws every row and touches nothing.
+ */
+
+import { useCallback, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type RefObject } from "react";
+
+import { rowScrollTop, visibleRows, type RowWindow } from "@/lib/windowing";
+
+export interface WindowedRows {
+ ref: RefObject<HTMLElement | null>;
+ window: RowWindow;
+ /** Padding that stands in for the rows not drawn; spread it on the element `ref` is on. */
+ style: CSSProperties;
+ /** Scrolls so `row` is on screen (a row that is not drawn yet draws after the scroll). */
+ scrollToRow(row: number): void;
+}
+
+function scrollParent(el: HTMLElement): HTMLElement {
+ for (let p = el.parentElement; p; p = p.parentElement) {
+ const o = getComputedStyle(p).overflowY;
+ if (o === "auto" || o === "scroll") return p;
+ }
+ return (document.scrollingElement as HTMLElement | null) ?? document.documentElement;
+}
+
+export function useWindowedRows({
+ enabled,
+ rows,
+ perRow,
+ estimatePitch,
+ gap,
+}: {
+ enabled: boolean;
+ rows: number;
+ /** Items in a row (columns; 1 for a list). */
+ perRow: number;
+ /** A row's pitch before any row is drawn (px). */
+ estimatePitch: () => number;
+ /** The gap between rows (px). */
+ gap: number;
+}): WindowedRows {
+ const ref = useRef<HTMLElement | null>(null);
+ const pitch = useRef(0);
+ const estimate = useRef(estimatePitch);
+ estimate.current = estimatePitch;
+ const [win, setWin] = useState<RowWindow>({ start: 0, end: Math.min(rows, 24), before: 0, after: 0 });
+
+ const read = useCallback(() => {
+ const el = ref.current;
+ if (!el) return null;
+ const scroller = scrollParent(el);
+ const scrollTop = scroller.scrollTop;
+ const offset = el.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scrollTop;
+ return { el, scroller, scrollTop, offset, viewport: scroller.clientHeight };
+ }, []);
+
+ const update = useCallback(() => {
+ const r = read();
+ if (!r) return;
+ // The real pitch: the distance between the tops of the first two rows drawn.
+ const kids = r.el.children;
+ if (kids.length > perRow) {
+ const d = (kids[perRow] as HTMLElement).offsetTop - (kids[0] as HTMLElement).offsetTop;
+ if (d > 0) pitch.current = d;
+ }
+ const p = pitch.current || estimate.current();
+ const next = visibleRows({ rows, pitch: p, scrollTop: r.scrollTop, viewport: r.viewport || 800, offset: r.offset });
+ setWin((cur) => (cur.start === next.start && cur.end === next.end && cur.before === next.before && cur.after === next.after ? cur : next));
+ }, [read, rows, perRow]);
+
+ // Follow the scroll (one update per frame) and the sizes of what scrolls and what is scrolled.
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!enabled || !el) return;
+ const scroller = scrollParent(el);
+ let frame = 0;
+ const schedule = () => {
+ if (frame) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ update();
+ });
+ };
+ update();
+ scroller.addEventListener("scroll", schedule, { passive: true });
+ const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
+ ro?.observe(scroller);
+ ro?.observe(el);
+ return () => {
+ scroller.removeEventListener("scroll", schedule);
+ ro?.disconnect();
+ if (frame) cancelAnimationFrame(frame);
+ };
+ }, [enabled, update]);
+
+ // A window just drawn gives a better pitch than the estimate.
+ useLayoutEffect(() => {
+ if (enabled) update();
+ }, [enabled, win.start, win.end, update]);
+
+ const scrollToRow = useCallback(
+ (row: number) => {
+ const r = read();
+ if (!r) return;
+ const to = rowScrollTop({ row, pitch: pitch.current || estimate.current(), gap, scrollTop: r.scrollTop, viewport: r.viewport, offset: r.offset });
+ if (to !== null) r.scroller.scrollTo({ top: Math.max(0, to) });
+ },
+ [read, gap],
+ );
+
+ const shown = useMemo<RowWindow>(() => (enabled ? win : { start: 0, end: rows, before: 0, after: 0 }), [enabled, win, rows]);
+ const style = useMemo<CSSProperties>(() => (enabled ? { paddingTop: shown.before, paddingBottom: shown.after } : {}), [enabled, shown.before, shown.after]);
+ return { ref, window: shown, style, scrollToRow };
+}
diff --git a/apps/cua-spaces-web/src/lib/ask-first.ts b/apps/cua-spaces-web/src/lib/ask-first.ts
index 7a98ac2f33..dba8097e03 100644
--- a/apps/cua-spaces-web/src/lib/ask-first.ts
+++ b/apps/cua-spaces-web/src/lib/ask-first.ts
@@ -46,6 +46,8 @@ export interface AskTask {
lastStatus: AgentRunStatus | null;
/** 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 redesign): the job is the Space's first message, @mentioning the agent. */
+ inSpace?: boolean;
}
const KEY = "cua.askFirst.tasks";
diff --git a/apps/cua-spaces-web/src/lib/design-baseline.json b/apps/cua-spaces-web/src/lib/design-baseline.json
index 6e56982e31..5323861f4b 100644
--- a/apps/cua-spaces-web/src/lib/design-baseline.json
+++ b/apps/cua-spaces-web/src/lib/design-baseline.json
@@ -133,7 +133,7 @@
"outlined-box": 1
},
"components/space-thread/identity.tsx": {
- "radius": 2
+ "radius": 1
},
"components/space-thread/members-panel.tsx": {
"radius": 1,
diff --git a/apps/cua-spaces-web/src/lib/mentions.ts b/apps/cua-spaces-web/src/lib/mentions.ts
index 9fc4c3737b..5206184bea 100644
--- a/apps/cua-spaces-web/src/lib/mentions.ts
+++ b/apps/cua-spaces-web/src/lib/mentions.ts
@@ -15,6 +15,10 @@ export interface MentionCandidate {
/** How the picker shows it (`Claude Code`, `Grace`). */
label: string;
kind: "agent" | "person";
+ /** An agent's kind (`claude-code`), for its mark when it isn't in the Space yet. */
+ harness?: string;
+ /** Under the name for an agent not in the Space yet ("Starts in this Space", "Not connected yet"). */
+ detail?: string;
}
/** `@` starts a mention at the start or after a space or an opening
diff --git a/apps/cua-spaces-web/src/lib/poll-plan.test.ts b/apps/cua-spaces-web/src/lib/poll-plan.test.ts
new file mode 100644
index 0000000000..3c313efb34
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/poll-plan.test.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+
+import { chatsPollMs, jittered, JobQueue, mapLimit, MissCache } from "./poll-plan";
+
+describe("chatsPollMs", () => {
+ it("is 5 s for a small account and slows as it grows, to a minute", () => {
+ expect(chatsPollMs(0)).toBe(5_000);
+ expect(chatsPollMs(20)).toBe(5_000);
+ expect(chatsPollMs(120)).toBe(5_000 + 100 * 40);
+ expect(chatsPollMs(3_000)).toBe(60_000);
+ expect(chatsPollMs(1_000_000)).toBe(60_000);
+ });
+
+ it("keeps the calls per second flat instead of growing with the Spaces", () => {
+ // Two calls per Space per poll: calls per second.
+ const rate = (n: number) => (2 * n) / (chatsPollMs(n) / 1000);
+ expect(rate(20)).toBeCloseTo(8);
+ expect(rate(3_000)).toBeLessThan(105); // was 1,200 a second at a flat 5 s
+ expect(rate(3_000)).toBeLessThan(rate(20) * 13);
+ });
+});
+
+describe("jittered", () => {
+ it("spreads a delay by the fraction either way", () => {
+ expect(jittered(10_000, 0.2, () => 0)).toBe(8_000);
+ expect(jittered(10_000, 0.2, () => 1)).toBe(12_000);
+ expect(jittered(10_000, 0.2, () => 0.5)).toBe(10_000);
+ });
+ it("never goes negative", () => {
+ expect(jittered(5, 5, () => 0)).toBe(0);
+ });
+});
+
+describe("mapLimit", () => {
+ it("answers in order and never runs more than the limit at once", async () => {
+ let live = 0;
+ let peak = 0;
+ const out = await mapLimit([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, async (n) => {
+ live++;
+ peak = Math.max(peak, live);
+ await new Promise((r) => setTimeout(r, 5));
+ live--;
+ return n * 2;
+ });
+ expect(out).toEqual([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
+ expect(peak).toBe(3);
+ });
+ it("handles an empty list and a limit larger than the list", async () => {
+ expect(await mapLimit([], 4, async () => 1)).toEqual([]);
+ expect(await mapLimit([1, 2], 50, async (n) => n)).toEqual([1, 2]);
+ });
+});
+
+describe("MissCache", () => {
+ it("leaves an id alone until its time is up", () => {
+ let now = 1_000;
+ const c = new MissCache(60_000, () => now);
+ expect(c.has("a")).toBe(false);
+ c.add("a");
+ expect(c.has("a")).toBe(true);
+ now += 59_999;
+ expect(c.has("a")).toBe(true);
+ now += 2;
+ expect(c.has("a")).toBe(false);
+ expect(c.size).toBe(0);
+ });
+ it("forgets Spaces that left the list", () => {
+ const c = new MissCache(60_000, () => 0);
+ c.add("a");
+ c.add("b");
+ c.prune(new Set(["b"]));
+ expect(c.has("a")).toBe(false);
+ expect(c.has("b")).toBe(true);
+ });
+});
+
+describe("JobQueue", () => {
+ it("runs a few jobs at a time and the rest in the order they came", async () => {
+ const q = new JobQueue(2);
+ const order: number[] = [];
+ let peak = 0;
+ await Promise.all(
+ [1, 2, 3, 4, 5].map((n) =>
+ q.run(async () => {
+ peak = Math.max(peak, q.active);
+ order.push(n);
+ await new Promise((r) => setTimeout(r, 5));
+ }),
+ ),
+ );
+ expect(order).toEqual([1, 2, 3, 4, 5]);
+ expect(peak).toBe(2);
+ expect(q.active).toBe(0);
+ expect(q.queued).toBe(0);
+ });
+ it("lets the next job start when one fails", async () => {
+ const q = new JobQueue(1);
+ const failed = q.run(async () => {
+ throw new Error("x");
+ });
+ const next = q.run(async () => "ok");
+ await expect(failed).rejects.toThrow("x");
+ await expect(next).resolves.toBe("ok");
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/poll-plan.ts b/apps/cua-spaces-web/src/lib/poll-plan.ts
new file mode 100644
index 0000000000..d724d9c859
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/poll-plan.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * How the page polls the host so the load does not grow with what the
+ * account owns. Before: the Agents tab read two thread calls for every Space
+ * every 5 s (2 x 3,000 calls per 5 s at 3,000 Spaces), asked again every
+ * time about Spaces with no thread, and every thumbnail was fetched the
+ * moment its tile drew. Pure helpers (no timers), so they are tested
+ * without a browser.
+ */
+
+/** The Agents tab's poll for `spaces` Spaces: 5 s up to 20 of them, then
+ * 40 ms more for each, at most a minute. */
+export function chatsPollMs(spaces: number): number {
+ return Math.min(60_000, 5_000 + Math.max(0, spaces - 20) * 40);
+}
+
+/** `ms` spread by up to `fraction` either way, so a thousand pages (or a
+ * thousand tabs after a reconnect) do not all ask in the same second. */
+export function jittered(ms: number, fraction = 0.2, random: () => number = Math.random): number {
+ return Math.max(0, Math.round(ms * (1 + (random() * 2 - 1) * fraction)));
+}
+
+/** `f` over `items`, at most `limit` at a time, answers in order. */
+export async function mapLimit<T, R>(items: readonly T[], limit: number, f: (item: T, index: number) => Promise<R>): Promise<R[]> {
+ const out = new Array<R>(items.length);
+ let next = 0;
+ const worker = async () => {
+ for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i]!, i);
+ };
+ await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, worker));
+ return out;
+}
+
+/** Ids that failed in a way that will not change soon (a Space with no
+ * thread: a stopped machine, an old daemon), not asked again for `ttlMs`. */
+export class MissCache {
+ private until = new Map<string, number>();
+ constructor(
+ private readonly ttlMs: number,
+ private readonly now: () => number = Date.now,
+ ) {}
+
+ add(id: string): void {
+ this.until.set(id, this.now() + this.ttlMs);
+ }
+
+ has(id: string): boolean {
+ const t = this.until.get(id);
+ if (t === undefined) return false;
+ if (t <= this.now()) {
+ this.until.delete(id);
+ return false;
+ }
+ return true;
+ }
+
+ /** Forgets ids not in `keep` (Spaces that left the list). */
+ prune(keep: ReadonlySet<string>): void {
+ for (const id of [...this.until.keys()]) if (!keep.has(id)) this.until.delete(id);
+ }
+
+ get size(): number {
+ return this.until.size;
+ }
+}
+
+/** A queue that runs at most `limit` jobs at once, in the order they came
+ * (thumbnails: a screenful of tiles drawing at once is a few calls at a time,
+ * not one per tile). */
+export class JobQueue {
+ private running = 0;
+ private waiting: Array<() => void> = [];
+ constructor(private readonly limit: number) {}
+
+ async run<T>(job: () => Promise<T>): Promise<T> {
+ if (this.running >= this.limit) await new Promise<void>((resolve) => this.waiting.push(resolve));
+ this.running++;
+ try {
+ return await job();
+ } finally {
+ this.running--;
+ this.waiting.shift()?.();
+ }
+ }
+
+ get active(): number {
+ return this.running;
+ }
+
+ get queued(): number {
+ return this.waiting.length;
+ }
+}
diff --git a/apps/cua-spaces-web/src/lib/windowing.test.ts b/apps/cua-spaces-web/src/lib/windowing.test.ts
new file mode 100644
index 0000000000..ce10dd2dfc
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/windowing.test.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+
+import { columnsFor, columnWidth, estimateTileRow, itemRange, OVERSCAN_ROWS, rowOf, rowScrollTop, visibleRows, WINDOW_FROM } from "./windowing";
+
+describe("visibleRows", () => {
+ const base = { rows: 1000, pitch: 100, viewport: 500, offset: 200, overscan: 2 };
+
+ it("draws the first screen and a little more at the top, the rest as spacers", () => {
+ const w = visibleRows({ ...base, scrollTop: 0 });
+ // The grid starts 200 px down; a 500 px viewport sees rows 0..3 (up to y=500): ceil((0-200+500)/100) = 3.
+ expect(w).toEqual({ start: 0, end: 5, before: 0, after: 995 * 100 - 0 });
+ expect(w.before + (w.end - w.start) * 100 + w.after).toBe(1000 * 100);
+ });
+
+ it("follows the scroll and keeps the overscan on both sides", () => {
+ const w = visibleRows({ ...base, scrollTop: 20_200 });
+ // 20 000 px into the grid is row 200; the viewport shows 200..205.
+ expect(w.start).toBe(198);
+ expect(w.end).toBe(207);
+ expect(w.before).toBe(198 * 100);
+ expect(w.after).toBe((1000 - 207) * 100);
+ });
+
+ it("ends at the last row and never past it", () => {
+ const w = visibleRows({ ...base, scrollTop: 1000 * 100 });
+ expect(w.end).toBe(1000);
+ expect(w.after).toBe(0);
+ expect(w.start).toBeLessThan(w.end);
+ expect(w.start).toBeGreaterThan(900);
+ });
+
+ it("draws every row of a list that is not long, and nothing for an empty one", () => {
+ expect(visibleRows({ ...base, rows: 0, scrollTop: 0 })).toEqual({ start: 0, end: 0, before: 0, after: 0 });
+ expect(visibleRows({ ...base, rows: 4, scrollTop: 0 })).toMatchObject({ start: 0, end: 4, after: 0 });
+ });
+
+ it("does not divide by a pitch that is not known yet", () => {
+ expect(visibleRows({ ...base, pitch: 0, scrollTop: 0 })).toEqual({ start: 0, end: 1000, before: 0, after: 0 });
+ });
+
+ it("uses an overscan by default", () => {
+ const w = visibleRows({ rows: 1000, pitch: 100, viewport: 500, offset: 0, scrollTop: 10_000 });
+ expect(w.start).toBe(100 - OVERSCAN_ROWS);
+ });
+
+ it("draws a bounded number of rows however long the list is (the point of it)", () => {
+ for (const rows of [100, 1_000, 100_000]) {
+ const w = visibleRows({ rows, pitch: 260, viewport: 900, offset: 150, scrollTop: 12_345 });
+ expect(w.end - w.start).toBeLessThanOrEqual(Math.ceil(900 / 260) + 2 * OVERSCAN_ROWS + 1);
+ }
+ });
+});
+
+describe("columns and rows", () => {
+ it("counts the columns the browser lays out for auto-fill minmax(232px, 1fr) with a 20 px gap", () => {
+ expect(columnsFor(232, 232, 20)).toBe(1);
+ expect(columnsFor(483, 232, 20)).toBe(1); // 2 columns need 232*2+20 = 484
+ expect(columnsFor(484, 232, 20)).toBe(2);
+ expect(columnsFor(1024, 232, 20)).toBe(4); // 4*232+3*20 = 988
+ expect(columnsFor(0, 232, 20)).toBe(1);
+ });
+
+ it("gives an item its row and a grid its column width", () => {
+ expect(rowOf(0, 4)).toBe(0);
+ expect(rowOf(3, 4)).toBe(0);
+ expect(rowOf(4, 4)).toBe(1);
+ expect(rowOf(9, 0)).toBe(9);
+ expect(columnWidth(988, 4, 20)).toBe(232);
+ });
+
+ it("estimates a tile row from its 16:10 picture and the two lines under it", () => {
+ expect(estimateTileRow(232)).toBe(145 + 48);
+ });
+
+ it("turns rows into the items to draw, clamped to the list", () => {
+ expect(itemRange(2, 5, 4, 100)).toEqual([8, 20]);
+ expect(itemRange(24, 30, 4, 100)).toEqual([96, 100]);
+ expect(itemRange(30, 40, 4, 100)).toEqual([100, 100]);
+ });
+
+ it("draws short lists whole", () => {
+ expect(WINDOW_FROM).toBeGreaterThan(70); // the page's own tests have fewer Spaces than this
+ });
+});
+
+describe("rowScrollTop", () => {
+ const view = { pitch: 100, gap: 20, viewport: 500, offset: 200 };
+
+ it("leaves a row that is on screen where it is", () => {
+ expect(rowScrollTop({ ...view, row: 1, scrollTop: 0 })).toBeNull();
+ });
+
+ it("scrolls up to a row above, to its top", () => {
+ expect(rowScrollTop({ ...view, row: 3, scrollTop: 2000 })).toBe(200 + 300);
+ });
+
+ it("scrolls down to a row below, to its bottom edge (not its gap)", () => {
+ // Row 50 spans 5200..5280 (the gap below is not part of it); the viewport ends there.
+ expect(rowScrollTop({ ...view, row: 50, scrollTop: 0 })).toBe(5200 + 80 - 500);
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/windowing.ts b/apps/cua-spaces-web/src/lib/windowing.ts
new file mode 100644
index 0000000000..d80cedb9b6
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/windowing.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Drawing only what is on screen, for the Spaces page's grid and list: with
+ * thousands of Spaces every select-all or filter keystroke redrew thousands
+ * of tiles. The maths is here (no DOM) so it is tested without a browser;
+ * `hooks/use-windowed-rows.ts` feeds it the scroll position.
+ *
+ * Rows are the unit: a grid row holds `columns` tiles, a list row one. Every
+ * row has the same pitch (its height plus the gap below it), measured from
+ * what is drawn, so the rows above and below the window are two spacers.
+ */
+
+/** Lists shorter than this are drawn whole: nothing to gain, and the page
+ * keeps its plain layout (and its tests, which have no layout engine). */
+export const WINDOW_FROM = 100;
+
+/** Rows drawn beyond each edge of the viewport (so a scroll or a Tab has
+ * something there before the next frame draws more). */
+export const OVERSCAN_ROWS = 3;
+
+export interface WindowInput {
+ /** Rows in all. */
+ rows: number;
+ /** One row's height plus the gap below it (px). */
+ pitch: number;
+ /** The scroll container's scrollTop (px). */
+ scrollTop: number;
+ /** The scroll container's visible height (px). */
+ viewport: number;
+ /** Where the first row starts inside the scroll container's content (px). */
+ offset: number;
+ overscan?: number;
+}
+
+export interface RowWindow {
+ /** First row drawn. */
+ start: number;
+ /** One past the last row drawn. */
+ end: number;
+ /** Height standing in for the rows before `start` (px). */
+ before: number;
+ /** Height standing in for the rows from `end` on (px). */
+ after: number;
+}
+
+/** The rows to draw for a scroll position. */
+export function visibleRows({ rows, pitch, scrollTop, viewport, offset, overscan = OVERSCAN_ROWS }: WindowInput): RowWindow {
+ if (rows <= 0 || pitch <= 0) return { start: 0, end: Math.max(0, rows), before: 0, after: 0 };
+ const top = scrollTop - offset;
+ const first = Math.floor(top / pitch);
+ const last = Math.ceil((top + viewport) / pitch);
+ const start = Math.min(rows, Math.max(0, first - overscan));
+ const end = Math.min(rows, Math.max(start, last + overscan));
+ return { start, end, before: start * pitch, after: (rows - end) * pitch };
+}
+
+/** Columns of a grid of `auto-fill, minmax(min, 1fr)` columns `width` wide
+ * with `gap` between them: what the browser lays out, so the rows computed
+ * here are the rows it draws. */
+export function columnsFor(width: number, min: number, gap: number): number {
+ if (width <= 0) return 1;
+ return Math.max(1, Math.floor((width + gap) / (min + gap)));
+}
+
+/** The row an item is in. */
+export function rowOf(index: number, columns: number): number {
+ return Math.floor(index / Math.max(1, columns));
+}
+
+/** The scrollTop that brings `row` into view with the least movement (the
+ * current one when it already is), or `null` when it already is. */
+export function rowScrollTop({
+ row,
+ pitch,
+ gap,
+ scrollTop,
+ viewport,
+ offset,
+}: {
+ row: number;
+ pitch: number;
+ /** The gap below a row, which is not part of the row itself. */
+ gap: number;
+ scrollTop: number;
+ viewport: number;
+ offset: number;
+}): number | null {
+ const top = offset + row * pitch;
+ const bottom = top + pitch - gap;
+ if (top >= scrollTop && bottom <= scrollTop + viewport) return null;
+ return top < scrollTop ? top : bottom - viewport;
+}
+
+/** The first and last item indexes of rows `start` to `end` (exclusive) of
+ * `count` items in `columns` columns. */
+export function itemRange(start: number, end: number, columns: number, count: number): [number, number] {
+ return [Math.min(count, start * columns), Math.min(count, end * columns)];
+}
+
+/** An estimate of a grid row's height before one is drawn: the 16:10
+ * picture plus the name and place lines under it (`SpaceTile`). */
+export function estimateTileRow(columnWidth: number): number {
+ return Math.round(columnWidth * 0.625) + 12 + 20 + 16;
+}
+
+/** The column width of a grid `width` wide in `columns` columns. */
+export function columnWidth(width: number, columns: number, gap: number): number {
+ return (width - gap * (columns - 1)) / columns;
+}
diff --git a/apps/cua-spaces-web/src/routeTree.gen.ts b/apps/cua-spaces-web/src/routeTree.gen.ts
index ec2cb8bebd..7ed1e834c7 100644
--- a/apps/cua-spaces-web/src/routeTree.gen.ts
+++ b/apps/cua-spaces-web/src/routeTree.gen.ts
@@ -34,6 +34,7 @@ import { Route as SettingsGeneralRouteImport } from './routes/settings/general'
import { Route as SpacesIndexRouteImport } from './routes/spaces/index'
import { Route as SpacesSpaceIdRouteImport } from './routes/spaces/$spaceId'
import { Route as VolumeIndexRouteImport } from './routes/volume/index'
+import { Route as SettingsConnectorsAppRouteImport } from './routes/settings/connectors.$app'
const IndexRoute = IndexRouteImport.update({
id: '/',
@@ -145,6 +146,11 @@ const VolumeIndexRoute = VolumeIndexRouteImport.update({
path: '/volume/',
getParentRoute: () => rootRouteImport,
} as any)
+const SettingsConnectorsAppRoute = SettingsConnectorsAppRouteImport.update({
+ id: '/$app',
+ path: '/$app',
+ getParentRoute: () => SettingsConnectorsRoute,
+} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
@@ -155,7 +161,7 @@ export interface FileRoutesByFullPath {
'/settings/advanced': typeof SettingsAdvancedRoute
'/settings/agents': typeof SettingsAgentsRoute
'/settings/connected-apps': typeof SettingsConnectedAppsRoute
- '/settings/connectors': typeof SettingsConnectorsRoute
+ '/settings/connectors': typeof SettingsConnectorsRouteWithChildren
'/settings/devices': typeof SettingsDevicesRoute
'/settings/experiments': typeof SettingsExperimentsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -169,6 +175,7 @@ export interface FileRoutesByFullPath {
'/settings/': typeof SettingsIndexRoute
'/spaces/': typeof SpacesIndexRoute
'/volume/': typeof VolumeIndexRoute
+ '/settings/connectors/$app': typeof SettingsConnectorsAppRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
@@ -178,7 +185,7 @@ export interface FileRoutesByTo {
'/settings/advanced': typeof SettingsAdvancedRoute
'/settings/agents': typeof SettingsAgentsRoute
'/settings/connected-apps': typeof SettingsConnectedAppsRoute
- '/settings/connectors': typeof SettingsConnectorsRoute
+ '/settings/connectors': typeof SettingsConnectorsRouteWithChildren
'/settings/devices': typeof SettingsDevicesRoute
'/settings/experiments': typeof SettingsExperimentsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -192,6 +199,7 @@ export interface FileRoutesByTo {
'/settings': typeof SettingsIndexRoute
'/spaces': typeof SpacesIndexRoute
'/volume': typeof VolumeIndexRoute
+ '/settings/connectors/$app': typeof SettingsConnectorsAppRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
@@ -203,7 +211,7 @@ export interface FileRoutesById {
'/settings/advanced': typeof SettingsAdvancedRoute
'/settings/agents': typeof SettingsAgentsRoute
'/settings/connected-apps': typeof SettingsConnectedAppsRoute
- '/settings/connectors': typeof SettingsConnectorsRoute
+ '/settings/connectors': typeof SettingsConnectorsRouteWithChildren
'/settings/devices': typeof SettingsDevicesRoute
'/settings/experiments': typeof SettingsExperimentsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -217,6 +225,7 @@ export interface FileRoutesById {
'/settings/': typeof SettingsIndexRoute
'/spaces/': typeof SpacesIndexRoute
'/volume/': typeof VolumeIndexRoute
+ '/settings/connectors/$app': typeof SettingsConnectorsAppRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
@@ -243,6 +252,7 @@ export interface FileRouteTypes {
| '/settings/'
| '/spaces/'
| '/volume/'
+ | '/settings/connectors/$app'
fileRoutesByTo: FileRoutesByTo
to:
| '/'
@@ -266,6 +276,7 @@ export interface FileRouteTypes {
| '/settings'
| '/spaces'
| '/volume'
+ | '/settings/connectors/$app'
id:
| '__root__'
| '/'
@@ -290,6 +301,7 @@ export interface FileRouteTypes {
| '/settings/'
| '/spaces/'
| '/volume/'
+ | '/settings/connectors/$app'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
@@ -464,15 +476,33 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof VolumeIndexRouteImport
parentRoute: typeof rootRouteImport
}
+ '/settings/connectors/$app': {
+ id: '/settings/connectors/$app'
+ path: '/$app'
+ fullPath: '/settings/connectors/$app'
+ preLoaderRoute: typeof SettingsConnectorsAppRouteImport
+ parentRoute: typeof SettingsConnectorsRoute
+ }
}
}
+interface SettingsConnectorsRouteChildren {
+ SettingsConnectorsAppRoute: typeof SettingsConnectorsAppRoute
+}
+
+const SettingsConnectorsRouteChildren: SettingsConnectorsRouteChildren = {
+ SettingsConnectorsAppRoute: SettingsConnectorsAppRoute,
+}
+
+const SettingsConnectorsRouteWithChildren =
+ SettingsConnectorsRoute._addFileChildren(SettingsConnectorsRouteChildren)
+
interface SettingsRouteRouteChildren {
SettingsAboutRoute: typeof SettingsAboutRoute
SettingsAdvancedRoute: typeof SettingsAdvancedRoute
SettingsAgentsRoute: typeof SettingsAgentsRoute
SettingsConnectedAppsRoute: typeof SettingsConnectedAppsRoute
- SettingsConnectorsRoute: typeof SettingsConnectorsRoute
+ SettingsConnectorsRoute: typeof SettingsConnectorsRouteWithChildren
SettingsDevicesRoute: typeof SettingsDevicesRoute
SettingsExperimentsRoute: typeof SettingsExperimentsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
@@ -484,7 +514,7 @@ const SettingsRouteRouteChildren: SettingsRouteRouteChildren = {
SettingsAdvancedRoute: SettingsAdvancedRoute,
SettingsAgentsRoute: SettingsAgentsRoute,
SettingsConnectedAppsRoute: SettingsConnectedAppsRoute,
- SettingsConnectorsRoute: SettingsConnectorsRoute,
+ SettingsConnectorsRoute: SettingsConnectorsRouteWithChildren,
SettingsDevicesRoute: SettingsDevicesRoute,
SettingsExperimentsRoute: SettingsExperimentsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
diff --git a/apps/cua-spaces-web/src/routes/agents/index.tsx b/apps/cua-spaces-web/src/routes/agents/index.tsx
index 255fa51feb..150b434199 100644
--- a/apps/cua-spaces-web/src/routes/agents/index.tsx
+++ b/apps/cua-spaces-web/src/routes/agents/index.tsx
@@ -9,6 +9,7 @@ import { AgentDmView, AgentList, AgentPage, AgentsEmpty, NewAgentSheet } from "@
import type { AddAgentStage } from "@/components/add-agent/add-agent-sheet";
import { useFlag } from "@/bridge/flags";
import { LegacyAgentsPage } from "@/legacy/routes/agents/index";
+import { useAgentAttempts, useAttemptAction } from "@/hooks/use-agent-attempts";
/** Which agent's DM is open, and in which of its Spaces (none: all of them). */
interface ChatSearch {
@@ -48,17 +49,30 @@ function AgentsChatPage() {
const navigate = useNavigate({ from: "/agents/" });
const { data: session } = useSession();
const identity = session?.signedIn ? (session.account.identity ?? null) : null;
- const { chats, spaces, me, refresh } = useAgentChats();
+ // The one list (agents in your Spaces and this device's runs that haven't started): Home shows it too.
+ const attempts = useAgentAttempts();
+ const act = useAttemptAction();
+ const { chats, spaces, me, refresh } = useAgentChats(attempts);
const now = useNow();
const [sheet, setSheet] = useState<AddAgentStage | null>(null);
const [info, setInfo] = useState(false);
- const chat = chats?.find((c) => c.key === search.agent) ?? (search.agent ? null : (chats?.[0] ?? null));
+ // A run that hasn't started opens its Space's thread; only agents have a DM here.
+ const chat = chats?.find((c) => c.key === search.agent && c.kind === "agent") ?? (search.agent ? null : (chats?.find((c) => c.kind === "agent") ?? null));
const space = chat && search.space && chat.spaces.some((s) => s.spaceId === search.space) ? search.space : null;
const select = (agent: string, sp?: string) => void navigate({ search: { agent, space: sp }, replace: true });
const taken = (spaceId: string) => (chats ?? []).flatMap((c) => c.spaces).filter((s) => s.spaceId === spaceId).map((s) => s.handle);
return (
<div data-agents-chat="" className="flex h-full min-h-0">
- <AgentList chats={chats ?? []} me={me} selected={chat?.key ?? null} onSelect={select} onNew={() => setSheet("pick")} now={now} />
+ <AgentList
+ chats={chats ?? []}
+ me={me}
+ selected={chat?.key ?? null}
+ onSelect={select}
+ onOpenRun={(c) => c.places[0] && void navigate({ to: "/spaces/$spaceId", params: { spaceId: c.places[0].spaceId } })}
+ onAction={act}
+ onNew={() => setSheet("pick")}
+ now={now}
+ />
{chats === null ? (
<div className="flex-1" />
) : chat ? (
@@ -66,7 +80,7 @@ function AgentsChatPage() {
<AgentDmView key={chat.key} chat={chat} space={space} onSpace={(sp) => select(chat.key, sp ?? undefined)} identity={identity} onInfo={() => setInfo(true)} me={me} />
<AgentPage chat={chat} open={info} onOpenChange={setInfo} me={me} identity={identity} />
</>
- ) : chats.length === 0 ? (
+ ) : chats.every((c) => c.kind !== "agent") ? (
<AgentsEmpty onStart={() => setSheet("start")} onConnect={() => setSheet("connect")} />
) : (
<div className="flex flex-1 items-center justify-center text-[13px] text-muted-foreground">That agent isn't in any of your Spaces now.</div>
diff --git a/apps/cua-spaces-web/src/routes/settings/connectors.$app.tsx b/apps/cua-spaces-web/src/routes/settings/connectors.$app.tsx
new file mode 100644
index 0000000000..b2b7161066
--- /dev/null
+++ b/apps/cua-spaces-web/src/routes/settings/connectors.$app.tsx
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { createFileRoute, redirect } from "@tanstack/react-router";
+
+import { flagOn } from "@/bridge";
+import { ConnectorAppPage } from "@/components/settings/connectors/app-detail";
+
+/** One coding app's page under Connectors (the redesign; off, Connectors as it was). */
+export const Route = createFileRoute("/settings/connectors/$app")({
+ beforeLoad: ({ params }) => {
+ if (!flagOn("spaces_redesign")) throw redirect({ to: "/settings/connectors", search: { app: params.app } });
+ },
+ component: AppPage,
+});
+
+function AppPage() {
+ const { app } = Route.useParams();
+ return <ConnectorAppPage agent={app} />;
+}
diff --git a/apps/cua-spaces-web/src/routes/settings/connectors.tsx b/apps/cua-spaces-web/src/routes/settings/connectors.tsx
index 7995cabb12..50a6c04dd0 100644
--- a/apps/cua-spaces-web/src/routes/settings/connectors.tsx
+++ b/apps/cua-spaces-web/src/routes/settings/connectors.tsx
@@ -1,12 +1,13 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { createFileRoute } from "@tanstack/react-router";
+import { createFileRoute, Outlet, useMatch } from "@tanstack/react-router";
-import { useAgentKeys, useCliInstall, useSettings } from "@/bridge";
+import { useAgentKeys, useCliInstall, useFlag, useSettings } from "@/bridge";
import { AccountKeysSection } from "@/components/settings/account-keys";
import { CliSettingsSection } from "@/components/settings/cli-section";
import { CodingAppsSection } from "@/components/settings/coding-apps-section";
+import { ConnectorsRedesign } from "@/components/settings/connectors/connectors-page";
import { useConnectedApps } from "@/hooks/use-connected-apps";
import { useQuiet } from "@/hooks/use-quiet";
@@ -21,6 +22,29 @@ export const Route = createFileRoute("/settings/connectors")({
* Its parts come from separate host reads; the page draws once they have answered, not one by one with the page jumping at each (CUA-1951).
*/
function ConnectorsPage() {
+ // An app's own page (`/settings/connectors/<app>`, the redesign) draws in place of the list.
+ const child = useMatch({ from: "/settings/connectors/$app", shouldThrow: false });
+ const redesign = useFlag("spaces_redesign");
+ if (child) return <Outlet />;
+ return redesign ? <Redesign /> : <Classic />;
+}
+
+/** The redesign: Coding apps with Connect and their pages, then Providers. */
+function Redesign() {
+ const { app } = Route.useSearch();
+ const { data } = useSettings();
+ const cli = useCliInstall();
+ const settled = useQuiet(`${data?.cli ? 1 : 0}|${cli.state.plan ? 1 : 0}`);
+ if (!settled) return <div className="h-96" aria-busy="true" />;
+ return (
+ <div data-settings-tab="connectors">
+ <ConnectorsRedesign focusApp={app} />
+ <CliSettingsSection />
+ </div>
+ );
+}
+
+function Classic() {
const { app } = Route.useSearch();
const { data } = useSettings();
const apps = useConnectedApps();
diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
index e36534c8da..facb9f6707 100644
--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
@@ -20,6 +20,8 @@ import { SpaceHeader } from "@/components/space-detail/space-header";
import { SpaceCall } from "@/components/space-thread/space-call";
import { StateLabel } from "@/components/state-dot";
import { PageTip } from "@/components/tips";
+import { creatingThread } from "@/components/space-thread/queued";
+import { useAskTasks } from "@/lib/ask-first";
import { ConfirmDialog } from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
@@ -104,6 +106,9 @@ function SpaceDetailPage() {
// The Space's thread (CUA-2155). A daemon without it answers unsupported,
// and the page keeps its classic layout; a create still in progress has none yet.
const thread = useSpaceThread(space && !space.id.startsWith("pending:") ? space.id : null);
+ const askFirstOn = useFlag("spaces_ask_first_home");
+ // Ask first's tasks: a Space being made for one draws as the Space page in its creating state.
+ const tasks = useAskTasks();
// Open on a creating row: once the create finished and the registry lists
// the Space, its row (and this id) goes; follow it to the Space's own id.
// Only a page that showed the row follows: the address of a row that is
@@ -399,15 +404,22 @@ function SpaceDetailPage() {
const desktopPip = desktopRow?.actions.find((a) => a.id === "pip");
const powerError = detail.powerError ? <p className="mb-4 text-[13px] text-destructive">{detail.powerError}</p> : null;
// One tip at a time (the core's `tips.view`, place `space`).
- const tip = <PageTip place="space" space={space} onShare={shareAction?.enabled ? share : undefined} />;
+ // A Space made for an Ask-first job is busy with its agent: no tip (it would also appear once ready and move the page).
+ const askSpace = askFirstOn && tasks.some((t) => t.pendingId === space.id || (t.inSpace && t.spaceId === space.id));
+ const tip = askSpace ? null : <PageTip place="space" space={space} onShare={shareAction?.enabled ? share : undefined} />;
// In the call layout the tip sits directly on the stage and the rail: no gap under it, so the rail meets it flush.
- const callTip = <PageTip place="space" space={space} onShare={shareAction?.enabled ? share : undefined} className="mb-0" />;
+ const callTip = askSpace ? null : <PageTip place="space" space={space} onShare={shareAction?.enabled ? share : undefined} className="mb-0" />;
// The call layout: the desktop on top, the thread below, the people on the
// right. A machine's own page (no desktop to call into) and a daemon
// without the thread keep the classic page.
// A create still in progress has no thread yet: its progress shows on the classic page.
- if (!detail.desktopNote && thread.status !== "unsupported" && !space.id.startsWith("pending:")) {
+ // A Space being made for an Ask-first job: the same page in its creating state (progress on
+ // the stage, the job queued in the thread); a failed create keeps the classic page's fixes.
+ const creating = space.id.startsWith("pending:") && askFirstOn && state !== "failed" && tasks.some((t) => t.pendingId === space.id);
+ const callThread = creating ? creatingThread(space.id) : thread;
+ const later = "Available once the Space is ready";
+ if (!detail.desktopNote && callThread.status !== "unsupported" && (creating || !space.id.startsWith("pending:"))) {
return (
<>
<SpaceCall
@@ -421,7 +433,9 @@ function SpaceDetailPage() {
title={detail.title}
place={place}
power={
- canPower(space)
+ creating
+ ? { state: "pending", label: "Being made", onClick: () => {} }
+ : canPower(space)
? pending
? { state: "pending", label: pending, onClick: () => {} }
: state === "stopped"
@@ -430,13 +444,13 @@ function SpaceDetailPage() {
: undefined
}
pip={
- desktopPip
+ !creating && desktopPip
? { id: desktopRow!.id, label: desktopPip.help ?? "Pop out", help: desktopPip.help ?? undefined, enabled: true, active: desktopPip.active, onClick: () => void onPip(desktopRow!) }
: undefined
}
- teleport={teleportAction ? { label: teleportAction.label, help: teleportAction.help ?? undefined, enabled: teleportAction.enabled, onClick: teleportApp } : undefined}
- share={shareAction ? { label: shareAction.label, help: shareAction.help ?? undefined, enabled: shareAction.enabled, onClick: share } : undefined}
- remove={canDelete(space) ? { label: detail.deleteLabel, enabled: true, onClick: () => setConfirm("delete") } : undefined}
+ teleport={creating ? { label: "Teleport an app", help: later, enabled: false, onClick: () => {} } : teleportAction ? { label: teleportAction.label, help: teleportAction.help ?? undefined, enabled: teleportAction.enabled, onClick: teleportApp } : undefined}
+ share={creating ? { label: "Share", help: later, enabled: false, onClick: () => {} } : shareAction ? { label: shareAction.label, help: shareAction.help ?? undefined, enabled: shareAction.enabled, onClick: share } : undefined}
+ remove={!creating && canDelete(space) ? { label: detail.deleteLabel, enabled: true, onClick: () => setConfirm("delete") } : undefined}
dismiss={state === "failed" ? { label: "Remove", enabled: true, onClick: dismiss } : undefined}
/>
}
@@ -452,11 +466,12 @@ function SpaceDetailPage() {
smallStage={surface("h-full", shownRow?.id ?? null, shownView?.app ?? null, false)}
aspect={aspect}
stageLabel={shownRow?.label ?? "Desktop"}
- thread={thread}
+ thread={callThread}
+ creating={creating}
facts={detail.facts}
more={sections}
- windows={stream?.rows.filter((r) => r.kind === "window") ?? []}
- desktop={desktopRow ?? null}
+ windows={creating ? [] : (stream?.rows.filter((r) => r.kind === "window") ?? [])}
+ desktop={creating ? null : (desktopRow ?? null)}
selected={shownRow?.id ?? null}
onSelect={(row) => setShown(row.kind === "window" ? { spaceId: space.id, row: row.id } : null)}
view={shownView}
diff --git a/apps/cua-spaces-web/src/routes/spaces/index.tsx b/apps/cua-spaces-web/src/routes/spaces/index.tsx
index 88d1d710d9..9b3141b195 100644
--- a/apps/cua-spaces-web/src/routes/spaces/index.tsx
+++ b/apps/cua-spaces-web/src/routes/spaces/index.tsx
@@ -17,6 +17,7 @@ import { SpaceContextMenu, SpaceMoreMenu, type MenuActions } from "@/components/
import { SelectAllBox, SelectBox, SelectionBar, stoppedDeletable, useSelection } from "@/components/spaces/selection";
import { SpaceTile, TILE_CELL } from "@/components/spaces/space-tile";
import { CreatingElsewhereTile } from "@/components/spaces/creating-elsewhere-tile";
+import { WindowedGrid, type WindowedGridHandle } from "@/components/spaces/windowed-grid";
import { SpacesToolbar } from "@/components/spaces/spaces-toolbar";
import { PageTip, useTipsLoaded } from "@/components/tips";
import { useNewSpace } from "@/hooks/use-new-space";
@@ -70,14 +71,21 @@ function SpacesPage() {
[spaces, machines, resources],
);
const item = (s: Space) => items.get(s.id)!;
- const shown = shownSpaces({
- spaces,
- search,
- mine: (s) => item(s).mine,
- machineOf: (s) => spaceMachineId(s, machines),
- bytes: (s) => item(s).bytes,
- matches: (s) => matchesQuery(core, s, item(s).machine, query),
- }).map(item);
+ // Only when the list, the filters or the numbers change: a pick or a menu redraws the page without
+ // filtering and sorting thousands of Spaces again.
+ const shown = useMemo(
+ () =>
+ shownSpaces({
+ spaces,
+ search,
+ mine: (s) => item(s).mine,
+ machineOf: (s) => spaceMachineId(s, machines),
+ bytes: (s) => item(s).bytes,
+ matches: (s) => matchesQuery(core, s, item(s).machine, query),
+ }).map(item),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `item` reads `items`
+ [spaces, search, items, machines, query, core],
+ );
const filter = search.state ?? "all";
// Spaces your other computers are creating (CUA-2349): first in the grid, until they are ready.
const elsewhere =
@@ -120,6 +128,7 @@ function SpacesPage() {
// The grid's tiles read the selection and the menus' actions through this,
// so a tile redraws only when its own Space, pick or state changes (picking
// one of 3,000 Spaces redrew all 3,000).
+ const grid = useRef<WindowedGridHandle>(null);
const live = useRef<GridLive>({ selection, actions });
live.current = { selection, actions };
// `?select=stopped` (the cleanup tip, a link): every stopped Space shown of yours, once the list is in.
@@ -127,6 +136,9 @@ function SpacesPage() {
useEffect(() => {
if (search.select !== "stopped" || !ready) return;
selection.selectStopped();
+ // The first one picked, on screen (a long grid draws only what is on screen).
+ const first = shown.findIndex(stoppedDeletable);
+ if (first >= 0) grid.current?.scrollToIndex(elsewhereTiles.length + first);
setSearch({ select: undefined });
// eslint-disable-next-line react-hooks/exhaustive-deps -- once, when the list is in
}, [search.select, ready]);
@@ -250,19 +262,25 @@ function SpacesPage() {
/>
</>
) : (
- <ul data-picking={selection.ids.size > 0 || undefined} className="group/grid grid grid-cols-[repeat(auto-fill,minmax(232px,1fr))] gap-x-5 gap-y-7">
- {elsewhereTiles}
- {shown.map((it) => (
- <GridTile
- key={it.space.id}
- item={it}
- selected={selection.has(it.space.id)}
- busy={bulk.running.has(it.space.id)}
- accessKey={keyvault.signedIn.has(it.space.id) ? keyvault.accessKey(it.space.id) : undefined}
- live={live}
- />
- ))}
- </ul>
+ <WindowedGrid
+ ref={grid}
+ picking={selection.ids.size > 0}
+ count={elsewhereTiles.length + shown.length}
+ renderAt={(i) => {
+ if (i < elsewhereTiles.length) return elsewhereTiles[i];
+ const it = shown[i - elsewhereTiles.length]!;
+ return (
+ <GridTile
+ key={it.space.id}
+ item={it}
+ selected={selection.has(it.space.id)}
+ busy={bulk.running.has(it.space.id)}
+ accessKey={keyvault.signedIn.has(it.space.id) ? keyvault.accessKey(it.space.id) : undefined}
+ live={live}
+ />
+ );
+ }}
+ />
);
}
})()}
diff --git a/apps/cua-spaces-web/vite.config.ts b/apps/cua-spaces-web/vite.config.ts
index 6d852bf5ab..23c08e8c47 100644
--- a/apps/cua-spaces-web/vite.config.ts
+++ b/apps/cua-spaces-web/vite.config.ts
@@ -59,8 +59,9 @@ export default defineConfig({
// runner under the whole suite's load takes seconds where a laptop
// takes milliseconds (see src/test-setup.ts).
setupFiles: ["src/test-setup.ts"],
- // The suite tests the redesign (`spaces_redesign`); src/legacy/__tests__
- // turn it off to keep the default UI working.
+ // The redesign (`spaces_redesign`) is the default; the suite sets it
+ // explicitly, and src/legacy/__tests__ turn it off to keep the classic
+ // pages working.
env: { VITE_CUA_FLAG_SPACES_REDESIGN: "1" },
testTimeout: 15_000,
},
diff --git a/apps/cua-spaces/src/components/SettingsPanel.test.tsx b/apps/cua-spaces/src/components/SettingsPanel.test.tsx
index 8fdae4b10f..e6ada5d96f 100644
--- a/apps/cua-spaces/src/components/SettingsPanel.test.tsx
+++ b/apps/cua-spaces/src/components/SettingsPanel.test.tsx
@@ -385,12 +385,12 @@ describe("SettingsPanel Privacy", () => {
expect(screen.getByTitle("Set by env DO_NOT_TRACK")).toBeInTheDocument();
});
- it("lists Account, Teams, General, Privacy, AI agents and Experiments in order, with Show again", async () => {
+ it("lists Account, Teams, General, Runtimes, Privacy, AI agents and Experiments in order, with Show again", async () => {
const onShowWelcome = vi.fn();
renderPanel({ telemetry: fakeTelemetry(), onShowWelcome });
await screen.findByText("Share usage data to help improve Cua");
const titles = screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent);
- expect(titles).toEqual(["Account", "Teams", "General", "Privacy", "AI agents", "Experiments", "Language"]);
+ expect(titles).toEqual(["Account", "Teams", "General", "Runtimes", "Privacy", "AI agents", "Experiments", "Language"]);
await userEvent.click(screen.getByRole("button", { name: "Show again" }));
expect(onShowWelcome).toHaveBeenCalled();
});
diff --git a/apps/cua-spaces/src/model/parity.test.ts b/apps/cua-spaces/src/model/parity.test.ts
index f71c40b881..42aae4d0df 100644
--- a/apps/cua-spaces/src/model/parity.test.ts
+++ b/apps/cua-spaces/src/model/parity.test.ts
@@ -254,6 +254,7 @@ describe('app core parity flows (webview)', () => {
'bulk-confirm',
'tips',
'pro-banner',
+ 'connectors',
]);
});
diff --git a/docs/content/docs/cua-cli/reference/cli/agents.mdx b/docs/content/docs/cua-cli/reference/cli/agents.mdx
index eb48859ff3..14fb707970 100644
--- a/docs/content/docs/cua-cli/reference/cli/agents.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/agents.mdx
@@ -1053,7 +1053,7 @@ cua connect setup [OPTIONS]
| <span id="cua-connect-setup--yes"></span>`--yes` | `-y` | boolean | `false` | Answer yes to every prompt. |
| <span id="cua-connect-setup--force"></span>`--force` | | boolean | `false` | Replace skill folders cua did not write (the old one is backed up). |
| <span id="cua-connect-setup--cua-driver"></span>`--cua-driver` | | boolean | `false` | Set up background computer-use instead: the cua-driver skill and the cua-driver MCP server (`cua-driver mcp`). --mcp-command then names the cua-driver binary. |
-| <span id="cua-connect-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also copy each agent's sign-in to Keyvault on This Mac, so its runs in your Spaces use it: Codex's ChatGPT sign-in (`~/.codex/auth.json`), Claude Code's `claude setup-token` (one browser approval), Hermes' provider key (`~/.hermes/.env`). The agent's own sign-in is never changed. |
+| <span id="cua-connect-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed. |
**Examples**
@@ -1178,7 +1178,7 @@ cua agents setup [OPTIONS]
| <span id="cua-agents-setup--yes"></span>`--yes` | `-y` | boolean | `false` | Answer yes to every prompt. |
| <span id="cua-agents-setup--force"></span>`--force` | | boolean | `false` | Replace skill folders cua did not write (the old one is backed up). |
| <span id="cua-agents-setup--cua-driver"></span>`--cua-driver` | | boolean | `false` | Set up background computer-use instead: the cua-driver skill and the cua-driver MCP server (`cua-driver mcp`). --mcp-command then names the cua-driver binary. |
-| <span id="cua-agents-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also copy each agent's sign-in to Keyvault on This Mac, so its runs in your Spaces use it: Codex's ChatGPT sign-in (`~/.codex/auth.json`), Claude Code's `claude setup-token` (one browser approval), Hermes' provider key (`~/.hermes/.env`). The agent's own sign-in is never changed. |
+| <span id="cua-agents-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed. |
**Examples**
diff --git a/docs/content/docs/cua-sdk/guides/local-runtimes.mdx b/docs/content/docs/cua-sdk/guides/local-runtimes.mdx
index 08b6dfd889..b2d05cc64e 100644
--- a/docs/content/docs/cua-sdk/guides/local-runtimes.mdx
+++ b/docs/content/docs/cua-sdk/guides/local-runtimes.mdx
@@ -288,3 +288,23 @@ The first match wins:
`default.kind` and `default.runtime` (`CUA_DEFAULT_KIND`,
`CUA_DEFAULT_RUNTIME`) work the same way, and `cua doctor` shows each default
with its source. Switch back with `cua config unset default.on`.
+
+## Choose what runs each kind
+
+Each kind of Space has its own setting: `runtime.container`, `runtime.vm` and
+`runtime.microvm`. Each is `auto` (the default), `builtin` (Cua's own, set up
+the first time it is needed) or `system` (only what is already installed on
+this machine; nothing is downloaded). With `system`, `runtime.<kind>_path`
+names the program to use instead of the one found on `PATH`, for example
+another Docker:
+
+```bash test="cli-shape" id="cua-config-set-runtime-container"
+cua config set runtime.container system
+cua config set runtime.container_path /opt/homebrew/bin/podman
+cua config unset runtime.container_path # back to the one found
+```
+
+The Cua app's Settings, Advanced shows the same settings, one row per kind,
+with the programs it found and a check of the path. `cua` and the daemon read
+the same values, so they use the same program. The older `runtime.linux` and
+`runtime.lume` still work: they are `runtime.container` and `runtime.vm`.
diff --git a/docs/content/docs/cua-sdk/reference/agent-setup.mdx b/docs/content/docs/cua-sdk/reference/agent-setup.mdx
index 7dbaec993b..1b10508d96 100644
--- a/docs/content/docs/cua-sdk/reference/agent-setup.mdx
+++ b/docs/content/docs/cua-sdk/reference/agent-setup.mdx
@@ -25,7 +25,10 @@ Returned by [`Cua.agent_setup`](/cua-sdk/reference/cua#cua).
| [`configure_mcp`](#agentsetupconfigure_mcp) | Configures the MCP server (default: `cua mcp`, `cua` resolved on PATH; `cua-local mcp` named `cua-local` for the Local app) for `agents`. |
| [`connect_json`](#agentsetupconnect_json) | Connect (and Reconnect) for `agents`: Cua's skills and MCP entry (`server`, default this channel's cua), and with `sign_in` the agent's sign-in copied into Keyvault on This Mac (Claude Code waits for its one browser approval). |
| [`connection_status_json`](#agentsetupconnection_status_json) | Whether each agent is really connected (CONTRACT §4: `{agents, checked_at_ms}`), as JSON, the same JSON `cua connect status --json` prints and the `connect_status` MCP tool answers. |
+| [`device_sign_in_start_json`](#agentsetupdevice_sign_in_start_json) | Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login --device-auth` in a folder Cua owns). |
+| [`device_sign_in_wait_json`](#agentsetupdevice_sign_in_wait_json) | Waits for a device sign-in to be approved and saves it into Keyvault on This Mac. |
| [`disconnect_json`](#agentsetupdisconnect_json) | Disconnect: what Connect did, undone (the previous config entry back from Cua's record, the skills, and with `sign_in` the copy in Keyvault). |
+| [`disconnect_parts_json`](#agentsetupdisconnect_parts_json) | Disconnect of some parts only (an app's page's switches): Cua's skills and/or its MCP entry, and with `sign_in` the copy in Keyvault. |
| [`install_skills`](#agentsetupinstall_skills) | Installs `skills` (empty: all bundled) for `agents`. |
| [`remove`](#agentsetupremove) | Removes what cua added for `agents` (skills and/or MCP). |
| [`select`](#agentsetupselect) | Resolves `all` (installed agents), `none` or `claude,codex` to ids. |
@@ -202,6 +205,107 @@ pub fn connection_status_json(&self, expected: Option<AgentMcpServer>, refresh:
**Returns** `String`
+### `AgentSetup.device_sign_in_start_json`
+
+Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+--device-auth` in a folder Cua owns). JSON `&#123;id, url, code&#125;`: show the
+link and the code, then wait with `Self.device_sign_in_wait_json`.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def device_sign_in_start_json(self, agent: str) -> str
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+deviceSignInStartJson(agent: string, asyncOpts_?: { signal: AbortSignal }): Promise<string>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func deviceSignInStartJson(agent: String) async throws -> String
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun deviceSignInStartJson(agent: String): String
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn device_sign_in_start_json(&self, agent: String) -> Result<String, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `agent` | `String` | required |
+
+**Returns** `String` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `AgentSetup.device_sign_in_wait_json`
+
+Waits for a device sign-in to be approved and saves it into Keyvault on
+This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def device_sign_in_wait_json(self, id: str) -> str
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+deviceSignInWaitJson(id: string, asyncOpts_?: { signal: AbortSignal }): Promise<string>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func deviceSignInWaitJson(id: String) async throws -> String
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun deviceSignInWaitJson(id: String): String
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn device_sign_in_wait_json(&self, id: String) -> Result<String, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `id` | `String` | required |
+
+**Returns** `String` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
### `AgentSetup.disconnect_json`
Disconnect: what Connect did, undone (the previous config entry back
@@ -254,6 +358,60 @@ pub async fn disconnect_json(&self, agents: Vec<String>, sign_in: bool) -> Resul
**Returns** `String` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+### `AgentSetup.disconnect_parts_json`
+
+Disconnect of some parts only (an app's page's switches): Cua's skills
+and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+`{outcomes, removed_sign_ins}`.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def disconnect_parts_json(self, agents: List[str], skills: bool, mcp: bool, sign_in: bool) -> str
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+disconnectPartsJson(agents: Array<string>, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func disconnectPartsJson(agents: [String], skills: Bool, mcp: Bool, signIn: Bool) async throws -> String
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun disconnectPartsJson(agents: List<String>, skills: Boolean, mcp: Boolean, signIn: Boolean): String
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn disconnect_parts_json(&self, agents: Vec<String>, skills: bool, mcp: bool, sign_in: bool) -> Result<String, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `agents` | `Vec<String>` | required |
+| `skills` | `bool` | required |
+| `mcp` | `bool` | required |
+| `sign_in` | `bool` | required |
+
+**Returns** `String` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
### `AgentSetup.install_skills`
Installs `skills` (empty: all bundled) for `agents`. Folders cua did
diff --git a/docs/content/docs/cua-sdk/reference/cua.mdx b/docs/content/docs/cua-sdk/reference/cua.mdx
index f035cc1db2..f4570ee858 100644
--- a/docs/content/docs/cua-sdk/reference/cua.mdx
+++ b/docs/content/docs/cua-sdk/reference/cua.mdx
@@ -1034,7 +1034,7 @@ Returned by [`config_get`](#config_get), [`config_list`](#config_list), [`config
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `key` | `String` | | `default.on`, `default.kind`, `default.runtime`, `runtime.lume`, `runtime.linux` or `telemetry.enabled`. |
+| `key` | `String` | | `default.on`, `default.kind`, `default.runtime`, `runtime.container`, `runtime.vm`, `runtime.microvm` (and their `_path`) or `telemetry.enabled`. |
| `value` | `String` | | The effective value. |
| `source` | `String` | | `env`, `config` or `default`. |
| `from` | `String` | | Where exactly: `env CUA_DEFAULT_ON`, `config /home/me/.cua/config.toml` or `default`. |
@@ -1224,6 +1224,8 @@ Returned by [`Cua.local`](#cua).
| [`push_image`](#localpush_image) | Copies an image (host architecture) to `destination`; returns the pushed manifest digest. |
| [`setup`](#localsetup) | Provisions `components` (`qemu`, `lume`; `runsc` reports its plan). |
| [`storage`](#localstorage) | Free space where local Spaces are written (Lume's VM storage, the cua home for QEMU, the container engine's data disk) and which catalog images are already pulled. |
+| [`runtime_check_path`](/cua-sdk/reference/runtime-kinds#localruntime_check_path) | What `path` is for `kind` (`container`, `vm`, `microvm`): there, runnable, which runtime and its version. |
+| [`runtime_kinds`](/cua-sdk/reference/runtime-kinds#localruntime_kinds) | Each kind of Space (`container`, `vm`, `microvm`) with its runtime setting (`runtime.<kind>`), the runtimes installed on this machine for it and what the path in use is. |
### `Local.build_image`
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index d07c15d525..138659b80d 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -26,6 +26,7 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| Page | Covers |
| --- | --- |
| [Cua client and local runtimes](/cua-sdk/reference/cua) | The Cua handle (embedded or daemon client, configuration, SDK version) and the local container and VM runtimes. |
+| [Runtime per kind](/cua-sdk/reference/runtime-kinds) | Which program runs containers, virtual machines and microVMs on this machine, and what a given binary is. |
| [Sandbox](/cua-sdk/reference/sandbox) | Create, find, connect to and control sandboxes, and their lifecycle: wait, suspend, resume, restart, detach and delete. |
| [Lifecycle](/cua-sdk/reference/sandbox/lifecycle) | Wait for, keep alive, give a lifetime to, suspend, resume, restart, resize, detach and delete a sandbox. |
| [Checkpoints and forks](/cua-sdk/reference/sandbox/checkpoints) | Save a local sandbox's state as a named checkpoint and start new sandboxes from it. |
@@ -97,4 +98,4 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| --- | --- |
| [Protocol](/cua-sdk/reference/protocol) | The gRPC contracts of cua-spacesd (`cua.env.v1`) and the cua daemon (`cua.daemon.v1`). |
-350 items, 432 methods. The [Types](/cua-sdk/reference/types) page lists them.
+353 items, 437 methods. The [Types](/cua-sdk/reference/types) page lists them.
diff --git a/docs/content/docs/cua-sdk/reference/meta.json b/docs/content/docs/cua-sdk/reference/meta.json
index fd83925141..689d931973 100644
--- a/docs/content/docs/cua-sdk/reference/meta.json
+++ b/docs/content/docs/cua-sdk/reference/meta.json
@@ -3,6 +3,7 @@
"pages": [
"---Sandboxes---",
"cua",
+ "runtime-kinds",
"sandbox",
"share",
"image",
diff --git a/docs/content/docs/cua-sdk/reference/runtime-kinds.mdx b/docs/content/docs/cua-sdk/reference/runtime-kinds.mdx
new file mode 100644
index 0000000000..f87fc1f005
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/runtime-kinds.mdx
@@ -0,0 +1,165 @@
+---
+title: "Runtime per kind"
+description: "Which program runs containers, virtual machines and microVMs on this machine, and what a given binary is."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs (UniFFI metadata of libcua_sdk)
+ Version: 0.9.0
+*/}
+
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+Each kind of Space has its own setting, `runtime.container`, `runtime.vm` and `runtime.microvm` (`auto`, `builtin` or `system`), and with `system` a `runtime.<kind>_path` naming the program to use. `runtime_kinds` reads them with what is installed for each kind; `runtime_check_path` tells what a binary is before it is saved. The Cua app's Settings, Advanced shows the same, and `cua` and the daemon use the same program.
+
+## Runtime per kind methods
+
+Methods of [`Local`](/cua-sdk/reference/cua#local).
+
+### `Local.runtime_kinds`
+
+Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+setting (`runtime.<kind>`), the runtimes installed on this machine
+for it and what the path in use is. Read-only: runs each runtime's
+`--version`, nothing else; probed in this process (the daemon runs
+on the same host).
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def runtime_kinds(self) -> List[RuntimeKindState]
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+runtimeKinds(asyncOpts_?: { signal: AbortSignal }): Promise<Array<RuntimeKindState>>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func runtimeKinds() async throws -> [RuntimeKindState]
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun runtimeKinds(): List<RuntimeKindState>
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn runtime_kinds(&self) -> Result<Vec<RuntimeKindState>, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+**Returns** [`Vec<RuntimeKindState>`](#runtimekindstate-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Local.runtime_check_path`
+
+What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+runnable, which runtime and its version. Settings checks a typed path
+with it before it is saved (`runtime.<kind>_path`).
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def runtime_check_path(self, kind: str, path: str) -> RuntimePathProbe
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+runtimeCheckPath(kind: string, path: string, asyncOpts_?: { signal: AbortSignal }): Promise<RuntimePathProbe>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func runtimeCheckPath(kind: String, path: String) async throws -> RuntimePathProbe
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun runtimeCheckPath(kind: String, path: String): RuntimePathProbe
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn runtime_check_path(&self, kind: String, path: String) -> Result<RuntimePathProbe, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `kind` | `String` | required |
+| `path` | `String` | required |
+
+**Returns** [`RuntimePathProbe`](#runtimepathprobe-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## `RuntimeKindState` record
+
+One kind of Space's runtime, as Settings shows it.
+
+Returned by [`Local.runtime_kinds`](#localruntime_kinds).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `kind` | `String` | | `container`, `vm` or `microvm`. |
+| `source` | `String` | | `runtime.<kind>`: `auto`, `builtin` or `system`. |
+| `path` | `Option<String>` | | `runtime.<kind>_path`, when set. |
+| `detected` | [`Vec<RuntimeDetected>`](#runtimedetected-record) | | What is installed here for the kind, the one used first. |
+| `check` | [`Option<RuntimePathProbe>`](#runtimepathprobe-record) | | The path in use (the custom one, else the first detected), probed. |
+| `expected` | `Vec<String>` | | The names of the tools the kind takes here (`Docker`, `Podman`). |
+
+## `RuntimeDetected` record
+
+A runtime installed on this machine for one kind of Space.
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `tool` | `String` | | `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`. |
+| `name` | `String` | | As people know it (`Docker`, `Apple container`). |
+| `path` | `String` | | |
+| `version` | `Option<String>` | | As `--version` says it (`27.3.1`). |
+| `guests` | `Option<String>` | | The guest system it runs, when only one (`macOS`, `Linux`). |
+
+## `RuntimePathProbe` record
+
+What a binary is, for one kind of Space (`runtime_check_path`).
+
+Returned by [`Local.runtime_check_path`](#localruntime_check_path).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `path` | `String` | | |
+| `exists` | `bool` | | A file is there. |
+| `executable` | `bool` | | It can be run. |
+| `tool` | `Option<String>` | | The tool it is, when it is one the kind takes. |
+| `name` | `Option<String>` | | |
+| `version` | `Option<String>` | | |
+| `min_version` / `minVersion` | `Option<String>` | | The oldest version cua runs on. |
+| `expected` | `Vec<String>` | | The names of the tools the kind takes here (`Docker`, `Podman`). |
+| `guests` | `Option<String>` | | |
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
index d68ff6541d..127986bb2b 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
@@ -18,7 +18,7 @@ The cua SDK: the only `#[uniffi::export]` crate of `libs/cua`.
These are the objects, records, enums and functions the language bindings export, documented once in the [Cua SDK reference](/cua-sdk/reference), whose Rust tabs show each signature. Objects are `Arc<T>` handles whose methods are `async fn` returning `Result<_, CuaError>`, records are structs with public fields, and names are snake_case.
-[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
+[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record), [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record), [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
## Types
diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdx
index 609568bdac..5ac30901b0 100644
--- a/docs/content/docs/cua-sdk/reference/types.mdx
+++ b/docs/content/docs/cua-sdk/reference/types.mdx
@@ -48,7 +48,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f
## All items
-322 items. Methods are listed on their object.
+325 items. Methods are listed on their object.
The 10 items of Batched forks are listed on [its page](/cua-sdk/reference/sandbox/fork-batch#all-items).
@@ -267,6 +267,9 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record) | record | A routine: a recurring turn of a persistent agent, fired by the daemon. |
| [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record) | record | One doctor check (one backend). |
| [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum) | enum | Status of one local runtime component. |
+| [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record) | record | A runtime installed on this machine for one kind of Space. |
+| [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record) | record | One kind of Space's runtime, as Settings shows it. |
+| [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record) | record | What a binary is, for one kind of Space (`runtime_check_path`). |
| [`Sandbox`](/cua-sdk/reference/sandbox#sandbox) | object | A sandbox handle. |
| [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations) | function | Every location word `on=` accepts, in display order: `local`, `cloud`, then the contrib providers (`e2b`, `daytona`, `modal`, ...) and your own… |
| [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record) | record | Options for `Sandboxes.create`. |
diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.md
index 835f8a1525..ff4d0f38f9 100644
--- a/libs/cua-spacesd/crates/cua-relay/README.md
+++ b/libs/cua-spacesd/crates/cua-relay/README.md
@@ -428,6 +428,8 @@ register machines: `CUA_RELAY_TOKENS`/`CUA_RELAY_TOKEN_FILE` or
| `CUA_RELAY_TOKENS` | unset | Static mode: comma-separated registration tokens. |
| `CUA_RELAY_TOKEN_FILE` | unset | Static mode: one token per line (`#` comments). |
| `CUA_RELAY_MAX_MACHINES_PER_TOKEN` | `16` | Static mode: machines per registration token. |
+| `CUA_RELAY_JOIN_RATE_PER_SEC` | `250` | Computer joins admitted per second once the burst is used. A restart brings every computer back at once: the rest get `503` with a jittered `Retry-After`, which the join client honours. `0` turns the limit off. |
+| `CUA_RELAY_JOIN_BURST` | `500` | Computer joins admitted at once. |
| `CUA_RELAY_ALLOW_ANONYMOUS_CLIENTS` | off | Static mode: also forward requests without a spacesd credential. |
| `CUA_RELAY_HOST_DOMAIN` | unset | Host mode: `<machine-id>.<domain>` routes to that machine, and path mode (`/m/<id>/…`) refuses on the main origin (S6; see "Machine origin" below). |
| `CUA_RELAY_ADMIN_TOKEN` | unset | Enables `GET /relay/v1/machines`. |
diff --git a/libs/cua-spacesd/crates/cua-relay/src/client.rs b/libs/cua-spacesd/crates/cua-relay/src/client.rs
index 2c40a6896c..de34428c72 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/client.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/client.rs
@@ -87,6 +87,10 @@ pub struct JoinConfig {
pub heartbeat: Duration,
/// Backoff cap.
pub max_backoff: Duration,
+ /// The first reconnect after a session that was up is spread over this
+ /// long (uniformly from a tenth of it): a relay restart drops every
+ /// machine at once, and they should not all knock together.
+ pub reconnect_spread: Duration,
/// Re-read the relay token from this file before every attempt (so
/// `cua host setup` can rotate the machine token under a running
/// service). Overrides `relay_token` when readable and non-empty.
@@ -111,6 +115,7 @@ impl JoinConfig {
local,
heartbeat: Duration::from_secs(15),
max_backoff: Duration::from_secs(30),
+ reconnect_spread: Duration::from_secs(5),
relay_token_file: None,
account: Arc::default(),
}
@@ -148,15 +153,37 @@ pub fn connect_url(relay_url: &str) -> Result<String, String> {
Ok(url.to_string())
}
-/// Backoff with full jitter in [base/2, base], doubling up to `cap`.
+/// Backoff with jitter in [base/2, base], doubling up to `cap`.
pub fn backoff(attempt: u32, cap: Duration) -> Duration {
+ backoff_with(attempt, cap, rand::thread_rng().gen_range(0.5..=1.0))
+}
+
+/// [`backoff`] with the jitter factor (0.5 to 1.0) given.
+pub fn backoff_with(attempt: u32, cap: Duration, jitter: f64) -> Duration {
let base = Duration::from_millis(500)
.saturating_mul(1u32 << attempt.min(16))
.min(cap);
- let jitter = rand::thread_rng().gen_range(0.5..=1.0);
base.mul_f64(jitter)
}
+/// How long to wait before the next connect. The first one after a session
+/// that was up is spread over `spread` (`unit` is a random number from 0 to
+/// 1): machines drop together when the relay restarts, and a thousand of
+/// them retrying within half a second is a storm. Later attempts back off.
+pub fn reconnect_delay(
+ attempt: u32,
+ cap: Duration,
+ was_up: bool,
+ spread: Duration,
+ unit: f64,
+) -> Duration {
+ if was_up && attempt == 0 && !spread.is_zero() {
+ let low = spread / 10;
+ return low + (spread - low).mul_f64(unit.clamp(0.0, 1.0));
+ }
+ backoff_with(attempt, cap, 0.5 + 0.5 * unit.clamp(0.0, 1.0))
+}
+
/// Why a session ended.
#[derive(Debug)]
pub enum SessionEnd {
@@ -166,6 +193,9 @@ pub enum SessionEnd {
Refused(String),
/// Transport failure.
Lost(String),
+ /// The relay is busy admitting joins (`503` with `Retry-After`): come
+ /// back after this long.
+ Throttled(Duration),
}
/// Runs until `shutdown`: connect, serve, reconnect with backoff.
@@ -178,13 +208,30 @@ pub async fn run(config: JoinConfig, shutdown: CancellationToken) {
SessionEnd::Shutdown => return,
SessionEnd::Refused(reason) => tracing::warn!(%reason, "relay join refused"),
SessionEnd::Lost(reason) => tracing::info!(%reason, "relay connection lost"),
+ SessionEnd::Throttled(after) => tracing::info!(?after, "the relay is busy"),
}
// A session that stayed up for a while resets the backoff.
if started.elapsed() > Duration::from_secs(60) {
attempt = 0;
}
- let delay = backoff(attempt, config.max_backoff);
- attempt = attempt.saturating_add(1);
+ let was_up = started.elapsed() > Duration::from_secs(10);
+ let delay = match &end {
+ // The relay said when: that, and up to a second more.
+ SessionEnd::Throttled(after) => {
+ *after + Duration::from_millis(rand::thread_rng().gen_range(0..1000))
+ }
+ _ => {
+ let d = reconnect_delay(
+ attempt,
+ config.max_backoff,
+ was_up,
+ config.reconnect_spread,
+ rand::thread_rng().gen_range(0.0..=1.0),
+ );
+ attempt = attempt.saturating_add(1);
+ d
+ }
+ };
tracing::info!(?delay, "reconnecting to the relay");
tokio::select! {
_ = tokio::time::sleep(delay) => {}
@@ -255,7 +302,7 @@ pub async fn session(config: &JoinConfig, shutdown: &CancellationToken) -> Sessi
}
};
let heartbeat = heartbeat(handle.clone(), config.heartbeat);
- tokio::select! {
+ let end = tokio::select! {
_ = shutdown.cancelled() => SessionEnd::Shutdown,
result = &mut driver => SessionEnd::Lost(match result {
Ok(Ok(())) => "relay closed the connection".into(),
@@ -264,7 +311,11 @@ pub async fn session(config: &JoinConfig, shutdown: &CancellationToken) -> Sessi
}),
_ = accept => SessionEnd::Lost("stream acceptor ended".into()),
reason = heartbeat => SessionEnd::Lost(reason),
- }
+ };
+ // The connection ends with the session: a stopped client must not leave
+ // its relay connection up until the relay's heartbeat notices.
+ driver.abort();
+ end
}
/// Records the relay keys and owner from the 101 response. With pinned
@@ -391,6 +442,54 @@ mod tests {
assert!(backoff(20, cap) >= Duration::from_secs(15));
}
+ #[test]
+ fn the_first_reconnect_after_a_session_is_spread_and_later_ones_back_off() {
+ let cap = Duration::from_secs(30);
+ let spread = Duration::from_secs(5);
+ // A session that was up: anywhere from a tenth of the spread to all of it.
+ assert_eq!(
+ reconnect_delay(0, cap, true, spread, 0.0),
+ Duration::from_millis(500)
+ );
+ assert_eq!(
+ reconnect_delay(0, cap, true, spread, 1.0),
+ Duration::from_secs(5)
+ );
+ assert_eq!(
+ reconnect_delay(0, cap, true, spread, 0.5),
+ Duration::from_millis(2750)
+ );
+ // One that never got up, or a second try: the doubling backoff, whatever the spread.
+ assert_eq!(
+ reconnect_delay(0, cap, false, spread, 1.0),
+ Duration::from_millis(500)
+ );
+ assert_eq!(
+ reconnect_delay(1, cap, true, spread, 1.0),
+ Duration::from_secs(1)
+ );
+ assert!(reconnect_delay(20, cap, true, spread, 1.0) <= cap);
+ // No spread configured: the old behaviour.
+ assert_eq!(
+ reconnect_delay(0, cap, true, Duration::ZERO, 1.0),
+ Duration::from_millis(500)
+ );
+ }
+
+ #[test]
+ fn a_thousand_machines_dropped_together_do_not_retry_in_one_second() {
+ // Evenly spaced "random" draws: how many of 1,000 retry in the busiest second.
+ let cap = Duration::from_secs(30);
+ let mut per_second = std::collections::BTreeMap::<u64, u32>::new();
+ for i in 0..1000 {
+ let d = reconnect_delay(0, cap, true, Duration::from_secs(5), f64::from(i) / 999.0);
+ *per_second.entry(d.as_secs()).or_default() += 1;
+ }
+ let busiest = per_second.values().copied().max().unwrap();
+ // Before: all 1,000 inside half a second. Now: about 220 a second.
+ assert!(busiest <= 260, "{busiest} in one second: {per_second:?}");
+ }
+
#[test]
fn pinned_key_must_match_the_handshake() {
use base64::Engine as _;
diff --git a/libs/cua-spacesd/crates/cua-relay/src/join_limit.rs b/libs/cua-spacesd/crates/cua-relay/src/join_limit.rs
new file mode 100644
index 0000000000..2b3e1ce8a7
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/src/join_limit.rs
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Admission control for machine joins. After a relay restart or a network
+//! blip every machine reconnects within seconds; a thousand TLS handshakes,
+//! token checks and directory writes in the same moment starve the streams
+//! that are already working. A token bucket admits a burst, then a steady
+//! rate; the rest are told to come back after a jittered `Retry-After`
+//! (HTTP 503), which the client honours ([`crate::client`]).
+
+use std::time::{Duration, Instant};
+
+/// Joins per second admitted once the burst is used (`join_rate_per_sec`).
+pub const DEFAULT_JOIN_RATE_PER_SEC: f64 = 250.0;
+/// Joins admitted at once (`join_burst`).
+pub const DEFAULT_JOIN_BURST: u32 = 500;
+
+/// A token bucket for joins. `rate <= 0` admits everything.
+#[derive(Debug)]
+pub struct JoinLimiter {
+ rate: f64,
+ burst: f64,
+ tokens: f64,
+ last: Instant,
+}
+
+impl JoinLimiter {
+ pub fn new(rate_per_sec: f64, burst: u32, now: Instant) -> Self {
+ let burst = f64::from(burst.max(1));
+ Self {
+ rate: rate_per_sec,
+ burst,
+ tokens: burst,
+ last: now,
+ }
+ }
+
+ /// Admits one join, or says how long until one would be.
+ pub fn admit(&mut self, now: Instant) -> Result<(), Duration> {
+ if self.rate <= 0.0 {
+ return Ok(());
+ }
+ let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
+ self.last = now;
+ self.tokens = (self.tokens + elapsed * self.rate).min(self.burst);
+ if self.tokens >= 1.0 {
+ self.tokens -= 1.0;
+ return Ok(());
+ }
+ Err(Duration::from_secs_f64((1.0 - self.tokens) / self.rate))
+ }
+}
+
+/// The `Retry-After` seconds for a refused join: the wait until a token is
+/// there, plus up to `spread` more so the refused do not all return together.
+/// At least one second (the header is whole seconds).
+pub fn retry_after_secs(wait: Duration, spread: Duration, unit_random: f64) -> u64 {
+ let extra = spread.as_secs_f64() * unit_random.clamp(0.0, 1.0);
+ (wait.as_secs_f64() + extra).ceil().max(1.0) as u64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_burst_is_admitted_then_the_rate() {
+ let t0 = Instant::now();
+ let mut l = JoinLimiter::new(100.0, 10, t0);
+ for _ in 0..10 {
+ assert!(l.admit(t0).is_ok());
+ }
+ let wait = l.admit(t0).unwrap_err();
+ assert!(
+ wait <= Duration::from_millis(10) && wait > Duration::ZERO,
+ "{wait:?}"
+ );
+ // 50 ms later: five more.
+ let t1 = t0 + Duration::from_millis(50);
+ for _ in 0..5 {
+ assert!(l.admit(t1).is_ok());
+ }
+ assert!(l.admit(t1).is_err());
+ }
+
+ #[test]
+ fn the_bucket_never_holds_more_than_the_burst() {
+ let t0 = Instant::now();
+ let mut l = JoinLimiter::new(100.0, 10, t0);
+ let later = t0 + Duration::from_secs(3600);
+ for _ in 0..10 {
+ assert!(l.admit(later).is_ok());
+ }
+ assert!(l.admit(later).is_err());
+ }
+
+ #[test]
+ fn no_rate_means_no_limit() {
+ let t0 = Instant::now();
+ let mut l = JoinLimiter::new(0.0, 1, t0);
+ for _ in 0..10_000 {
+ assert!(l.admit(t0).is_ok());
+ }
+ }
+
+ #[test]
+ fn a_thousand_at_once_settle_at_the_rate() {
+ // 1,000 machines at t0; 250/s with a burst of 500: 500 admitted at once,
+ // the rest as the bucket refills, all within about two seconds.
+ let t0 = Instant::now();
+ let mut l = JoinLimiter::new(250.0, 500, t0);
+ let mut pending: Vec<usize> = (0..1000).collect();
+ let mut now = t0;
+ let mut admitted_at_t0 = 0;
+ let mut rounds = 0;
+ while !pending.is_empty() {
+ let mut next = Vec::new();
+ for m in pending {
+ match l.admit(now) {
+ Ok(()) => {
+ if now == t0 {
+ admitted_at_t0 += 1;
+ }
+ }
+ Err(_) => next.push(m),
+ }
+ }
+ pending = next;
+ now += Duration::from_millis(100);
+ rounds += 1;
+ assert!(rounds < 100, "never settled");
+ }
+ assert_eq!(admitted_at_t0, 500);
+ assert!(now - t0 <= Duration::from_secs(3), "{:?}", now - t0);
+ }
+
+ #[test]
+ fn retry_after_is_whole_seconds_and_spread() {
+ assert_eq!(
+ retry_after_secs(Duration::from_millis(5), Duration::ZERO, 0.0),
+ 1
+ );
+ assert_eq!(
+ retry_after_secs(Duration::from_millis(5), Duration::from_secs(4), 1.0),
+ 5
+ );
+ assert_eq!(
+ retry_after_secs(Duration::from_secs(2), Duration::from_secs(4), 0.5),
+ 4
+ );
+ let spread: std::collections::BTreeSet<u64> = (0..=10)
+ .map(|i| {
+ retry_after_secs(
+ Duration::from_millis(100),
+ Duration::from_secs(5),
+ f64::from(i) / 10.0,
+ )
+ })
+ .collect();
+ assert!(spread.len() >= 5, "{spread:?}");
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-relay/src/lib.rs b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
index 49eb03fbc4..92be28cd15 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
@@ -41,6 +41,7 @@ pub mod directory;
pub mod grants;
pub mod handover;
pub mod ident;
+pub mod join_limit;
pub mod mesh;
pub mod mux;
pub mod oidc;
diff --git a/libs/cua-spacesd/crates/cua-relay/src/main.rs b/libs/cua-spacesd/crates/cua-relay/src/main.rs
index 54f872895e..262feab79f 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/main.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/main.rs
@@ -94,6 +94,14 @@ struct Args {
/// Public base URL (assertion issuer and computer URLs).
#[arg(long, env = "CUA_RELAY_PUBLIC_URL")]
public_url: Option<String>,
+ /// Computer joins admitted per second once the burst is used (a restart
+ /// brings every computer back at once; the rest are told to retry
+ /// shortly). 0: no limit.
+ #[arg(long, env = "CUA_RELAY_JOIN_RATE_PER_SEC", default_value_t = cua_relay::join_limit::DEFAULT_JOIN_RATE_PER_SEC)]
+ join_rate_per_sec: f64,
+ /// Computer joins admitted at once.
+ #[arg(long, env = "CUA_RELAY_JOIN_BURST", default_value_t = cua_relay::join_limit::DEFAULT_JOIN_BURST)]
+ join_burst: u32,
/// Maximum computers per account.
#[arg(long, env = "CUA_RELAY_MAX_MACHINES_PER_ACCOUNT", default_value_t = 32)]
max_machines_per_account: usize,
@@ -412,6 +420,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let relay = Relay::try_new(RelayConfig {
tokens,
max_machines_per_token: args.max_machines_per_token,
+ join_rate_per_sec: args.join_rate_per_sec,
+ join_burst: args.join_burst,
max_streams_per_machine: args.max_streams_per_machine,
max_global_streams: args.max_global_streams,
machine_max_streams: args.machine_max_streams,
diff --git a/libs/cua-spacesd/crates/cua-relay/src/server.rs b/libs/cua-spacesd/crates/cua-relay/src/server.rs
index b2431c0351..29cf369e1c 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/server.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/server.rs
@@ -71,6 +71,11 @@ pub struct RelayConfig {
pub tokens: Vec<String>,
/// Maximum machines connected per registration token.
pub max_machines_per_token: usize,
+ /// Machine joins admitted per second once the burst is used; the rest are
+ /// refused with 503 and a `Retry-After`. 0: no limit. See [`crate::join_limit`].
+ pub join_rate_per_sec: f64,
+ /// Machine joins admitted at once.
+ pub join_burst: u32,
/// Maximum concurrent client streams per machine.
pub max_streams_per_machine: u32,
/// A machine without a heartbeat for this long is dropped.
@@ -171,6 +176,8 @@ impl Default for RelayConfig {
Self {
tokens: Vec::new(),
max_machines_per_token: 16,
+ join_rate_per_sec: crate::join_limit::DEFAULT_JOIN_RATE_PER_SEC,
+ join_burst: crate::join_limit::DEFAULT_JOIN_BURST,
// Down from an earlier 1000 (S7): yamux's own per-connection
// cap (machine_max_streams) is now the smaller crate::mux::
// MAX_STREAMS, so this app-level check (which answers with a
@@ -384,6 +391,8 @@ pub struct Relay {
pub(crate) meter: Arc<Meter>,
/// Connection outcome counters (`cua_relay_connections_total`).
pub(crate) conns: Arc<crate::conn_metrics::ConnMetrics>,
+ /// Admission control for machine joins (a reconnect storm after a restart).
+ join_limiter: Arc<Mutex<crate::join_limit::JoinLimiter>>,
/// When this relay started (the reconnect grace counts from it).
started: Instant,
/// Share links: browser sign-in state and public-link rate limits.
@@ -502,6 +511,11 @@ impl Relay {
} = crate::hosted::open(&config, &storage)?;
#[cfg(not(feature = "hosted"))]
let (meter, teams, org) = crate::free::open();
+ let join_limiter = Arc::new(Mutex::new(crate::join_limit::JoinLimiter::new(
+ config.join_rate_per_sec,
+ config.join_burst,
+ Instant::now(),
+ )));
let relay = Self {
config: Arc::new(config),
machines: Arc::default(),
@@ -521,6 +535,7 @@ impl Relay {
storage,
meter,
conns: Arc::default(),
+ join_limiter,
started: Instant::now(),
share: Arc::default(),
};
@@ -1183,6 +1198,28 @@ async fn machine_connect_inner(
else {
return text(StatusCode::BAD_REQUEST, "missing or invalid computer id");
};
+ // A reconnect storm (every machine back at once after a restart) is let
+ // in at a steady rate; the rest are told when to come back.
+ let admitted = relay
+ .join_limiter
+ .lock()
+ .expect("join limiter")
+ .admit(Instant::now());
+ if let Err(wait) = admitted {
+ let unit = {
+ use rand::Rng as _;
+ rand::thread_rng().gen::<f64>()
+ };
+ let secs = crate::join_limit::retry_after_secs(wait, Duration::from_secs(5), unit);
+ let mut response = text(
+ StatusCode::SERVICE_UNAVAILABLE,
+ "the relay is busy; try again shortly",
+ );
+ if let Ok(v) = HeaderValue::from_str(&secs.to_string()) {
+ response.headers_mut().insert(header::RETRY_AFTER, v);
+ }
+ return response;
+ }
let registrant = if let Some(index) = relay.token_index(&headers) {
if relay.directory.get(&id).is_some() {
return text(
@@ -1279,12 +1316,36 @@ async fn machine_connect_inner(
user_cuts: Mutex::default(),
clients: Mutex::default(),
});
- if let Some(old) = relay
- .machines
- .lock()
- .expect("machines")
- .insert(id.clone(), machine.clone())
- {
+ // The limit was checked before the upgrade, and joins that arrive together all
+ // pass it. Settle it here, where the machine is added: the oldest sessions of a
+ // token keep their places, a newer one over the limit is dropped (it retries).
+ let (replaced, over_limit) = {
+ let mut machines = relay.machines.lock().expect("machines");
+ let mut replaced = machines.insert(id.clone(), machine.clone());
+ let over_limit = matches!(machine.registrant, Registrant::Static(_)) && {
+ let mut same: Vec<u64> = machines
+ .values()
+ .filter(|m| m.registrant == machine.registrant)
+ .map(|m| m.generation)
+ .collect();
+ same.sort_unstable();
+ same.iter().position(|g| *g == generation).unwrap_or(0)
+ >= relay.config.max_machines_per_token
+ };
+ if over_limit {
+ machines.remove(&id);
+ if let Some(old) = replaced.take() {
+ machines.insert(id.clone(), old);
+ }
+ }
+ (replaced, over_limit)
+ };
+ if over_limit {
+ tracing::info!(machine = %id, "computer limit for this token reached");
+ driver.abort();
+ return;
+ }
+ if let Some(old) = replaced {
tracing::info!(machine = %id, "replacing previous session");
old.cut_clients();
old.abort.abort();
diff --git a/libs/cua-spacesd/crates/cua-relay/src/transport.rs b/libs/cua-spacesd/crates/cua-relay/src/transport.rs
index ee892328da..ab8528b2f6 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/transport.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/transport.rs
@@ -4,6 +4,7 @@
//! Host join transport only. TLS, WebSocket validation and the whole-connect
//! deadline remain owned by tungstenite and `client::session` respectively.
use std::ffi::OsString;
+use std::time::Duration;
use bytes::Bytes;
use http::{Method, Request, StatusCode, Uri};
@@ -50,15 +51,31 @@ pub(super) async fn connect(
tokio_tungstenite::client_async_tls_with_config(request, stream, None, None)
.await
.map_err(|e| match e {
- tungstenite::Error::Http(response) => {
- SessionEnd::Refused(format!("HTTP {}", response.status()))
- }
+ tungstenite::Error::Http(response) => match retry_after(&response) {
+ Some(after) if response.status() == StatusCode::SERVICE_UNAVAILABLE => {
+ SessionEnd::Throttled(after)
+ }
+ _ => SessionEnd::Refused(format!("HTTP {}", response.status())),
+ },
tungstenite::Error::Tls(_) => lost("origin TLS failed"),
tungstenite::Error::Io(_) => lost("origin handshake I/O failed"),
_ => lost("WebSocket upgrade failed"),
})
}
+/// A refusal's `Retry-After` in seconds (at most two minutes), when it has one.
+fn retry_after<T>(response: &http::Response<T>) -> Option<Duration> {
+ let secs: u64 = response
+ .headers()
+ .get(http::header::RETRY_AFTER)?
+ .to_str()
+ .ok()?
+ .trim()
+ .parse()
+ .ok()?;
+ Some(Duration::from_secs(secs.min(120)))
+}
+
fn destination(uri: &Uri) -> Result<Uri, &'static str> {
let (scheme, port) = match uri.scheme_str() {
Some("wss") => ("https", 443),
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/load.rs b/libs/cua-spacesd/crates/cua-relay/tests/load.rs
new file mode 100644
index 0000000000..db20763d6e
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/load.rs
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Load through the relay: many clients at once to joined machines, with
+//! request-rate and latency floors. A real relay and real machine tunnels
+//! (`client::run`) to a small HTTP backend per machine; every request goes
+//! client -> relay -> tunnel -> backend and back. Prints one `LOAD` line per
+//! scenario (requests, rate, p50/p99) so a run can be compared with the
+//! last. The floors are far below what a laptop does (debug build) so they
+//! catch a collapse (a lock held across a stream, a serialised tunnel), not
+//! noise.
+
+use std::convert::Infallible;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cua_relay::server::{Relay, RelayConfig};
+use http_body_util::Full;
+use hyper::body::Bytes;
+use hyper::{Request, Response};
+use hyper_util::rt::TokioIo;
+use tokio::net::TcpListener;
+use tokio_util::sync::CancellationToken;
+
+const TOKEN: &str = "static-registration-token";
+
+/// A machine's local spacesd stand-in: answers every request with a short
+/// body naming the machine.
+async fn backend(name: String) -> std::net::SocketAddr {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ while let Ok((stream, _)) = listener.accept().await {
+ let name = name.clone();
+ tokio::spawn(async move {
+ let svc = hyper::service::service_fn(
+ move |_req: Request<hyper::body::Incoming>| {
+ let body = format!("ok {name}");
+ async move { Ok::<_, Infallible>(Response::new(Full::new(Bytes::from(body)))) }
+ },
+ );
+ let _ = hyper::server::conn::http1::Builder::new()
+ .serve_connection(TokioIo::new(stream), svc)
+ .await;
+ });
+ }
+ });
+ addr
+}
+
+async fn start_relay() -> (Relay, String) {
+ let relay = Relay::new(RelayConfig {
+ tokens: vec![TOKEN.into()],
+ require_client_credentials: false,
+ // One static token joins every machine here (the default caps a token at 16).
+ max_machines_per_token: 64,
+ ..RelayConfig::default()
+ });
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let serving = relay.clone();
+ tokio::spawn(async move {
+ let _ = serving.serve(listener, std::future::pending()).await;
+ });
+ (relay, base)
+}
+
+async fn join(relay: &Relay, base: &str, stop: &CancellationToken) -> String {
+ let id = format!("load{}", uuid::Uuid::new_v4().simple());
+ let addr = backend(id.clone()).await;
+ let mut config = cua_relay::client::JoinConfig::new(
+ base.replace("http://", "ws://"),
+ TOKEN.into(),
+ id.clone(),
+ addr,
+ );
+ config.heartbeat = Duration::from_secs(5);
+ tokio::spawn(cua_relay::client::run(config, stop.clone()));
+ for _ in 0..400 {
+ if relay.machine_ids().contains(&id) {
+ return id;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!("{id} did not join");
+}
+
+struct Run {
+ rate: f64,
+ p50: Duration,
+ p99: Duration,
+ failed: usize,
+}
+
+/// `total` requests from `concurrency` clients at once, spread over
+/// `machines`; every answer must be that machine's own.
+async fn drive(base: &str, machines: &[String], concurrency: usize, total: usize) -> Run {
+ let client = reqwest::Client::builder()
+ .pool_max_idle_per_host(concurrency)
+ .build()
+ .unwrap();
+ let next = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let start = Instant::now();
+ let mut tasks = Vec::new();
+ for _ in 0..concurrency {
+ let (client, next, base, machines) = (
+ client.clone(),
+ next.clone(),
+ base.to_string(),
+ machines.to_vec(),
+ );
+ tasks.push(tokio::spawn(async move {
+ let (mut latencies, mut failed) = (Vec::new(), 0usize);
+ loop {
+ let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ if i >= total {
+ return (latencies, failed);
+ }
+ let id = &machines[i % machines.len()];
+ let t = Instant::now();
+ let ok = match client
+ .get(format!("{base}/m/{id}/ping"))
+ .header("x-cua-env-authorization", "Bearer t")
+ .timeout(Duration::from_secs(10))
+ .send()
+ .await
+ {
+ Ok(r) if r.status().is_success() => {
+ r.text().await.is_ok_and(|b| b == format!("ok {id}"))
+ }
+ _ => false,
+ };
+ latencies.push(t.elapsed());
+ if !ok {
+ failed += 1;
+ }
+ }
+ }));
+ }
+ let (mut latencies, mut failed) = (Vec::with_capacity(total), 0);
+ for t in tasks {
+ let (l, f) = t.await.unwrap();
+ latencies.extend(l);
+ failed += f;
+ }
+ let elapsed = start.elapsed();
+ latencies.sort();
+ let at = |q: f64| latencies[((latencies.len() as f64 * q) as usize).min(latencies.len() - 1)];
+ Run {
+ rate: total as f64 / elapsed.as_secs_f64(),
+ p50: at(0.50),
+ p99: at(0.99),
+ failed,
+ }
+}
+
+fn report(name: &str, total: usize, r: &Run) {
+ println!(
+ "LOAD {name}: requests={total} rate={:.0}/s p50={:?} p99={:?} failed={}",
+ r.rate, r.p50, r.p99, r.failed
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn one_machine_takes_many_clients_at_once() {
+ let (relay, base) = start_relay().await;
+ let stop = CancellationToken::new();
+ let id = join(&relay, &base, &stop).await;
+ const TOTAL: usize = 3000;
+ let r = drive(&base, &[id], 64, TOTAL).await;
+ report("one machine, 64 clients", TOTAL, &r);
+ assert_eq!(r.failed, 0, "every request answered by its machine");
+ assert!(
+ r.rate >= 200.0,
+ "{:.0} requests/s through one tunnel",
+ r.rate
+ );
+ assert!(r.p99 < Duration::from_secs(2), "p99 {:?}", r.p99);
+ stop.cancel();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn many_machines_share_the_relay_fairly() {
+ let (relay, base) = start_relay().await;
+ let stop = CancellationToken::new();
+ let mut ids = Vec::new();
+ for _ in 0..20 {
+ ids.push(join(&relay, &base, &stop).await);
+ }
+ const TOTAL: usize = 4000;
+ let r = drive(&base, &ids, 128, TOTAL).await;
+ report("20 machines, 128 clients", TOTAL, &r);
+ assert_eq!(r.failed, 0, "every request answered by its own machine");
+ assert!(
+ r.rate >= 200.0,
+ "{:.0} requests/s across 20 tunnels",
+ r.rate
+ );
+ assert!(r.p99 < Duration::from_secs(2), "p99 {:?}", r.p99);
+ // Still answering its own health check right after.
+ let health = reqwest::Client::new()
+ .get(format!("{base}/healthz"))
+ .timeout(Duration::from_millis(500))
+ .send()
+ .await
+ .unwrap();
+ assert!(health.status().is_success());
+ stop.cancel();
+}
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/reconnect_storm.rs b/libs/cua-spacesd/crates/cua-relay/tests/reconnect_storm.rs
new file mode 100644
index 0000000000..c27d38dd19
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/reconnect_storm.rs
@@ -0,0 +1,380 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A reconnect storm: a thousand machines join at once, the network between
+//! them and the relay is cut and comes back, and they all rejoin. What keeps
+//! that from starving the relay:
+//!
+//! * the relay admits joins at a steady rate (token bucket) and tells the rest
+//! to come back after a jittered `Retry-After` (HTTP 503), which the client
+//! honours;
+//! * a machine whose session was up retries first after a random wait over
+//! `reconnect_spread`, not within half a second.
+//!
+//! The network is a TCP forwarder that can be cut (every connection dropped)
+//! and held down for a moment. A second test checks the per-token machine
+//! limit: the machines past it keep trying, and take a freed place.
+//!
+//! Prints `STORM` lines (time to all online, the most joins in one second,
+//! the slowest `/healthz` during it) to compare runs. Debug build and a
+//! laptop: a few tens of seconds.
+
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use cua_relay::server::{Relay, RelayConfig};
+use tokio::net::{TcpListener, TcpStream};
+use tokio::task::AbortHandle;
+use tokio_util::sync::CancellationToken;
+
+const TOKEN: &str = "static-registration-token";
+const MACHINES: usize = 1000;
+
+/// A thousand tunnels are four thousand sockets with the forwarder in the
+/// middle: more than a default shell allows.
+#[cfg(unix)]
+fn raise_fd_limit() {
+ unsafe {
+ let mut r = libc::rlimit {
+ rlim_cur: 0,
+ rlim_max: 0,
+ };
+ if libc::getrlimit(libc::RLIMIT_NOFILE, &mut r) == 0 {
+ r.rlim_cur = r.rlim_max.min(10_240);
+ libc::setrlimit(libc::RLIMIT_NOFILE, &r);
+ }
+ }
+}
+#[cfg(not(unix))]
+fn raise_fd_limit() {}
+
+/// A forwarder in front of the relay: `cut` drops every connection through it,
+/// `down` makes it refuse new ones until `up`.
+struct Network {
+ addr: std::net::SocketAddr,
+ conns: Arc<Mutex<Vec<AbortHandle>>>,
+ down: Arc<AtomicBool>,
+ attempts: Arc<AtomicUsize>,
+}
+
+impl Network {
+ async fn start(relay: std::net::SocketAddr) -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let conns: Arc<Mutex<Vec<AbortHandle>>> = Arc::default();
+ let down = Arc::new(AtomicBool::new(false));
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let (c, d, a) = (conns.clone(), down.clone(), attempts.clone());
+ tokio::spawn(async move {
+ while let Ok((mut inbound, _)) = listener.accept().await {
+ a.fetch_add(1, Ordering::Relaxed);
+ if d.load(Ordering::SeqCst) {
+ continue; // dropped: the machine sees a failed connect
+ }
+ let task = tokio::spawn(async move {
+ if let Ok(mut outbound) = TcpStream::connect(relay).await {
+ let _ = tokio::io::copy_bidirectional(&mut inbound, &mut outbound).await;
+ }
+ });
+ c.lock().unwrap().push(task.abort_handle());
+ }
+ });
+ Self {
+ addr,
+ conns,
+ down,
+ attempts,
+ }
+ }
+
+ fn cut(&self) {
+ for h in self.conns.lock().unwrap().drain(..) {
+ h.abort();
+ }
+ }
+}
+
+async fn start_relay(config: RelayConfig) -> (Relay, std::net::SocketAddr) {
+ let relay = Relay::new(config);
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let serving = relay.clone();
+ tokio::spawn(async move {
+ let _ = serving.serve(listener, std::future::pending()).await;
+ });
+ (relay, addr)
+}
+
+/// A local spacesd stand-in every machine splices streams into (none are opened here).
+async fn backend() -> std::net::SocketAddr {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { while listener.accept().await.is_ok() {} });
+ addr
+}
+
+fn join_config(
+ relay: std::net::SocketAddr,
+ id: &str,
+ local: std::net::SocketAddr,
+) -> cua_relay::client::JoinConfig {
+ let mut c =
+ cua_relay::client::JoinConfig::new(format!("ws://{relay}"), TOKEN.into(), id.into(), local);
+ c.heartbeat = Duration::from_secs(5);
+ c.max_backoff = Duration::from_secs(4);
+ c.reconnect_spread = Duration::from_secs(3);
+ c
+}
+
+/// Waits for `want` machines online, noting the most that joined in one
+/// second and the slowest `/healthz` meanwhile.
+async fn until_online(
+ relay: &Relay,
+ base: &str,
+ want: usize,
+ within: Duration,
+) -> (Duration, usize, Duration) {
+ let started = Instant::now();
+ let client = reqwest::Client::builder()
+ .pool_max_idle_per_host(0)
+ .build()
+ .unwrap();
+ let (mut peak, mut slowest) = (0usize, Duration::ZERO);
+ let mut window: std::collections::VecDeque<(Instant, usize)> =
+ std::collections::VecDeque::new();
+ loop {
+ let online = relay.machine_ids().len();
+ let now = Instant::now();
+ window.push_back((now, online));
+ while window
+ .front()
+ .is_some_and(|(t, _)| now - *t > Duration::from_secs(1))
+ {
+ window.pop_front();
+ }
+ let low = window.iter().map(|(_, n)| *n).min().unwrap_or(online);
+ peak = peak.max(online.saturating_sub(low));
+ let t = Instant::now();
+ let health = client
+ .get(format!("{base}/healthz"))
+ .timeout(Duration::from_secs(5))
+ .send()
+ .await;
+ slowest = slowest.max(t.elapsed());
+ assert!(
+ health.is_ok_and(|h| h.status().is_success()),
+ "the relay stopped answering during the storm"
+ );
+ if online >= want {
+ return (started.elapsed(), peak, slowest);
+ }
+ assert!(
+ started.elapsed() < within,
+ "{online} of {want} online after {within:?}"
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_thousand_machines_cut_off_and_back_do_not_starve_the_relay() {
+ raise_fd_limit();
+ let (relay, relay_addr) = start_relay(RelayConfig {
+ tokens: vec![TOKEN.into()],
+ require_client_credentials: false,
+ max_machines_per_token: MACHINES + 100,
+ ..RelayConfig::default()
+ })
+ .await;
+ let base = format!("http://{relay_addr}");
+ let net = Network::start(relay_addr).await;
+ let local = backend().await;
+ let stop = CancellationToken::new();
+ for i in 0..MACHINES {
+ let id = format!("storm{i:04}{}", uuid::Uuid::new_v4().simple());
+ tokio::spawn(cua_relay::client::run(
+ join_config(net.addr, &id, local),
+ stop.clone(),
+ ));
+ }
+
+ // 1. Every machine knocks at once: the relay admits a burst then a steady
+ // rate, and the rest come back when told.
+ let (first, peak, slowest) =
+ until_online(&relay, &base, MACHINES, Duration::from_secs(90)).await;
+ println!("STORM join: machines={MACHINES} all online in {first:?}, most joined in one second={peak}, slowest /healthz={slowest:?}");
+ assert!(
+ peak <= 800,
+ "{peak} machines joined in one second: the limiter (burst 500, 250/s) did not hold"
+ );
+
+ // 2. The network is cut, held down for a second, and comes back.
+ tokio::time::sleep(Duration::from_secs(11)).await; // sessions count as "was up" after 10 s
+ net.down.store(true, Ordering::SeqCst);
+ net.cut();
+ for _ in 0..100 {
+ if relay.machine_ids().len() < MACHINES / 10 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ let dropped = relay.machine_ids().len();
+ assert!(
+ dropped < MACHINES / 2,
+ "{dropped} machines still online after the cut"
+ );
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ let attempts_before = net.attempts.load(Ordering::Relaxed);
+ net.down.store(false, Ordering::SeqCst);
+ let back = Instant::now();
+
+ let (again, peak, slowest) =
+ until_online(&relay, &base, MACHINES, Duration::from_secs(60)).await;
+ let attempts = net.attempts.load(Ordering::Relaxed) - attempts_before;
+ println!(
+ "STORM rejoin: all online again {again:?} after the network came back, connection attempts={attempts} for {MACHINES} machines, most joined in one second={peak}, slowest /healthz={slowest:?} ({:?} since)",
+ back.elapsed()
+ );
+ assert!(
+ peak <= 800,
+ "{peak} machines joined in one second after the cut"
+ );
+ assert!(
+ slowest < Duration::from_secs(3),
+ "/healthz took {slowest:?} during the rejoin"
+ );
+ // Spread, not hammered: each machine knocked a few times at most.
+ assert!(
+ attempts <= MACHINES * 4,
+ "{attempts} connection attempts for {MACHINES} machines"
+ );
+ stop.cancel();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn machines_past_the_token_limit_keep_trying_and_take_a_freed_place() {
+ const LIMIT: usize = 8;
+ const TOTAL: usize = 20;
+ let (relay, addr) = start_relay(RelayConfig {
+ tokens: vec![TOKEN.into()],
+ require_client_credentials: false,
+ max_machines_per_token: LIMIT,
+ ..RelayConfig::default()
+ })
+ .await;
+ let local = backend().await;
+ let mut stops = Vec::new();
+ let mut ids = Vec::new();
+ for i in 0..TOTAL {
+ let id = format!("limit{i:02}{}", uuid::Uuid::new_v4().simple());
+ let stop = CancellationToken::new();
+ let mut config = join_config(addr, &id, local);
+ config.max_backoff = Duration::from_millis(800);
+ tokio::spawn(cua_relay::client::run(config, stop.clone()));
+ stops.push(stop);
+ ids.push(id);
+ }
+ let settle = |want: usize| {
+ let relay = relay.clone();
+ async move {
+ let deadline = Instant::now() + Duration::from_secs(20);
+ while relay.machine_ids().len() != want {
+ assert!(
+ Instant::now() < deadline,
+ "{} online, wanted {want}",
+ relay.machine_ids().len()
+ );
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ }
+ };
+ // Exactly the limit is online; the others are refused (429) and retry.
+ settle(LIMIT).await;
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ assert_eq!(
+ relay.machine_ids().len(),
+ LIMIT,
+ "the limit holds while the rest keep trying"
+ );
+
+ // Three leave: three of the waiting take their places, the limit still holds.
+ let online_before: std::collections::BTreeSet<String> =
+ relay.machine_ids().into_iter().collect();
+ let leaving: Vec<usize> = ids
+ .iter()
+ .enumerate()
+ .filter(|(_, id)| online_before.contains(*id))
+ .map(|(i, _)| i)
+ .take(3)
+ .collect();
+ for i in &leaving {
+ stops[*i].cancel();
+ }
+ let deadline = Instant::now() + Duration::from_secs(20);
+ loop {
+ let now: std::collections::BTreeSet<String> = relay.machine_ids().into_iter().collect();
+ let newcomers = now.difference(&online_before).count();
+ if newcomers == 3 && now.len() == LIMIT {
+ break;
+ }
+ assert!(
+ now.len() <= LIMIT,
+ "{} online past the limit of {LIMIT}",
+ now.len()
+ );
+ assert!(
+ Instant::now() < deadline,
+ "the freed places were not taken: {} online, {newcomers} new",
+ now.len()
+ );
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ for s in &stops {
+ s.cancel();
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_busy_relay_answers_503_with_a_retry_after() {
+ use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Error};
+ let (_relay, addr) = start_relay(RelayConfig {
+ tokens: vec![TOKEN.into()],
+ require_client_credentials: false,
+ // Two joins at once, then one every five seconds.
+ join_burst: 2,
+ join_rate_per_sec: 0.2,
+ ..RelayConfig::default()
+ })
+ .await;
+ let join = |id: &str| {
+ let mut request = format!("ws://{addr}{}", cua_relay::CONNECT_PATH)
+ .into_client_request()
+ .unwrap();
+ let h = request.headers_mut();
+ h.insert("authorization", format!("Bearer {TOKEN}").parse().unwrap());
+ h.insert(cua_relay::MACHINE_ID_HEADER, id.parse().unwrap());
+ async move { tokio_tungstenite::connect_async(request).await }
+ };
+ let (_a, _) = join("busy-aaaa").await.expect("the first is admitted");
+ let (_b, _) = join("busy-bbbb").await.expect("the second is admitted");
+ match join("busy-cccc").await {
+ Err(Error::Http(response)) => {
+ assert_eq!(response.status(), 503);
+ let secs: u64 = response
+ .headers()
+ .get("retry-after")
+ .expect("a Retry-After")
+ .to_str()
+ .unwrap()
+ .parse()
+ .unwrap();
+ // Five seconds for the next token, plus up to five more of spread.
+ assert!((1..=11).contains(&secs), "Retry-After {secs}");
+ }
+ other => panic!(
+ "the third join should be told to wait, got {:?}",
+ other.map(|_| ())
+ ),
+ }
+}
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index c6cdfb9f03..4be4383ad7 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -3175,6 +3175,7 @@ dependencies = [
"async-trait",
"base64 0.22.1",
"cua-agent-setup",
+ "cua-agents",
"cua-auth",
"cua-create-failure",
"cua-home",
diff --git a/libs/cua/crates/cua-agent-setup/src/connection.rs b/libs/cua/crates/cua-agent-setup/src/connection.rs
index 42eadf28dd..945885937c 100644
--- a/libs/cua/crates/cua-agent-setup/src/connection.rs
+++ b/libs/cua/crates/cua-agent-setup/src/connection.rs
@@ -285,7 +285,7 @@ pub fn parse_version(out: &str) -> Option<String> {
.map(str::to_string)
}
-fn base_command(env: &HostEnv, program: &Path) -> Command {
+pub(crate) fn base_command(env: &HostEnv, program: &Path) -> Command {
let mut cmd = Command::new(program);
#[cfg(windows)]
{
@@ -838,11 +838,21 @@ impl AgentSetup {
let a = registry::find(agent)
.ok_or_else(|| signin::CopyRefusal::Failed(signin::unknown(agent).to_string()))?;
let copy = signin::read_copy(&self.env, a.id, wait)?;
- let saved = vault.save(&copy).map_err(|e| {
+ self.save_sign_in(a.id, &copy, vault)
+ }
+
+ /// Saves a sign-in made for `agent` into `vault` and notes it.
+ fn save_sign_in(
+ &self,
+ agent: &str,
+ copy: &SignInCopy,
+ vault: &dyn SignInVault,
+ ) -> std::result::Result<ImportedSignIn, signin::CopyRefusal> {
+ let saved = vault.save(copy).map_err(|e| {
signin::CopyRefusal::Failed(format!("Connected. Sign-in not copied: {e}"))
})?;
if let Ok(mut state) = State::load(&self.state_path) {
- let r = state.connections.entry(a.id.to_string()).or_default();
+ let r = state.connections.entry(agent.to_string()).or_default();
r.sign_in = Some(crate::state::SignInRecord {
env: saved.env.clone(),
label: saved.label.clone(),
@@ -854,6 +864,48 @@ impl AgentSetup {
Ok(saved)
}
+ /// Starts `agent`'s device-code sign-in (Codex: `codex login
+ /// --device-auth`) in a folder Cua owns, next to its state; the link and
+ /// code to show. Your own sign-in is never read or changed.
+ pub fn start_device_sign_in(
+ &self,
+ agent: &str,
+ ) -> std::result::Result<signin::DeviceSignIn, signin::CopyRefusal> {
+ let dir = self
+ .state_path
+ .parent()
+ .unwrap_or(Path::new("."))
+ .join("agent-sign-ins")
+ .join(agent);
+ signin::start_device_sign_in(&self.env, &dir, agent)
+ }
+
+ /// Waits for a device sign-in to be approved and saves it into `vault`.
+ pub fn finish_device_sign_in(
+ &self,
+ login: signin::DeviceSignIn,
+ vault: &dyn SignInVault,
+ wait: Duration,
+ ) -> std::result::Result<ImportedSignIn, signin::CopyRefusal> {
+ let copy = login.wait(wait)?;
+ let agent = copy.source.clone();
+ self.save_sign_in(&agent, &copy, vault)
+ }
+
+ /// The whole device sign-in for `agent`: start it, `show` the link and
+ /// code, wait (up to `wait`) for the approval, save it into `vault`.
+ pub fn device_sign_in(
+ &self,
+ agent: &str,
+ vault: &dyn SignInVault,
+ wait: Duration,
+ show: ShowDeviceSignIn<'_>,
+ ) -> std::result::Result<ImportedSignIn, signin::CopyRefusal> {
+ let login = self.start_device_sign_in(agent)?;
+ show(agent, &login);
+ self.finish_device_sign_in(login, vault, wait)
+ }
+
/// Deletes the copies of `agent`'s sign-in from `vault`; the variables
/// removed.
pub fn remove_sign_in(
@@ -883,6 +935,25 @@ impl AgentSetup {
parts: ConnectParts,
vault: Option<&dyn SignInVault>,
wait: Duration,
+ ) -> crate::Result<Vec<ConnectResult>> {
+ self.connect_with(agents, server, parts, vault, wait, None)
+ }
+
+ /// [`Self::connect`], and an agent that signs in with a code (Codex)
+ /// does so here: its device sign-in starts in a folder Cua owns,
+ /// `show` gets the link and the code to enter, and the sign-in made for
+ /// Cua is saved once it's approved. Without `show` such
+ /// an agent's sign-in is left for the app's Connect, as before. The
+ /// device sign-in waits up to [`signin::DEVICE_SIGN_IN_WAIT`]. The CLI's
+ /// `connect setup --sign-in` and the app take this same path.
+ pub fn connect_with(
+ &self,
+ agents: &[String],
+ server: &McpServer,
+ parts: ConnectParts,
+ vault: Option<&dyn SignInVault>,
+ wait: Duration,
+ mut show: Option<ShowDeviceSignIn<'_>>,
) -> crate::Result<Vec<ConnectResult>> {
let mut out = Vec::new();
for id in agents {
@@ -909,7 +980,12 @@ impl AgentSetup {
"Connected. Sign-in not copied: Keyvault isn't available here.".into(),
),
},
- Some(v) => match self.import_sign_in(a.id, v, wait) {
+ Some(v) => match match show.as_deref_mut() {
+ Some(show) if signin::signs_in_with_a_code(a.id) => {
+ self.device_sign_in(a.id, v, signin::DEVICE_SIGN_IN_WAIT, show)
+ }
+ _ => self.import_sign_in(a.id, v, wait),
+ } {
Ok(i) => SignInResult {
imported: Some(i),
refused: None,
@@ -960,6 +1036,10 @@ impl AgentSetup {
}
}
+/// Shows a device sign-in's link and code (`agent`, the sign-in) while it
+/// waits for the approval.
+pub type ShowDeviceSignIn<'a> = &'a mut dyn FnMut(&str, &signin::DeviceSignIn);
+
/// The name rows show ("Codex", not the registry's "OpenAI Codex").
pub fn display_name(a: &registry::AgentSpec) -> &'static str {
match a.id {
diff --git a/libs/cua/crates/cua-agent-setup/src/signin.rs b/libs/cua/crates/cua-agent-setup/src/signin.rs
index c1e0224cdd..8ef7ca2d3a 100644
--- a/libs/cua/crates/cua-agent-setup/src/signin.rs
+++ b/libs/cua/crates/cua-agent-setup/src/signin.rs
@@ -6,9 +6,9 @@
//!
//! | Agent | Signed in | Copied to Keyvault |
//! |---|---|---|
-//! | Codex | `$CODEX_HOME/auth.json` (`tokens`, `OPENAI_API_KEY`); with keyring storage, `codex login status`'s exit code | the whole `auth.json` (OpenAI's documented headless route), as `CODEX_AUTH_JSON` |
+//! | Codex | `$CODEX_HOME/auth.json` (`tokens`, `OPENAI_API_KEY`); with keyring storage, `codex login status`'s exit code | a sign-in made for Cua: `codex login --device-auth` in a folder Cua owns ([`DeviceSignIn`]), as `CODEX_AUTH_JSON`; never your own `auth.json` |
//! | Claude Code | `claude auth status` (exit 0, `authMethod`), else `.credentials.json` / `.claude.json` | the token `claude setup-token` prints after one browser approval, as `CLAUDE_CODE_OAUTH_TOKEN`; never the Keychain item `Claude Code-credentials` |
-//! | Hermes | `$HERMES_HOME/.env` provider keys, `auth.json` `providers` | the key of the provider `config.yaml` uses (OpenRouter, Anthropic, OpenAI); OAuth providers: not yet |
+//! | Hermes | `$HERMES_HOME/.env` provider keys, `auth.json` `providers` (whether a key is there; never its value) | nothing: it uses the providers connected in Settings, Connectors |
//! | Cursor | `~/.config/cursor/auth.json`, `~/.cursor/auth.json`, `CURSOR_API_KEY`; else unknown | nothing (no supported export) |
//! | OpenClaw | legacy `auth-profiles.json`; else unknown (profiles are in SQLite) | nothing yet |
//! | T3 Code | uses the agents it controls | nothing (it uses Codex's and Claude's own) |
@@ -161,63 +161,12 @@ fn codex_check(env: &HostEnv) -> Check {
}
}
-fn codex_copy(env: &HostEnv) -> Result<SignInCopy, CopyRefusal> {
- let file = codex_home(env).join("auth.json");
- let text = match std::fs::read_to_string(&file) {
- Ok(t) if !t.trim().is_empty() => t,
- _ if codex_uses_keyring(env) => {
- return Err(CopyRefusal::NotYet(
- "Codex keeps its sign-in in the Keychain here; Cua can't copy it yet.".into(),
- ));
- }
- _ => {
- return Err(CopyRefusal::NotSignedIn(
- "No ChatGPT sign-in on This Mac yet.".into(),
- ));
- }
- };
- let v: Value = serde_json::from_str(&text).map_err(|_| {
- CopyRefusal::Failed(format!(
- "{} can't be read.",
- crate::connection::tilde(env, &file)
- ))
- })?;
- let tokens = v.get("tokens");
- if tokens.is_some_and(|t| non_empty(t.get("refresh_token")) || non_empty(t.get("access_token")))
- {
- // One line: the store keeps single-line values.
- let value = serde_json::to_string(&v).map_err(|e| CopyRefusal::Failed(e.to_string()))?;
- let expires_ms = if tokens.is_some_and(|t| non_empty(t.get("refresh_token"))) {
- None
- } else {
- tokens
- .and_then(|t| t.get("access_token"))
- .and_then(Value::as_str)
- .and_then(jwt_exp_ms)
- };
- return Ok(SignInCopy {
- source: "codex".into(),
- env: CODEX_AUTH_ENV.into(),
- label: "Codex · ChatGPT sign-in".into(),
- value,
- expires_ms,
- });
- }
- if let Some(key) = v
- .get("OPENAI_API_KEY")
- .and_then(Value::as_str)
- .filter(|k| !k.trim().is_empty())
- {
- return Ok(SignInCopy {
- source: "codex".into(),
- env: "OPENAI_API_KEY".into(),
- label: "Codex · OpenAI key".into(),
- value: key.trim().into(),
- expires_ms: None,
- });
- }
- Err(CopyRefusal::NotSignedIn(
- "No ChatGPT sign-in on This Mac yet.".into(),
+/// Codex's sign-in for a run in a Space: one made for Cua with Codex's own
+/// device-code login ([`DeviceSignIn`]); your own `auth.json` is never read.
+fn codex_copy() -> Result<SignInCopy, CopyRefusal> {
+ Err(CopyRefusal::NotYet(
+ "Connected. Codex signs in with a code: run `cua connect setup --agents codex --sign-in`, or use Connect in Cua Spaces."
+ .into(),
))
}
@@ -451,18 +400,9 @@ const HERMES_KEYS: &[&str] = &[
"AI_GATEWAY_API_KEY",
];
-/// Hermes providers that sign in with OAuth (`hermes auth`): not copied yet.
-const HERMES_OAUTH: &[&str] = &[
- "nous",
- "openai-codex",
- "xai-oauth",
- "qwen-oauth",
- "minimax-oauth",
-];
-
-/// The providers a Hermes run in a Space can use, with the key each reads
-/// and what the row calls it.
-const HERMES_COPYABLE: &[(&str, &str, &str)] = &[
+/// Hermes' providers Cua names, with the key each reads and what the row
+/// calls it.
+const HERMES_NAMED: &[(&str, &str, &str)] = &[
("openrouter", "OPENROUTER_API_KEY", "OpenRouter key"),
("anthropic", "ANTHROPIC_API_KEY", "Anthropic key"),
("openai", "OPENAI_API_KEY", "OpenAI key"),
@@ -496,28 +436,28 @@ fn hermes_oauth_providers(env: &HostEnv) -> Vec<String> {
.unwrap_or_default()
}
-/// What Hermes' `.env` key for `provider` is: `(env, label, value)`.
-fn hermes_key(env: &HostEnv) -> Option<(&'static str, &'static str, String)> {
- let keys = dotenv(&hermes_home(env).join(".env"));
- let get = |k: &str| keys.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
+/// Which of Hermes' `.env` keys its provider uses: `(env, label)`. Only
+/// whether the name is there; the value is never kept.
+fn hermes_key(env: &HostEnv) -> Option<(&'static str, &'static str)> {
+ let names: Vec<String> = dotenv(&hermes_home(env).join(".env"))
+ .into_iter()
+ .map(|(k, _)| k)
+ .collect();
+ let has = |k: &str| names.iter().any(|n| n == k);
let provider = hermes_provider(env);
- if provider == "auto" {
- return HERMES_COPYABLE
- .iter()
- .find_map(|(_, k, l)| get(k).map(|v| (*k, *l, v)));
- }
- HERMES_COPYABLE
+ HERMES_NAMED
.iter()
- .find(|(p, _, _)| *p == provider)
- .and_then(|(_, k, l)| get(k).map(|v| (*k, *l, v)))
+ .filter(|(p, _, _)| provider == "auto" || *p == provider)
+ .find(|(_, k, _)| has(k))
+ .map(|(_, k, l)| (*k, *l))
}
fn hermes_label(env: &HostEnv) -> Option<&'static str> {
let provider = hermes_provider(env);
- if let Some((_, l, _)) = hermes_key(env) {
+ if let Some((_, l)) = hermes_key(env) {
return Some(l);
}
- HERMES_COPYABLE
+ HERMES_NAMED
.iter()
.find(|(p, _, _)| *p == provider)
.map(|(_, _, l)| *l)
@@ -538,35 +478,12 @@ fn hermes_check(env: &HostEnv) -> Check {
}
}
-fn hermes_copy(env: &HostEnv) -> Result<SignInCopy, CopyRefusal> {
- let provider = hermes_provider(env);
- if HERMES_OAUTH.contains(&provider.as_str()) {
- return Err(CopyRefusal::NotYet(format!(
- "Hermes signs in to {provider} with OAuth; Cua can't copy that sign-in yet."
- )));
- }
- match hermes_key(env) {
- Some((k, l, v)) => Ok(SignInCopy {
- source: "hermes".into(),
- env: k.into(),
- label: format!("Hermes · {l}"),
- value: v,
- expires_ms: None,
- }),
- None if provider == "auto" && !hermes_oauth_providers(env).is_empty() => {
- Err(CopyRefusal::NotYet(
- "Hermes signs in with OAuth; Cua can't copy that sign-in yet.".into(),
- ))
- }
- None if provider != "auto" && !HERMES_COPYABLE.iter().any(|(p, _, _)| *p == provider) => {
- Err(CopyRefusal::NotYet(format!(
- "Runs in a Space can't use Hermes' {provider} key yet."
- )))
- }
- None => Err(CopyRefusal::NotSignedIn(
- "No provider key in Hermes' .env on This Mac yet.".into(),
- )),
- }
+/// Hermes uses the provider keys connected in Settings, Connectors; its own
+/// `.env` is never copied.
+fn hermes_copy() -> Result<SignInCopy, CopyRefusal> {
+ Err(CopyRefusal::NotYet(
+ "Connected. Hermes uses your Anthropic or OpenAI connection: connect one in Settings, Connectors.".into(),
+ ))
}
// ------------------------------------------------- Cursor, OpenClaw, T3
@@ -637,9 +554,10 @@ pub fn check(env: &HostEnv, agent: &str) -> Check {
}
}
-/// Whether Connect copies this agent's sign-in at all.
+/// Whether Connect makes a sign-in for this agent at all (Claude Code's
+/// `setup-token`, Codex's device code).
pub fn importable(agent: &str) -> bool {
- matches!(agent, "codex" | "claude-code" | "hermes")
+ matches!(agent, "codex" | "claude-code")
}
/// Whether Cua can start the agent's own sign-in (`codex login`).
@@ -657,22 +575,239 @@ pub fn copy_label(env: &HostEnv, agent: &str) -> Option<String> {
}
}
-/// Where the sign-in is read from, as Advanced shows it.
-pub fn copy_source(env: &HostEnv, agent: &str) -> Option<String> {
+/// How the sign-in is made, as Advanced shows it.
+pub fn copy_source(_env: &HostEnv, agent: &str) -> Option<String> {
match agent {
- "codex" => Some(crate::connection::tilde(
- env,
- &codex_home(env).join("auth.json"),
- )),
+ "codex" => Some("codex login --device-auth".into()),
"claude-code" => Some("claude setup-token".into()),
- "hermes" => Some(crate::connection::tilde(
- env,
- &hermes_home(env).join(".env"),
- )),
_ => None,
}
}
+// ------------------------------------------------------- device sign-in
+
+/// How long the device code waits for the person to enter it (Codex's own is 15 minutes).
+pub const DEVICE_SIGN_IN_WAIT: Duration = Duration::from_secs(15 * 60);
+
+/// How long Codex has to print its link and code.
+const DEVICE_CODE_WAIT: Duration = Duration::from_secs(30);
+
+/// Codex's ChatGPT sign-in made for Cua: `codex login --device-auth` run with
+/// `CODEX_HOME` in a folder Cua owns, so your own Codex sign-in is never read
+/// or changed. [`start_device_sign_in`] answers the link and the one-time
+/// code to show; [`DeviceSignIn::wait`] waits for the approval, copies the
+/// new sign-in and deletes the folder. Dropped unfinished, the login is
+/// stopped and the folder deleted.
+pub struct DeviceSignIn {
+ pub url: String,
+ pub code: String,
+ child: Option<std::process::Child>,
+ home: PathBuf,
+}
+
+impl std::fmt::Debug for DeviceSignIn {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("DeviceSignIn")
+ .field("url", &self.url)
+ .field("code", &self.code)
+ .finish()
+ }
+}
+
+/// Text without terminal colors.
+fn plain(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut chars = s.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '\u{1b}' {
+ // CSI: ESC [ ... final byte in @..~
+ if chars.peek() == Some(&'[') {
+ chars.next();
+ for d in chars.by_ref() {
+ if ('@'..='~').contains(&d) {
+ break;
+ }
+ }
+ }
+ continue;
+ }
+ out.push(c);
+ }
+ out
+}
+
+/// The link and the one-time code in what Codex printed.
+pub fn find_device_code(out: &str) -> Option<(String, String)> {
+ let text = plain(out);
+ let url = text
+ .split_whitespace()
+ .find(|w| w.starts_with("https://"))?
+ .trim_end_matches(['.', ','])
+ .to_string();
+ let code = text.split_whitespace().find(|w| {
+ let parts: Vec<&str> = w.split('-').collect();
+ parts.len() == 2
+ && parts.iter().all(|p| {
+ (4..=5).contains(&p.len())
+ && p.chars()
+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
+ })
+ })?;
+ Some((url, code.to_string()))
+}
+
+/// Whether `agent` signs in for Cua with a code entered in the browser
+/// (its device sign-in) rather than a token command or a copy.
+pub fn signs_in_with_a_code(agent: &str) -> bool {
+ agent == "codex"
+}
+
+/// Starts Codex's device-code sign-in in `dir` (a folder Cua owns, emptied first).
+pub fn start_device_sign_in(
+ env: &HostEnv,
+ dir: &Path,
+ agent: &str,
+) -> Result<DeviceSignIn, CopyRefusal> {
+ if !signs_in_with_a_code(agent) {
+ return Err(CopyRefusal::NotYet(format!(
+ "{} has no device sign-in.",
+ registry::find(agent)
+ .map(crate::connection::display_name)
+ .unwrap_or(agent)
+ )));
+ }
+ let bin = crate::connection::binary(env, registry::find("codex").unwrap())
+ .ok_or_else(|| CopyRefusal::Failed("Codex isn't installed on This Mac.".into()))?;
+ if !env.run_agent_clis {
+ return Err(CopyRefusal::Failed(
+ "agent commands are off in this environment".into(),
+ ));
+ }
+ let _ = std::fs::remove_dir_all(dir);
+ std::fs::create_dir_all(dir)
+ .map_err(|e| CopyRefusal::Failed(format!("Couldn't make {}: {e}", dir.display())))?;
+ let mut child = crate::connection::base_command(env, &bin)
+ .args(["login", "--device-auth"])
+ .env("CODEX_HOME", dir)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .map_err(|e| CopyRefusal::Failed(format!("Couldn't start Codex's sign-in: {e}")))?;
+ let (tx, rx) = std::sync::mpsc::channel::<String>();
+ for pipe in [
+ child
+ .stdout
+ .take()
+ .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
+ child
+ .stderr
+ .take()
+ .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
+ ]
+ .into_iter()
+ .flatten()
+ {
+ let tx = tx.clone();
+ std::thread::spawn(move || {
+ let mut buf = [0u8; 1024];
+ let mut pipe = pipe;
+ while let Ok(n) = pipe.read(&mut buf) {
+ if n == 0 {
+ break;
+ }
+ let _ = tx.send(String::from_utf8_lossy(&buf[..n]).into_owned());
+ }
+ });
+ }
+ drop(tx);
+ let start = std::time::Instant::now();
+ let mut seen = String::new();
+ let mut login = DeviceSignIn {
+ url: String::new(),
+ code: String::new(),
+ child: Some(child),
+ home: dir.to_path_buf(),
+ };
+ while start.elapsed() < DEVICE_CODE_WAIT {
+ match rx.recv_timeout(Duration::from_millis(200)) {
+ Ok(chunk) => {
+ seen.push_str(&chunk);
+ if let Some((url, code)) = find_device_code(&seen) {
+ login.url = url;
+ login.code = code;
+ return Ok(login);
+ }
+ }
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
+ }
+ }
+ Err(CopyRefusal::Failed(
+ "Codex didn't show a sign-in code. Try again.".into(),
+ ))
+}
+
+use std::io::Read as _;
+
+impl DeviceSignIn {
+ /// Waits up to `wait` for the code to be entered and approved, then
+ /// copies the sign-in Codex made in the folder and deletes the folder.
+ pub fn wait(mut self, wait: Duration) -> Result<SignInCopy, CopyRefusal> {
+ let mut child = self.child.take().expect("waited once");
+ let start = std::time::Instant::now();
+ let status = loop {
+ match child.try_wait() {
+ Ok(Some(s)) => break Some(s),
+ Ok(None) if start.elapsed() < wait => {
+ std::thread::sleep(Duration::from_millis(250))
+ }
+ _ => {
+ let _ = child.kill();
+ let _ = child.wait();
+ break None;
+ }
+ }
+ };
+ let file = self.home.join("auth.json");
+ let text = std::fs::read_to_string(&file).ok();
+ let _ = std::fs::remove_dir_all(&self.home);
+ let Some(status) = status else {
+ return Err(CopyRefusal::Cancelled(
+ "The sign-in code expired before it was entered.".into(),
+ ));
+ };
+ let text = match (status.success(), text) {
+ (true, Some(t)) if !t.trim().is_empty() => t,
+ _ => {
+ return Err(CopyRefusal::Cancelled(
+ "The ChatGPT sign-in didn't finish.".into(),
+ ));
+ }
+ };
+ let v: Value = serde_json::from_str(&text)
+ .map_err(|_| CopyRefusal::Failed("Codex's sign-in couldn't be read.".into()))?;
+ let value = serde_json::to_string(&v).map_err(|e| CopyRefusal::Failed(e.to_string()))?;
+ Ok(SignInCopy {
+ source: "codex".into(),
+ env: CODEX_AUTH_ENV.into(),
+ label: "Codex · ChatGPT sign-in".into(),
+ value,
+ expires_ms: None,
+ })
+ }
+}
+
+impl Drop for DeviceSignIn {
+ fn drop(&mut self) {
+ if let Some(mut c) = self.child.take() {
+ let _ = c.kill();
+ let _ = c.wait();
+ let _ = std::fs::remove_dir_all(&self.home);
+ }
+ }
+}
+
/// Why a sign-in wasn't copied (the row's one line).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CopyRefusal {
@@ -710,9 +845,9 @@ impl CopyRefusal {
/// approval (`claude setup-token`, waiting up to `wait`).
pub fn read_copy(env: &HostEnv, agent: &str, wait: Duration) -> Result<SignInCopy, CopyRefusal> {
match agent {
- "codex" => codex_copy(env),
+ "codex" => codex_copy(),
"claude-code" => claude_copy(env, wait),
- "hermes" => hermes_copy(env),
+ "hermes" => hermes_copy(),
other => Err(CopyRefusal::NotYet(format!(
"{} has no sign-in Cua can copy.",
registry::find(other)
diff --git a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs
index 5d0eb749a2..1dbe6bba9d 100644
--- a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs
+++ b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs
@@ -101,6 +101,17 @@ fn agent_script(version_line: &str, extra: &str) -> String {
)
}
+/// Codex's device-code login: the link and code in color, then the sign-in in `$CODEX_HOME`.
+const CODEX_EXTRA: &str = r#" login)
+ if [ "$2" = "--device-auth" ]; then
+ printf '1. Open this link\n \033[94mhttps://auth.openai.com/codex/device\033[0m\n2. Enter this one-time code\n \033[94mABCD-12345\033[0m\n'
+ sleep 0.3
+ [ -f "$HOME/.fake-codex-cancel" ] && exit 1
+ printf '{"auth_mode":"chatgpt","tokens":{"refresh_token":"rt-for-cua"}}' > "$CODEX_HOME/auth.json"
+ exit 0
+ fi ;;
+"#;
+
const CLAUDE_EXTRA: &str = r#" auth)
if [ -f "$HOME/.fake-claude-signed-in" ]; then echo '{"authMethod":"claude.ai"}'; exit 0; fi
echo '{"authMethod":"none"}'; exit 1 ;;
@@ -147,7 +158,10 @@ impl World {
fn install(&self, id: &str, version: &str) {
match id {
- "codex" => self.script("codex", &agent_script(&format!("codex-cli {version}"), "")),
+ "codex" => self.script(
+ "codex",
+ &agent_script(&format!("codex-cli {version}"), CODEX_EXTRA),
+ ),
"claude-code" => self.script(
"claude",
&agent_script(&format!("{version} (Claude Code)"), CLAUDE_EXTRA),
@@ -192,6 +206,16 @@ impl World {
}
}
+ /// Codex's sign-in made for Cua (its device-code login, approved at once by the fake).
+ fn device_sign_in(&self) {
+ let mut env = self.env.clone();
+ env.run_agent_clis = true;
+ let s = AgentSetup::new(env);
+ let login = s.start_device_sign_in("codex").unwrap();
+ s.finish_device_sign_in(login, &self.vault, Duration::from_secs(10))
+ .unwrap();
+ }
+
fn setup(&self) -> AgentSetup {
AgentSetup::new(self.env.clone())
}
@@ -365,7 +389,8 @@ fn installed_signed_in_or_not_connected_or_not() {
}
assert_eq!(r.previous_version.as_deref(), Some("1.2.3"));
let expect_import = match id {
- "hermes" | "claude-code" | "codex" => ImportState::Missing,
+ // Hermes uses Settings' provider connections; it makes no sign-in of its own.
+ "claude-code" | "codex" => ImportState::Missing,
_ => ImportState::Unsupported,
};
assert_eq!(r.signin_import, expect_import, "{id}");
@@ -395,22 +420,41 @@ fn connected_but_not_signed_in_says_so_and_offers_sign_in_where_cua_can_start_it
}
#[test]
-fn sign_ins_are_copied_to_keyvault_and_their_expiry_is_seen() {
- // Codex: its auth.json, as is.
+fn sign_ins_are_made_for_cua_and_never_read_from_the_apps_own_files() {
+ // Codex: its own device-code login in a folder Cua owns; your auth.json is never read.
let w = World::new();
w.install("codex", "0.61.0");
w.sign_in("codex");
- w.connect("codex", true);
+ let own = std::fs::read_to_string(w.home.join(".codex/auth.json")).unwrap();
+ w.connect("codex", false);
+ let mut env = w.env.clone();
+ env.run_agent_clis = true;
+ let s = AgentSetup::new(env);
+ let login = s.start_device_sign_in("codex").unwrap();
+ assert_eq!(login.url, "https://auth.openai.com/codex/device");
+ assert_eq!(login.code, "ABCD-12345");
+ let saved = s
+ .finish_device_sign_in(login, &w.vault, Duration::from_secs(10))
+ .unwrap();
+ assert_eq!(saved.env, "CODEX_AUTH_JSON");
+ assert_eq!(saved.label, "Codex · ChatGPT sign-in");
+ let v: serde_json::Value = serde_json::from_str(&w.vault.value("codex").unwrap()).unwrap();
+ assert_eq!(v["tokens"]["refresh_token"], "rt-for-cua");
+ // Your own sign-in is untouched, and Cua's folder is gone.
+ assert_eq!(
+ std::fs::read_to_string(w.home.join(".codex/auth.json")).unwrap(),
+ own
+ );
+ assert!(
+ !s.state_path()
+ .parent()
+ .unwrap()
+ .join("agent-sign-ins/codex")
+ .exists()
+ );
let r = check(&w, "codex", ConnectionState::Connected, None);
- assert!(r.signin_imported);
assert_eq!(r.signin_import, ImportState::Ok);
- assert_eq!(r.sign_in.as_deref(), Some("ChatGPT sign-in"));
- let v: serde_json::Value = serde_json::from_str(&w.vault.value("codex").unwrap()).unwrap();
- assert_eq!(v["tokens"]["refresh_token"], "rt-1");
- let items = w.vault.imported().unwrap();
- assert_eq!(items[0].label, "Codex · ChatGPT sign-in");
- assert_eq!(items[0].env, "CODEX_AUTH_JSON");
- // The copy expired: Reconnect copies it again.
+ // Its expiry is seen: the row asks to reconnect.
w.vault.expire("codex");
let r = check(
&w,
@@ -419,8 +463,42 @@ fn sign_ins_are_copied_to_keyvault_and_their_expiry_is_seen() {
Some(ProblemAction::Reconnect),
);
assert_eq!(r.signin_import, ImportState::Expired);
- w.connect("codex", true);
- check(&w, "codex", ConnectionState::Connected, None);
+ // Connect alone never copies Codex's own file.
+ let r = w
+ .setup()
+ .connect(
+ &["codex".into()],
+ &w.server(),
+ ConnectParts::ALL,
+ Some(&FakeVault::default()),
+ Duration::from_secs(5),
+ )
+ .unwrap();
+ assert_eq!(
+ r[0].sign_in.as_ref().unwrap().refused.as_deref(),
+ Some("not_yet")
+ );
+
+ // A code never entered: cancelled, nothing saved, the folder gone.
+ let w2 = World::new();
+ w2.install("codex", "0.61.0");
+ w2.write(".fake-codex-cancel", "1");
+ let mut env = w2.env.clone();
+ env.run_agent_clis = true;
+ let s2 = AgentSetup::new(env);
+ let login = s2.start_device_sign_in("codex").unwrap();
+ let err = s2
+ .finish_device_sign_in(login, &w2.vault, Duration::from_secs(10))
+ .unwrap_err();
+ assert_eq!(err.kind(), "cancelled");
+ assert!(w2.vault.value("codex").is_none());
+ assert!(
+ !s2.state_path()
+ .parent()
+ .unwrap()
+ .join("agent-sign-ins/codex")
+ .exists()
+ );
// Claude Code: the token `claude setup-token` prints.
let w = World::new();
@@ -434,15 +512,14 @@ fn sign_ins_are_copied_to_keyvault_and_their_expiry_is_seen() {
Some("sk-ant-oat01-FAKEtoken_0123456789abcdef")
);
- // Hermes: the provider key its config uses.
+ // Hermes: its .env is never copied; it uses the providers connected in Settings.
let w = World::new();
w.install("hermes", "0.22.5");
w.sign_in("hermes");
w.connect("hermes", true);
- let r = check(&w, "hermes", ConnectionState::Connected, None);
- assert_eq!(r.signin_import, ImportState::Ok);
+ let r = w.row("hermes");
assert_eq!(r.sign_in.as_deref(), Some("OpenRouter key"));
- assert_eq!(w.vault.value("hermes").as_deref(), Some("sk-or-v1-fake"));
+ assert!(w.vault.value("hermes").is_none());
}
#[test]
@@ -462,10 +539,12 @@ fn a_refused_sign_in_copy_leaves_the_tools_connected_with_one_line() {
.unwrap();
assert!(r[0].tools_ok);
let s = r[0].sign_in.as_ref().unwrap();
- assert_eq!(s.refused.as_deref(), Some("not_signed_in"));
- assert_eq!(
- s.line.as_deref(),
- Some("No ChatGPT sign-in on This Mac yet.")
+ assert_eq!(s.refused.as_deref(), Some("not_yet"));
+ assert!(
+ s.line
+ .as_deref()
+ .unwrap()
+ .contains("Codex signs in with a code")
);
// Claude's browser approval cancelled.
w.install("claude-code", "2.4.1");
@@ -511,10 +590,8 @@ fn a_refused_sign_in_copy_leaves_the_tools_connected_with_one_line() {
Duration::from_secs(5),
)
.unwrap();
- assert_eq!(
- r[0].sign_in.as_ref().unwrap().refused.as_deref(),
- Some("not_yet")
- );
+ // Hermes makes no sign-in of its own.
+ assert!(r[0].sign_in.is_none());
assert!(w.vault.value("hermes").is_none());
// A config Cua can't write: the row names the file.
w.install("cursor", "1.0.0");
@@ -686,7 +763,8 @@ fn uninstalled_after_connecting_offers_disconnect_which_undoes_both() {
".codex/config.toml",
"# mine\n[mcp_servers.cua]\ncommand = \"/opt/mine/wrapper\"\nargs = [\"serve\"]\n",
);
- w.connect("codex", true);
+ w.connect("codex", false);
+ w.device_sign_in();
w.uninstall("codex");
let r = check(
&w,
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index 7db1b7f00c..2f75bccc36 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -732,9 +732,21 @@ impl Store {
self.unmark();
return Ok(None);
};
- let c: Credentials = serde_json::from_str(&raw).map_err(|_| {
- Error::Unauthenticated("stored Cua credentials are invalid; log in again".into())
- })?;
+ let c: Credentials = match serde_json::from_str(&raw) {
+ Ok(c) => c,
+ Err(_) => {
+ // Cut short or garbage: signing in again writes a good file over
+ // it, so the damaged one is kept beside it (owner-only, like the
+ // original) rather than lost. Not for the keychain: nothing of
+ // it is copied out.
+ if let Store::File(p) = self {
+ keep_damaged(p, raw.as_bytes());
+ }
+ return Err(Error::Unauthenticated(
+ "stored Cua credentials are invalid; log in again".into(),
+ ));
+ }
+ };
c.expires()?;
// Sessions stored before the marker existed get one on first read.
if !self.marker_path().is_file() {
@@ -1642,6 +1654,15 @@ fn secret_entry(name: &str) -> Result<VaultEntry> {
VaultEntry::new(keyring_service(), &format!("{KEYRING_ACCOUNT}.{name}")).map_err(store_err)
}
+/// Keeps a damaged credentials file as `<name>.damaged`, owner-only. Best
+/// effort: a copy that cannot be written is not an error (the caller is
+/// already reporting the damage).
+fn keep_damaged(p: &Path, data: &[u8]) {
+ let mut name = p.file_name().unwrap_or_default().to_os_string();
+ name.push(".damaged");
+ let _ = write_private(&p.with_file_name(name), data);
+}
+
/// Writes a file readable only by the owner (0600 on Unix), atomically.
fn write_private(p: &Path, data: &[u8]) -> std::io::Result<()> {
// A test must never write credentials into the real ~/.cua.
@@ -2789,6 +2810,41 @@ mod tests {
assert!(c.needs_refresh());
}
+ #[test]
+ fn a_damaged_credentials_file_is_an_error_to_log_in_again_and_is_kept() {
+ let d = tempfile::tempdir().unwrap();
+ let path = d.path().join("credentials.json");
+ let store = Store::File(path.clone());
+ for garbage in [
+ "{",
+ "{\"access_token\": \"a",
+ "",
+ "null",
+ "[]",
+ "\u{0}\u{1}garbage",
+ ] {
+ std::fs::write(&path, garbage).unwrap();
+ let err = store.load().unwrap_err();
+ assert!(
+ matches!(err, Error::Unauthenticated(ref m) if m.contains("log in again")),
+ "{garbage:?}: {err:?}"
+ );
+ let kept = d.path().join("credentials.json.damaged");
+ assert_eq!(std::fs::read_to_string(&kept).unwrap(), garbage);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ assert_eq!(
+ std::fs::metadata(&kept).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+ }
+ // Signing in again writes a good file over it; the copy stays.
+ std::fs::remove_file(&path).unwrap();
+ assert!(store.load().unwrap().is_none());
+ }
+
#[test]
fn named_secrets_live_next_to_the_session_owner_only() {
let d = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-cli/src/agents.rs b/libs/cua/crates/cua-cli/src/agents.rs
index b99d614ca7..a004ea36e9 100644
--- a/libs/cua/crates/cua-cli/src/agents.rs
+++ b/libs/cua/crates/cua-cli/src/agents.rs
@@ -97,11 +97,12 @@ pub struct SetupCmdArgs {
/// names the cua-driver binary.
#[arg(long)]
pub cua_driver: bool,
- /// Also copy each agent's sign-in to Keyvault on This Mac, so its runs
- /// in your Spaces use it: Codex's ChatGPT sign-in (`~/.codex/auth.json`),
- /// Claude Code's `claude setup-token` (one browser approval), Hermes'
- /// provider key (`~/.hermes/.env`). The agent's own sign-in is never
- /// changed.
+ /// Also make a sign-in for each agent's runs in your Spaces and keep it
+ /// in Keyvault on This Mac: Claude Code's `claude setup-token` (one
+ /// browser approval) and Codex's own device sign-in (a link and a code
+ /// to enter there, in a folder Cua owns); Hermes uses the providers
+ /// connected in Cua Spaces (Settings, Connectors).
+ /// The agent's own sign-in files are never read or changed.
#[arg(long, conflicts_with = "cua_driver")]
pub sign_in: bool,
}
@@ -745,13 +746,25 @@ fn run_connect(
mcp: !args.skills_only,
sign_in: true,
};
+ // A sign-in with a code (Codex): the link and the code go to stderr, so
+ // `--json` stays one line on stdout.
+ let mut show = |agent: &str, d: &cua_agent_setup::signin::DeviceSignIn| {
+ let name = cua_agent_setup::registry::find(agent)
+ .map(cua_agent_setup::connection::display_name)
+ .unwrap_or(agent);
+ eprintln!(
+ " {name}: open {} and enter the code {} (it works once and expires in 15 minutes).",
+ d.url, d.code
+ );
+ };
let res = setup
- .connect(
+ .connect_with(
&ids,
&server,
parts,
vault.as_deref(),
cua_agent_setup::signin::SETUP_TOKEN_WAIT,
+ Some(&mut show),
)
.map_err(err)?;
let failed = res.iter().any(|r| !r.tools_ok);
diff --git a/libs/cua/crates/cua-cli/src/do_cmd.rs b/libs/cua/crates/cua-cli/src/do_cmd.rs
index 74d5ea6418..b3767af4ec 100644
--- a/libs/cua/crates/cua-cli/src/do_cmd.rs
+++ b/libs/cua/crates/cua-cli/src/do_cmd.rs
@@ -31,14 +31,25 @@ const LEGACY_PROVIDERS: &[&str] = &[
"direct",
"sandbox",
];
-/// Default host spacesd (`CUA_HOST_ENV_URL`): this machine, on the
-/// channel's port (3211, or 3221 for `cua-local`).
+/// Default host spacesd (`CUA_HOST_ENV_URL`): this machine, on the port
+/// `cua host setup` chose (when another macOS user's host held the
+/// channel's), else the channel's (3211, or 3221 for `cua-local`).
pub fn default_host_env_url() -> String {
- host_env_url_on(cua_home::channel::CuaChannel::current())
+ let config = cua_host::Host::new(cua_home::cua_home())
+ .config()
+ .ok()
+ .flatten();
+ host_env_url_on(cua_home::channel::CuaChannel::current(), config.as_ref())
}
-fn host_env_url_on(channel: cua_home::channel::CuaChannel) -> String {
- format!("http://127.0.0.1:{}", channel.ports().tcp)
+fn host_env_url_on(
+ channel: cua_home::channel::CuaChannel,
+ config: Option<&cua_host::HostConfig>,
+) -> String {
+ let port = config
+ .map_or(channel.ports(), |c| c.service_ports(channel))
+ .tcp;
+ format!("http://127.0.0.1:{port}")
}
#[derive(Args, Debug)]
@@ -1295,8 +1306,27 @@ mod tests {
/// port: `cua-local`'s is not Stable's 3211.
#[test]
fn the_host_target_is_this_machines_spacesd_on_the_channels_port() {
- assert_eq!(host_env_url_on(CuaChannel::Stable), "http://127.0.0.1:3211");
- assert_eq!(host_env_url_on(CuaChannel::Local), "http://127.0.0.1:3221");
+ assert_eq!(
+ host_env_url_on(CuaChannel::Stable, None),
+ "http://127.0.0.1:3211"
+ );
+ assert_eq!(
+ host_env_url_on(CuaChannel::Local, None),
+ "http://127.0.0.1:3221"
+ );
+ // A host set up beside another user's keeps the port setup chose.
+ let moved = cua_host::HostConfig {
+ port: Some(3231),
+ ..Default::default()
+ };
+ assert_eq!(
+ host_env_url_on(CuaChannel::Stable, Some(&moved)),
+ "http://127.0.0.1:3231"
+ );
+ assert_eq!(
+ host_env_url_on(CuaChannel::Stable, Some(&cua_host::HostConfig::default())),
+ "http://127.0.0.1:3211"
+ );
}
/// Stable's ports are the ones cua-spacesd binds with no flag, so a
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index d7d5124c05..48f83395b7 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -4213,6 +4213,9 @@ mod tests {
fn state(&self) -> cua_host::ServiceState {
panic!("must not read service state")
}
+ fn port_free(&self, _: std::net::SocketAddr, _: cua_host::ports::Transport) -> bool {
+ true
+ }
}
let relay = FakeRelay::start().await;
let dir = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-cli/tests/connect_status.rs b/libs/cua/crates/cua-cli/tests/connect_status.rs
index cb85cf21de..a1d5e63f34 100644
--- a/libs/cua/crates/cua-cli/tests/connect_status.rs
+++ b/libs/cua/crates/cua-cli/tests/connect_status.rs
@@ -25,6 +25,20 @@ fn script(dir: &Path, name: &str, body: &str) {
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
}
+/// Codex with its device-code login: prints the link and the code, then the
+/// sign-in it makes lands in `$CODEX_HOME` (the folder Cua owns).
+const CODEX_DEVICE: &str = r#"#!/bin/sh
+case "$1" in
+ --version) echo "codex-cli 0.61.0" ;;
+ login)
+ if [ "$2" = "--device-auth" ]; then
+ printf '1. Open this link\n https://auth.openai.com/codex/device\n2. Enter this one-time code\n ABCD-12345\n'
+ printf '{"auth_mode":"chatgpt","tokens":{"refresh_token":"rt-made-for-cua"}}' > "$CODEX_HOME/auth.json"
+ fi ;;
+esac
+exit 0
+"#;
+
fn agent(version: &str) -> String {
format!("#!/bin/sh\n[ \"$1\" = --version ] && echo \"{version}\"\nexit 0\n")
}
@@ -159,7 +173,7 @@ async fn cli_mcp_and_app_report_the_same_connection_in_every_state() {
let vault = h.dir.path().join("keychain");
std::fs::create_dir_all(&vault).unwrap();
script(&bin, "cua", FAKE_CUA);
- script(&bin, "codex", &agent("codex-cli 0.61.0"));
+ script(&bin, "codex", CODEX_DEVICE);
script(&bin, "hermes", &agent("Hermes Agent v0.22.5"));
script(&bin, "cursor-agent", &agent("2026.10.21"));
h.set("PATH", format!("{}:/usr/bin:/bin", bin.display()))
@@ -184,7 +198,7 @@ async fn cli_mcp_and_app_report_the_same_connection_in_every_state() {
std::fs::create_dir_all(home.join(".codex")).unwrap();
std::fs::write(
home.join(".codex/auth.json"),
- r#"{"auth_mode":"chatgpt","tokens":{"id_token":"x","access_token":"y","refresh_token":"rt"}}"#,
+ r#"{"auth_mode":"chatgpt","tokens":{"id_token":"x","access_token":"y","refresh_token":"rt-yours"}}"#,
)
.unwrap();
@@ -213,17 +227,35 @@ async fn cli_mcp_and_app_report_the_same_connection_in_every_state() {
.iter()
.find(|a| a["agent"] == "codex")
.unwrap();
+ // Codex signs in with its own device-code login, made for Cua; your own
+ // `~/.codex/auth.json` is never read.
assert_eq!(
codex["sign_in"]["imported"]["label"], "Codex · ChatGPT sign-in",
"{res}"
);
+ assert!(
+ out.stderr.contains("https://auth.openai.com/codex/device")
+ && out.stderr.contains("ABCD-12345"),
+ "{}",
+ out.stderr
+ );
+ let saved =
+ cua_spaces::agents::keys::AgentKeys::new(cua_auth::Store::TestKeychain(vault.clone()))
+ .values(&["CODEX_AUTH_JSON"]);
+ assert!(
+ saved["CODEX_AUTH_JSON"].contains("rt-made-for-cua"),
+ "{saved:?}"
+ );
+ assert!(!saved["CODEX_AUTH_JSON"].contains("rt-yours"));
let hermes = res["agents"]
.as_array()
.unwrap()
.iter()
.find(|a| a["agent"] == "hermes")
.unwrap();
- assert_eq!(hermes["sign_in"]["refused"], "not_signed_in", "{res}");
+ // Hermes makes no sign-in of its own (it uses the providers connected in
+ // Cua Spaces), and its `.env` is never read.
+ assert!(hermes["sign_in"].is_null(), "{res}");
let r = all_three(&h, &bin).await;
assert_eq!(row(&r, "codex")["state"], "connected", "{r}");
assert_eq!(row(&r, "codex")["signin_import"], "ok");
diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rs
index c96bf943ee..9c6274cf01 100644
--- a/libs/cua/crates/cua-daemon/src/local.rs
+++ b/libs/cua/crates/cua-daemon/src/local.rs
@@ -276,11 +276,17 @@ pub async fn resolve_placement_for(
Runtime::Firecracker => BackendKind::Firecracker,
Runtime::Vz => BackendKind::Vz,
Runtime::Containerization => BackendKind::Containerization,
+ // `runtime.microvm`: Cua's own monitor, Apple's container
+ // already on this Mac, or (auto) the monitor when it runs here.
_ if cfg!(target_os = "macos") => {
- if cua_sandbox_core::placement::HostFacts::current().vz {
- BackendKind::Vz
- } else {
- BackendKind::Containerization
+ use cua_vmm::kinds::{KindSource, RuntimeKind, source};
+ match source(RuntimeKind::Microvm) {
+ KindSource::Builtin => BackendKind::Vz,
+ KindSource::System => BackendKind::Containerization,
+ KindSource::Auto if cua_sandbox_core::placement::HostFacts::current().vz => {
+ BackendKind::Vz
+ }
+ KindSource::Auto => BackendKind::Containerization,
}
}
_ => BackendKind::Firecracker,
diff --git a/libs/cua/crates/cua-host/src/helper_migration_tests.rs b/libs/cua/crates/cua-host/src/helper_migration_tests.rs
index 6e8ab70e0e..917d5f5fbf 100644
--- a/libs/cua/crates/cua-host/src/helper_migration_tests.rs
+++ b/libs/cua/crates/cua-host/src/helper_migration_tests.rs
@@ -138,6 +138,9 @@ impl ServiceManager for FakeHelper {
detail: String::new(),
}
}
+ fn port_free(&self, _: std::net::SocketAddr, _: crate::ports::Transport) -> bool {
+ true
+ }
}
/// A GUI session, and permissions not granted (to the new identity).
diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rs
index efd0219725..5cb497521c 100644
--- a/libs/cua/crates/cua-host/src/host.rs
+++ b/libs/cua/crates/cua-host/src/host.rs
@@ -411,16 +411,54 @@ pub struct HostConfig {
/// machine ($0).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usd_per_hour: Option<String>,
+ /// The service's TCP port when it is not the channel's (3211, or 3221
+ /// for Local): another program, most often another macOS user's host
+ /// service, held the channel's port when setup ran (see
+ /// [`crate::ports`]). Unset: the channel's.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub port: Option<u16>,
+ /// The service's QUIC (UDP) port when it is not the channel's (3212, or
+ /// 3222 for Local). Unset: the channel's.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub quic_port: Option<u16>,
+ /// `CUA_CREDENTIAL_STORE` as it was set where `cua host setup` ran
+ /// (`file` when the session was saved in `credentials.json`, as over
+ /// SSH, where the login keychain cannot be used): passed on to the
+ /// service, so it and the `cua daemon` it starts read the same session.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub credential_store: Option<String>,
+ /// `CUA_HOME` as it was set where `cua host setup` ran: passed on to
+ /// the service, so it and the `cua daemon` it starts use the same home.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cua_home: Option<String>,
}
-/// `CUA_MESH` where setup runs, when set.
-fn mesh_env() -> Option<String> {
- std::env::var("CUA_MESH")
+impl HostConfig {
+ /// The ports the service listens on for a build of `channel`: the ones
+ /// setup chose, else the channel's.
+ pub fn service_ports(&self, channel: CuaChannel) -> cua_home::channel::Ports {
+ let ports = channel.ports();
+ cua_home::channel::Ports {
+ tcp: self.port.unwrap_or(ports.tcp),
+ quic: self.quic_port.unwrap_or(ports.quic),
+ ..ports
+ }
+ }
+}
+
+/// `name` where setup runs, when set and not empty.
+fn setup_env(name: &str) -> Option<String> {
+ std::env::var(name)
.ok()
.map(|v| v.trim().to_owned())
.filter(|v| !v.is_empty())
}
+/// `CUA_MESH` where setup runs, when set.
+fn mesh_env() -> Option<String> {
+ setup_env("CUA_MESH")
+}
+
/// A macOS privacy pane the user must grant the driver in.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -826,6 +864,11 @@ fn valid_machine_id(id: &str) -> bool {
/// The environment variables of cua-spacesd's `--port` and `--quic-port`.
const PORT_ENV: &str = "CUA_ENV_PORT";
const QUIC_PORT_ENV: &str = "CUA_ENV_QUIC_PORT";
+/// How long setup waits for this user's stopped service to let go of its
+/// ports before it takes them to be another program's.
+const PORT_RELEASE_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
+/// The credential store setting (`file` or `keychain`) of `cua-auth`.
+const CREDENTIAL_STORE_ENV: &str = "CUA_CREDENTIAL_STORE";
/// The environment variable with this machine's cost per hour (US
/// dollars), passed on to the host service.
@@ -1203,7 +1246,10 @@ impl Host {
// passed: it is 3212 for every channel, by design (a port of the
// mesh's own network that guest Spaces and older cua-spacesd builds
// fix, so two hosts on one Mac do not compete for it).
- let (ports, stable) = (channel.ports(), CuaChannel::Stable.ports());
+ //
+ // The same goes for a pair setup chose because another program
+ // (another macOS user's host service) held the channel's.
+ let (ports, stable) = (config.service_ports(channel), CuaChannel::Stable.ports());
if ports.tcp != stable.tcp {
args.extend(["--port".to_string(), ports.tcp.to_string()]);
env.push((PORT_ENV.into(), ports.tcp.to_string()));
@@ -1221,6 +1267,16 @@ impl Host {
if let Some(usd) = &config.usd_per_hour {
env.push((HOST_USD_PER_HOUR.into(), usd.clone()));
}
+ // The session store and home setup used: without them the service
+ // (and the `cua daemon` it starts) would look for the sign-in in
+ // the default store, the keychain, which a session saved to the
+ // file over SSH is not in.
+ if let Some(store) = &config.credential_store {
+ env.push((CREDENTIAL_STORE_ENV.into(), store.clone()));
+ }
+ if let Some(home) = &config.cua_home {
+ env.push(("CUA_HOME".into(), home.clone()));
+ }
ServiceSpec {
program: config.driver_bin.clone(),
args,
@@ -1334,6 +1390,8 @@ impl Host {
provide_spaces,
mesh: mesh_env(),
usd_per_hour: host_usd_per_hour(),
+ credential_store: setup_env(CREDENTIAL_STORE_ENV),
+ cua_home: setup_env("CUA_HOME"),
..Default::default()
};
if opts.download_first && helper_launcher.is_none() {
@@ -1450,13 +1508,16 @@ impl Host {
return Err(Error::Service(missing_libraries_message(&missing)));
}
*stage = SetupStage::Service;
- write_json(&self.paths.config(), &config)?;
if runner == RunnerKind::AppHelper {
// Never two services: the old LaunchAgent (and its binary)
// goes before the helper starts.
self.retire_legacy()?;
}
let manager = self.manager(runner);
+ let previous = self.config().ok().flatten();
+ self.choose_ports(&mut config, previous.as_ref(), manager.as_ref())
+ .await?;
+ write_json(&self.paths.config(), &config)?;
manager.install(&self.service_spec(&config))?;
manager.start()?;
if let Err(e) = confirm_running(manager.as_ref(), &self.paths.log()).await {
@@ -1480,6 +1541,79 @@ impl Host {
self.status().await
}
+ /// Sets `config`'s ports ([`HostConfig::port`], [`HostConfig::quic_port`]):
+ /// the ones this service already has, else the channel's, while they
+ /// are free; when another program holds them (most often another macOS
+ /// user's host service on the same Mac), a per-user pair
+ /// ([`crate::ports`]). This user's own service holding them is not
+ /// another program: it is stopped (setup restarts it anyway) and its
+ /// ports kept, so running setup again never moves them.
+ ///
+ /// A direct host listens where `--direct` says; only its QUIC port can
+ /// move.
+ async fn choose_ports(
+ &self,
+ config: &mut HostConfig,
+ previous: Option<&HostConfig>,
+ manager: &dyn ServiceManager,
+ ) -> Result<()> {
+ use crate::ports::{self, Transport};
+ let channel = CuaChannel::current();
+ let default = channel.ports();
+ let listen = config
+ .listen
+ .as_deref()
+ .and_then(|l| l.parse::<SocketAddr>().ok());
+ // A joined host binds loopback; a direct one its listen address.
+ let ip = listen.map_or(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), |l| {
+ l.ip()
+ });
+ let fixed_tcp = listen.map(|l| l.port());
+ let free = |(tcp, quic): ports::PortPair| {
+ (fixed_tcp.is_some() || manager.port_free(SocketAddr::new(ip, tcp), Transport::Tcp))
+ && manager.port_free(SocketAddr::new(ip, quic), Transport::Udp)
+ };
+ let mut preferred: Vec<ports::PortPair> = Vec::new();
+ if let Some(p) = previous {
+ let p = p.service_ports(channel);
+ preferred.push((p.tcp, p.quic));
+ }
+ preferred.push((default.tcp, default.quic));
+ if !free(preferred[0]) && manager.state().installed {
+ // Perhaps this user's own service: stop it and give it a moment
+ // to let go of its sockets.
+ let _ = manager.stop();
+ let deadline = tokio::time::Instant::now() + PORT_RELEASE_WAIT;
+ while !free(preferred[0]) && tokio::time::Instant::now() < deadline {
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ }
+ let candidates = ports::candidates(&preferred, ports::per_user_seed());
+ let Some((tcp, quic)) = ports::first_free(&candidates, free) else {
+ let (lo, hi) = ports::per_user_range();
+ return Err(Error::Service(format!(
+ "no free port for the host service: {}/{} (TCP/UDP) and the per-user ports \
+ {lo}-{hi} are all in use by other programs; stop one of them, then run \
+ `{} host setup` again",
+ preferred[0].0,
+ preferred[0].1,
+ crate::cli()
+ )));
+ };
+ let tcp = fixed_tcp.map_or(tcp, |_| default.tcp);
+ if quic != preferred[0].1 || (fixed_tcp.is_none() && tcp != preferred[0].0) {
+ tracing::warn!(
+ "port {}/{} is in use by another program (another user's Cua host on this \
+ machine?); this host service listens on {tcp} (TCP) and {quic} (QUIC) instead",
+ preferred[0].0,
+ preferred[0].1,
+ );
+ }
+ config.port = (tcp != default.tcp).then_some(tcp);
+ config.quic_port = (quic != default.quic).then_some(quic);
+ Ok(())
+ }
+
/// Whether a setup with `opts` provides Spaces: what it says, else
/// [`default_provide_spaces`] for this machine (what it already has
/// when it was set up before; on for a new relay setup).
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index 58463fe488..0519a12094 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -43,6 +43,7 @@ mod helper_migration_tests;
mod host;
pub mod machine;
pub mod pairing;
+pub mod ports;
pub mod preflight;
pub mod provided;
pub mod relay;
diff --git a/libs/cua/crates/cua-host/src/ports.rs b/libs/cua/crates/cua-host/src/ports.rs
new file mode 100644
index 0000000000..6470f7c0ff
--- /dev/null
+++ b/libs/cua/crates/cua-host/src/ports.rs
@@ -0,0 +1,196 @@
+//! Which TCP and QUIC (UDP) ports the host service listens on.
+//!
+//! One host service runs per macOS user (per channel). The first one on a
+//! machine keeps its channel's ports (3211 TCP and 3212 QUIC for Stable,
+//! 3221 and 3222 for Local), as it always has. When another program, most
+//! often another user's host service, already holds them, setup moves this
+//! user's service to a pair of its own: `3211 + 10k` and `3212 + 10k` for
+//! `k` in `2..=78` (3231/3232 up to 3991/3992; `k = 1` is Local's pair),
+//! starting at a slot derived from the user id so two users rarely try the
+//! same pair, and taking the first free one from there. The pair is kept in
+//! the host config, so a later setup keeps it while it stays free.
+//!
+//! The mesh media port (3212) is not one of them: it is a port of the
+//! mesh's own in-process network, not a socket of the operating system, so
+//! two users' services never compete for it.
+
+use std::net::{SocketAddr, TcpListener, UdpSocket};
+
+/// A spacesd port pair: `(tcp, quic)`.
+pub type PortPair = (u16, u16);
+
+/// A socket kind the service binds.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Transport {
+ /// The HTTP/WebSocket listener.
+ Tcp,
+ /// The QUIC media listener.
+ Udp,
+}
+
+/// Whether `addr` can be bound for `transport` right now, the way
+/// cua-spacesd binds it (a std listener or UDP socket, closed again at
+/// once).
+pub fn os_port_free(addr: SocketAddr, transport: Transport) -> bool {
+ match transport {
+ Transport::Tcp => TcpListener::bind(addr).is_ok(),
+ Transport::Udp => UdpSocket::bind(addr).is_ok(),
+ }
+}
+
+/// The lowest and highest per-user slot (`3211 + 10k`).
+const FIRST_SLOT: u16 = 2;
+const LAST_SLOT: u16 = 78;
+
+/// The per-user pair of `slot`.
+fn slot_pair(slot: u16) -> PortPair {
+ (3211 + 10 * slot, 3212 + 10 * slot)
+}
+
+/// The per-user port range, for messages (`3231-3992`).
+pub(crate) fn per_user_range() -> (u16, u16) {
+ (slot_pair(FIRST_SLOT).0, slot_pair(LAST_SLOT).1)
+}
+
+/// A number that differs between the users of one machine and stays the
+/// same for each: the user id on Unix, a hash of the user name elsewhere.
+pub(crate) fn per_user_seed() -> u32 {
+ #[cfg(unix)]
+ {
+ // SAFETY: getuid has no preconditions and cannot fail.
+ unsafe { libc::getuid() }
+ }
+ #[cfg(not(unix))]
+ {
+ let name = std::env::var("USERNAME").unwrap_or_default();
+ name.bytes().fold(2_166_136_261u32, |h, b| {
+ (h ^ u32::from(b)).wrapping_mul(16_777_619)
+ })
+ }
+}
+
+/// The pairs to try, in order: `preferred` (the pair this user's service
+/// already has, then the channel's), then every per-user pair, starting at
+/// the one `seed` picks. No pair twice.
+pub(crate) fn candidates(preferred: &[PortPair], seed: u32) -> Vec<PortPair> {
+ let slots = LAST_SLOT - FIRST_SLOT + 1;
+ let start = (seed % u32::from(slots)) as u16;
+ let mut out: Vec<PortPair> = Vec::new();
+ for pair in preferred
+ .iter()
+ .copied()
+ .chain((0..slots).map(|i| slot_pair(FIRST_SLOT + (start + i) % slots)))
+ {
+ if !out.contains(&pair) {
+ out.push(pair);
+ }
+ }
+ out
+}
+
+/// The first of `candidates` that `free` accepts.
+pub(crate) fn first_free(
+ candidates: &[PortPair],
+ mut free: impl FnMut(PortPair) -> bool,
+) -> Option<PortPair> {
+ candidates.iter().copied().find(|&pair| free(pair))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::net::{IpAddr, Ipv4Addr};
+
+ const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
+
+ /// A port nothing holds right now (the OS hands out a free one, and
+ /// the socket is closed again).
+ fn free_tcp_port() -> u16 {
+ TcpListener::bind((LOOPBACK, 0))
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port()
+ }
+
+ fn free_udp_port() -> u16 {
+ UdpSocket::bind((LOOPBACK, 0))
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port()
+ }
+
+ fn pair_free(pair: PortPair) -> bool {
+ os_port_free(SocketAddr::new(LOOPBACK, pair.0), Transport::Tcp)
+ && os_port_free(SocketAddr::new(LOOPBACK, pair.1), Transport::Udp)
+ }
+
+ /// A pair whose TCP or UDP port another socket holds is skipped; a free
+ /// first choice is kept.
+ #[test]
+ fn a_pair_held_by_another_socket_is_skipped() {
+ let held_tcp = TcpListener::bind((LOOPBACK, 0)).unwrap();
+ let held_udp = UdpSocket::bind((LOOPBACK, 0)).unwrap();
+ let tcp_busy = (held_tcp.local_addr().unwrap().port(), free_udp_port());
+ let udp_busy = (free_tcp_port(), held_udp.local_addr().unwrap().port());
+ let free = (free_tcp_port(), free_udp_port());
+
+ assert!(!os_port_free(
+ SocketAddr::new(LOOPBACK, tcp_busy.0),
+ Transport::Tcp
+ ));
+ assert!(!os_port_free(
+ SocketAddr::new(LOOPBACK, udp_busy.1),
+ Transport::Udp
+ ));
+ assert_eq!(
+ first_free(&[tcp_busy, udp_busy, free], pair_free),
+ Some(free)
+ );
+ assert_eq!(first_free(&[free, tcp_busy], pair_free), Some(free));
+ assert_eq!(first_free(&[tcp_busy, udp_busy], pair_free), None);
+
+ // Once the other socket lets go, its pair is free again.
+ drop(held_tcp);
+ assert!(os_port_free(
+ SocketAddr::new(LOOPBACK, tcp_busy.0),
+ Transport::Tcp
+ ));
+ }
+
+ /// The preferred pairs come first, then each per-user pair once,
+ /// starting at the seed's slot and never Stable's or Local's pair.
+ #[test]
+ fn candidates_start_with_the_preferred_then_the_users_own_slot() {
+ let c = candidates(&[(3211, 3212), (3211, 3212)], 0);
+ assert_eq!(c[0], (3211, 3212));
+ assert_eq!(c[1], (3231, 3232));
+ assert_eq!(c.len(), 1 + 77);
+ assert!(
+ !c[1..].contains(&(3221, 3222)),
+ "Local's pair is not a slot"
+ );
+ assert_eq!(*c.last().unwrap(), (3991, 3992));
+ assert_eq!(per_user_range(), (3231, 3992));
+
+ // Another user starts elsewhere, and wraps around.
+ let c = candidates(&[(3211, 3212)], 501);
+ assert_eq!(c[1], slot_pair(FIRST_SLOT + (501 % 77) as u16));
+ assert_eq!(c.len(), 78);
+ let mut sorted = c[1..].to_vec();
+ sorted.sort();
+ sorted.dedup();
+ assert_eq!(sorted.len(), 77, "every slot once");
+
+ // The same user always gets the same order.
+ assert_eq!(
+ candidates(&[(3211, 3212)], 502),
+ candidates(&[(3211, 3212)], 502)
+ );
+ // A pair the user already has comes first, before the channel's.
+ let c = candidates(&[(3301, 3302), (3211, 3212)], 502);
+ assert_eq!(&c[..2], &[(3301, 3302), (3211, 3212)]);
+ assert_eq!(c.iter().filter(|p| **p == (3301, 3302)).count(), 1);
+ }
+}
diff --git a/libs/cua/crates/cua-host/src/service.rs b/libs/cua/crates/cua-host/src/service.rs
index e0bcf3fc37..c914b6a580 100644
--- a/libs/cua/crates/cua-host/src/service.rs
+++ b/libs/cua/crates/cua-host/src/service.rs
@@ -259,6 +259,10 @@ pub trait ServiceManager: Send + Sync {
fn uninstall(&self) -> Result<()>;
/// Current state.
fn state(&self) -> ServiceState;
+ /// Whether the service this runs could bind `addr` for `transport`
+ /// now (setup asks before it chooses the service's ports). The real
+ /// runners ask the operating system ([`crate::ports::os_port_free`]).
+ fn port_free(&self, addr: std::net::SocketAddr, transport: crate::ports::Transport) -> bool;
}
// ------------------------------------------------------------- generators
@@ -672,6 +676,9 @@ impl ServiceManager for Systemd {
),
}
}
+ fn port_free(&self, addr: std::net::SocketAddr, transport: crate::ports::Transport) -> bool {
+ crate::ports::os_port_free(addr, transport)
+ }
}
/// launchd LaunchAgent (GUI domain of the current user).
@@ -763,6 +770,9 @@ impl ServiceManager for Launchd {
detail: self.plist_path().display().to_string(),
}
}
+ fn port_free(&self, addr: std::net::SocketAddr, transport: crate::ports::Transport) -> bool {
+ crate::ports::os_port_free(addr, transport)
+ }
}
/// How long [`launchd_restart`] waits for a bootout to finish.
@@ -1081,6 +1091,9 @@ impl ServiceManager for WindowsTask {
detail: text.trim().to_string(),
}
}
+ fn port_free(&self, addr: std::net::SocketAddr, transport: crate::ports::Transport) -> bool {
+ crate::ports::os_port_free(addr, transport)
+ }
}
/// Running processes by executable path (the logon entry has no pidfile:
@@ -1303,6 +1316,9 @@ impl ServiceManager for ProcessRunner {
detail: pid.map(|p| format!("pid {p}")).unwrap_or_default(),
}
}
+ fn port_free(&self, addr: std::net::SocketAddr, transport: crate::ports::Transport) -> bool {
+ crate::ports::os_port_free(addr, transport)
+ }
}
// ------------------------------------------------------------- app helper
@@ -1615,6 +1631,9 @@ impl ServiceManager for AppHelper {
detail: format!("{} in {}", self.channel.app_name(), self.app.display()),
}
}
+ fn port_free(&self, addr: std::net::SocketAddr, transport: crate::ports::Transport) -> bool {
+ crate::ports::os_port_free(addr, transport)
+ }
}
/// A registration that did not leave the helper allowed to run, in words.
@@ -1662,6 +1681,9 @@ impl ServiceManager for MissingAppHelper {
detail: format!("{}: the Cua Spaces app is not installed", app_helper_name()),
}
}
+ fn port_free(&self, addr: std::net::SocketAddr, transport: crate::ports::Transport) -> bool {
+ crate::ports::os_port_free(addr, transport)
+ }
}
fn missing_app() -> Error {
@@ -1750,6 +1772,11 @@ pub struct FakeServiceManager {
running: Mutex<bool>,
/// `start` fails while this is set.
pub fail_start: Mutex<bool>,
+ /// Ports another program holds (any address, TCP and UDP alike): never
+ /// free. Every other port is free, so no test binds a real one.
+ pub held_by_others: Mutex<Vec<u16>>,
+ /// Ports this service holds while it runs (free once it is stopped).
+ pub held_while_running: Mutex<Vec<u16>>,
}
impl ServiceManager for FakeServiceManager {
@@ -1788,6 +1815,12 @@ impl ServiceManager for FakeServiceManager {
detail: String::new(),
}
}
+ fn port_free(&self, addr: std::net::SocketAddr, _: crate::ports::Transport) -> bool {
+ let port = addr.port();
+ !self.held_by_others.lock().unwrap().contains(&port)
+ && !(*self.running.lock().unwrap()
+ && self.held_while_running.lock().unwrap().contains(&port))
+ }
}
/// The manager for `kind` (resolving `Auto`), for the current user.
diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rs
index a3cef07ca4..407e285a70 100644
--- a/libs/cua/crates/cua-host/src/tests.rs
+++ b/libs/cua/crates/cua-host/src/tests.rs
@@ -1513,6 +1513,9 @@ impl ServiceManager for AsLaunchd {
fn state(&self) -> ServiceState {
self.0.state()
}
+ fn port_free(&self, addr: std::net::SocketAddr, t: crate::ports::Transport) -> bool {
+ self.0.port_free(addr, t)
+ }
}
/// A [`SessionProbe`] that just answers whether a GUI session exists.
@@ -2527,3 +2530,229 @@ fn the_default_for_providing_spaces() {
Some(Err(Error::NotFound("x".into())))
));
}
+
+/// The ports setup chose (another macOS user's host held the channel's)
+/// reach the service on the command line and in its environment, so it and
+/// everything it starts listen there and find each other.
+#[test]
+fn a_host_moved_off_the_channels_ports_is_told_its_own() {
+ let home = tempfile::tempdir().unwrap();
+ let host = Host::new(home.path());
+ let config = crate::HostConfig {
+ mode: "relay".into(),
+ relay_url: Some("https://relay.example".into()),
+ machine_id: Some("machine-0001".into()),
+ port: Some(3231),
+ quic_port: Some(3232),
+ ..Default::default()
+ };
+ let spec = host.service_spec_for(&config, cua_home::channel::CuaChannel::Stable);
+ let flag = |name: &str| {
+ spec.args
+ .iter()
+ .position(|a| a == name)
+ .map(|i| spec.args[i + 1].clone())
+ };
+ assert_eq!(flag("--port").as_deref(), Some("3231"));
+ assert_eq!(flag("--quic-port").as_deref(), Some("3232"));
+ let var = |k: &str, v: &str| (k.to_string(), v.to_string());
+ assert!(spec.env.contains(&var("CUA_ENV_PORT", "3231")));
+ assert!(spec.env.contains(&var("CUA_ENV_QUIC_PORT", "3232")));
+ assert!(spec.env.iter().all(|(k, _)| k != "CUA_CHANNEL"));
+ let plist = crate::service::launchd_plist(&spec);
+ assert!(
+ plist.contains("<key>CUA_ENV_PORT</key>\n <string>3231</string>"),
+ "{plist}"
+ );
+ assert!(
+ plist.contains("<key>CUA_ENV_QUIC_PORT</key>\n <string>3232</string>"),
+ "{plist}"
+ );
+ let back: crate::HostConfig =
+ serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
+ assert_eq!((back.port, back.quic_port), (Some(3231), Some(3232)));
+ // Unset, nothing is written: a config from before reads the same.
+ let json = serde_json::to_string(&crate::HostConfig::default()).unwrap();
+ assert!(!json.contains("port"), "{json}");
+}
+
+/// The credential store and home `cua host setup` ran with reach the
+/// service (LaunchAgent, systemd unit), so the service and the daemon it
+/// starts read the session the CLI signed in with (`file` over SSH, where
+/// the keychain cannot be used). Without them, nothing is added.
+#[test]
+fn the_service_keeps_the_credential_store_and_home_setup_ran_with() {
+ let home = tempfile::tempdir().unwrap();
+ let host = Host::new(home.path());
+ let config = crate::HostConfig {
+ mode: "relay".into(),
+ relay_url: Some("https://relay.example".into()),
+ machine_id: Some("machine-0001".into()),
+ ..Default::default()
+ };
+ let spec = host.service_spec(&config);
+ assert!(
+ spec.env
+ .iter()
+ .all(|(k, _)| k != "CUA_CREDENTIAL_STORE" && k != "CUA_HOME"),
+ "{:?}",
+ spec.env
+ );
+ let json = serde_json::to_string(&config).unwrap();
+ assert!(
+ !json.contains("credential_store") && !json.contains("cua_home"),
+ "{json}"
+ );
+
+ let config = crate::HostConfig {
+ credential_store: Some("file".into()),
+ cua_home: Some("/Users/ada/.cua-spare".into()),
+ ..config
+ };
+ let spec = host.service_spec(&config);
+ let var = |k: &str, v: &str| (k.to_string(), v.to_string());
+ assert!(spec.env.contains(&var("CUA_CREDENTIAL_STORE", "file")));
+ assert!(spec.env.contains(&var("CUA_HOME", "/Users/ada/.cua-spare")));
+ let plist = crate::service::launchd_plist(&spec);
+ assert!(
+ plist.contains("<key>CUA_CREDENTIAL_STORE</key>\n <string>file</string>"),
+ "{plist}"
+ );
+ assert!(
+ plist.contains("<key>CUA_HOME</key>\n <string>/Users/ada/.cua-spare</string>"),
+ "{plist}"
+ );
+ let unit = crate::service::systemd_unit(&spec, false);
+ assert!(
+ unit.contains("Environment=CUA_CREDENTIAL_STORE=file\n"),
+ "{unit}"
+ );
+ let back: crate::HostConfig =
+ serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
+ assert_eq!(back.credential_store.as_deref(), Some("file"));
+ assert_eq!(back.cua_home.as_deref(), Some("/Users/ada/.cua-spare"));
+}
+
+/// The ports a setup in relay mode left in the config.
+fn chosen_ports(host: &Host) -> (Option<u16>, Option<u16>) {
+ let c = host.config().unwrap().unwrap();
+ (c.port, c.quic_port)
+}
+
+/// Another program (another macOS user's host service) holds the channel's
+/// ports: setup moves this user's service to a per-user pair, tells it, and
+/// keeps that pair on every later setup, even once the channel's are free.
+#[tokio::test]
+async fn setup_moves_off_ports_another_user_holds_and_keeps_its_own() {
+ let relay = FakeRelay::start().await;
+ relay.add_account("acct-token", "user-1", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ let ch = cua_home::channel::CuaChannel::current().ports();
+ *f.manager.held_by_others.lock().unwrap() = vec![ch.tcp, ch.quic];
+
+ host.setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))
+ .await
+ .unwrap();
+ let (tcp, quic) = chosen_ports(&host);
+ let (tcp, quic) = (tcp.unwrap(), quic.unwrap());
+ assert_eq!(quic, tcp + 1);
+ assert!((3231..=3991).contains(&tcp) && tcp % 10 == 1, "{tcp}");
+ let spec = f.manager.spec.lock().unwrap().clone().unwrap();
+ let port = tcp.to_string();
+ assert!(
+ spec.args
+ .windows(2)
+ .any(|w| w[0] == "--port" && w[1] == port),
+ "{:?}",
+ spec.args
+ );
+ assert!(
+ spec.env
+ .contains(&("CUA_ENV_QUIC_PORT".to_string(), quic.to_string()))
+ );
+
+ // Again, with the service running on its pair: it stays there.
+ *f.manager.held_while_running.lock().unwrap() = vec![tcp, quic];
+ host.setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))
+ .await
+ .unwrap();
+ assert_eq!(chosen_ports(&host), (Some(tcp), Some(quic)));
+
+ // The other user leaves: still this pair (nothing moves under the
+ // clients that know it).
+ f.manager.held_by_others.lock().unwrap().clear();
+ host.setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))
+ .await
+ .unwrap();
+ assert_eq!(chosen_ports(&host), (Some(tcp), Some(quic)));
+}
+
+/// This user's own running service holding the channel's ports is not
+/// another program: setup again stops it and keeps them (nothing is passed,
+/// as for every single-user host).
+#[tokio::test]
+async fn setup_again_keeps_the_ports_its_own_service_holds() {
+ let relay = FakeRelay::start().await;
+ relay.add_account("acct-token", "user-1", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ let ch = cua_home::channel::CuaChannel::current().ports();
+ host.setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))
+ .await
+ .unwrap();
+ assert_eq!(chosen_ports(&host), (None, None));
+ assert_eq!(
+ f.manager.calls.lock().unwrap().clone(),
+ vec!["install".to_string(), "start".to_string()],
+ "free ports: the service is not stopped first"
+ );
+
+ *f.manager.held_while_running.lock().unwrap() = vec![ch.tcp, ch.quic];
+ f.manager.calls.lock().unwrap().clear();
+ host.setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))
+ .await
+ .unwrap();
+ assert_eq!(chosen_ports(&host), (None, None));
+ assert_eq!(
+ f.manager.calls.lock().unwrap().first().map(String::as_str),
+ Some("stop")
+ );
+ let spec = f.manager.spec.lock().unwrap().clone().unwrap();
+ assert!(
+ spec.args
+ .iter()
+ .all(|a| a != "--port" && a != "--quic-port"),
+ "{:?}",
+ spec.args
+ );
+}
+
+/// With the channel's ports and every per-user pair held, setup fails at
+/// the service stage, says so in plain words, and installs nothing.
+#[tokio::test]
+async fn setup_says_so_when_no_port_is_free() {
+ let relay = FakeRelay::start().await;
+ relay.add_account("acct-token", "user-1", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ let ch = cua_home::channel::CuaChannel::current().ports();
+ *f.manager.held_by_others.lock().unwrap() = std::iter::once(ch.tcp)
+ .chain((2..=78).map(|k| 3211 + 10 * k))
+ .collect();
+
+ let (stage, err) = host
+ .setup_staged(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))
+ .await
+ .unwrap_err();
+ assert_eq!(stage, SetupStage::Service);
+ let msg = err.to_string();
+ assert!(
+ msg.contains(&format!(
+ "no free port for the host service: {}/{} (TCP/UDP) and the per-user ports 3231-3992 are all in use",
+ ch.tcp, ch.quic
+ )),
+ "{msg}"
+ );
+ assert!(f.manager.calls.lock().unwrap().is_empty());
+}
diff --git a/libs/cua/crates/cua-sandbox-core/src/lib.rs b/libs/cua/crates/cua-sandbox-core/src/lib.rs
index b6a35dad53..1d270a5350 100644
--- a/libs/cua/crates/cua-sandbox-core/src/lib.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/lib.rs
@@ -29,6 +29,8 @@ pub use cua_vmm::cleanup;
pub use cua_vmm::error::failure_kind as runtime_failure_kind;
/// GPU options per runtime ([`gpu::GpuSupport`]).
pub use cua_vmm::gpu;
+/// Which software runs each kind of Space here (`runtime.<kind>`).
+pub use cua_vmm::kinds as runtime_kinds;
/// Create progress: what a create is doing (pulling, booting, waiting for
/// the guest), reported to the [`progress::scope`] that started it.
pub use cua_vmm::progress;
diff --git a/libs/cua/crates/cua-sandbox-core/src/settings.rs b/libs/cua/crates/cua-sandbox-core/src/settings.rs
index 1dd31dad0c..973f7a9852 100644
--- a/libs/cua/crates/cua-sandbox-core/src/settings.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/settings.rs
@@ -35,7 +35,7 @@ pub struct Key {
}
/// Every setting, in display order.
-pub const KEYS: [Key; 13] = [
+pub const KEYS: [Key; 17] = [
Key {
name: "default.on",
env: "CUA_DEFAULT_ON",
@@ -61,16 +61,40 @@ pub const KEYS: [Key; 13] = [
description: "anonymous usage telemetry (on, off; alias `telemetry`); DO_NOT_TRACK=1 also turns it off. See `cua telemetry status`",
},
Key {
- name: "runtime.lume",
- env: "CUA_RUNTIME_LUME",
+ name: "runtime.container",
+ env: "CUA_RUNTIME_CONTAINER",
default: "auto",
- description: "the Lume macOS Spaces run on: auto (this Mac's own, else built-in), builtin (cua's pinned, signed Lume, set up on first use) or system (only this Mac's own; nothing is downloaded)",
+ description: "what runs container Spaces: auto (a working Docker engine here, else on a Mac cua's own; cua's own once it exists), builtin (cua's own: on a Mac a VM with Docker and gVisor, set up on first use) or system (only the engine already installed here; nothing is downloaded). Was runtime.linux",
},
Key {
- name: "runtime.linux",
- env: "CUA_RUNTIME_LINUX",
+ name: "runtime.container_path",
+ env: "CUA_RUNTIME_CONTAINER_PATH",
+ default: "",
+ description: "with runtime.container = system: the docker or podman binary to use instead of the one found on PATH (its engine is the one Spaces use)",
+ },
+ Key {
+ name: "runtime.vm",
+ env: "CUA_RUNTIME_VM",
default: "auto",
- description: "the engine local Linux Spaces run on, on a Mac: auto (a working Docker engine on this Mac, else built-in; built-in once it exists), builtin (cua's own VM with Docker and gVisor, set up on first use) or system (only this Mac's own engine; nothing is downloaded)",
+ description: "what runs virtual machine Spaces: auto (on a Mac this Mac's own Lume when new enough, else cua's own), builtin (cua's own: on a Mac its pinned, signed Lume, set up on first use) or system (only the one already installed here; nothing is downloaded). Was runtime.lume",
+ },
+ Key {
+ name: "runtime.vm_path",
+ env: "CUA_RUNTIME_VM_PATH",
+ default: "",
+ description: "with runtime.vm = system: the lume (Mac) or qemu-system-<arch> (Linux) binary to use instead of the one found on PATH",
+ },
+ Key {
+ name: "runtime.microvm",
+ env: "CUA_RUNTIME_MICROVM",
+ default: "auto",
+ description: "what runs microVM Spaces: auto (cua's own when this machine runs it, else what is installed here), builtin (cua's own: on a Mac its monitor, on Linux its Firecracker) or system (only what is already installed here: on a Mac Apple's container, on Linux Firecracker)",
+ },
+ Key {
+ name: "runtime.microvm_path",
+ env: "CUA_RUNTIME_MICROVM_PATH",
+ default: "",
+ description: "with runtime.microvm = system: the container (Mac) or firecracker (Linux) binary to use instead of the one found on PATH",
},
Key {
name: "runtime.linux_cpus",
@@ -117,7 +141,44 @@ pub const KEYS: [Key; 13] = [
];
/// Short names `cua config` accepts for a setting.
-const ALIASES: &[(&str, &str)] = &[("telemetry", "telemetry.enabled")];
+const ALIASES: &[(&str, &str)] = &[
+ ("telemetry", "telemetry.enabled"),
+ // The per-OS runtime settings became per kind (`runtime.container`,
+ // `runtime.vm`): the old names still work.
+ ("runtime.linux", "runtime.container"),
+ ("runtime.lume", "runtime.vm"),
+];
+
+/// The settings that replaced a per-OS one: the new name, the old name
+/// in the config file's `[runtime]` table and the old environment
+/// variable. Both are still read (the new ones win), and a write keeps the
+/// old name in step for an older `cua-spacesd` that reads only it.
+pub const LEGACY_RUNTIME: &[(&str, &str, &str)] = &[
+ ("runtime.container", "linux", "CUA_RUNTIME_LINUX"),
+ ("runtime.vm", "lume", "CUA_RUNTIME_LUME"),
+];
+
+fn legacy_of(key: &Key) -> Option<(&'static str, &'static str)> {
+ LEGACY_RUNTIME
+ .iter()
+ .find(|(n, _, _)| *n == key.name)
+ .map(|(_, toml, env)| (*toml, *env))
+}
+
+/// The kinds of Space with a runtime setting each (`runtime.<kind>` and
+/// `runtime.<kind>_path`), as `--kind` names them.
+pub const RUNTIME_KINDS: [&str; 3] = ["container", "vm", "microvm"];
+
+/// `auto`, `builtin` or `system` (`built-in` too), as a runtime setting
+/// takes it.
+pub fn runtime_source_word(v: &str) -> Option<&'static str> {
+ match v.trim().to_ascii_lowercase().as_str() {
+ "auto" | "" => Some("auto"),
+ "builtin" | "built-in" | "cua" => Some("builtin"),
+ "system" | "installed" => Some("system"),
+ _ => None,
+ }
+}
/// The setting named `name`.
pub fn key(name: &str) -> Result<Key, SettingsError> {
@@ -221,7 +282,11 @@ pub struct Settings {
impl Settings {
/// The process environment and `$CUA_HOME/config.toml`.
pub fn load() -> Result<Self, SettingsError> {
- Self::load_with(config_path(), |k| std::env::var(k).ok())
+ let mut s = Self::load_with(config_path(), |k| std::env::var(k).ok())?;
+ // The per-OS runtime settings under their per-kind names (a read
+ // still works without: a read-only home only skips this).
+ let _ = s.migrate_legacy();
+ Ok(s)
}
/// `path` and an arbitrary environment (tests).
@@ -238,7 +303,7 @@ impl Settings {
let doc = text
.parse::<toml_edit::DocumentMut>()
.map_err(|e| SettingsError(format!("{}: {e}", path.display())))?;
- let env = KEYS
+ let mut vars: Vec<(&'static str, String)> = KEYS
.iter()
.filter_map(|k| {
env(k.env)
@@ -246,7 +311,23 @@ impl Settings {
.map(|v| (k.env, v.trim().to_string()))
})
.collect();
- Ok(Self { path, doc, env })
+ // The old per-OS variables, when the new one is not set.
+ for (name, _, old) in LEGACY_RUNTIME {
+ let k = KEYS
+ .iter()
+ .find(|k| k.name == *name)
+ .expect("legacy keys exist");
+ if !vars.iter().any(|(e, _)| *e == k.env)
+ && let Some(v) = env(old).filter(|v| !v.trim().is_empty())
+ {
+ vars.push((old, v.trim().to_string()));
+ }
+ }
+ Ok(Self {
+ path,
+ doc,
+ env: vars,
+ })
}
/// The config file this reads and writes.
@@ -256,6 +337,13 @@ impl Settings {
fn config_value(&self, key: &Key) -> Option<String> {
let (section, name) = key.name.split_once('.')?;
+ self.config_value_at(section, name).or_else(|| {
+ let (old, _) = legacy_of(key)?;
+ self.config_value_at(section, old)
+ })
+ }
+
+ fn config_value_at(&self, section: &str, name: &str) -> Option<String> {
let item = self.doc.get(section)?.get(name)?;
let v = item.as_value()?;
Some(match v {
@@ -270,11 +358,16 @@ impl Settings {
/// The effective value of `key` (environment, then config, then the
/// built-in default).
pub fn entry(&self, key: Key) -> Entry {
- if let Some((_, v)) = self.env.iter().find(|(e, _)| *e == key.env) {
+ let old_env = legacy_of(&key).map(|(_, e)| e);
+ if let Some((e, v)) = self
+ .env
+ .iter()
+ .find(|(e, _)| *e == key.env || Some(*e) == old_env)
+ {
return Entry {
key,
value: v.clone(),
- source: Source::Env(key.env),
+ source: Source::Env(e),
};
}
if let Some(v) = self.config_value(&key) {
@@ -319,20 +412,51 @@ impl Settings {
}
_ => toml_edit::value(value.clone()),
};
- self.doc[section][name] = item;
+ self.doc[section][name] = item.clone();
+ // An older cua-spacesd reads only the per-OS name: keep it in step.
+ if let Some((old, _)) = legacy_of(&key) {
+ self.doc[section][old] = item;
+ }
self.save()?;
Ok(value)
}
+ /// Writes each per-kind runtime setting that the config file holds
+ /// only under its old per-OS name (`[runtime] linux`, `lume`) under its
+ /// new one too. Returns whether anything was written. [`Settings::load`]
+ /// runs it, so the file says the new names from then on.
+ pub fn migrate_legacy(&mut self) -> Result<bool, SettingsError> {
+ let mut changed = false;
+ for (name, old, _) in LEGACY_RUNTIME {
+ let (section, new) = name.split_once('.').expect("keys are section.name");
+ if self.config_value_at(section, new).is_some() {
+ continue;
+ }
+ let Some(v) = self.config_value_at(section, old) else {
+ continue;
+ };
+ let v = runtime_source_word(&v).unwrap_or("auto");
+ self.doc[section][new] = toml_edit::value(v);
+ changed = true;
+ }
+ if changed {
+ self.save()?;
+ }
+ Ok(changed)
+ }
+
/// Removes `key` from the config file. Returns whether it was set.
pub fn unset(&mut self, key: Key) -> Result<bool, SettingsError> {
let (section, name) = key.name.split_once('.').expect("keys are section.name");
- let removed = self
- .doc
- .get_mut(section)
- .and_then(|t| t.as_table_like_mut())
- .and_then(|t| t.remove(name))
- .is_some();
+ let mut removed = false;
+ for n in std::iter::once(name).chain(legacy_of(&key).map(|(old, _)| old)) {
+ removed |= self
+ .doc
+ .get_mut(section)
+ .and_then(|t| t.as_table_like_mut())
+ .and_then(|t| t.remove(n))
+ .is_some();
+ }
if removed {
if self
.doc
@@ -492,22 +616,30 @@ pub fn normalize(key: Key, value: &str) -> Result<String, SettingsError> {
out.join(",")
}
}
- "runtime.lume" => cua_vmm::lume::builtin::LumeSource::parse(v)
- .ok_or_else(|| {
- SettingsError(format!(
- "runtime.lume: expected auto, builtin or system, got {v:?}"
- ))
- })?
- .as_str()
- .to_string(),
- "runtime.linux" => cua_vmm::managed::LinuxSource::parse(v)
+ "runtime.container" | "runtime.vm" | "runtime.microvm" => runtime_source_word(v)
.ok_or_else(|| {
SettingsError(format!(
- "runtime.linux: expected auto, builtin or system, got {v:?}"
+ "{}: expected auto, builtin or system, got {v:?}",
+ key.name
))
})?
- .as_str()
.to_string(),
+ "runtime.container_path" | "runtime.vm_path" | "runtime.microvm_path" => {
+ let path = match v.strip_prefix("~/") {
+ Some(rest) => std::env::var_os("HOME")
+ .map(PathBuf::from)
+ .unwrap_or_default()
+ .join(rest),
+ None => PathBuf::from(v),
+ };
+ if !path.is_absolute() {
+ return Err(SettingsError(format!(
+ "{}: expected the full path of a program (unset it to use the one found), got {v:?}",
+ key.name
+ )));
+ }
+ path.display().to_string()
+ }
"nudges.risky_actions" => match v.to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => "on".into(),
"0" | "false" | "no" | "off" => "off".into(),
@@ -699,6 +831,93 @@ mod tests {
assert_eq!(s.default_kind().unwrap().0, Kind::Vm);
}
+ /// The per-OS runtime settings became per kind: an old config file
+ /// and old variables still count, `cua config` takes the old names, a
+ /// write keeps the old name in step (an older cua-spacesd reads it) and
+ /// the migration writes the new names.
+ #[test]
+ fn per_os_runtime_settings_migrate_to_per_kind() {
+ let d = tempfile::tempdir().unwrap();
+ let path = d.path().join("config.toml");
+ std::fs::write(&path, "[runtime]\nlinux = \"builtin\"\nlume = \"system\"\n").unwrap();
+ let s = settings(d.path(), &[]);
+ let container = s.entry(key("runtime.container").unwrap());
+ assert_eq!(
+ (container.value.as_str(), container.source.kind()),
+ ("builtin", "config")
+ );
+ assert_eq!(s.entry(key("runtime.vm").unwrap()).value, "system");
+ assert_eq!(s.entry(key("runtime.microvm").unwrap()).value, "auto");
+ // The old names are aliases.
+ assert_eq!(key("runtime.linux").unwrap().name, "runtime.container");
+ assert_eq!(key("runtime.lume").unwrap().name, "runtime.vm");
+
+ let mut s = settings(d.path(), &[]);
+ assert!(s.migrate_legacy().unwrap());
+ assert!(!s.migrate_legacy().unwrap());
+ let text = std::fs::read_to_string(&path).unwrap();
+ assert!(text.contains("container = \"builtin\""), "{text}");
+ assert!(text.contains("vm = \"system\""), "{text}");
+
+ // A new value wins and the old name follows it.
+ let mut s = settings(d.path(), &[]);
+ s.set(key("runtime.container").unwrap(), "system").unwrap();
+ let text = std::fs::read_to_string(&path).unwrap();
+ assert!(
+ text.contains("container = \"system\"") && text.contains("linux = \"system\""),
+ "{text}"
+ );
+ assert_eq!(
+ settings(d.path(), &[])
+ .entry(key("runtime.container").unwrap())
+ .value,
+ "system"
+ );
+ // Unset removes both.
+ let mut s = settings(d.path(), &[]);
+ assert!(s.unset(key("runtime.container").unwrap()).unwrap());
+ let s = settings(d.path(), &[]);
+ let e = s.entry(key("runtime.container").unwrap());
+ assert_eq!((e.value.as_str(), e.source.kind()), ("auto", "default"));
+
+ // The old variable counts; the new one wins over it.
+ let s = settings(d.path(), &[("CUA_RUNTIME_LINUX", "builtin")]);
+ assert_eq!(
+ s.entry(key("runtime.container").unwrap()).source,
+ Source::Env("CUA_RUNTIME_LINUX")
+ );
+ let s = settings(
+ d.path(),
+ &[
+ ("CUA_RUNTIME_LINUX", "builtin"),
+ ("CUA_RUNTIME_CONTAINER", "system"),
+ ],
+ );
+ assert_eq!(s.entry(key("runtime.container").unwrap()).value, "system");
+ }
+
+ /// A runtime path is a full path (`~/` is the home folder); unset goes
+ /// back to the one found.
+ #[test]
+ fn runtime_paths_are_full_paths() {
+ let d = tempfile::tempdir().unwrap();
+ let mut s = settings(d.path(), &[]);
+ let k = key("runtime.container_path").unwrap();
+ assert_eq!(s.entry(k).value, "");
+ assert_eq!(
+ s.set(k, " /opt/homebrew/bin/podman ").unwrap(),
+ "/opt/homebrew/bin/podman"
+ );
+ assert!(s.set(k, "podman").unwrap_err().0.contains("full path"));
+ assert!(s.set(key("runtime.microvm").unwrap(), "docker").is_err());
+ assert_eq!(
+ s.set(key("runtime.microvm").unwrap(), "Built-in").unwrap(),
+ "builtin"
+ );
+ assert!(s.unset(k).unwrap());
+ assert_eq!(settings(d.path(), &[]).entry(k).source, Source::Default);
+ }
+
#[test]
fn set_validates_and_normalizes() {
let d = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs b/libs/cua/crates/cua-sdk/src/native/agent_setup.rs
index 85602cf7cb..40fc3b1053 100644
--- a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs
+++ b/libs/cua/crates/cua-sdk/src/native/agent_setup.rs
@@ -437,6 +437,16 @@ pub fn sign_in_vault() -> Option<Box<dyn cua_agent_setup::SignInVault>> {
}
}
+/// Device sign-ins waiting to be approved, by id (started and waited in two calls).
+fn device_logins() -> &'static std::sync::Mutex<
+ std::collections::HashMap<String, cua_agent_setup::signin::DeviceSignIn>,
+> {
+ static L: std::sync::OnceLock<
+ std::sync::Mutex<std::collections::HashMap<String, cua_agent_setup::signin::DeviceSignIn>>,
+ > = std::sync::OnceLock::new();
+ L.get_or_init(Default::default)
+}
+
fn to_json<T: serde::Serialize>(v: &T) -> Result<String> {
serde_json::to_string(v).map_err(|e| CuaError::Internal(e.to_string()))
}
@@ -494,6 +504,95 @@ impl AgentSetup {
.await
}
+ /// Disconnect of some parts only (an app's page's switches): Cua's skills
+ /// and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ /// `{outcomes, removed_sign_ins}`.
+ pub async fn disconnect_parts_json(
+ &self,
+ agents: Vec<String>,
+ skills: bool,
+ mcp: bool,
+ sign_in: bool,
+ ) -> Result<String> {
+ self.blocking(move |s| {
+ let vault = sign_in_vault();
+ let (outcomes, removed) = s.disconnect(
+ &agents,
+ cua_agent_setup::Parts { skills, mcp },
+ cua_agent_setup::RemoveOptions::default(),
+ sign_in,
+ vault.as_deref(),
+ )?;
+ to_json(&serde_json::json!({"outcomes": outcomes, "removed_sign_ins": removed}))
+ })
+ .await
+ }
+
+ /// Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ /// --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ /// link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ pub async fn device_sign_in_start_json(&self, agent: String) -> Result<String> {
+ self.blocking(move |s| {
+ let login = s
+ .start_device_sign_in(&agent)
+ .map_err(|r| CuaError::Internal(r.line().to_string()))?;
+ let id = format!(
+ "{agent}-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0)
+ );
+ let out = serde_json::json!({"id": id, "url": login.url, "code": login.code});
+ device_logins()
+ .lock()
+ .map_err(|e| CuaError::Internal(e.to_string()))?
+ .insert(id, login);
+ to_json(&out)
+ })
+ .await
+ }
+
+ /// Waits for a device sign-in to be approved and saves it into Keyvault on
+ /// This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ pub async fn device_sign_in_wait_json(&self, id: String) -> Result<String> {
+ self.blocking(move |s| {
+ let login = device_logins()
+ .lock()
+ .map_err(|e| CuaError::Internal(e.to_string()))?
+ .remove(&id)
+ .ok_or_else(|| {
+ CuaError::InvalidArgument(format!("no sign-in {id:?} is waiting"))
+ })?;
+ let vault = sign_in_vault();
+ let r = match vault.as_deref() {
+ None => cua_agent_setup::connection::SignInResult {
+ imported: None,
+ refused: Some("failed".into()),
+ line: Some("Keyvault isn't available here.".into()),
+ },
+ Some(v) => match s.finish_device_sign_in(
+ login,
+ v,
+ cua_agent_setup::signin::DEVICE_SIGN_IN_WAIT,
+ ) {
+ Ok(i) => cua_agent_setup::connection::SignInResult {
+ imported: Some(i),
+ refused: None,
+ line: None,
+ },
+ Err(r) => cua_agent_setup::connection::SignInResult {
+ imported: None,
+ refused: Some(r.kind().into()),
+ line: Some(r.line().into()),
+ },
+ },
+ };
+ to_json(&r)
+ })
+ .await
+ }
+
/// Disconnect: what Connect did, undone (the previous config entry back
/// from Cua's record, the skills, and with `sign_in` the copy in
/// Keyvault). JSON `{outcomes, removed_sign_ins}`.
diff --git a/libs/cua/crates/cua-sdk/src/native/config.rs b/libs/cua/crates/cua-sdk/src/native/config.rs
index 9f8fa536ce..0ffc34ad58 100644
--- a/libs/cua/crates/cua-sdk/src/native/config.rs
+++ b/libs/cua/crates/cua-sdk/src/native/config.rs
@@ -15,8 +15,9 @@ use cua_sandbox_core::settings::{self, Entry, Settings};
/// One setting's effective value.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ConfigEntry {
- /// `default.on`, `default.kind`, `default.runtime`, `runtime.lume`,
- /// `runtime.linux` or `telemetry.enabled`.
+ /// `default.on`, `default.kind`, `default.runtime`, `runtime.container`,
+ /// `runtime.vm`, `runtime.microvm` (and their `_path`) or
+ /// `telemetry.enabled`.
pub key: String,
/// The effective value.
pub value: String,
@@ -177,7 +178,7 @@ mod tests {
config_list()
.unwrap()
.iter()
- .any(|e| e.key == "runtime.linux")
+ .any(|e| e.key == "runtime.container")
);
assert!(config_path().ends_with("config.toml"));
}
diff --git a/libs/cua/crates/cua-sdk/src/native/local.rs b/libs/cua/crates/cua-sdk/src/native/local.rs
index 7774ef72e5..a48f6f4033 100644
--- a/libs/cua/crates/cua-sdk/src/native/local.rs
+++ b/libs/cua/crates/cua-sdk/src/native/local.rs
@@ -6,6 +6,7 @@
use super::{Backend, run};
use crate::{CuaError, Result};
+use cua_sandbox_core::runtime_kinds as kinds;
/// Status of one local runtime component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
@@ -142,6 +143,95 @@ impl From<cua_daemon::storage::StorageReport> for LocalStorage {
}
}
+/// A runtime installed on this machine for one kind of Space.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct RuntimeDetected {
+ /// `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ pub tool: String,
+ /// As people know it (`Docker`, `Apple container`).
+ pub name: String,
+ pub path: String,
+ /// As `--version` says it (`27.3.1`).
+ pub version: Option<String>,
+ /// The guest system it runs, when only one (`macOS`, `Linux`).
+ pub guests: Option<String>,
+}
+
+/// What a binary is, for one kind of Space (`runtime_check_path`).
+#[derive(Debug, Clone, PartialEq, Eq, Default, uniffi::Record)]
+pub struct RuntimePathProbe {
+ pub path: String,
+ /// A file is there.
+ pub exists: bool,
+ /// It can be run.
+ pub executable: bool,
+ /// The tool it is, when it is one the kind takes.
+ pub tool: Option<String>,
+ pub name: Option<String>,
+ pub version: Option<String>,
+ /// The oldest version cua runs on.
+ pub min_version: Option<String>,
+ /// The names of the tools the kind takes here (`Docker`, `Podman`).
+ pub expected: Vec<String>,
+ pub guests: Option<String>,
+}
+
+/// One kind of Space's runtime, as Settings shows it.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct RuntimeKindState {
+ /// `container`, `vm` or `microvm`.
+ pub kind: String,
+ /// `runtime.<kind>`: `auto`, `builtin` or `system`.
+ pub source: String,
+ /// `runtime.<kind>_path`, when set.
+ pub path: Option<String>,
+ /// What is installed here for the kind, the one used first.
+ pub detected: Vec<RuntimeDetected>,
+ /// The path in use (the custom one, else the first detected), probed.
+ pub check: Option<RuntimePathProbe>,
+ /// The names of the tools the kind takes here (`Docker`, `Podman`).
+ pub expected: Vec<String>,
+}
+
+impl From<kinds::PathProbe> for RuntimePathProbe {
+ fn from(p: kinds::PathProbe) -> Self {
+ Self {
+ path: p.path.display().to_string(),
+ exists: p.exists,
+ executable: p.executable,
+ tool: p.tool,
+ name: p.name,
+ version: p.version,
+ min_version: p.min_version,
+ expected: p.expected,
+ guests: p.guests,
+ }
+ }
+}
+
+impl From<kinds::KindReport> for RuntimeKindState {
+ fn from(r: kinds::KindReport) -> Self {
+ Self {
+ kind: r.kind.as_str().into(),
+ source: r.source.as_str().into(),
+ path: r.path.map(|p| p.display().to_string()),
+ detected: r
+ .detected
+ .into_iter()
+ .map(|d| RuntimeDetected {
+ tool: d.tool,
+ name: d.name,
+ path: d.path.display().to_string(),
+ version: d.version,
+ guests: d.guests,
+ })
+ .collect(),
+ check: r.check.map(Into::into),
+ expected: r.expected,
+ }
+ }
+}
+
/// Local runtimes and images.
#[derive(uniffi::Object)]
pub struct Local {
@@ -150,6 +240,33 @@ pub struct Local {
#[uniffi::export]
impl Local {
+ /// Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ /// setting (`runtime.<kind>`), the runtimes installed on this machine
+ /// for it and what the path in use is. Read-only: runs each runtime's
+ /// `--version`, nothing else; probed in this process (the daemon runs
+ /// on the same host).
+ pub async fn runtime_kinds(&self) -> Result<Vec<RuntimeKindState>> {
+ run(async { Ok(kinds::report().await.into_iter().map(Into::into).collect()) }).await
+ }
+
+ /// What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ /// runnable, which runtime and its version. Settings checks a typed path
+ /// with it before it is saved (`runtime.<kind>_path`).
+ pub async fn runtime_check_path(&self, kind: String, path: String) -> Result<RuntimePathProbe> {
+ let k = kinds::RuntimeKind::parse(&kind).ok_or_else(|| {
+ CuaError::InvalidArgument(format!(
+ "kind: expected container, vm or microvm, got {kind:?}"
+ ))
+ })?;
+ let p = match path.trim().strip_prefix("~/") {
+ Some(rest) => {
+ std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(rest)
+ }
+ None => std::path::PathBuf::from(path.trim()),
+ };
+ run(async move { Ok(kinds::probe(k, &p).await.into()) }).await
+ }
+
/// Inspects local runtimes (read-only: never installs or starts
/// anything).
pub async fn doctor(&self) -> Result<DoctorReport> {
diff --git a/libs/cua/crates/cua-spaces-app-core/Cargo.toml b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
index 34c5cbf4e2..ef0c55e026 100644
--- a/libs/cua/crates/cua-spaces-app-core/Cargo.toml
+++ b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
@@ -45,5 +45,7 @@ base64.workspace = true
cua-keyvault.workspace = true
# Drift guard: the first run lists every agent the setup's registry knows.
cua-agent-setup.workspace = true
+# Drift guard: every agent the @ picker offers to start is a real harness.
+cua-agents.workspace = true
tokio = { workspace = true, features = ["full"] }
tempfile.workspace = true
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/connectors.json b/libs/cua/crates/cua-spaces-app-core/parity/connectors.json
new file mode 100644
index 0000000000..d3677afdcd
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/parity/connectors.json
@@ -0,0 +1,57 @@
+{
+ "name": "connectors",
+ "about": "Settings, Connectors (redesign) and summoning agents in a Space: the coding apps with Connect and Connected, the Providers with Connect or Sign out, each provider's Connect sheet (an app's own sign-in, a pasted key, a key from your shell), what one Connect on an app does (its token command, its device code, or the provider's sheet), an app's page, what sending an @mention does (add, wake, or why it can't be woken), and the one agent list Home and the Agents page draw (agents in Spaces and this device's runs that haven't started).",
+ "connectors": [
+ {
+ "step": "nothing connected",
+ "input": {
+ "apps": [
+ { "agent": "claude-code", "name": "Claude Code", "installed": true, "configured": false, "skills": false, "mcp": false, "mcpConfig": "~/.claude.json" },
+ { "agent": "codex", "name": "OpenAI Codex", "installed": true, "configured": true, "skills": true, "mcp": true, "mcpConfig": "~/.codex/config.toml" },
+ { "agent": "vscode", "name": "VS Code (Copilot agent mode)", "installed": true, "configured": true, "skills": true, "mcp": true, "mcpConfig": null }
+ ],
+ "keys": { "keys": [] },
+ "shellKeys": ["ANTHROPIC_API_KEY"]
+ }
+ },
+ {
+ "step": "Claude Code signed in, an OpenAI key pasted, Codex connecting",
+ "input": {
+ "apps": [
+ { "agent": "claude-code", "name": "Claude Code", "installed": true, "configured": true, "skills": true, "mcp": true, "mcpConfig": "~/.claude.json" },
+ { "agent": "codex", "name": "OpenAI Codex", "installed": true, "configured": true, "skills": true, "mcp": true, "mcpConfig": "~/.codex/config.toml" }
+ ],
+ "keys": { "keys": [
+ { "provider": "other", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000000000 },
+ { "provider": "openai", "env": "OPENAI_API_KEY", "last4": "3f9a", "addedMs": 1790000100000 }
+ ] },
+ "busy": [{ "id": "app:codex", "step": "signing-in" }]
+ }
+ }
+ ],
+ "sheets": ["anthropic", "openai", "github"],
+ "plans": ["claude-code", "codex", "vscode", "copilot-cli"],
+ "details": ["claude-code", "vscode"],
+ "summon": {
+ "input": {
+ "members": [{ "handle": "hermes", "harness": "hermes", "label": "Hermes" }],
+ "people": ["grace"],
+ "canAdd": true,
+ "connectors": { "apps": [{ "agent": "claude-code", "name": "Claude Code", "installed": true }], "keys": { "keys": [{ "provider": "openai", "env": "OPENAI_API_KEY", "last4": "3f9a", "addedMs": 1 }] } }
+ },
+ "texts": ["@claude fix the build", "@codex bump the timeout, @hermes review it", "cc @grace and @nobody"]
+ },
+ "agentList": {
+ "spaces": [
+ { "spaceId": "relay:a/b", "spaceName": "ubuntu-build", "members": [
+ { "handle": "hermes", "harness": "hermes", "displayName": "Hermes", "ownerId": "acct_ada", "status": "working", "activity": "bumping the retry timeout", "lastMs": 5 },
+ { "handle": "claude", "harness": "claude-code", "displayName": "Claude Code", "ownerId": "acct_grace", "status": "idle", "needsMs": [9] }
+ ] }
+ ],
+ "attempts": [
+ { "id": "a", "spaceId": "relay:x/y", "spaceName": "space-1", "harness": "claude-code", "label": "Claude Code", "job": "fix the build", "atMs": 10, "state": "not-connected", "note": "Claude Code isn't connected yet", "connectLabel": "Connect Claude Code", "app": "claude-code" },
+ { "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" }
+ ]
+ }
+}
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.json
new file mode 100644
index 0000000000..4f6d530eb2
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.json
@@ -0,0 +1,129 @@
+{
+ "flow": "connectors",
+ "frames": [
+ {
+ "apps": [
+ "claude-code | not-connected | - | Connect | -",
+ "codex | not-connected | Needs a sign-in to OpenAI. | Connect | -",
+ "vscode | connected | - | - | Connected"
+ ],
+ "footer": "Sign-ins and keys stay on this Mac in the Keychain. Each one is only given to the apps that use it.",
+ "providers": [
+ "anthropic | not-connected | Not connected | Connect",
+ "openai | not-connected | Not connected | Connect",
+ "github | not-connected | Not connected | Connect"
+ ],
+ "step": "nothing connected"
+ },
+ {
+ "apps": [
+ "claude-code | connected | - | - | Connected",
+ "codex | connecting | Enter the code in your browser… | Connect | -"
+ ],
+ "footer": "Sign-ins and keys stay on this Mac in the Keychain. Each one is only given to the apps that use it.",
+ "providers": [
+ "anthropic | connected | Claude sign-in, for Claude Code | Sign out",
+ "openai | connected | API key •••• 3f9a | Sign out",
+ "github | not-connected | Not connected | Connect"
+ ],
+ "step": "Claude Code signed in, an OpenAI key pasted, Codex connecting"
+ },
+ {
+ "key": "anthropic | -",
+ "sheet": "anthropic",
+ "title": "Connect Anthropic",
+ "ways": [
+ "app-token | Sign in with Claude | Sign in",
+ "key | Paste an API key | Paste key",
+ "shell | Use ANTHROPIC_API_KEY from your shell | Use it"
+ ]
+ },
+ {
+ "key": "openai | -",
+ "sheet": "openai",
+ "title": "Connect OpenAI",
+ "ways": [
+ "app-device | Sign in with ChatGPT | Sign in",
+ "key | Paste an API key | Paste key"
+ ]
+ },
+ {
+ "key": "other | COPILOT_GITHUB_TOKEN",
+ "sheet": "github",
+ "title": "Connect GitHub",
+ "ways": [
+ "key | Paste an API key | Paste key"
+ ]
+ },
+ {
+ "does": "true | true | false | - | anthropic",
+ "plan": "claude-code"
+ },
+ {
+ "does": "false | false | true | - | openai",
+ "plan": "codex"
+ },
+ {
+ "does": "false | false | false | - | -",
+ "plan": "vscode"
+ },
+ {
+ "does": "false | false | false | github | -",
+ "plan": "copilot-cli"
+ },
+ {
+ "detail": "claude-code",
+ "note": null,
+ "signIn": "Signs in with Anthropic | Claude sign-in, for Claude Code | Sign out",
+ "status": "Connected",
+ "toggles": [
+ "skills | Cua skills | true",
+ "mcp | Cua tools (MCP) | true",
+ "auto | Keep it set up | true"
+ ]
+ },
+ {
+ "detail": "vscode",
+ "note": null,
+ "signIn": "- | - | -",
+ "status": null,
+ "toggles": []
+ },
+ {
+ "candidates": [
+ "hermes | Hermes | true | In this Space",
+ "claude | Claude Code | false | Not connected yet",
+ "codex | Codex | false | Starts in this Space",
+ "openclaw | OpenClaw | false | Starts in this Space"
+ ]
+ },
+ {
+ "send": "@claude fix the build",
+ "steps": [
+ "claude | blocked | Claude Code isn't connected yet | Connect Claude Code | Only visible to you"
+ ]
+ },
+ {
+ "send": "@codex bump the timeout, @hermes review it",
+ "steps": [
+ "codex | add | - | - | -",
+ "hermes | wake | - | - | -"
+ ]
+ },
+ {
+ "send": "cc @grace and @nobody",
+ "steps": []
+ },
+ {
+ "agents": [
+ "attempt | Claude Code | not-connected | Claude Code isn't connected yet | Connect Claude Code",
+ "agent | Claude Code | you | Waiting for you in ubuntu-build | -",
+ "agent | Hermes | working | Bumping the retry timeout in ubuntu-build | -",
+ "attempt | Codex | creating | Waiting for space-2 to be ready | -",
+ "attempt | Hermes | failed | Didn't start | Try again"
+ ],
+ "seeAll": "See all 5",
+ "summary": "1 working"
+ }
+ ]
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
index 16793f681f..af6502060c 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
@@ -76,6 +76,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -197,6 +201,10 @@
"- fs-path text: Stored in = ~/.cua/volume/data ?/Users/maya/.cua/volume/data",
"- mount choice: Add Cua Volume to Finder {*On|Off}",
"- mount-path text: In Finder at = ~/Cua Volume [Show in Finder] ?/Users/maya/Cua Volume < /Users/maya/Cua Volume>",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -332,6 +340,10 @@
"- fs-path text: Stored in = ~/.cua/volume/data ?/Users/maya/.cua/volume/data",
"- mount choice: Add Cua Volume to Finder {*On|Off}",
"- mount-path text: In Finder at = ~/Cua Volume [Show in Finder] ?/Users/maya/Cua Volume < /Users/maya/Cua Volume>",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -463,6 +475,10 @@
"- fs-path text: Stored in = ~/.cua/volume/data ?/Users/maya/.cua/volume/data",
"- mount choice: Add Cua Volume to Finder {*On|Off}",
"- mount-path text: In Finder at = ~/Cua Volume [Show in Finder] ?/Users/maya/Cua Volume < /Users/maya/Cua Volume>",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -581,6 +597,10 @@
"- fs-path text: Stored in = ~/.cua/volume/data ?/Users/maya/.cua/volume/data",
"- mount choice: Add Cua Volume to Finder {*On|Off}",
"- mount-path text: In Finder at = ~/Cua Volume [Show in Finder] ?/Users/maya/Cua Volume < /Users/maya/Cua Volume>",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -699,6 +719,10 @@
"- fs-path text: Stored in = ~/.cua/volume/data ?/Users/maya/.cua/volume/data",
"- mount choice: Add Cua Volume to Finder {*On|Off}",
"- mount-path text: In Finder at = ~/Cua Volume [Show in Finder] ?/Users/maya/Cua Volume < /Users/maya/Cua Volume>",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -810,6 +834,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -933,6 +961,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -1059,6 +1091,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json
index ae9ffa8f50..644d80961c 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json
@@ -672,6 +672,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# AI agents (agents) [Configure all detected agents] (disabled)"
],
"settings": 0
@@ -692,6 +696,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {On|*Off} (disabled) ?Set by DO_NOT_TRACK",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -713,6 +721,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
@@ -739,6 +751,10 @@
"- welcome text: Welcome [Show again]",
"- tips toggle: Show tips {*On|Off}",
"- reset-tips text: Reset tips [Reset]",
+ "# Runtimes (runtimes)",
+ "- runtime:container choice: Containers {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:vm choice: Virtual machines {*Automatic|Cua’s own|Already installed} ?Checking…",
+ "- runtime:microvm choice: MicroVMs {*Automatic|Cua’s own|Already installed} ?Checking…",
"# Privacy (privacy)",
"- telemetry choice: Share usage data to help improve Cua {*On|Off}",
"- telemetry-note note: Which features you use and when something goes wrong. Linked to your account through a random ID while you're signed in. Never your files, what you type or your screen. <What is collected https://cua.ai/docs/cua-sdk/concepts/telemetry>",
diff --git a/libs/cua/crates/cua-spaces-app-core/src/agent_list.rs b/libs/cua/crates/cua-spaces-app-core/src/agent_list.rs
new file mode 100644
index 0000000000..d2c2f72461
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/agent_list.rs
@@ -0,0 +1,487 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Every agent you work with, as one list: the Agents page and Home's "Your
+//! agents" both draw it, so they never disagree.
+//!
+//! - **Agents in Spaces** (the threads' members): one row per agent across
+//! its Spaces, keyed on who owns it, its kind and its name; its status
+//! line (waiting for you, working on what, failed, stopped, asleep).
+//! - **Runs that never became one** (this device's): a job whose Space is
+//! still being made, an @mention of an agent that isn't connected yet, a
+//! start that failed. Each keeps its job, its Space, and the action that
+//! moves it on (Connect, Try again).
+//!
+//! Order: what needs your Connect, what waits for you, what's working,
+//! what's starting, then the most recent.
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ListMember {
+ /// Its handle in the Space (`claude`).
+ pub handle: String,
+ pub harness: String,
+ /// The name it chose (empty: the handle).
+ pub display_name: String,
+ /// Who owns it (empty: not known; then the row is per Space).
+ pub owner_id: String,
+ /// `working`, `claimed`, `idle`, `asleep`, `paused`, `failed`, `stopped`, ...
+ pub status: String,
+ pub activity: Option<String>,
+ pub unread: u32,
+ pub last_ms: u64,
+ /// When each thing waiting for you was asked (newest decides the order).
+ pub needs_ms: Vec<u64>,
+ /// It asked to join and waits to be let in: not listed.
+ pub pending: bool,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ListSpace {
+ pub space_id: String,
+ pub space_name: String,
+ pub members: Vec<ListMember>,
+}
+
+/// A run of this device's that isn't an agent in a Space (yet).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ListAttempt {
+ pub id: String,
+ /// Its Space (a `pending:` id while it is being made).
+ pub space_id: String,
+ pub space_name: String,
+ pub harness: String,
+ /// The agent's name ("Claude Code").
+ pub label: String,
+ /// What it was asked to do.
+ pub job: String,
+ pub at_ms: u64,
+ /// `creating`, `not-connected`, `failed`, `stopped`.
+ pub state: String,
+ /// Not connected: the thread's own words ("Claude Code isn't connected yet") and Connect's.
+ pub note: Option<String>,
+ pub connect_label: Option<String>,
+ /// The Connectors app Connect runs for.
+ pub app: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct AgentListInput {
+ pub spaces: Vec<ListSpace>,
+ pub attempts: Vec<ListAttempt>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListAction {
+ /// `connect`, `retry`.
+ pub id: String,
+ pub label: String,
+}
+
+/// Where a row's agent is: a Space and its handle there.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListPlace {
+ pub space_id: String,
+ pub space_name: String,
+ pub handle: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentListRow {
+ pub key: String,
+ /// `agent` (in a Space) or `attempt` (this device's run).
+ pub kind: String,
+ pub label: String,
+ pub harness: String,
+ /// `you`, `not-connected`, `working`, `creating`, `failed`, `stopped`, `idle`, `asleep`.
+ pub tone: String,
+ pub line: String,
+ /// What it was asked to do (a run's job; an agent's current work).
+ pub job: Option<String>,
+ pub last_ms: u64,
+ pub unread: u32,
+ pub places: Vec<ListPlace>,
+ pub action: Option<ListAction>,
+ pub app: Option<String>,
+ /// For an attempt: its id.
+ pub attempt: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentListView {
+ pub rows: Vec<AgentListRow>,
+ /// Waiting for you, working or starting.
+ pub live: usize,
+ /// "2 working" (absent with none).
+ pub summary: Option<String>,
+ pub title: String,
+ /// "See all 5".
+ pub see_all_label: String,
+}
+
+/// One agent across Spaces: the same owner, kind and name. Without an owner, its handle in its Space.
+pub fn member_key(space_id: &str, m: &ListMember) -> String {
+ if m.owner_id.is_empty() {
+ return format!("{space_id}/{}", m.handle);
+ }
+ let kind = if m.harness.is_empty() {
+ "other"
+ } else {
+ &m.harness
+ };
+ let name = if m.display_name.is_empty() {
+ &m.handle
+ } else {
+ &m.display_name
+ };
+ format!("{}/{kind}/{}", m.owner_id, name.trim().to_lowercase())
+}
+
+/// "bumping the retry timeout in ubuntu-build" reads "Bumping the retry timeout".
+fn sentence(s: &str) -> String {
+ let t = s.trim();
+ let t = match t.rfind(" in ") {
+ Some(i) if !t[i + 4..].contains(' ') => &t[..i],
+ _ => t,
+ };
+ let t = if t.eq_ignore_ascii_case("waiting for you") {
+ "Waiting"
+ } else {
+ t
+ };
+ let mut c = t.chars();
+ c.next()
+ .map(|f| f.to_uppercase().collect::<String>() + c.as_str())
+ .unwrap_or_default()
+}
+
+const WORKING: &[&str] = &["working", "claimed"];
+
+pub fn view(input: &AgentListInput) -> AgentListView {
+ struct Acc {
+ row: AgentListRow,
+ statuses: Vec<(String, String, Option<String>)>,
+ needs: Vec<(u64, String)>,
+ }
+ let mut order: Vec<String> = vec![];
+ let mut by: std::collections::HashMap<String, Acc> = Default::default();
+ for sp in &input.spaces {
+ for m in sp.members.iter().filter(|m| !m.pending) {
+ let key = member_key(&sp.space_id, m);
+ let acc = by.entry(key.clone()).or_insert_with(|| {
+ order.push(key.clone());
+ Acc {
+ row: AgentListRow {
+ key: key.clone(),
+ kind: "agent".into(),
+ label: if m.display_name.is_empty() {
+ m.handle.clone()
+ } else {
+ m.display_name.clone()
+ },
+ harness: m.harness.clone(),
+ tone: "idle".into(),
+ line: String::new(),
+ job: None,
+ last_ms: 0,
+ unread: 0,
+ places: vec![],
+ action: None,
+ app: None,
+ attempt: None,
+ },
+ statuses: vec![],
+ needs: vec![],
+ }
+ });
+ acc.row.places.push(ListPlace {
+ space_id: sp.space_id.clone(),
+ space_name: sp.space_name.clone(),
+ handle: m.handle.clone(),
+ });
+ acc.row.unread += m.unread;
+ acc.row.last_ms = acc.row.last_ms.max(m.last_ms);
+ acc.needs
+ .extend(m.needs_ms.iter().map(|&t| (t, sp.space_name.clone())));
+ acc.statuses
+ .push((m.status.clone(), sp.space_name.clone(), m.activity.clone()));
+ }
+ }
+ let mut rows: Vec<AgentListRow> = order
+ .into_iter()
+ .filter_map(|k| by.remove(&k))
+ .map(|mut a| {
+ let newest = a.needs.iter().max_by_key(|(t, _)| *t).cloned();
+ if let Some((t, _)) = &newest {
+ a.row.last_ms = a.row.last_ms.max(*t);
+ }
+ let r = &mut a.row;
+ let working = a
+ .statuses
+ .iter()
+ .find(|(s, ..)| WORKING.contains(&s.as_str()));
+ let failed = a.statuses.iter().find(|(s, ..)| s == "failed");
+ let stopped = a.statuses.iter().find(|(s, ..)| s == "stopped");
+ let in_spaces = |n: usize| {
+ if n > 1 {
+ format!("{n} Spaces")
+ } else {
+ String::new()
+ }
+ };
+ if let Some((_, space)) = newest {
+ r.tone = "you".into();
+ // The newest ask says where.
+ r.line = format!("Waiting for you in {space}");
+ } else if let Some((_, space, activity)) = working {
+ r.tone = "working".into();
+ let what = activity.as_deref().map(sentence).filter(|s| !s.is_empty());
+ r.job = activity.clone().filter(|s| !s.is_empty());
+ r.line = format!("{} in {space}", what.unwrap_or_else(|| "Working".into()));
+ } else if let Some((_, space, _)) = failed {
+ r.tone = "failed".into();
+ r.line = format!("Failed in {space}");
+ } else if let Some((_, space, _)) = stopped {
+ r.tone = "stopped".into();
+ r.line = format!("Stopped in {space}");
+ } else if a
+ .statuses
+ .iter()
+ .all(|(s, ..)| s == "asleep" || s == "paused")
+ {
+ r.tone = "asleep".into();
+ r.line = if r.places.len() > 1 {
+ format!("Asleep in {}", in_spaces(r.places.len()))
+ } else {
+ format!("Asleep in {}", r.places[0].space_name)
+ };
+ } else {
+ r.tone = "idle".into();
+ r.line = if r.places.len() > 1 {
+ format!("In {}", in_spaces(r.places.len()))
+ } else {
+ format!("In {}", r.places[0].space_name)
+ };
+ }
+ a.row
+ })
+ .collect();
+ rows.extend(input.attempts.iter().map(|t| {
+ let (tone, line, action) = match t.state.as_str() {
+ "creating" => (
+ "creating",
+ format!("Waiting for {} to be ready", t.space_name),
+ None,
+ ),
+ "not-connected" => (
+ "not-connected",
+ t.note
+ .clone()
+ .unwrap_or_else(|| format!("{} isn't connected yet", t.label)),
+ t.connect_label.clone().map(|label| ListAction {
+ id: "connect".into(),
+ label,
+ }),
+ ),
+ "stopped" => ("stopped", format!("Stopped in {}", t.space_name), None),
+ _ => (
+ "failed",
+ if t.space_name.is_empty() {
+ "Didn't start".to_string()
+ } else {
+ format!("Didn't start in {}", t.space_name)
+ },
+ Some(ListAction {
+ id: "retry".into(),
+ label: "Try again".into(),
+ }),
+ ),
+ };
+ AgentListRow {
+ key: format!("attempt:{}", t.id),
+ kind: "attempt".into(),
+ label: t.label.clone(),
+ harness: t.harness.clone(),
+ tone: tone.into(),
+ line,
+ job: Some(t.job.clone()).filter(|j| !j.is_empty()),
+ last_ms: t.at_ms,
+ unread: 0,
+ places: if t.space_id.is_empty() {
+ vec![]
+ } else {
+ vec![ListPlace {
+ space_id: t.space_id.clone(),
+ space_name: t.space_name.clone(),
+ handle: String::new(),
+ }]
+ },
+ action,
+ app: t.app.clone(),
+ attempt: Some(t.id.clone()),
+ }
+ }));
+ let rank = |r: &AgentListRow| match r.tone.as_str() {
+ // A run of yours that can't start needs you most: it is waiting on your Connect.
+ "not-connected" => 0,
+ "you" => 1,
+ "working" => 2,
+ "creating" => 3,
+ _ => 4,
+ };
+ rows.sort_by(|a, b| {
+ rank(a)
+ .cmp(&rank(b))
+ .then(b.last_ms.cmp(&a.last_ms))
+ .then(a.label.cmp(&b.label))
+ });
+ let working = rows.iter().filter(|r| r.tone == "working").count();
+ let live = rows
+ .iter()
+ .filter(|r| matches!(r.tone.as_str(), "you" | "working" | "creating"))
+ .count();
+ AgentListView {
+ summary: (working > 0).then(|| format!("{working} working")),
+ live,
+ title: "Your agents".into(),
+ see_all_label: format!("See all {}", rows.len()),
+ rows,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn member(handle: &str, status: &str) -> ListMember {
+ ListMember {
+ handle: handle.into(),
+ harness: "hermes".into(),
+ display_name: "Hermes".into(),
+ owner_id: "acct_ada".into(),
+ status: status.into(),
+ ..Default::default()
+ }
+ }
+
+ fn attempt(id: &str, state: &str) -> ListAttempt {
+ ListAttempt {
+ id: id.into(),
+ space_id: format!("pending:{id}"),
+ space_name: "space-1".into(),
+ harness: "claude-code".into(),
+ label: "Claude Code".into(),
+ job: "fix the build".into(),
+ at_ms: 10,
+ state: state.into(),
+ note: (state == "not-connected").then(|| "Claude Code isn't connected yet".into()),
+ connect_label: (state == "not-connected").then(|| "Connect Claude Code".into()),
+ app: Some("claude-code".into()),
+ }
+ }
+
+ #[test]
+ fn a_cant_wake_run_and_a_creating_run_are_in_the_one_list() {
+ let v = view(&AgentListInput {
+ spaces: vec![ListSpace {
+ space_id: "relay:a/b".into(),
+ space_name: "ubuntu-build".into(),
+ members: vec![ListMember {
+ activity: Some("bumping the retry timeout".into()),
+ last_ms: 5,
+ ..member("hermes", "working")
+ }],
+ }],
+ attempts: vec![attempt("a", "not-connected"), attempt("b", "creating")],
+ });
+ let tones: Vec<_> = v.rows.iter().map(|r| r.tone.as_str()).collect();
+ assert_eq!(tones, ["not-connected", "working", "creating"]);
+ let nc = &v.rows[0];
+ assert_eq!(nc.kind, "attempt");
+ assert_eq!(nc.line, "Claude Code isn't connected yet");
+ assert_eq!(nc.action.as_ref().unwrap().label, "Connect Claude Code");
+ assert_eq!(nc.job.as_deref(), Some("fix the build"));
+ assert_eq!(nc.places[0].space_id, "pending:a");
+ assert_eq!(v.rows[1].line, "Bumping the retry timeout in ubuntu-build");
+ assert_eq!(v.rows[2].line, "Waiting for space-1 to be ready");
+ assert_eq!(v.summary.as_deref(), Some("1 working"));
+ assert_eq!(v.live, 2);
+ assert_eq!(v.see_all_label, "See all 3");
+ }
+
+ #[test]
+ fn failed_and_stopped_runs_keep_their_space_and_retry() {
+ let v = view(&AgentListInput {
+ spaces: vec![ListSpace {
+ space_id: "s".into(),
+ space_name: "web".into(),
+ members: vec![
+ member("hermes", "failed"),
+ ListMember {
+ owner_id: "x".into(),
+ ..member("codex", "stopped")
+ },
+ ],
+ }],
+ attempts: vec![attempt("c", "failed")],
+ });
+ let lines: Vec<_> = v.rows.iter().map(|r| r.line.as_str()).collect();
+ assert!(lines.contains(&"Failed in web"));
+ assert!(lines.contains(&"Stopped in web"));
+ assert!(lines.contains(&"Didn't start in space-1"));
+ let retry = v.rows.iter().find(|r| r.kind == "attempt").unwrap();
+ assert_eq!(retry.action.as_ref().unwrap().id, "retry");
+ }
+
+ #[test]
+ fn one_agent_in_two_spaces_is_one_row_and_waiting_for_you_comes_first() {
+ let v = view(&AgentListInput {
+ spaces: vec![
+ ListSpace {
+ space_id: "s1".into(),
+ space_name: "one".into(),
+ members: vec![member("hermes", "asleep")],
+ },
+ ListSpace {
+ space_id: "s2".into(),
+ space_name: "two".into(),
+ members: vec![
+ member("hermes", "asleep"),
+ ListMember {
+ owner_id: "acct_grace".into(),
+ display_name: "Claude Code".into(),
+ needs_ms: vec![99],
+ ..member("claude", "idle")
+ },
+ ],
+ },
+ ],
+ attempts: vec![],
+ });
+ assert_eq!(v.rows.len(), 2);
+ assert_eq!(v.rows[0].tone, "you");
+ assert_eq!(v.rows[0].line, "Waiting for you in two");
+ assert_eq!(v.rows[1].line, "Asleep in 2 Spaces");
+ assert_eq!(v.rows[1].places.len(), 2);
+ // Without an owner, the row is per Space.
+ assert_eq!(
+ member_key(
+ "s1",
+ &ListMember {
+ owner_id: String::new(),
+ ..member("x", "idle")
+ }
+ ),
+ "s1/x"
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
new file mode 100644
index 0000000000..8f4a29c044
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
@@ -0,0 +1,1240 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Settings, Connectors: the coding apps Cua works with and the providers
+//! they sign in to, with one Connect for each.
+//!
+//! - **Coding apps.** One row per app on this computer, with Connect (or
+//! Connected) and a chevron to the app's own page. Connect does
+//! everything once: Cua's skills and MCP server in the app, then the
+//! app's model sign-in, so the matching provider is connected too
+//! ([`connect_plan`]).
+//! - **An app's page** ([`app_detail`]): the separate switches (skills, MCP,
+//! setting the app up again automatically), which provider it signs in
+//! with and how, Sign in and Sign out, and taking Cua out of the app.
+//! - **Providers.** Anthropic, OpenAI and GitHub, each with Connect: the
+//! provider's own sign-in where one exists for this use, else a key
+//! ([`provider_sheet`]). Other keys follow by variable name.
+//! - **The setup card** ([`setup_card`]): what a task that couldn't start
+//! because its app isn't connected says, with "Connect <app>".
+//!
+//! Only official sign-in paths are offered: an app's own token command
+//! (`claude setup-token`, which prints a token meant for this use), a key
+//! the person pastes, or a key already exported in their shell. Cua never
+//! reads another app's private sign-in store for these.
+//!
+//! Every credential lives where the agent keys do (`agent_keys`: the
+//! daemon's Keychain-backed store); this module only decides the words.
+
+use serde::{Deserialize, Serialize};
+
+use crate::agent_keys::{AgentKeyInput, AgentKeyRow, AgentKeysInput};
+use crate::model::SpaceOs;
+
+/// How a provider can be connected.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Way {
+ /// An app's own token command, run on This Mac with one browser
+ /// approval; the token is saved under `env` and only that app uses it.
+ AppToken {
+ app: &'static str,
+ env: &'static str,
+ label: &'static str,
+ help: &'static str,
+ },
+ /// An app's own device-code sign-in, run on This Mac in a folder Cua
+ /// owns (Codex: `codex login --device-auth`); the person enters a code
+ /// on the provider's page. Saved under `env`; only that app uses it.
+ AppDevice {
+ app: &'static str,
+ env: &'static str,
+ label: &'static str,
+ help: &'static str,
+ },
+ /// A key the person pastes.
+ Key,
+ /// The key already exported in the person's shell, saved once.
+ Shell,
+}
+
+/// A provider row.
+struct Provider {
+ id: &'static str,
+ label: &'static str,
+ /// The variable a pasted key is saved as.
+ env: &'static str,
+ /// Other variables that also mean this provider is connected (a
+ /// sign-in token, a key saved under another name).
+ also: &'static [&'static str],
+ used_by: &'static str,
+ key_help: &'static str,
+ placeholder: &'static str,
+ ways: &'static [Way],
+}
+
+const CLAUDE_TOKEN: Way = Way::AppToken {
+ app: "claude-code",
+ env: "CLAUDE_CODE_OAUTH_TOKEN",
+ label: "Sign in with Claude",
+ help: "Opens your browser to approve. Uses your Claude plan. Only Claude Code uses this sign-in.",
+};
+
+const CODEX_DEVICE: Way = Way::AppDevice {
+ app: "codex",
+ env: "CODEX_AUTH_JSON",
+ label: "Sign in with ChatGPT",
+ help: "Shows a code to enter on openai.com. Uses your ChatGPT plan. Only Codex uses this sign-in.",
+};
+
+const PROVIDERS: &[Provider] = &[
+ Provider {
+ id: "anthropic",
+ label: "Anthropic",
+ env: "ANTHROPIC_API_KEY",
+ also: &["CLAUDE_CODE_OAUTH_TOKEN"],
+ used_by: "Claude Code, Hermes and other apps that use Claude.",
+ key_help: "Create a key at console.anthropic.com. Every app that uses Claude can use it.",
+ placeholder: "sk-ant-…",
+ ways: &[CLAUDE_TOKEN, Way::Key, Way::Shell],
+ },
+ Provider {
+ id: "openai",
+ label: "OpenAI",
+ env: "OPENAI_API_KEY",
+ also: &["CODEX_AUTH_JSON"],
+ used_by: "Codex, Hermes and other apps that use OpenAI models.",
+ key_help: "Create a key at platform.openai.com. Every app that uses OpenAI can use it.",
+ placeholder: "sk-…",
+ ways: &[CODEX_DEVICE, Way::Key, Way::Shell],
+ },
+ Provider {
+ id: "github",
+ label: "GitHub",
+ env: "COPILOT_GITHUB_TOKEN",
+ also: &[],
+ used_by: "GitHub Copilot CLI.",
+ key_help: "Create a fine-grained token with the Copilot Requests permission at github.com/settings/tokens.",
+ placeholder: "github_pat_…",
+ ways: &[Way::Key, Way::Shell],
+ },
+];
+
+/// Which providers an app signs in to, and the way its Connect uses.
+struct AppSignIn {
+ app: &'static str,
+ /// Any one of these connected is enough.
+ providers: &'static [&'static str],
+ /// The way Connect starts when none is connected (`None`: it asks with
+ /// the provider's sheet).
+ way: Option<Way>,
+}
+
+const APPS: &[AppSignIn] = &[
+ AppSignIn {
+ app: "claude-code",
+ providers: &["anthropic"],
+ way: Some(CLAUDE_TOKEN),
+ },
+ AppSignIn {
+ app: "codex",
+ providers: &["openai"],
+ way: Some(CODEX_DEVICE),
+ },
+ AppSignIn {
+ app: "copilot-cli",
+ providers: &["github"],
+ way: None,
+ },
+ AppSignIn {
+ app: "hermes",
+ providers: &["anthropic", "openai"],
+ way: None,
+ },
+ AppSignIn {
+ app: "t3code",
+ providers: &["anthropic", "openai"],
+ way: None,
+ },
+];
+
+fn provider(id: &str) -> Option<&'static Provider> {
+ PROVIDERS.iter().find(|p| p.id == id)
+}
+
+fn app_sign_in(app: &str) -> Option<&'static AppSignIn> {
+ APPS.iter().find(|a| a.app == app)
+}
+
+/// Every variable the providers own (they are not listed under Other keys).
+fn provider_env(env: &str) -> bool {
+ PROVIDERS
+ .iter()
+ .any(|p| p.env == env || p.also.contains(&env))
+}
+
+/// One coding app on this computer (`agents.setup`, plus what the page knows).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ConnectorAppInput {
+ /// Setup id (`claude-code`, `codex`, ...).
+ pub agent: String,
+ pub name: String,
+ pub installed: bool,
+ /// Cua's skills and MCP server are both in place.
+ pub configured: bool,
+ /// Cua's skills are in the app.
+ pub skills: bool,
+ /// Cua's MCP server is in the app's settings (`None`: the app has no MCP settings Cua writes).
+ pub mcp: Option<bool>,
+ /// The app's settings file, for its page.
+ pub mcp_config: Option<String>,
+}
+
+/// Something running for a row: `app:<id>` or `provider:<id>`.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ConnectorBusy {
+ pub id: String,
+ /// `connecting` (tools), `signing-in` (a browser approval), `signing-out`.
+ pub step: String,
+}
+
+/// Why the last change to a row failed.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ConnectorFailure {
+ pub id: String,
+ pub line: String,
+}
+
+/// What the Connectors page reads.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ConnectorsInput {
+ pub apps: Vec<ConnectorAppInput>,
+ /// The saved keys and sign-ins (`agentKeys.list`).
+ pub keys: AgentKeysInput,
+ /// Provider variables exported in the person's shell (names only).
+ pub shell_keys: Vec<String>,
+ /// "Set up new apps automatically".
+ pub auto: bool,
+ /// Apps the person turned off: never set up again on their own.
+ pub off: Vec<String>,
+ pub busy: Vec<ConnectorBusy>,
+ pub failures: Vec<ConnectorFailure>,
+}
+
+impl ConnectorsInput {
+ fn key(&self, env: &str) -> Option<&AgentKeyInput> {
+ self.keys.keys.iter().find(|k| k.env == env)
+ }
+ fn busy(&self, id: &str) -> Option<&str> {
+ self.busy
+ .iter()
+ .find(|b| b.id == id)
+ .map(|b| b.step.as_str())
+ }
+ fn failure(&self, id: &str) -> Option<&str> {
+ self.failures
+ .iter()
+ .find(|f| f.id == id)
+ .map(|f| f.line.as_str())
+ }
+ fn app(&self, id: &str) -> Option<&ConnectorAppInput> {
+ self.apps.iter().find(|a| a.agent == id)
+ }
+}
+
+/// The saved credential that connects a provider, first match wins: the
+/// pasted key, then a sign-in token.
+fn provider_credential<'a>(input: &'a ConnectorsInput, p: &Provider) -> Option<&'a AgentKeyInput> {
+ input
+ .key(p.env)
+ .or_else(|| p.also.iter().find_map(|e| input.key(e)))
+}
+
+fn provider_connected(input: &ConnectorsInput, id: &str) -> bool {
+ provider(id).is_some_and(|p| provider_credential(input, p).is_some())
+}
+
+/// The app's sign-in is in place: one of its providers is connected, or it
+/// signs in on its own.
+fn app_signed_in(input: &ConnectorsInput, app: &str) -> bool {
+ match app_sign_in(app) {
+ Some(a) => a.providers.iter().any(|p| provider_connected(input, p)),
+ None => true,
+ }
+}
+
+fn dots(k: &AgentKeyInput) -> String {
+ if k.last4.is_empty() {
+ "Saved".into()
+ } else {
+ format!("\u{2022}\u{2022}\u{2022}\u{2022} {}", k.last4)
+ }
+}
+
+/// How a saved credential reads on its provider's row.
+fn credential_text(p: &Provider, k: &AgentKeyInput) -> String {
+ match k.env.as_str() {
+ "CLAUDE_CODE_OAUTH_TOKEN" => "Claude sign-in, for Claude Code".into(),
+ "CODEX_AUTH_JSON" => "ChatGPT sign-in, for Codex".into(),
+ e if e == p.env => format!("API key {}", dots(k)),
+ e => format!("{e} {}", dots(k)),
+ }
+}
+
+/// A button on a row.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectorButton {
+ /// `connect`, `sign-out`, `try-again`.
+ pub id: String,
+ pub label: String,
+ pub enabled: bool,
+}
+
+fn button(id: &str, label: impl Into<String>, enabled: bool) -> ConnectorButton {
+ ConnectorButton {
+ id: id.into(),
+ label: label.into(),
+ enabled,
+ }
+}
+
+/// One coding app's row.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectorAppRow {
+ pub agent: String,
+ pub name: String,
+ /// `connected`, `not-connected`, `connecting`, `failed`.
+ pub state: String,
+ /// The row's second line: what is missing, what is happening, or why it failed.
+ pub line: Option<String>,
+ /// Connect, or Try again (absent when connected: the row says so instead).
+ pub button: Option<ConnectorButton>,
+ /// "Connected", beside the chevron once done.
+ pub connected_label: Option<String>,
+ /// The page the row opens ("Claude Code settings", for the chevron's label).
+ pub open_label: String,
+}
+
+/// A provider's row.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectorProviderRow {
+ pub id: String,
+ pub label: String,
+ /// `connected`, `not-connected`, `connecting`, `failed`.
+ pub state: String,
+ /// "Not connected", "API key •••• 3f9a", "Claude sign-in, for Claude Code",
+ /// "Approve in your browser…".
+ pub status: String,
+ /// Who uses it.
+ pub detail: String,
+ /// Connect, or Sign out.
+ pub button: ConnectorButton,
+ /// When it was connected (the page writes "Added <date>").
+ pub added_ms: Option<u64>,
+ /// The saved variables Sign out removes.
+ pub sign_out_envs: Vec<String>,
+}
+
+/// The page.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectorsView {
+ pub apps_title: String,
+ pub apps: Vec<ConnectorAppRow>,
+ /// "We didn't find a coding app yet…", when there is none.
+ pub apps_empty: Option<String>,
+ pub auto_label: String,
+ pub auto_help: String,
+ pub auto: bool,
+ pub providers_title: String,
+ /// Under Providers: where credentials stay.
+ pub providers_footer: String,
+ pub providers: Vec<ConnectorProviderRow>,
+ /// Keys under any other variable (`agent_keys`' rows).
+ pub others: Vec<AgentKeyRow>,
+ pub add_other_label: String,
+ pub other_help: String,
+ /// Why credentials can't be read or saved here.
+ pub notice: Option<String>,
+ pub can_edit: bool,
+ pub added_label: String,
+}
+
+/// Where credentials stay, in the words of the system the app runs on.
+fn vault(os: SpaceOs) -> Option<&'static str> {
+ match os {
+ SpaceOs::Macos => Some("the Keychain"),
+ SpaceOs::Windows => Some("Windows Credential Manager"),
+ SpaceOs::Linux | SpaceOs::Unknown => None,
+ }
+}
+
+fn notice(input: &ConnectorsInput) -> Option<String> {
+ input
+ .keys
+ .error
+ .as_ref()
+ .map(|e| format!("Couldn't read your sign-ins: {e}"))
+ .or_else(|| {
+ input
+ .keys
+ .unavailable
+ .as_ref()
+ .map(|why| format!("Sign-ins can't be saved here: {why}."))
+ })
+}
+
+fn app_row(input: &ConnectorsInput, a: &ConnectorAppInput) -> ConnectorAppRow {
+ let id = format!("app:{}", a.agent);
+ let busy = input.busy(&id);
+ let failure = input.failure(&id);
+ let signed_in = app_signed_in(input, &a.agent);
+ let done = a.configured && signed_in;
+ let needs = app_sign_in(&a.agent).filter(|_| !signed_in).map(|s| {
+ s.providers
+ .iter()
+ .filter_map(|p| provider(p))
+ .map(|p| p.label)
+ .collect::<Vec<_>>()
+ .join(" or ")
+ });
+ let (state, line, btn) = if let Some(step) = busy {
+ let line = match step {
+ "signing-in"
+ if app_sign_in(&a.agent)
+ .is_some_and(|s| matches!(s.way, Some(Way::AppDevice { .. }))) =>
+ {
+ "Enter the code in your browser…".to_string()
+ }
+ "signing-in" => "Approve in your browser…".to_string(),
+ "signing-out" => "Signing out…".to_string(),
+ _ => format!("Adding Cua to {}…", a.name),
+ };
+ (
+ "connecting",
+ Some(line),
+ Some(button("connect", "Connect", false)),
+ )
+ } else if let Some(why) = failure {
+ (
+ "failed",
+ Some(why.to_string()),
+ Some(button("try-again", "Try again", true)),
+ )
+ } else if done {
+ ("connected", None, None)
+ } else if a.configured {
+ (
+ "not-connected",
+ needs.map(|n| format!("Needs a sign-in to {n}.")),
+ Some(button("connect", "Connect", true)),
+ )
+ } else {
+ (
+ "not-connected",
+ None,
+ Some(button("connect", "Connect", true)),
+ )
+ };
+ ConnectorAppRow {
+ agent: a.agent.clone(),
+ name: a.name.clone(),
+ state: state.into(),
+ line,
+ button: btn,
+ connected_label: done.then(|| "Connected".into()).filter(|_| busy.is_none()),
+ open_label: format!("{} settings", a.name),
+ }
+}
+
+fn provider_row(input: &ConnectorsInput, p: &Provider, can_edit: bool) -> ConnectorProviderRow {
+ let id = format!("provider:{}", p.id);
+ let busy = input.busy(&id);
+ let cred = provider_credential(input, p);
+ let (state, status, btn) = if let Some(step) = busy {
+ let status = match step {
+ "signing-out" => "Signing out…",
+ "signing-in" if p.ways.iter().any(|w| matches!(w, Way::AppDevice { .. })) => {
+ "Enter the code in your browser…"
+ }
+ "signing-in" => "Approve in your browser…",
+ _ => "Connecting…",
+ };
+ (
+ "connecting",
+ status.to_string(),
+ button("connect", "Connect", false),
+ )
+ } else if let Some(why) = input.failure(&id) {
+ (
+ "failed",
+ why.to_string(),
+ button("connect", "Try again", can_edit),
+ )
+ } else if let Some(k) = cred {
+ (
+ "connected",
+ credential_text(p, k),
+ button("sign-out", "Sign out", can_edit),
+ )
+ } else {
+ (
+ "not-connected",
+ "Not connected".into(),
+ button("connect", "Connect", can_edit),
+ )
+ };
+ ConnectorProviderRow {
+ id: p.id.into(),
+ label: p.label.into(),
+ state: state.into(),
+ status,
+ detail: format!("For {}", p.used_by),
+ button: btn,
+ added_ms: cred.filter(|_| busy.is_none()).map(|k| k.added_ms),
+ sign_out_envs: std::iter::once(p.env)
+ .chain(p.also.iter().copied())
+ .filter(|e| input.key(e).is_some())
+ .map(Into::into)
+ .collect(),
+ }
+}
+
+/// The page on a Mac.
+pub fn view(input: &ConnectorsInput) -> ConnectorsView {
+ view_on(input, SpaceOs::Macos)
+}
+
+/// [`view`] in a shell on `os`.
+pub fn view_on(input: &ConnectorsInput, os: SpaceOs) -> ConnectorsView {
+ let notice = notice(input);
+ let can_edit = notice.is_none();
+ let apps: Vec<ConnectorAppRow> = input
+ .apps
+ .iter()
+ .filter(|a| a.installed)
+ .map(|a| app_row(input, a))
+ .collect();
+ let mut others: Vec<&AgentKeyInput> = input
+ .keys
+ .keys
+ .iter()
+ .filter(|k| !provider_env(&k.env))
+ .collect();
+ others.sort_by(|a, b| a.env.cmp(&b.env));
+ let this = os.this_machine_lower();
+ let place = vault(os).map(|v| format!(" in {v}")).unwrap_or_default();
+ ConnectorsView {
+ apps_title: "Coding apps".into(),
+ apps_empty: apps
+ .is_empty()
+ .then(|| "We didn't find a coding app yet. Install one and Cua will notice.".into()),
+ apps,
+ auto_label: "Set up new apps automatically".into(),
+ auto_help: "When you install another coding app, Cua adds itself and tells you.".into(),
+ auto: input.auto,
+ providers_title: "Providers".into(),
+ providers_footer: format!(
+ "Sign-ins and keys stay on {this}{place}. Each one is only given to the apps that use it."
+ ),
+ providers: PROVIDERS
+ .iter()
+ .map(|p| provider_row(input, p, can_edit))
+ .collect(),
+ others: others
+ .into_iter()
+ .map(|k| AgentKeyRow {
+ env: k.env.clone(),
+ provider: "other".into(),
+ title: k.env.clone(),
+ detail: format!("For apps that read {}.", k.env),
+ set: true,
+ status: dots(k),
+ added_ms: Some(k.added_ms),
+ action_label: "Replace".into(),
+ remove_label: Some("Remove".into()),
+ })
+ .collect(),
+ add_other_label: "Add another key".into(),
+ other_help: "For another provider, save its key under the variable its app reads, like \
+ GEMINI_API_KEY."
+ .into(),
+ can_edit,
+ notice,
+ added_label: "Added".into(),
+ }
+}
+
+/// What one Connect on an app does, in order.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectPlan {
+ /// Add Cua's skills and MCP server (`agents.connect`).
+ pub tools: bool,
+ /// Run the app's own token command (`agents.connect` with `signIn`): one
+ /// browser approval.
+ pub app_token: bool,
+ /// Run the app's own device-code sign-in (`agents.signInStart`, then
+ /// `agents.signInWait`): a code to show, entered on the provider's page.
+ pub device: bool,
+ /// Then open this provider's Connect sheet (the app has no token
+ /// command of its own).
+ pub provider: Option<String>,
+ /// The provider the token command signs in to (its row shows the approval too).
+ pub token_provider: Option<String>,
+}
+
+/// What Connect on `agent` does now.
+pub fn connect_plan(input: &ConnectorsInput, agent: &str) -> ConnectPlan {
+ let app = input.app(agent).filter(|a| a.installed);
+ let configured = app.is_some_and(|a| a.configured);
+ let signed_in = app_signed_in(input, agent);
+ let s = app_sign_in(agent);
+ // The app's own token command runs on This Mac: only where the app is.
+ let app_token = !signed_in
+ && app.is_some()
+ && s.is_some_and(|s| matches!(s.way, Some(Way::AppToken { .. })));
+ let device = !signed_in
+ && app.is_some()
+ && s.is_some_and(|s| matches!(s.way, Some(Way::AppDevice { .. })));
+ let provider = if signed_in || app_token || device {
+ None
+ } else {
+ s.and_then(|s| s.providers.first())
+ .map(|p| (*p).to_string())
+ };
+ ConnectPlan {
+ // Cua's tools go into the app where it is on this computer.
+ tools: app.is_some() && !configured,
+ app_token,
+ device,
+ provider,
+ token_provider: if app_token || device {
+ s.and_then(|s| s.providers.first())
+ .map(|p| (*p).to_string())
+ } else {
+ None
+ },
+ }
+}
+
+/// The provider ids `agent` signs in to (any one is enough; empty: it signs in on its own).
+pub fn app_providers(agent: &str) -> Vec<String> {
+ app_sign_in(agent)
+ .map(|s| s.providers.iter().map(|p| (*p).to_string()).collect())
+ .unwrap_or_default()
+}
+
+/// Whether `agent` has a sign-in it can use in a Space now.
+pub fn signed_in(input: &ConnectorsInput, agent: &str) -> bool {
+ app_signed_in(input, agent)
+}
+
+/// A provider's name ("Anthropic").
+pub fn provider_label(id: &str) -> Option<&'static str> {
+ provider(id).map(|p| p.label)
+}
+
+/// One way to connect a provider, as its sheet shows it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ProviderWay {
+ /// `app-token`, `key`, `shell`.
+ pub id: String,
+ pub label: String,
+ pub help: String,
+ pub button: String,
+ /// For `app-token`: the app whose command runs (`agents.connect` with `signIn`).
+ pub app: Option<String>,
+ /// For `shell`: the variable read from the shell.
+ pub env: Option<String>,
+}
+
+/// A provider's Connect sheet.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ProviderSheetView {
+ pub provider: String,
+ pub title: String,
+ pub lede: String,
+ pub ways: Vec<ProviderWay>,
+ pub cancel_label: String,
+ /// The key field, when the person picks Paste a key.
+ pub key_label: String,
+ pub key_placeholder: String,
+ pub key_help: String,
+ pub save_label: String,
+ /// What `agentKeys.set` gets with a pasted key: `anthropic`, `openai`, or `other` with `key_env`.
+ pub key_provider: String,
+ pub key_env: Option<String>,
+}
+
+/// The sheet for `provider` (None: an unknown provider).
+pub fn provider_sheet(input: &ConnectorsInput, provider_id: &str) -> Option<ProviderSheetView> {
+ provider_sheet_on(input, provider_id, SpaceOs::Macos)
+}
+
+/// [`provider_sheet`] in a shell on `os`.
+pub fn provider_sheet_on(
+ input: &ConnectorsInput,
+ provider_id: &str,
+ os: SpaceOs,
+) -> Option<ProviderSheetView> {
+ let p = provider(provider_id)?;
+ let installed = |app: &str| input.app(app).is_some_and(|a| a.installed);
+ let ways = p
+ .ways
+ .iter()
+ .filter_map(|w| match *w {
+ Way::AppToken {
+ app, label, help, ..
+ } => installed(app).then(|| ProviderWay {
+ id: "app-token".into(),
+ label: label.into(),
+ help: help.into(),
+ button: "Sign in".into(),
+ app: Some(app.into()),
+ env: None,
+ }),
+ Way::AppDevice {
+ app, label, help, ..
+ } => installed(app).then(|| ProviderWay {
+ id: "app-device".into(),
+ label: label.into(),
+ help: help.into(),
+ button: "Sign in".into(),
+ app: Some(app.into()),
+ env: None,
+ }),
+ Way::Key => Some(ProviderWay {
+ id: "key".into(),
+ label: "Paste an API key".into(),
+ help: p.key_help.into(),
+ button: "Paste key".into(),
+ app: None,
+ env: None,
+ }),
+ Way::Shell => input
+ .shell_keys
+ .iter()
+ .any(|k| k == p.env)
+ .then(|| ProviderWay {
+ id: "shell".into(),
+ label: format!("Use {} from your shell", p.env),
+ help: "Cua saves a copy now. It doesn't follow later changes in your shell."
+ .into(),
+ button: "Use it".into(),
+ app: None,
+ env: Some(p.env.into()),
+ }),
+ })
+ .collect();
+ let this = os.this_machine_lower();
+ let place = vault(os).map(|v| format!("in {v} ")).unwrap_or_default();
+ Some(ProviderSheetView {
+ provider: p.id.into(),
+ title: format!("Connect {}", p.label),
+ lede: format!("For {}", p.used_by),
+ ways,
+ cancel_label: "Cancel".into(),
+ key_label: "API key".into(),
+ key_placeholder: p.placeholder.into(),
+ key_help: format!("It's saved {place}on {this} and won't be shown again."),
+ save_label: "Save".into(),
+ key_provider: if matches!(p.id, "anthropic" | "openai") {
+ p.id
+ } else {
+ "other"
+ }
+ .into(),
+ key_env: (!matches!(p.id, "anthropic" | "openai")).then(|| p.env.into()),
+ })
+}
+
+/// A switch on an app's page.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectorToggle {
+ /// `skills`, `mcp`, `auto`.
+ pub id: String,
+ pub label: String,
+ pub help: String,
+ pub on: bool,
+ pub enabled: bool,
+}
+
+/// The sign-in part of an app's page.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectorSignIn {
+ /// "Signs in with Anthropic".
+ pub title: String,
+ /// The provider row's status for it ("Claude sign-in, for Claude Code", "Not connected").
+ pub status: String,
+ pub connected: bool,
+ /// How Connect signs it in ("Claude sign-in, through claude setup-token").
+ pub way: String,
+ /// The provider it uses (for Sign in and Sign out).
+ pub provider: String,
+ pub button: ConnectorButton,
+}
+
+/// One app's page.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AppDetailView {
+ pub agent: String,
+ pub name: String,
+ pub back_label: String,
+ /// Under the title: "Connected", "Not connected", or what is missing.
+ pub status: String,
+ pub connected: bool,
+ /// Connect, while not connected.
+ pub connect: Option<ConnectorButton>,
+ pub tools_title: String,
+ pub toggles: Vec<ConnectorToggle>,
+ pub sign_in_title: String,
+ /// Absent for an app that signs in on its own.
+ pub sign_in: Option<ConnectorSignIn>,
+ /// Instead of `sign_in`: the app signs in on its own.
+ pub sign_in_note: Option<String>,
+ pub settings_file_label: String,
+ pub settings_file: Option<String>,
+ /// "Remove Cua from Claude Code", while Cua is in it.
+ pub remove_label: Option<String>,
+}
+
+fn way_text(app: &str) -> &'static str {
+ match app {
+ "claude-code" => {
+ "Connect runs claude setup-token: one browser approval, using your Claude plan. Or connect Anthropic with an API key."
+ }
+ "codex" => {
+ "Connect signs Codex in with ChatGPT: a code to enter on openai.com, using your ChatGPT plan. Or connect OpenAI with an API key."
+ }
+ "copilot-cli" => "Connect asks for a GitHub token with the Copilot Requests permission.",
+ _ => "It uses whichever of these providers you connect.",
+ }
+}
+
+/// `agent`'s page (None: not on this computer).
+pub fn app_detail(input: &ConnectorsInput, agent: &str) -> Option<AppDetailView> {
+ let a = input.app(agent)?;
+ let row = app_row(input, a);
+ let can_edit = notice(input).is_none();
+ let busy = input.busy(&format!("app:{agent}")).is_some();
+ let mut toggles = vec![ConnectorToggle {
+ id: "skills".into(),
+ label: "Cua skills".into(),
+ help: format!("Teaches {} how to use your Spaces.", a.name),
+ on: a.skills,
+ enabled: !busy,
+ }];
+ if let Some(on) = a.mcp {
+ toggles.push(ConnectorToggle {
+ id: "mcp".into(),
+ label: "Cua tools (MCP)".into(),
+ help: format!("Lets {} open, use and share your Spaces.", a.name),
+ on,
+ enabled: !busy,
+ });
+ }
+ toggles.push(ConnectorToggle {
+ id: "auto".into(),
+ label: "Keep it set up".into(),
+ help: format!("If {} changes its settings, Cua adds itself again.", a.name),
+ on: !input.off.contains(&a.agent),
+ enabled: !busy,
+ });
+ let sign_in = app_sign_in(agent).map(|s| {
+ // The provider it uses: the first connected one, else the first.
+ let pid = s
+ .providers
+ .iter()
+ .find(|p| provider_connected(input, p))
+ .or(s.providers.first())
+ .copied()
+ .unwrap_or_default();
+ let p = provider(pid);
+ let prow = p.map(|p| provider_row(input, p, can_edit));
+ let connected = prow.as_ref().is_some_and(|r| r.state == "connected");
+ let names: Vec<&str> = s
+ .providers
+ .iter()
+ .filter_map(|p| provider(p))
+ .map(|p| p.label)
+ .collect();
+ ConnectorSignIn {
+ title: format!("Signs in with {}", names.join(" or ")),
+ status: prow.as_ref().map(|r| r.status.clone()).unwrap_or_default(),
+ connected,
+ way: way_text(agent).into(),
+ provider: pid.into(),
+ button: if connected {
+ button("sign-out", "Sign out", can_edit && !busy)
+ } else {
+ button("sign-in", "Sign in", can_edit && !busy)
+ },
+ }
+ });
+ let sign_in_note = sign_in.is_none().then(|| {
+ format!(
+ "{} signs in on its own. Cua doesn't need a sign-in for it.",
+ a.name
+ )
+ });
+ Some(AppDetailView {
+ agent: a.agent.clone(),
+ name: a.name.clone(),
+ back_label: "Connectors".into(),
+ status: match row.state.as_str() {
+ "connected" => "Connected".into(),
+ _ => row.line.clone().unwrap_or_else(|| "Not connected".into()),
+ },
+ connected: row.state == "connected",
+ connect: row.button.filter(|_| row.state != "connected"),
+ tools_title: format!("Cua in {}", a.name),
+ toggles,
+ sign_in_title: "Sign-in".into(),
+ sign_in,
+ sign_in_note,
+ settings_file_label: "Settings file".into(),
+ settings_file: a.mcp_config.clone(),
+ remove_label: (a.skills || a.mcp == Some(true))
+ .then(|| format!("Remove Cua from {}", a.name)),
+ })
+}
+
+/// The card a task shows when its app isn't connected yet.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SetupCardView {
+ pub title: String,
+ pub body: String,
+ /// "Connect Claude Code".
+ pub connect_label: String,
+ /// While Connect runs.
+ pub connecting_label: String,
+ /// Once connected (the task starts again on its own).
+ pub connected_label: String,
+ pub retry_label: String,
+ pub change_label: String,
+ pub details_label: String,
+}
+
+/// The card for a task whose app `agent` (called `name`) can't sign in.
+pub fn setup_card(input: &ConnectorsInput, agent: &str, name: &str) -> SetupCardView {
+ let plan = connect_plan(input, agent);
+ let provider = app_sign_in(agent)
+ .and_then(|s| s.providers.first())
+ .and_then(|p| provider(p))
+ .map(|p| p.label);
+ let body = match provider {
+ Some(p) if plan.app_token => format!(
+ "{name} needs a sign-in to {p} to work here. Connect it once: approve in your browser, and every Space can use it."
+ ),
+ Some(p) => format!(
+ "{name} needs a sign-in to {p} to work here. Connect it once and every Space can use it."
+ ),
+ None => format!("Connect {name} once and every Space can use it."),
+ };
+ SetupCardView {
+ title: format!("Connect {name} to start"),
+ body,
+ connect_label: format!("Connect {name}"),
+ connecting_label: if plan.app_token {
+ "Approve in your browser…".into()
+ } else if plan.device {
+ "Enter the code in your browser…".into()
+ } else {
+ "Connecting…".into()
+ },
+ connected_label: format!("{name} is connected. Starting again…"),
+ retry_label: "Try again".into(),
+ change_label: "Change computer".into(),
+ details_label: "Details".into(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app(agent: &str, name: &str, configured: bool) -> ConnectorAppInput {
+ ConnectorAppInput {
+ agent: agent.into(),
+ name: name.into(),
+ installed: true,
+ configured,
+ skills: configured,
+ mcp: Some(configured),
+ mcp_config: Some(format!("~/.{agent}/settings.json")),
+ }
+ }
+
+ fn key(env: &str, last4: &str) -> AgentKeyInput {
+ AgentKeyInput {
+ provider: if env == "ANTHROPIC_API_KEY" {
+ "anthropic".into()
+ } else if env == "OPENAI_API_KEY" {
+ "openai".into()
+ } else {
+ "other".into()
+ },
+ env: env.into(),
+ last4: last4.into(),
+ added_ms: 1_000,
+ }
+ }
+
+ fn input() -> ConnectorsInput {
+ ConnectorsInput {
+ apps: vec![
+ app("claude-code", "Claude Code", false),
+ app("codex", "OpenAI Codex", true),
+ app("vscode", "VS Code (Copilot agent mode)", false),
+ ],
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn apps_start_with_connect_and_providers_not_connected() {
+ let v = view(&input());
+ assert_eq!(v.apps_title, "Coding apps");
+ assert_eq!(v.providers_title, "Providers");
+ let claude = &v.apps[0];
+ assert_eq!(claude.state, "not-connected");
+ assert_eq!(claude.button.as_ref().unwrap().label, "Connect");
+ assert_eq!(claude.connected_label, None);
+ assert_eq!(claude.open_label, "Claude Code settings");
+ // Codex has Cua but no OpenAI sign-in: still Connect, with what's missing.
+ let codex = &v.apps[1];
+ assert_eq!(codex.state, "not-connected");
+ assert_eq!(codex.line.as_deref(), Some("Needs a sign-in to OpenAI."));
+ let ids: Vec<_> = v.providers.iter().map(|p| p.id.as_str()).collect();
+ assert_eq!(ids, ["anthropic", "openai", "github"]);
+ assert!(
+ v.providers
+ .iter()
+ .all(|p| p.status == "Not connected" && p.button.label == "Connect")
+ );
+ }
+
+ #[test]
+ fn an_app_that_signs_in_on_its_own_is_connected_with_cua_in_it() {
+ let mut i = input();
+ i.apps[2].configured = true;
+ let v = view(&i);
+ assert_eq!(v.apps[2].state, "connected");
+ assert_eq!(v.apps[2].connected_label.as_deref(), Some("Connected"));
+ assert!(v.apps[2].button.is_none());
+ }
+
+ #[test]
+ fn connecting_claude_code_connects_anthropic_too() {
+ let mut i = input();
+ i.apps[0].configured = true;
+ i.keys.keys.push(key("CLAUDE_CODE_OAUTH_TOKEN", "AAAA"));
+ let v = view(&i);
+ assert_eq!(v.apps[0].state, "connected");
+ let a = &v.providers[0];
+ assert_eq!(a.state, "connected");
+ assert_eq!(a.status, "Claude sign-in, for Claude Code");
+ assert_eq!(a.button.label, "Sign out");
+ assert_eq!(a.sign_out_envs, ["CLAUDE_CODE_OAUTH_TOKEN"]);
+ // The sign-in token is the provider's, not an Other key.
+ assert!(v.others.is_empty());
+ }
+
+ #[test]
+ fn a_pasted_key_reads_with_its_last_four_and_others_follow() {
+ let mut i = input();
+ i.keys.keys.push(key("OPENAI_API_KEY", "3f9a"));
+ i.keys.keys.push(key("MISTRAL_API_KEY", "9999"));
+ let v = view(&i);
+ assert_eq!(
+ v.providers[1].status,
+ "API key \u{2022}\u{2022}\u{2022}\u{2022} 3f9a"
+ );
+ assert_eq!(v.apps[1].state, "connected");
+ assert_eq!(v.others.len(), 1);
+ assert_eq!(v.others[0].env, "MISTRAL_API_KEY");
+ }
+
+ #[test]
+ fn busy_and_failed_rows_say_so() {
+ let mut i = input();
+ i.busy.push(ConnectorBusy {
+ id: "app:claude-code".into(),
+ step: "signing-in".into(),
+ });
+ i.busy.push(ConnectorBusy {
+ id: "provider:anthropic".into(),
+ step: "signing-in".into(),
+ });
+ i.failures.push(ConnectorFailure {
+ id: "app:codex".into(),
+ line: "Couldn't add Cua to ~/.codex/config.toml.".into(),
+ });
+ let v = view(&i);
+ assert_eq!(v.apps[0].state, "connecting");
+ assert_eq!(v.apps[0].line.as_deref(), Some("Approve in your browser…"));
+ assert!(!v.apps[0].button.as_ref().unwrap().enabled);
+ assert_eq!(v.providers[0].state, "connecting");
+ assert_eq!(v.providers[0].status, "Approve in your browser…");
+ assert_eq!(v.apps[1].state, "failed");
+ assert_eq!(v.apps[1].button.as_ref().unwrap().label, "Try again");
+ }
+
+ #[test]
+ fn connect_uses_only_official_sign_ins() {
+ let i = input();
+ // Claude Code: its own token command, once.
+ assert_eq!(
+ connect_plan(&i, "claude-code"),
+ ConnectPlan {
+ tools: true,
+ app_token: true,
+ device: false,
+ provider: None,
+ token_provider: Some("anthropic".into())
+ }
+ );
+ // Codex: its own device-code sign-in, in a folder Cua owns.
+ assert_eq!(
+ connect_plan(&i, "codex"),
+ ConnectPlan {
+ tools: false,
+ app_token: false,
+ device: true,
+ provider: None,
+ token_provider: Some("openai".into())
+ }
+ );
+ // Not on This Mac: the OpenAI sheet asks for a key.
+ let mut no_codex = i.clone();
+ no_codex.apps.retain(|a| a.agent != "codex");
+ assert_eq!(
+ connect_plan(&no_codex, "codex").provider.as_deref(),
+ Some("openai")
+ );
+ // Not on This Mac: no token command to run here; the provider's sheet asks.
+ let mut away = i.clone();
+ away.apps.retain(|a| a.agent != "claude-code");
+ assert_eq!(
+ connect_plan(&away, "claude-code"),
+ ConnectPlan {
+ tools: false,
+ app_token: false,
+ device: false,
+ provider: Some("anthropic".into()),
+ token_provider: None
+ }
+ );
+ // An app that signs in on its own: only Cua's tools.
+ assert_eq!(
+ connect_plan(&i, "vscode"),
+ ConnectPlan {
+ tools: true,
+ app_token: false,
+ device: false,
+ provider: None,
+ token_provider: None
+ }
+ );
+ }
+
+ #[test]
+ fn provider_sheet_offers_sign_in_key_and_shell() {
+ let mut i = input();
+ i.shell_keys.push("ANTHROPIC_API_KEY".into());
+ let s = provider_sheet(&i, "anthropic").unwrap();
+ assert_eq!(s.title, "Connect Anthropic");
+ let ids: Vec<_> = s.ways.iter().map(|w| w.id.as_str()).collect();
+ assert_eq!(ids, ["app-token", "key", "shell"]);
+ assert_eq!(s.ways[0].app.as_deref(), Some("claude-code"));
+ assert_eq!(s.ways[2].label, "Use ANTHROPIC_API_KEY from your shell");
+ // Without Claude Code there is no Claude sign-in to offer; without the
+ // variable, no shell row.
+ i.apps.retain(|a| a.agent != "claude-code");
+ i.shell_keys.clear();
+ let s = provider_sheet(&i, "anthropic").unwrap();
+ let ids: Vec<_> = s.ways.iter().map(|w| w.id.as_str()).collect();
+ assert_eq!(ids, ["key"]);
+ assert_eq!((s.key_provider.as_str(), s.key_env), ("anthropic", None));
+ let g = provider_sheet(&i, "github").unwrap();
+ assert_eq!(
+ (g.key_provider.as_str(), g.key_env.as_deref()),
+ ("other", Some("COPILOT_GITHUB_TOKEN"))
+ );
+ assert!(provider_sheet(&i, "nope").is_none());
+ }
+
+ #[test]
+ fn app_detail_has_switches_and_its_sign_in() {
+ let mut i = input();
+ i.apps[0].configured = true;
+ i.apps[0].skills = true;
+ i.apps[0].mcp = Some(true);
+ let d = app_detail(&i, "claude-code").unwrap();
+ assert_eq!(d.tools_title, "Cua in Claude Code");
+ let ids: Vec<_> = d.toggles.iter().map(|t| t.id.as_str()).collect();
+ assert_eq!(ids, ["skills", "mcp", "auto"]);
+ assert!(d.toggles.iter().all(|t| t.on));
+ let s = d.sign_in.as_ref().unwrap();
+ assert_eq!(s.title, "Signs in with Anthropic");
+ assert_eq!(s.button.label, "Sign in");
+ assert!(!d.connected);
+ assert_eq!(d.status, "Needs a sign-in to Anthropic.");
+ assert_eq!(
+ d.remove_label.as_deref(),
+ Some("Remove Cua from Claude Code")
+ );
+ // Signed in: Sign out, and Connected.
+ i.keys.keys.push(key("CLAUDE_CODE_OAUTH_TOKEN", "AAAA"));
+ let d = app_detail(&i, "claude-code").unwrap();
+ assert!(d.connected);
+ assert_eq!(d.sign_in.unwrap().button.label, "Sign out");
+ // Turned off: Keep it set up is off.
+ i.off.push("claude-code".into());
+ let d = app_detail(&i, "claude-code").unwrap();
+ assert!(!d.toggles.iter().find(|t| t.id == "auto").unwrap().on);
+ // An app that signs in on its own says so.
+ let d = app_detail(&i, "vscode").unwrap();
+ assert!(d.sign_in.is_none());
+ assert!(d.sign_in_note.unwrap().contains("signs in on its own"));
+ }
+
+ #[test]
+ fn setup_card_names_the_app() {
+ let i = input();
+ let c = setup_card(&i, "claude-code", "Claude Code");
+ assert_eq!(c.title, "Connect Claude Code to start");
+ assert_eq!(c.connect_label, "Connect Claude Code");
+ assert_eq!(c.connecting_label, "Approve in your browser…");
+ assert!(c.body.contains("sign-in to Anthropic"));
+ let c = setup_card(&i, "codex", "OpenAI Codex");
+ assert_eq!(c.connect_label, "Connect OpenAI Codex");
+ assert_eq!(c.connecting_label, "Enter the code in your browser…");
+ }
+
+ #[test]
+ fn notice_turns_buttons_off() {
+ let mut i = input();
+ i.keys.error = Some("the daemon isn't running".into());
+ let v = view(&i);
+ assert!(!v.can_edit);
+ assert_eq!(
+ v.notice.as_deref(),
+ Some("Couldn't read your sign-ins: the daemon isn't running")
+ );
+ assert!(v.providers.iter().all(|p| !p.button.enabled));
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index 98e26a70dc..0c927032a8 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -9,16 +9,19 @@
//!
//! [`METHODS`] lists every method; `dispatch_covers_every_method` checks it.
+use crate::agent_list;
use crate::keyvault::{approval, browse, vault, view as kv};
use crate::model::*;
+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, cloud_connect,
- cloud_page, cloud_sheet, devices, diagnostics, drive_mount_preview, drive_page, drive_settings,
- driver_preview, experiments, host, local_network, login_item, machines, notch, notifications,
- nudges, onboarding, onboarding_preview, palette, paths, persistent, presence, relay_usage,
- resources, settings, share, sign_in, space_menu, telemetry, tips, upsell, window, wizard,
+ cloud_page, cloud_sheet, connectors, devices, diagnostics, drive_mount_preview, drive_page,
+ drive_settings, driver_preview, experiments, host, local_network, login_item, machines, notch,
+ notifications, nudges, onboarding, onboarding_preview, palette, paths, persistent, presence,
+ relay_usage, resources, runtimes, settings, share, sign_in, space_menu, summon, telemetry,
+ tips, upsell, window, wizard,
};
use serde::Serialize;
use serde::de::DeserializeOwned;
@@ -186,11 +189,27 @@ pub const METHODS: &[&str] = &[
"settings.defaults",
"settings.formatHotkey",
"settings.page",
+ "settings.runtimePathVerdict",
+ "settings.runtimeChoose",
"loginItem.launchPlan",
"agentKeys.view",
"agentKeys.form",
"agentKeys.removeConfirm",
"agentKeys.nameProblem",
+ "connectors.view",
+ "connectors.connectPlan",
+ "connectors.providerSheet",
+ "connectors.appDetail",
+ "connectors.setupCard",
+ "summon.candidates",
+ "summon.plan",
+ "summon.failed",
+ "summon.firstMessage",
+ "summon.parseMentions",
+ "summon.queuedNote",
+ "profileCard.person",
+ "agentList.view",
+ "profileCard.agent",
"about.view",
"diagnostics.createReport",
"diagnostics.reportMailto",
@@ -969,6 +988,50 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
&a.get("input")?,
&a.get::<String>("env")?,
)),
+ "connectors.view" => out(connectors::view_on(
+ &a.get("input")?,
+ a.get::<Option<SpaceOs>>("hostOs")?
+ .unwrap_or(SpaceOs::Macos),
+ )),
+ "connectors.connectPlan" => out(connectors::connect_plan(
+ &a.get("input")?,
+ &a.get::<String>("agent")?,
+ )),
+ "connectors.providerSheet" => out(connectors::provider_sheet_on(
+ &a.get("input")?,
+ &a.get::<String>("provider")?,
+ a.get::<Option<SpaceOs>>("hostOs")?
+ .unwrap_or(SpaceOs::Macos),
+ )),
+ "connectors.appDetail" => out(connectors::app_detail(
+ &a.get("input")?,
+ &a.get::<String>("agent")?,
+ )),
+ "connectors.setupCard" => out(connectors::setup_card(
+ &a.get("input")?,
+ &a.get::<String>("agent")?,
+ &a.get::<String>("name")?,
+ )),
+ "summon.candidates" => out(summon::candidates(&a.get("input")?)),
+ "summon.plan" => out(summon::plan(&a.get("input")?, &a.get::<String>("text")?)),
+ "summon.failed" => out(summon::failed(
+ &a.get("input")?,
+ &a.get::<String>("harness")?,
+ &a.get::<String>("handle")?,
+ &a.get::<String>("error")?,
+ )),
+ "summon.firstMessage" => out(summon::first_message(
+ &a.get("input")?,
+ &a.get::<String>("agent")?,
+ &a.get::<String>("prompt")?,
+ )),
+ "agentList.view" => out(agent_list::view(&a.get("input")?)),
+ "profileCard.person" => out(profile_card::person(&a.get("input")?)),
+ "profileCard.agent" => out(profile_card::agent(&a.get("input")?)),
+ "summon.queuedNote" => out(summon::queued_note(
+ a.get::<Option<bool>>("creating")?.unwrap_or(false),
+ )),
+ "summon.parseMentions" => out(summon::parse_mentions(&a.get::<String>("text")?)),
"agentKeys.nameProblem" => out(agent_keys::name_problem(&a.get::<String>("name")?)),
"about.view" => out(about::view(&a.get::<about::AboutInput>("input")?)),
"diagnostics.createReport" => out(diagnostics::create_report(&a.get("input")?)),
@@ -999,6 +1062,12 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
&a.get::<Option<settings::SettingsInput>>("input")?
.unwrap_or_default(),
)),
+ "settings.runtimePathVerdict" => out(runtimes::path_verdict(&a.get("check")?)),
+ "settings.runtimeChoose" => out(runtimes::choose(
+ a.get::<Option<runtimes::RuntimesInput>>("input")?.as_ref(),
+ &a.get::<String>("row")?,
+ &a.get::<String>("option")?,
+ )),
"settings.withStorage" => out(settings::with_storage(
&a.get("page")?,
&a.get("storage")?,
diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
index d1ad45dba9..2daf27045f 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
@@ -34,6 +34,10 @@
//! | [`experiments`] | Settings, Experiments: one switch per feature still being built, and what each hides while off |
//! | [`login_item`] | launch at login: the Settings toggle, the first run's Done checkbox, when the app turns it on |
//! | [`agent_keys`] | Settings, Agents: the provider keys agents get (rows, the add or replace sheet, names refused, the remove question) |
+//! | [`connectors`] | Settings, Connectors: coding apps with Connect, their pages, Providers, the provider sheet, a task's setup card |
+//! | [`summon`] | @mentioning agents in a Space: the composer's picker, what sending does, why an agent can't be woken, Ask first's first message |
+//! | [`profile_card`] | the card a person or an agent opens to in a Space: access, presence, who runs an agent and on what, its status, Details |
+//! | [`agent_list`] | every agent you work with as one list (agents in Spaces and this device's unfinished runs): the Agents page and Home draw it |
//! | [`about`] | Settings, About: name, version, links, the update controls; the refresh after an update |
//! | [`notch`] | notch geometry, notch mode and tiles |
//! | [`window`] | the main window's chrome (account line, New Space, empty state) and the menu bar item's menu |
@@ -59,6 +63,7 @@
pub mod about;
pub mod account;
pub mod agent_keys;
+pub mod agent_list;
pub mod agent_prompts;
pub mod agents;
pub mod bulk_confirm;
@@ -67,6 +72,7 @@ pub mod cloud_connect;
pub mod cloud_page;
pub mod cloud_sheet;
pub mod connection;
+pub mod connectors;
pub mod devices;
pub mod diagnostics;
pub mod dispatch;
@@ -97,13 +103,16 @@ pub mod parity;
pub mod paths;
pub mod persistent;
pub mod presence;
+pub mod profile_card;
pub mod relay_usage;
pub mod resources;
+pub mod runtimes;
pub mod settings;
pub mod share;
pub mod sign_in;
pub mod space_menu;
pub mod spaces;
+pub mod summon;
pub mod teams;
pub mod telemetry;
pub mod teleport;
diff --git a/libs/cua/crates/cua-spaces-app-core/src/parity.rs b/libs/cua/crates/cua-spaces-app-core/src/parity.rs
index ce5278d1b3..761b8a033e 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/parity.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/parity.rs
@@ -248,6 +248,11 @@ pub const FLOWS: &[(&str, &str, &str)] = &[
include_str!("../parity/pro-banner.json"),
include_str!("../parity/golden/pro-banner.json"),
),
+ (
+ "connectors",
+ include_str!("../parity/connectors.json"),
+ include_str!("../parity/golden/connectors.json"),
+ ),
];
/// The core calls a flow makes, over JSON. A host implements it with its
@@ -1992,6 +1997,7 @@ pub fn run(name: &str, flow_json: &str, h: &dyn Host) -> Result<Value, String> {
"bulk-confirm" => run_bulk_confirm(&flow, h),
"tips" => run_tips(&flow, h),
"pro-banner" => run_pro_banner(&flow, h),
+ "connectors" => run_connectors(&flow, h),
other => Err(format!("unknown flow {other}")),
}
}
@@ -5022,3 +5028,127 @@ fn run_pro_banner(f: &Value, h: &dyn Host) -> Result<Value, String> {
}
Ok(json!({ "flow": "pro-banner", "frames": frames }))
}
+
+/// Settings, Connectors (redesign), summoning agents and the one agent list.
+fn run_connectors(f: &Value, h: &dyn Host) -> Result<Value, String> {
+ let line = |parts: &[&Value]| {
+ parts
+ .iter()
+ .map(|v| match v {
+ Value::Null => "-".to_string(),
+ Value::String(s) => s.clone(),
+ other => other.to_string(),
+ })
+ .collect::<Vec<_>>()
+ .join(" | ")
+ };
+ let mut frames = Vec::new();
+ let mut last = Value::Null;
+ for step in f["connectors"].as_array().into_iter().flatten() {
+ let v = c(h, "connectors.view", json!({ "input": step["input"] }))?;
+ let apps: Vec<String> = v["apps"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|a| {
+ line(&[
+ &a["agent"],
+ &a["state"],
+ &a["line"],
+ &a["button"]["label"],
+ &a["connectedLabel"],
+ ])
+ })
+ .collect();
+ let providers: Vec<String> = v["providers"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|p| line(&[&p["id"], &p["state"], &p["status"], &p["button"]["label"]]))
+ .collect();
+ frames.push(json!({ "step": step["step"], "apps": apps, "providers": providers, "footer": v["providersFooter"] }));
+ last = step["input"].clone();
+ }
+ let first = &f["connectors"][0]["input"];
+ for p in f["sheets"].as_array().into_iter().flatten() {
+ let s = c(
+ h,
+ "connectors.providerSheet",
+ json!({ "input": first, "provider": p }),
+ )?;
+ let ways: Vec<String> = s["ways"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|w| line(&[&w["id"], &w["label"], &w["button"]]))
+ .collect();
+ frames.push(json!({ "sheet": p, "title": s["title"], "ways": ways, "key": line(&[&s["keyProvider"], &s["keyEnv"]]) }));
+ }
+ for a in f["plans"].as_array().into_iter().flatten() {
+ let p = c(
+ h,
+ "connectors.connectPlan",
+ json!({ "input": first, "agent": a }),
+ )?;
+ frames.push(json!({ "plan": a, "does": line(&[&p["tools"], &p["appToken"], &p["device"], &p["provider"], &p["tokenProvider"]]) }));
+ }
+ for a in f["details"].as_array().into_iter().flatten() {
+ let d = c(
+ h,
+ "connectors.appDetail",
+ json!({ "input": last, "agent": a }),
+ )?;
+ let toggles: Vec<String> = d["toggles"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|t| line(&[&t["id"], &t["label"], &t["on"]]))
+ .collect();
+ frames.push(json!({ "detail": a, "status": d["status"], "toggles": toggles, "signIn": line(&[&d["signIn"]["title"], &d["signIn"]["status"], &d["signIn"]["button"]["label"]]), "note": d["signInNote"] }));
+ }
+ let si = &f["summon"]["input"];
+ let cands = c(h, "summon.candidates", json!({ "input": si }))?;
+ let cands: Vec<String> = cands
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|x| line(&[&x["handle"], &x["label"], &x["member"], &x["detail"]]))
+ .collect();
+ frames.push(json!({ "candidates": cands }));
+ for t in f["summon"]["texts"].as_array().into_iter().flatten() {
+ let p = c(h, "summon.plan", json!({ "input": si, "text": t }))?;
+ let steps: Vec<String> = p["steps"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|s| {
+ line(&[
+ &s["handle"],
+ &s["action"],
+ &s["cantWake"]["text"],
+ &s["cantWake"]["connectLabel"],
+ &s["cantWake"]["onlyYouLabel"],
+ ])
+ })
+ .collect();
+ frames.push(json!({ "send": t, "steps": steps }));
+ }
+ let list = c(h, "agentList.view", json!({ "input": f["agentList"] }))?;
+ let rows: Vec<String> = list["rows"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|r| {
+ line(&[
+ &r["kind"],
+ &r["label"],
+ &r["tone"],
+ &r["line"],
+ &r["action"]["label"],
+ ])
+ })
+ .collect();
+ frames
+ .push(json!({ "agents": rows, "summary": list["summary"], "seeAll": list["seeAllLabel"] }));
+ Ok(json!({ "flow": "connectors", "frames": frames }))
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/profile_card.rs b/libs/cua/crates/cua-spaces-app-core/src/profile_card.rs
new file mode 100644
index 0000000000..9c1d3c562d
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/profile_card.rs
@@ -0,0 +1,487 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The card a person or an agent opens to in a Space (their name in the
+//! thread, a mention, a row in "In this space"): one calm shape for both.
+//!
+//! - **A person** ([`person`]): name, email, their access here (Owner, Can
+//! edit, Can view), team, Active now or last seen; Change access and
+//! Remove from Space for the owner and admins.
+//! - **An agent** ([`agent`]): name with an Agent badge, one line on who runs
+//! it, where and on what ("Run by Ada in this Space, uses Anthropic"), its
+//! status (Working on "…", Idle, Not connected with Connect), Configure,
+//! Remove from Space; everything else (handle, harness and
+//! version, how and when it joined, who may task, stop or approve it) folded
+//! under Details, with ids copyable.
+
+use serde::{Deserialize, Serialize};
+
+use crate::connectors::{self, ConnectorsInput};
+
+/// A row under Details.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CardDetail {
+ pub label: String,
+ pub value: String,
+ /// An id: a Copy button beside it.
+ pub copy: bool,
+}
+
+fn detail(label: &str, value: impl Into<String>, copy: bool) -> CardDetail {
+ CardDetail {
+ label: label.into(),
+ value: value.into(),
+ copy,
+ }
+}
+
+/// "Just now", "5 minutes ago", "3 hours ago", "2 days ago".
+pub fn ago(then_ms: u64, now_ms: u64) -> String {
+ let s = now_ms.saturating_sub(then_ms) / 1000;
+ let plural = |n: u64, unit: &str| format!("{n} {unit}{} ago", if n == 1 { "" } else { "s" });
+ match s {
+ 0..=59 => "just now".into(),
+ 60..=3599 => plural(s / 60, "minute"),
+ 3600..=86_399 => plural(s / 3600, "hour"),
+ _ => plural(s / 86_400, "day"),
+ }
+}
+
+// ------------------------------------------------------------------ people
+
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct PersonCardInput {
+ pub name: String,
+ /// Who the Space is shared with as (an email or account id), when known.
+ pub who: Option<String>,
+ /// It's you.
+ pub me: bool,
+ /// `owner`, `editor`, `viewer` (absent: not known).
+ pub access: Option<String>,
+ pub team: Option<String>,
+ /// Connected to the Space now.
+ pub active: bool,
+ pub last_seen_ms: Option<u64>,
+ pub now_ms: u64,
+ /// You are the Space's owner or an admin.
+ pub can_manage: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AccessChoice {
+ pub value: String,
+ pub label: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PersonCardView {
+ pub name: String,
+ /// "(you)" after the name.
+ pub you_label: Option<String>,
+ pub email: Option<String>,
+ /// "Owner", "Can edit", "Can view".
+ pub access: Option<String>,
+ pub team: Option<String>,
+ /// "Active now", "Last seen 3 hours ago".
+ pub presence: Option<String>,
+ pub active: bool,
+ /// Change access: the choices and the current one (owner and admins, not on the owner or yourself).
+ pub change_access_label: Option<String>,
+ pub access_choices: Vec<AccessChoice>,
+ pub access_value: Option<String>,
+ pub remove_label: Option<String>,
+}
+
+fn access_label(a: &str) -> Option<&'static str> {
+ match a {
+ "owner" => Some("Owner"),
+ "editor" | "edit" => Some("Can edit"),
+ "viewer" | "view" => Some("Can view"),
+ _ => None,
+ }
+}
+
+pub fn person(i: &PersonCardInput) -> PersonCardView {
+ let email = i.who.clone().filter(|w| w.contains('@'));
+ let owner = i.access.as_deref() == Some("owner");
+ let manage = i.can_manage && !i.me && !owner && i.who.is_some();
+ PersonCardView {
+ name: i.name.clone(),
+ you_label: i.me.then(|| "(you)".into()),
+ access: i.access.as_deref().and_then(access_label).map(Into::into),
+ team: i.team.clone(),
+ presence: if i.active {
+ Some("Active now".into())
+ } else {
+ i.last_seen_ms
+ .map(|t| format!("Last seen {}", ago(t, i.now_ms)))
+ },
+ active: i.active,
+ change_access_label: manage.then(|| "Change access".into()),
+ access_choices: if manage {
+ vec![
+ AccessChoice {
+ value: "viewer".into(),
+ label: "Can view".into(),
+ },
+ AccessChoice {
+ value: "editor".into(),
+ label: "Can edit".into(),
+ },
+ ]
+ } else {
+ vec![]
+ },
+ access_value: manage
+ .then_some(match i.access.as_deref() {
+ Some("editor" | "edit") => "editor",
+ _ => "viewer",
+ })
+ .map(Into::into),
+ remove_label: manage.then(|| "Remove from Space".into()),
+ email,
+ }
+}
+
+// ------------------------------------------------------------------ agents
+
+/// The Space-startable kinds Cua knows the sign-in of (the Connectors app id).
+fn app_of(harness: &str) -> Option<&'static str> {
+ match harness {
+ "claude-code" => Some("claude-code"),
+ "codex" | "openai-codex" => Some("codex"),
+ "hermes" => Some("hermes"),
+ "cursor" => Some("cursor"),
+ "openclaw" => Some("openclaw"),
+ "copilot-cli" => Some("copilot-cli"),
+ _ => None,
+ }
+}
+
+/// One right, as the page words it ("Can give it tasks", "Ada").
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct CardRight {
+ pub label: String,
+ pub holders: String,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct AgentCardInput {
+ pub display_name: String,
+ pub handle: String,
+ /// `claude-code`, `hermes`, ...
+ pub harness: String,
+ /// "Claude Code 2.1.3", as it reported it (absent: it didn't say).
+ pub harness_reported: Option<String>,
+ pub owner_name: String,
+ pub owner_id: String,
+ pub owner_is_me: bool,
+ /// The computer it posts from (an agent connected from outside).
+ pub device: Option<String>,
+ /// `space` (started in this Space) or `external`.
+ pub origin: String,
+ /// The member's status (`working`, `idle`, `asleep`, `pending`, ...).
+ pub status: String,
+ /// What it is doing, when it says.
+ pub activity: Option<String>,
+ /// "Started in this Space", "Joined with a code".
+ pub joined_how: String,
+ pub joined_at_ms: Option<u64>,
+ pub now_ms: u64,
+ pub rights: Vec<CardRight>,
+ /// You may remove it.
+ pub can_remove: bool,
+ /// This device's sign-ins (for an agent of yours: Not connected).
+ pub connectors: ConnectorsInput,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentCardView {
+ pub name: String,
+ pub badge: String,
+ /// "Run by Ada in this Space, uses Anthropic".
+ pub line: String,
+ /// `working`, `idle`, `not-connected`, `pending`.
+ pub status: String,
+ pub status_text: String,
+ /// "Connect Claude Code", while Not connected.
+ pub connect_label: Option<String>,
+ /// The Connectors app it runs as (Connect and Open its settings).
+ pub app: Option<String>,
+ pub settings_label: Option<String>,
+ pub remove_label: Option<String>,
+ pub details_label: String,
+ pub details: Vec<CardDetail>,
+}
+
+pub fn agent(i: &AgentCardInput) -> AgentCardView {
+ let app = app_of(&i.harness);
+ let name = if i.display_name.is_empty() {
+ i.handle.clone()
+ } else {
+ i.display_name.clone()
+ };
+ let who = if i.owner_is_me {
+ "you".to_string()
+ } else {
+ i.owner_name.clone()
+ };
+ let place = match (&i.device, i.origin.as_str()) {
+ (Some(d), _) => format!("on {d}"),
+ (None, "space") => "in this Space".to_string(),
+ _ => String::new(),
+ };
+ // The provider it signs in to: the one connected here, else the first it uses.
+ let providers = app.map(connectors::app_providers).unwrap_or_default();
+ let provider = providers
+ .iter()
+ .find(|p| {
+ app.is_some_and(|a| i.owner_is_me && connectors::signed_in(&i.connectors, a))
+ && connectors::provider_label(p).is_some()
+ })
+ .or(providers.first())
+ .and_then(|p| connectors::provider_label(p));
+ let mut line = format!("Run by {who}");
+ if !place.is_empty() {
+ line.push(' ');
+ line.push_str(&place);
+ }
+ if let Some(p) = provider {
+ line.push_str(&format!(", uses {p}"));
+ }
+ // Your own agent with no sign-in it can use: Not connected, with Connect.
+ let not_connected =
+ i.owner_is_me && app.is_some_and(|a| !connectors::signed_in(&i.connectors, a));
+ let label = app_label(&i.harness).unwrap_or(&name).to_string();
+ let (status, status_text) = if i.status == "pending" {
+ ("pending", "Waiting to be let in".to_string())
+ } else if not_connected {
+ ("not-connected", "Not connected".to_string())
+ } else if i.status == "working" || i.status == "busy" {
+ (
+ "working",
+ match &i.activity {
+ Some(a) if !a.is_empty() => format!("Working on \u{201c}{a}\u{201d}"),
+ _ => "Working".into(),
+ },
+ )
+ } else {
+ ("idle", "Idle".to_string())
+ };
+ let in_settings = i.owner_is_me
+ && app.is_some_and(|a| {
+ i.connectors
+ .apps
+ .iter()
+ .any(|x| x.agent == a && x.installed)
+ });
+ let mut details = vec![detail("Handle", format!("@{}", i.handle), true)];
+ details.push(detail(
+ "Runs",
+ i.harness_reported
+ .clone()
+ .unwrap_or_else(|| "Not reported".into()),
+ false,
+ ));
+ let joined = match i.joined_at_ms {
+ Some(t) => format!("{}, {}", i.joined_how, ago(t, i.now_ms)),
+ None => i.joined_how.clone(),
+ };
+ details.push(detail("Joined", joined, false));
+ if !i.owner_id.is_empty() {
+ details.push(detail("Owner's id", i.owner_id.clone(), true));
+ }
+ details.extend(
+ i.rights
+ .iter()
+ .map(|r| detail(&r.label, r.holders.clone(), false)),
+ );
+ AgentCardView {
+ name,
+ badge: "Agent".into(),
+ line,
+ status: status.into(),
+ status_text,
+ connect_label: not_connected.then(|| format!("Connect {label}")),
+ app: app.map(Into::into),
+ settings_label: in_settings.then(|| "Configure".into()),
+ remove_label: i.can_remove.then(|| "Remove from Space".into()),
+ details_label: "Details".into(),
+ details,
+ }
+}
+
+fn app_label(harness: &str) -> Option<&'static str> {
+ match harness {
+ "claude-code" => Some("Claude Code"),
+ "codex" | "openai-codex" => Some("Codex"),
+ "hermes" => Some("Hermes"),
+ "cursor" => Some("Cursor"),
+ "openclaw" => Some("OpenClaw"),
+ "copilot-cli" => Some("GitHub Copilot CLI"),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::agent_keys::{AgentKeyInput, AgentKeysInput};
+
+ const NOW: u64 = 1_000_000_000;
+
+ #[test]
+ fn owner_sees_an_editor_with_change_access_and_remove() {
+ let v = person(&PersonCardInput {
+ name: "Grace".into(),
+ who: Some("[email protected]".into()),
+ access: Some("editor".into()),
+ team: Some("Acme".into()),
+ active: true,
+ now_ms: NOW,
+ can_manage: true,
+ ..Default::default()
+ });
+ assert_eq!(v.email.as_deref(), Some("[email protected]"));
+ assert_eq!(v.access.as_deref(), Some("Can edit"));
+ assert_eq!(v.presence.as_deref(), Some("Active now"));
+ assert_eq!(v.change_access_label.as_deref(), Some("Change access"));
+ assert_eq!(v.access_value.as_deref(), Some("editor"));
+ assert_eq!(v.remove_label.as_deref(), Some("Remove from Space"));
+ }
+
+ #[test]
+ fn your_own_card_and_a_viewer_who_cant_manage_have_no_access_actions() {
+ let me = person(&PersonCardInput {
+ name: "Ada".into(),
+ who: Some("[email protected]".into()),
+ me: true,
+ access: Some("owner".into()),
+ last_seen_ms: Some(NOW - 3 * 3600 * 1000),
+ now_ms: NOW,
+ can_manage: true,
+ ..Default::default()
+ });
+ assert_eq!(me.you_label.as_deref(), Some("(you)"));
+ assert_eq!(me.access.as_deref(), Some("Owner"));
+ assert_eq!(me.presence.as_deref(), Some("Last seen 3 hours ago"));
+ assert!(me.change_access_label.is_none() && me.remove_label.is_none());
+ let other = person(&PersonCardInput {
+ name: "Linus".into(),
+ who: Some("[email protected]".into()),
+ access: Some("viewer".into()),
+ can_manage: false,
+ ..Default::default()
+ });
+ assert!(other.change_access_label.is_none() && other.remove_label.is_none());
+ assert_eq!(other.email.as_deref(), Some("[email protected]"));
+ }
+
+ fn agent_input() -> AgentCardInput {
+ AgentCardInput {
+ display_name: "Claude Code".into(),
+ handle: "claude".into(),
+ harness: "claude-code".into(),
+ harness_reported: Some("Claude Code 2.1.3".into()),
+ owner_name: "Ada".into(),
+ owner_id: "acct_ada".into(),
+ owner_is_me: true,
+ origin: "space".into(),
+ status: "working".into(),
+ activity: Some("fix the build".into()),
+ joined_how: "Started in this Space".into(),
+ joined_at_ms: Some(NOW - 120_000),
+ now_ms: NOW,
+ rights: vec![CardRight {
+ label: "Can give it tasks".into(),
+ holders: "Owner".into(),
+ }],
+ can_remove: true,
+ connectors: ConnectorsInput {
+ apps: vec![crate::connectors::ConnectorAppInput {
+ agent: "claude-code".into(),
+ name: "Claude Code".into(),
+ installed: true,
+ ..Default::default()
+ }],
+ keys: AgentKeysInput {
+ keys: vec![AgentKeyInput {
+ provider: "other".into(),
+ env: "CLAUDE_CODE_OAUTH_TOKEN".into(),
+ last4: String::new(),
+ added_ms: 1,
+ }],
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn an_agent_card_says_who_runs_it_where_and_on_what_in_one_line() {
+ let v = agent(&agent_input());
+ assert_eq!(v.badge, "Agent");
+ assert_eq!(v.line, "Run by you in this Space, uses Anthropic");
+ assert_eq!(v.status_text, "Working on \u{201c}fix the build\u{201d}");
+ assert_eq!(v.settings_label.as_deref(), Some("Configure"));
+ assert_eq!(v.remove_label.as_deref(), Some("Remove from Space"));
+ assert!(v.connect_label.is_none());
+ let labels: Vec<_> = v.details.iter().map(|d| d.label.as_str()).collect();
+ assert_eq!(
+ labels,
+ [
+ "Handle",
+ "Runs",
+ "Joined",
+ "Owner's id",
+ "Can give it tasks"
+ ]
+ );
+ assert!(v.details[0].copy && v.details[3].copy);
+ assert_eq!(v.details[2].value, "Started in this Space, 2 minutes ago");
+ }
+
+ #[test]
+ fn someone_elses_agent_on_their_computer_has_no_settings_and_isnt_checked_here() {
+ let mut i = agent_input();
+ i.owner_is_me = false;
+ i.owner_name = "Linus".into();
+ i.device = Some("linus-thinkpad".into());
+ i.origin = "external".into();
+ i.status = "idle".into();
+ i.connectors.keys.keys.clear();
+ i.can_remove = false;
+ let v = agent(&i);
+ assert_eq!(v.line, "Run by Linus on linus-thinkpad, uses Anthropic");
+ assert_eq!(v.status_text, "Idle");
+ assert!(
+ v.settings_label.is_none() && v.remove_label.is_none() && v.connect_label.is_none()
+ );
+ }
+
+ #[test]
+ fn your_agent_with_no_sign_in_is_not_connected_with_connect() {
+ let mut i = agent_input();
+ i.connectors.keys.keys.clear();
+ let v = agent(&i);
+ assert_eq!(v.status, "not-connected");
+ assert_eq!(v.status_text, "Not connected");
+ assert_eq!(v.connect_label.as_deref(), Some("Connect Claude Code"));
+ }
+
+ #[test]
+ fn ago_reads_plainly() {
+ assert_eq!(ago(NOW - 5_000, NOW), "just now");
+ assert_eq!(ago(NOW - 60_000, NOW), "1 minute ago");
+ assert_eq!(ago(NOW - 2 * 86_400_000, NOW), "2 days ago");
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/runtimes.rs b/libs/cua/crates/cua-spaces-app-core/src/runtimes.rs
new file mode 100644
index 0000000000..dfedadcf64
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/runtimes.rs
@@ -0,0 +1,888 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Settings, Advanced, "Which software runs Spaces": one row per kind of
+//! Space (Containers, Virtual machines, MicroVMs), each Automatic, Cua's
+//! own or Already installed (`runtime.<kind>`).
+//!
+//! * Automatic and Cua's own show nothing more.
+//! * Already installed shows the runtimes the host found for the kind
+//! (name, path, version) and the path that will be used, which a person
+//! can change (`runtime.<kind>_path`): Detected while it is one of the
+//! found ones, Custom otherwise (with "Reset to detected"), and one line
+//! about what that path is ([`path_verdict`]).
+//! * A kind this machine cannot run at all says "Not available" and why,
+//! from the runtime doctor; before the doctor answered, "Checking…".
+//!
+//! Every row is always there, on every host, whatever the host knows yet.
+
+use serde::{Deserialize, Serialize};
+
+use crate::model::SpaceOs;
+use crate::settings::{SettingsOption, SettingsRow, SettingsRowKind, SettingsSection, row};
+
+/// A runtime the host found for one kind (the SDK's `RuntimeDetected`).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct DetectedRuntime {
+ /// `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ pub tool: String,
+ /// As people know it (`Docker`, `Apple container`).
+ pub name: String,
+ pub path: String,
+ /// As its `--version` says it (`27.3.1`).
+ pub version: Option<String>,
+ /// The one guest system it runs, when only one (`macOS`, `Linux`).
+ pub guests: Option<String>,
+}
+
+/// What a binary is for one kind (the SDK's `RuntimePathProbe`).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct RuntimePathCheck {
+ pub path: String,
+ /// A file is there.
+ pub exists: bool,
+ /// It can be run.
+ pub executable: bool,
+ /// The tool it is, when it is one the kind takes.
+ pub tool: Option<String>,
+ pub name: Option<String>,
+ pub version: Option<String>,
+ /// The oldest version Cua runs on.
+ pub min_version: Option<String>,
+ /// The tools the kind takes here (`Docker`, `Podman`).
+ pub expected: Vec<String>,
+ pub guests: Option<String>,
+}
+
+/// One kind as the host read it (the SDK's `RuntimeKindState`).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct RuntimeKindInput {
+ /// `container`, `vm` or `microvm`.
+ pub kind: String,
+ /// `runtime.<kind>`: `auto`, `builtin`, `system` (none: auto).
+ pub source: Option<String>,
+ /// `runtime.<kind>_path`, when set.
+ pub path: Option<String>,
+ /// What is installed for the kind, the one used first (none: not
+ /// looked for yet).
+ pub detected: Option<Vec<DetectedRuntime>>,
+ /// The path in use, probed.
+ pub check: Option<RuntimePathCheck>,
+ /// The tools the kind takes on this machine (`Docker`, `Podman`).
+ pub expected: Vec<String>,
+}
+
+/// What Settings knows about this machine's runtimes.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct RuntimesInput {
+ /// This machine's system (none: not said; every option is offered).
+ pub os: Option<SpaceOs>,
+ /// `arm64`, `amd64`.
+ pub host_arch: Option<String>,
+ /// The runtime doctor's ready backends (none: not read yet).
+ pub local_backends: Option<Vec<String>>,
+ /// Why each other backend is not ready.
+ pub local_details: Option<std::collections::HashMap<String, String>>,
+ /// Each kind's setting and what is installed for it (none: not read).
+ pub kinds: Option<Vec<RuntimeKindInput>>,
+}
+
+/// A path's one line: whether it can be used, and what it is.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RuntimePathVerdict {
+ pub ok: bool,
+ pub line: String,
+}
+
+/// The kinds, in Settings' order: id and label.
+pub const KINDS: [(&str, &str); 3] = [
+ ("container", "Containers"),
+ ("vm", "Virtual machines"),
+ ("microvm", "MicroVMs"),
+];
+
+/// The options' words.
+pub const AUTOMATIC: &str = "Automatic";
+pub const CUAS_OWN: &str = "Cua\u{2019}s own";
+pub const INSTALLED: &str = "Already installed";
+pub const NOT_AVAILABLE: &str = "Not available";
+pub const CHECKING: &str = "Checking\u{2026}";
+pub const DETECTED: &str = "Detected";
+pub const CUSTOM: &str = "Custom";
+pub const RESET: &str = "Reset to detected";
+
+/// Whether a kind runs here.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Availability {
+ /// The doctor has not answered.
+ Checking,
+ Ready,
+ /// Why not, as a sentence about the kind ("MicroVMs need macOS 26").
+ Unavailable(String),
+}
+
+fn is_mac(os: Option<SpaceOs>) -> bool {
+ matches!(os, Some(SpaceOs::Macos) | None)
+}
+
+/// Whether `kind` runs on this machine, from its runtime doctor.
+pub fn availability(kind: &str, input: &RuntimesInput) -> Availability {
+ let Some(backends) = input.local_backends.as_deref() else {
+ return Availability::Checking;
+ };
+ let has = |names: &[&str]| backends.iter().any(|b| names.contains(&b.as_str()));
+ let intel = crate::wizard::arch_word(input.host_arch.as_deref()) == Some("amd64");
+ match kind {
+ // A Mac always has Cua's own (a VM with Docker and gVisor).
+ "container" if is_mac(input.os) => Availability::Ready,
+ "container" => {
+ // The names New Space reads a container engine by.
+ let engines = crate::wizard::LocalEngine::Container.backends();
+ if backends.iter().any(|b| engines.contains(b)) {
+ Availability::Ready
+ } else {
+ Availability::Unavailable("Containers need Docker or Podman".into())
+ }
+ }
+ // Lume (Cua's own, or this Mac's) runs on Apple silicon only.
+ "vm" if is_mac(input.os) => {
+ if intel && !has(&["qemu"]) {
+ Availability::Unavailable("Virtual machines need a Mac with Apple silicon".into())
+ } else {
+ Availability::Ready
+ }
+ }
+ "vm" if has(&["qemu", "lume"]) => Availability::Ready,
+ "vm" => Availability::Unavailable("Virtual machines need QEMU".into()),
+ "microvm" => {
+ use crate::wizard::{LocalProbe, MicrovmStatus, microvm_status_of};
+ let probe = LocalProbe {
+ backends: input.local_backends.as_deref(),
+ details: input.local_details.as_ref(),
+ host_arch: input.host_arch.as_deref(),
+ };
+ match microvm_status_of(&probe, input.os.unwrap_or(SpaceOs::Macos)) {
+ MicrovmStatus::Checking => Availability::Checking,
+ MicrovmStatus::Ready(_) => Availability::Ready,
+ MicrovmStatus::Blocked(why) => {
+ // "Needs macOS 26." as "MicroVMs need macOS 26".
+ let mut c = why.trim().chars();
+ let why = c
+ .next()
+ .map(|f| f.to_lowercase().chain(c).collect::<String>())
+ .unwrap_or_default();
+ let why = why
+ .strip_prefix("needs ")
+ .map(|w| format!("need {w}"))
+ .unwrap_or(why);
+ Availability::Unavailable(format!("MicroVMs {}", why.trim_end_matches('.')))
+ }
+ }
+ }
+ _ => Availability::Ready,
+ }
+}
+
+/// Whether Cua has its own runtime for `kind` on `os`.
+fn has_own(kind: &str, os: Option<SpaceOs>) -> bool {
+ match kind {
+ // A VM with Docker and gVisor; a built-in Lume: Mac only.
+ "container" | "vm" => is_mac(os),
+ // Cua's monitor on a Mac, its own Firecracker on Linux.
+ "microvm" => matches!(os, Some(SpaceOs::Macos) | Some(SpaceOs::Linux) | None),
+ _ => false,
+ }
+}
+
+/// `auto`, `builtin` or `system` (anything else: auto).
+fn source_of(word: Option<&str>) -> &'static str {
+ match word.map(|w| w.trim().to_ascii_lowercase()).as_deref() {
+ Some("builtin" | "built-in") => "builtin",
+ Some("system") => "system",
+ _ => "auto",
+ }
+}
+
+/// `major.minor` of a version (`27.3.1` is `27.3`).
+pub fn short_version(v: &str) -> String {
+ let parts: Vec<&str> = v.trim().split('.').collect();
+ if parts.len() >= 2 {
+ format!("{}.{}", parts[0], parts[1])
+ } else {
+ v.trim().to_string()
+ }
+}
+
+/// A detected runtime as its option reads: `Docker — /usr/local/bin/docker
+/// (27.3)`, with the one guest system it runs when only one.
+pub fn detected_label(d: &DetectedRuntime) -> String {
+ let mut s = format!("{} \u{2014} {}", d.name, d.path);
+ if let Some(v) = d.version.as_deref().filter(|v| !v.is_empty()) {
+ s.push_str(&format!(" ({})", short_version(v)));
+ }
+ if let Some(g) = d.guests.as_deref().filter(|g| !g.is_empty()) {
+ s.push_str(&format!(" \u{b7} {g} only"));
+ }
+ s
+}
+
+fn version_tuple(v: &str) -> Vec<u64> {
+ v.trim()
+ .trim_start_matches('v')
+ .split('.')
+ .map(|p| {
+ p.chars()
+ .take_while(char::is_ascii_digit)
+ .collect::<String>()
+ })
+ .map(|p| p.parse().unwrap_or(0))
+ .collect()
+}
+
+/// Whether `v` is older than `min`.
+fn older(v: &str, min: &str) -> bool {
+ let (mut a, mut b) = (version_tuple(v), version_tuple(min));
+ let n = a.len().max(b.len());
+ a.resize(n, 0);
+ b.resize(n, 0);
+ a < b
+}
+
+/// "A", "A or B", "A, B or C".
+fn join_or(names: &[String]) -> String {
+ match names {
+ [] => String::new(),
+ [one] => one.clone(),
+ [rest @ .., last] => format!("{} or {last}", rest.join(", ")),
+ }
+}
+
+/// What a path is, in one line: "Docker 27.3 found", "Not a Docker or
+/// Podman binary", "Lume 0.5.3 is too old (needs 0.6.0)".
+pub fn path_verdict(check: &RuntimePathCheck) -> RuntimePathVerdict {
+ let bad = |line: String| RuntimePathVerdict { ok: false, line };
+ if check.path.trim().is_empty() {
+ return bad("No path".into());
+ }
+ if !check.exists {
+ return bad("Nothing at this path".into());
+ }
+ if !check.executable {
+ return bad("Not a program that can run".into());
+ }
+ let Some(tool) = check.tool.as_deref() else {
+ return bad(if check.expected.is_empty() {
+ "Not a runtime Cua knows".into()
+ } else {
+ format!("Not a {} binary", join_or(&check.expected))
+ });
+ };
+ let name = check.name.clone().unwrap_or_else(|| tool.to_string());
+ if let (Some(v), Some(min)) = (check.version.as_deref(), check.min_version.as_deref())
+ && older(v, min)
+ {
+ return bad(format!("{name} {v} is too old (needs {min})"));
+ }
+ let mut line = match check.version.as_deref() {
+ Some(v) => format!("{name} {} found", short_version(v)),
+ None => format!("{name} found"),
+ };
+ if let Some(g) = check.guests.as_deref() {
+ line.push_str(&format!(" \u{b7} runs {g} only"));
+ }
+ RuntimePathVerdict { ok: true, line }
+}
+
+/// The path a kind uses: its custom path, else the first runtime found.
+pub fn path_in_use(k: &RuntimeKindInput) -> Option<String> {
+ k.path
+ .clone()
+ .filter(|p| !p.trim().is_empty())
+ .or_else(|| k.detected.as_ref()?.first().map(|d| d.path.clone()))
+}
+
+/// The custom path is none of the detected ones.
+pub fn is_custom(k: &RuntimeKindInput) -> bool {
+ match k.path.as_deref().filter(|p| !p.trim().is_empty()) {
+ None => false,
+ Some(p) => !k.detected.iter().flatten().any(|d| d.path == p),
+ }
+}
+
+fn kind_rows(kind: &str, label: &str, input: &RuntimesInput) -> Vec<SettingsRow> {
+ use SettingsRowKind::*;
+ let k = input
+ .kinds
+ .iter()
+ .flatten()
+ .find(|k| k.kind == kind)
+ .cloned()
+ .unwrap_or_else(|| RuntimeKindInput {
+ kind: kind.into(),
+ ..Default::default()
+ });
+ let id = format!("runtime:{kind}");
+ let availability = availability(kind, input);
+ if let Availability::Unavailable(why) = &availability {
+ let mut r = row(&id, Text, label);
+ r.value = Some(NOT_AVAILABLE.into());
+ r.help = Some(why.clone());
+ r.enabled = false;
+ return vec![r];
+ }
+ let source = source_of(k.source.as_deref());
+ let mut main = row(&id, Choice, label);
+ main.options = [
+ ("auto", AUTOMATIC),
+ ("builtin", CUAS_OWN),
+ ("system", INSTALLED),
+ ]
+ .into_iter()
+ .filter(|(o, _)| *o != "builtin" || has_own(kind, input.os) || source == "builtin")
+ .map(|(o, l)| SettingsOption {
+ id: o.into(),
+ label: l.into(),
+ active: o == source,
+ })
+ .collect();
+ if availability == Availability::Checking {
+ main.help = Some(CHECKING.into());
+ }
+ let mut rows = vec![main];
+ if source != "system" {
+ return rows;
+ }
+ let in_use = path_in_use(&k);
+ let custom = is_custom(&k);
+ let detected_id = format!("runtime-detected:{kind}");
+ rows.push(match k.detected.as_deref() {
+ None => row(&detected_id, Note, "Looking for what is installed\u{2026}"),
+ Some([]) => {
+ let label = if k.expected.is_empty() {
+ "Nothing found on this computer".to_string()
+ } else {
+ format!("No {} found on this computer", join_or(&k.expected))
+ };
+ row(&detected_id, Note, &label)
+ }
+ Some(found) => {
+ let mut r = row(&detected_id, Choice, "Installed");
+ r.options = found
+ .iter()
+ .map(|d| SettingsOption {
+ id: d.path.clone(),
+ label: detected_label(d),
+ active: !custom && in_use.as_deref() == Some(d.path.as_str()),
+ })
+ .collect();
+ r
+ }
+ });
+ let mut path = row(
+ &format!("runtime-path:{kind}"),
+ Field,
+ if custom { CUSTOM } else { DETECTED },
+ );
+ path.value = in_use.clone();
+ path.placeholder = Some("Full path of the program".into());
+ if custom {
+ path.button = Some(RESET.into());
+ }
+ rows.push(path);
+ let check_id = format!("runtime-check:{kind}");
+ match (&k.check, &in_use) {
+ (Some(c), Some(p)) if &c.path == p => {
+ let v = path_verdict(c);
+ rows.push(row(&check_id, if v.ok { Note } else { Error }, &v.line));
+ }
+ (_, Some(_)) => rows.push(row(&check_id, Note, CHECKING)),
+ _ => {}
+ }
+ rows
+}
+
+/// Settings' Runtimes section: every kind's rows, whatever is known.
+pub fn section(input: Option<&RuntimesInput>) -> SettingsSection {
+ let empty = RuntimesInput::default();
+ let input = input.unwrap_or(&empty);
+ SettingsSection {
+ id: "runtimes".into(),
+ title: "Runtimes".into(),
+ button: None,
+ button_enabled: false,
+ button_help: None,
+ rows: KINDS
+ .iter()
+ .flat_map(|(kind, label)| kind_rows(kind, label, input))
+ .collect(),
+ }
+}
+
+/// What a row in the section changes: the setting and its new value
+/// (`None`: unset it, back to the default or the detected path).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RuntimeSettingChange {
+ /// `runtime.container`, `runtime.vm_path`.
+ pub key: String,
+ pub value: Option<String>,
+}
+
+/// The setting a choice in the section changes, for the host to write
+/// (none: not a runtime row). Picking the first detected runtime unsets
+/// the path (detection then decides); another detected one, or a typed
+/// path, sets it; an empty path ("Reset to detected") unsets it.
+pub fn choose(
+ input: Option<&RuntimesInput>,
+ row_id: &str,
+ option: &str,
+) -> Option<RuntimeSettingChange> {
+ let (prefix, kind) = row_id.split_once(':')?;
+ if !KINDS.iter().any(|(k, _)| *k == kind) {
+ return None;
+ }
+ let change = |suffix: &str, value: Option<String>| RuntimeSettingChange {
+ key: format!("runtime.{kind}{suffix}"),
+ value,
+ };
+ match prefix {
+ "runtime" => Some(change("", Some(source_of(Some(option)).into()))),
+ "runtime-path" => Some(change(
+ "_path",
+ Some(option.trim().to_string()).filter(|p| !p.is_empty()),
+ )),
+ "runtime-detected" => {
+ let first = input
+ .and_then(|i| i.kinds.as_ref())
+ .and_then(|ks| ks.iter().find(|k| k.kind == kind))
+ .and_then(|k| k.detected.as_ref()?.first().map(|d| d.path.clone()));
+ Some(change(
+ "_path",
+ (first.as_deref() != Some(option)).then(|| option.to_string()),
+ ))
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn docker() -> DetectedRuntime {
+ DetectedRuntime {
+ tool: "docker".into(),
+ name: "Docker".into(),
+ path: "/usr/local/bin/docker".into(),
+ version: Some("27.3.1".into()),
+ guests: None,
+ }
+ }
+
+ fn podman() -> DetectedRuntime {
+ DetectedRuntime {
+ tool: "podman".into(),
+ name: "Podman".into(),
+ path: "/opt/homebrew/bin/podman".into(),
+ version: Some("5.2.1".into()),
+ guests: None,
+ }
+ }
+
+ fn ok_check(path: &str, name: &str, version: &str) -> RuntimePathCheck {
+ RuntimePathCheck {
+ path: path.into(),
+ exists: true,
+ executable: true,
+ tool: Some(name.to_ascii_lowercase()),
+ name: Some(name.into()),
+ version: Some(version.into()),
+ expected: vec!["Docker".into(), "Podman".into()],
+ ..Default::default()
+ }
+ }
+
+ fn mac(kinds: Vec<RuntimeKindInput>) -> RuntimesInput {
+ RuntimesInput {
+ os: Some(SpaceOs::Macos),
+ host_arch: Some("arm64".into()),
+ local_backends: Some(vec!["lume".into(), "managed".into(), "vz".into()]),
+ local_details: None,
+ kinds: Some(kinds),
+ }
+ }
+
+ fn ids(s: &SettingsSection) -> Vec<&str> {
+ s.rows.iter().map(|r| r.id.as_str()).collect()
+ }
+
+ fn get<'a>(s: &'a SettingsSection, id: &str) -> &'a SettingsRow {
+ s.rows
+ .iter()
+ .find(|r| r.id == id)
+ .unwrap_or_else(|| panic!("no {id} in {:?}", ids(s)))
+ }
+
+ fn active(r: &SettingsRow) -> Option<&str> {
+ r.options.iter().find(|o| o.active).map(|o| o.id.as_str())
+ }
+
+ /// Before the host knew anything, every kind's row is there, checking.
+ #[test]
+ fn every_kind_has_a_row_before_anything_is_known() {
+ let s = section(None);
+ assert_eq!(
+ ids(&s),
+ ["runtime:container", "runtime:vm", "runtime:microvm"]
+ );
+ for r in &s.rows {
+ assert_eq!(r.kind, SettingsRowKind::Choice);
+ assert_eq!(r.help.as_deref(), Some(CHECKING));
+ assert_eq!(active(r), Some("auto"));
+ let labels: Vec<_> = r.options.iter().map(|o| o.label.as_str()).collect();
+ assert_eq!(labels, [AUTOMATIC, CUAS_OWN, INSTALLED]);
+ }
+ let labels: Vec<_> = s.rows.iter().map(|r| r.label.as_str()).collect();
+ assert_eq!(labels, ["Containers", "Virtual machines", "MicroVMs"]);
+ }
+
+ /// Automatic and Cua's own show nothing more.
+ #[test]
+ fn automatic_and_cuas_own_show_nothing_more() {
+ let s = section(Some(&mac(vec![
+ RuntimeKindInput {
+ kind: "container".into(),
+ source: Some("auto".into()),
+ detected: Some(vec![docker()]),
+ ..Default::default()
+ },
+ RuntimeKindInput {
+ kind: "vm".into(),
+ source: Some("builtin".into()),
+ ..Default::default()
+ },
+ ])));
+ assert_eq!(
+ ids(&s),
+ ["runtime:container", "runtime:vm", "runtime:microvm"]
+ );
+ assert_eq!(active(get(&s, "runtime:vm")), Some("builtin"));
+ assert!(s.rows.iter().all(|r| r.help.is_none()));
+ }
+
+ /// Already installed: the runtimes found, the path in use autofilled
+ /// from the first, Detected, and what it is.
+ #[test]
+ fn already_installed_lists_what_is_found_and_the_path_used() {
+ let s = section(Some(&mac(vec![RuntimeKindInput {
+ kind: "container".into(),
+ source: Some("system".into()),
+ detected: Some(vec![docker(), podman()]),
+ check: Some(ok_check("/usr/local/bin/docker", "Docker", "27.3.1")),
+ ..Default::default()
+ }])));
+ assert_eq!(
+ ids(&s),
+ [
+ "runtime:container",
+ "runtime-detected:container",
+ "runtime-path:container",
+ "runtime-check:container",
+ "runtime:vm",
+ "runtime:microvm"
+ ]
+ );
+ let d = get(&s, "runtime-detected:container");
+ let labels: Vec<_> = d.options.iter().map(|o| o.label.as_str()).collect();
+ assert_eq!(
+ labels,
+ [
+ "Docker \u{2014} /usr/local/bin/docker (27.3)",
+ "Podman \u{2014} /opt/homebrew/bin/podman (5.2)"
+ ]
+ );
+ assert_eq!(active(d), Some("/usr/local/bin/docker"));
+ let p = get(&s, "runtime-path:container");
+ assert_eq!(
+ (
+ p.kind,
+ p.label.as_str(),
+ p.value.as_deref(),
+ p.button.as_deref()
+ ),
+ (
+ SettingsRowKind::Field,
+ DETECTED,
+ Some("/usr/local/bin/docker"),
+ None
+ )
+ );
+ let c = get(&s, "runtime-check:container");
+ assert_eq!(
+ (c.kind, c.label.as_str()),
+ (SettingsRowKind::Note, "Docker 27.3 found")
+ );
+ }
+
+ /// A custom path wins over detection: Custom, Reset to detected, and the
+ /// drop-down names none of the found ones.
+ #[test]
+ fn a_custom_path_overrides_detection() {
+ let k = RuntimeKindInput {
+ kind: "container".into(),
+ source: Some("system".into()),
+ path: Some("/Users/me/bin/docker".into()),
+ detected: Some(vec![docker()]),
+ check: Some(ok_check("/Users/me/bin/docker", "Docker", "28.0.0")),
+ ..Default::default()
+ };
+ assert_eq!(path_in_use(&k).as_deref(), Some("/Users/me/bin/docker"));
+ let s = section(Some(&mac(vec![k.clone()])));
+ let p = get(&s, "runtime-path:container");
+ assert_eq!(
+ (p.label.as_str(), p.value.as_deref(), p.button.as_deref()),
+ (CUSTOM, Some("/Users/me/bin/docker"), Some(RESET))
+ );
+ assert_eq!(active(get(&s, "runtime-detected:container")), None);
+ assert_eq!(
+ get(&s, "runtime-check:container").label,
+ "Docker 28.0 found"
+ );
+ // The second found one, picked: still Detected.
+ let s = section(Some(&mac(vec![RuntimeKindInput {
+ path: Some("/opt/homebrew/bin/podman".into()),
+ detected: Some(vec![docker(), podman()]),
+ check: Some(ok_check("/opt/homebrew/bin/podman", "Podman", "5.2.1")),
+ ..k
+ }])));
+ assert_eq!(get(&s, "runtime-path:container").label, DETECTED);
+ assert_eq!(
+ active(get(&s, "runtime-detected:container")),
+ Some("/opt/homebrew/bin/podman")
+ );
+ }
+
+ #[test]
+ fn a_bad_path_says_what_is_wrong() {
+ let k = RuntimeKindInput {
+ kind: "container".into(),
+ source: Some("system".into()),
+ path: Some("/bin/ls".into()),
+ detected: Some(vec![]),
+ expected: vec!["Docker".into(), "Podman".into()],
+ check: Some(RuntimePathCheck {
+ path: "/bin/ls".into(),
+ exists: true,
+ executable: true,
+ expected: vec!["Docker".into(), "Podman".into()],
+ ..Default::default()
+ }),
+ };
+ let s = section(Some(&mac(vec![k])));
+ let c = get(&s, "runtime-check:container");
+ assert_eq!(
+ (c.kind, c.label.as_str()),
+ (SettingsRowKind::Error, "Not a Docker or Podman binary")
+ );
+ assert_eq!(
+ get(&s, "runtime-detected:container").label,
+ "No Docker or Podman found on this computer"
+ );
+ }
+
+ #[test]
+ fn verdicts() {
+ let v = |c: RuntimePathCheck| path_verdict(&c);
+ let base = RuntimePathCheck {
+ path: "/x/docker".into(),
+ expected: vec!["Docker".into(), "Podman".into()],
+ ..Default::default()
+ };
+ assert_eq!(
+ v(base.clone()),
+ RuntimePathVerdict {
+ ok: false,
+ line: "Nothing at this path".into()
+ }
+ );
+ assert_eq!(
+ v(RuntimePathCheck {
+ exists: true,
+ ..base.clone()
+ })
+ .line,
+ "Not a program that can run"
+ );
+ assert_eq!(
+ v(RuntimePathCheck {
+ exists: true,
+ executable: true,
+ ..base.clone()
+ })
+ .line,
+ "Not a Docker or Podman binary"
+ );
+ assert_eq!(
+ v(ok_check("/x/docker", "Docker", "27.3.1")),
+ RuntimePathVerdict {
+ ok: true,
+ line: "Docker 27.3 found".into()
+ }
+ );
+ let lume = |version: &str| RuntimePathCheck {
+ path: "/opt/homebrew/bin/lume".into(),
+ exists: true,
+ executable: true,
+ tool: Some("lume".into()),
+ name: Some("Lume".into()),
+ version: Some(version.into()),
+ min_version: Some("0.6.0".into()),
+ expected: vec!["Lume".into()],
+ guests: Some("macOS".into()),
+ };
+ assert_eq!(
+ v(lume("0.5.3")),
+ RuntimePathVerdict {
+ ok: false,
+ line: "Lume 0.5.3 is too old (needs 0.6.0)".into()
+ }
+ );
+ assert_eq!(
+ v(lume("0.6.1")),
+ RuntimePathVerdict {
+ ok: true,
+ line: "Lume 0.6 found \u{b7} runs macOS only".into()
+ }
+ );
+ assert!(v(lume("0.10.0")).ok);
+ }
+
+ /// A kind that can't run here says so, and why, instead of its choices.
+ #[test]
+ fn a_kind_that_cannot_run_says_why() {
+ let intel = RuntimesInput {
+ os: Some(SpaceOs::Macos),
+ host_arch: Some("amd64".into()),
+ local_backends: Some(vec!["container".into()]),
+ ..Default::default()
+ };
+ let s = section(Some(&intel));
+ let vm = get(&s, "runtime:vm");
+ assert_eq!(
+ (vm.kind, vm.value.as_deref(), vm.help.as_deref()),
+ (
+ SettingsRowKind::Text,
+ Some(NOT_AVAILABLE),
+ Some("Virtual machines need a Mac with Apple silicon")
+ )
+ );
+ let micro = get(&s, "runtime:microvm");
+ assert_eq!(micro.value.as_deref(), Some(NOT_AVAILABLE));
+ assert_eq!(
+ micro.help.as_deref(),
+ Some("MicroVMs need a Mac with Apple silicon")
+ );
+ assert_eq!(get(&s, "runtime:container").kind, SettingsRowKind::Choice);
+ let old_mac = RuntimesInput {
+ host_arch: Some("arm64".into()),
+ local_backends: Some(vec!["lume".into(), "managed".into()]),
+ ..intel.clone()
+ };
+ assert_eq!(
+ get(&section(Some(&old_mac)), "runtime:microvm")
+ .help
+ .as_deref(),
+ Some("MicroVMs need macOS 26")
+ );
+ let linux = RuntimesInput {
+ os: Some(SpaceOs::Linux),
+ host_arch: Some("amd64".into()),
+ local_backends: Some(vec![]),
+ ..Default::default()
+ };
+ let s = section(Some(&linux));
+ assert_eq!(
+ get(&s, "runtime:container").help.as_deref(),
+ Some("Containers need Docker or Podman")
+ );
+ assert_eq!(
+ get(&s, "runtime:vm").help.as_deref(),
+ Some("Virtual machines need QEMU")
+ );
+ }
+
+ /// Cua's own is offered only where Cua has one.
+ #[test]
+ fn cuas_own_is_offered_where_cua_has_one() {
+ let linux = RuntimesInput {
+ os: Some(SpaceOs::Linux),
+ local_backends: Some(vec![
+ "container".into(),
+ "qemu".into(),
+ "firecracker".into(),
+ ]),
+ ..Default::default()
+ };
+ let s = section(Some(&linux));
+ let opts = |id: &str| {
+ get(&s, id)
+ .options
+ .iter()
+ .map(|o| o.id.clone())
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(opts("runtime:container"), ["auto", "system"]);
+ assert_eq!(opts("runtime:vm"), ["auto", "system"]);
+ assert_eq!(opts("runtime:microvm"), ["auto", "builtin", "system"]);
+ }
+
+ /// What each choice writes, and the precedence between the first
+ /// detected runtime (no path) and any other path.
+ #[test]
+ fn choices_write_the_per_kind_settings() {
+ let input = mac(vec![RuntimeKindInput {
+ kind: "container".into(),
+ source: Some("system".into()),
+ detected: Some(vec![docker(), podman()]),
+ ..Default::default()
+ }]);
+ let c = |row: &str, o: &str| choose(Some(&input), row, o);
+ let ch = |key: &str, value: Option<&str>| {
+ Some(RuntimeSettingChange {
+ key: key.into(),
+ value: value.map(str::to_string),
+ })
+ };
+ assert_eq!(
+ c("runtime:microvm", "system"),
+ ch("runtime.microvm", Some("system"))
+ );
+ assert_eq!(
+ c("runtime:vm", "builtin"),
+ ch("runtime.vm", Some("builtin"))
+ );
+ assert_eq!(
+ c("runtime-detected:container", "/usr/local/bin/docker"),
+ ch("runtime.container_path", None)
+ );
+ assert_eq!(
+ c("runtime-detected:container", "/opt/homebrew/bin/podman"),
+ ch("runtime.container_path", Some("/opt/homebrew/bin/podman"))
+ );
+ assert_eq!(
+ c("runtime-path:container", " /Users/me/bin/docker "),
+ ch("runtime.container_path", Some("/Users/me/bin/docker"))
+ );
+ assert_eq!(
+ c("runtime-path:container", ""),
+ ch("runtime.container_path", None)
+ );
+ assert_eq!(c("notch", "show"), None);
+ assert_eq!(c("runtime:nope", "auto"), None);
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/settings.rs b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
index 87a1895ef5..66d1681c49 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/settings.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
@@ -393,21 +393,6 @@ pub struct TelemetryInput {
pub notice_shown: bool,
}
-/// This machine's runtime doctor, for Settings, Advanced, Runtimes'
-/// MicroVM row (the same facts New Space's MicroVM tile follows).
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", default)]
-pub struct MicrovmInput {
- /// This machine's system (`macos`, `linux`, `windows`).
- pub os: Option<crate::model::SpaceOs>,
- /// Ready backends (none: not read yet).
- pub local_backends: Option<Vec<String>>,
- /// Why each other backend is not ready, by backend name.
- pub local_details: Option<std::collections::HashMap<String, String>>,
- /// This machine's architecture (`arm64`, `amd64`).
- pub host_arch: Option<String>,
-}
-
/// What the Settings page shows.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
@@ -457,22 +442,15 @@ pub struct SettingsInput {
/// "Connect to the desktop automatically" (none: no row; a shell
/// without the preview cover leaves it out).
pub auto_connect: Option<bool>,
- /// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,
- /// `system`); none: no Runtimes section.
- #[serde(default)]
- pub lume_source: Option<String>,
- /// Which engine local Linux Spaces run on (`runtime.linux`: `auto`,
- /// `builtin`, `system`); none: no Linux row.
- #[serde(default)]
- pub linux_source: Option<String>,
/// Overflow into your clouds when this machine is full
/// (`placement.overflow`); none: no row.
#[serde(default)]
pub overflow: Option<bool>,
- /// What this machine's runtime doctor said, for Runtimes' MicroVM row
- /// (whether microVMs run here, and why not); none: no MicroVM row.
+ /// Settings, Advanced's runtimes: each kind's setting, what is
+ /// installed for it and whether it runs here. None: nothing read yet
+ /// (the rows still show, "Checking…").
#[serde(default)]
- pub microvm: Option<MicrovmInput>,
+ pub runtimes: Option<crate::runtimes::RuntimesInput>,
/// Settings, General's Show tips switch: tips are on
/// (`!AppSettings.tips.off`). A shell that does not say reads as on.
#[serde(default = "default_true")]
@@ -499,10 +477,8 @@ impl Default for SettingsInput {
keyvault_site_icons: true,
keyvault_protection: vec![],
auto_connect: None,
- lume_source: None,
- linux_source: None,
overflow: None,
- microvm: None,
+ runtimes: None,
show_tips: true,
}
}
@@ -897,14 +873,8 @@ pub fn page(input: &SettingsInput) -> SettingsPage {
},
];
- if input.lume_source.is_some() || input.linux_source.is_some() || input.microvm.is_some() {
- let mut runtimes =
- runtimes_section(input.lume_source.as_deref(), input.linux_source.as_deref());
- if let Some(m) = &input.microvm {
- runtimes.rows.extend(microvm_rows(m));
- }
- sections.push(runtimes);
- }
+ // Every kind's runtime row, on every host, whatever is known yet.
+ sections.push(crate::runtimes::section(input.runtimes.as_ref()));
if let Some(t) = &input.telemetry {
let mut share = row("telemetry", Choice, "Share usage data to help improve Cua");
@@ -984,110 +954,6 @@ pub fn page(input: &SettingsInput) -> SettingsPage {
}
}
-/// The help under Settings, Runtimes, macOS VMs.
-pub const MACOS_RUNTIME_HELP: &str =
- "Built-in is Cua\u{2019}s signed Lume, downloaded the first time you need it (6 MB).";
-
-/// The help under Settings, Runtimes, Linux.
-pub const LINUX_RUNTIME_HELP: &str =
- "Built-in is a gVisor Linux VM, downloaded the first time you need it (480 MB).";
-
-/// Settings, Runtimes: one row per local runtime Cua can provide itself,
-/// each Automatic, Built-in or System.
-/// * macOS VMs (`macos-runtime`, `runtime.lume`'s values): Built-in is
-/// Cua's signed Lume, set up on first use; System this Mac's own Lume.
-/// * Linux (`linux-runtime`, `runtime.linux`'s values): Built-in is Cua's
-/// own VM with Docker and gVisor, set up on first use; System this Mac's
-/// own container engine; Automatic Docker when it runs, else built-in.
-pub fn runtimes_section(lume_source: Option<&str>, linux_source: Option<&str>) -> SettingsSection {
- use SettingsRowKind::*;
- let choice = |id: &str, label: &str, source: &str| {
- let source = match source {
- "builtin" | "system" => source,
- _ => "auto",
- };
- let mut r = row(id, Choice, label);
- r.options = vec![
- opt("auto", "Automatic", source == "auto"),
- opt("builtin", "Built-in", source == "builtin"),
- opt("system", "System", source == "system"),
- ];
- r
- };
- let mut rows = vec![];
- if let Some(source) = lume_source {
- rows.push(choice("macos-runtime", "macOS VMs", source));
- rows.push(row("macos-runtime-note", Note, MACOS_RUNTIME_HELP));
- }
- if let Some(source) = linux_source {
- rows.push(choice("linux-runtime", "Linux", source));
- rows.push(row("linux-runtime-note", Note, LINUX_RUNTIME_HELP));
- }
- SettingsSection {
- id: "runtimes".into(),
- title: "Runtimes".into(),
- button: None,
- button_enabled: false,
- button_help: None,
- rows,
- }
-}
-
-/// Runtimes' MicroVM row: whether this machine runs microVMs and on what,
-/// or why not (New Space only greys MicroVM out; the reason is told here).
-pub fn microvm_rows(m: &MicrovmInput) -> Vec<SettingsRow> {
- use crate::wizard::{LocalProbe, MicrovmStatus, microvm_status_of};
- use SettingsRowKind::*;
- let probe = LocalProbe {
- backends: m.local_backends.as_deref(),
- details: m.local_details.as_ref(),
- host_arch: m.host_arch.as_deref(),
- };
- let os = m.os.unwrap_or(crate::model::SpaceOs::Macos);
- let mut status = row("microvm-runtime", Text, "MicroVM");
- let note = match microvm_status_of(&probe, os) {
- MicrovmStatus::Checking => {
- status.value = Some("Checking\u{2026}".into());
- None
- }
- MicrovmStatus::Ready(runtimes) => {
- status.value = Some("Ready".into());
- let names: Vec<String> = runtimes.iter().map(|r| r.label()).collect();
- Some(row(
- "microvm-runtime-note",
- Note,
- &format!("MicroVM Spaces run on {}.", join_or(&names)),
- ))
- }
- MicrovmStatus::Blocked(why) => {
- status.value = Some("Not available".into());
- Some(row(
- "microvm-runtime-note",
- Error,
- &format!("MicroVM {}", lower_first(&why)),
- ))
- }
- };
- std::iter::once(status).chain(note).collect()
-}
-
-/// "A", "A or B", "A, B or C".
-fn join_or(names: &[String]) -> String {
- match names {
- [] => String::new(),
- [one] => one.clone(),
- [rest @ .., last] => format!("{} or {last}", rest.join(", ")),
- }
-}
-
-fn lower_first(s: &str) -> String {
- let mut c = s.chars();
- match c.next() {
- Some(f) => format!("{}{}", f.to_lowercase(), c.as_str()),
- None => String::new(),
- }
-}
-
/// The Settings page with Settings, Storage (the Cua Volume's store,
/// Finder volume and cache, [`crate::drive_settings::storage_section`])
/// after General, while the Cua Volume experiment is on. Off, Storage is
@@ -1119,93 +985,18 @@ pub fn with_storage(
mod tests {
use super::*;
+ /// Every host's page has the Runtimes section with the three kinds,
+ /// even before anything was read.
#[test]
- fn the_runtimes_section_shows_the_lume_choice() {
+ fn the_runtimes_section_is_always_there() {
let p = page(&SettingsInput::default());
- assert!(
- !p.sections.iter().any(|s| s.id == "runtimes"),
- "not until read"
- );
- let page = page(&SettingsInput {
- lume_source: Some("system".into()),
- ..Default::default()
- });
- let r = &page
- .sections
- .iter()
- .find(|s| s.id == "runtimes")
- .unwrap()
- .rows[0];
- assert_eq!(r.id, "macos-runtime");
- let active: Vec<_> = r
- .options
- .iter()
- .filter(|o| o.active)
- .map(|o| o.id.as_str())
- .collect();
- assert_eq!(active, ["system"]);
- let ids: Vec<_> = r.options.iter().map(|o| o.label.as_str()).collect();
- assert_eq!(ids, ["Automatic", "Built-in", "System"]);
- }
-
- #[test]
- fn runtimes_say_whether_microvms_run_here_and_why_not() {
- use crate::model::SpaceOs;
- let page_for = |m: MicrovmInput| {
- let p = page(&SettingsInput {
- microvm: Some(m),
- ..Default::default()
- });
- let s = p.sections.into_iter().find(|s| s.id == "runtimes").unwrap();
- s.rows
- .into_iter()
- .map(|r| (r.id, r.value.or(Some(r.label)).unwrap_or_default()))
- .collect::<Vec<_>>()
- };
- let mac = |ready: &[&str]| MicrovmInput {
- os: Some(SpaceOs::Macos),
- local_backends: Some(ready.iter().map(|b| b.to_string()).collect()),
- local_details: None,
- host_arch: Some("arm64".into()),
- };
- assert_eq!(
- page_for(mac(&["docker", "vz", "containerization"])),
- [
- ("microvm-runtime".to_string(), "Ready".to_string()),
- (
- "microvm-runtime-note".to_string(),
- "MicroVM Spaces run on Virtualization.framework or Apple Containerization."
- .to_string()
- ),
- ]
- );
- assert_eq!(
- page_for(mac(&["docker"])),
- [
- ("microvm-runtime".to_string(), "Not available".to_string()),
- (
- "microvm-runtime-note".to_string(),
- "MicroVM needs macOS 26.".to_string()
- ),
- ]
- );
- assert_eq!(
- page_for(MicrovmInput {
- local_backends: None,
- ..mac(&[])
- }),
- [(
- "microvm-runtime".to_string(),
- "Checking\u{2026}".to_string()
- )]
- );
- // Without the doctor's answer, no MicroVM row (and no section).
- assert!(
- page(&SettingsInput::default())
- .sections
- .iter()
- .all(|s| s.id != "runtimes")
- );
+ let s = p.sections.iter().find(|s| s.id == "runtimes").unwrap();
+ let ids: Vec<_> = s.rows.iter().map(|r| r.id.as_str()).collect();
+ assert_eq!(ids, ["runtime:container", "runtime:vm", "runtime:microvm"]);
+ // After General.
+ let order: Vec<_> = p.sections.iter().map(|s| s.id.as_str()).collect();
+ let at = |id: &str| order.iter().position(|s| *s == id).unwrap();
+ assert!(at("general") < at("runtimes"));
}
#[test]
@@ -1226,39 +1017,6 @@ mod tests {
assert!(!damaged_path(&ok).exists());
}
- #[test]
- fn the_runtimes_section_shows_the_linux_choice() {
- let page = page(&SettingsInput {
- lume_source: Some("auto".into()),
- linux_source: Some("builtin".into()),
- ..Default::default()
- });
- let s = page.sections.iter().find(|s| s.id == "runtimes").unwrap();
- let ids: Vec<_> = s.rows.iter().map(|r| r.id.as_str()).collect();
- assert_eq!(
- ids,
- [
- "macos-runtime",
- "macos-runtime-note",
- "linux-runtime",
- "linux-runtime-note"
- ]
- );
- let linux = &s.rows[2];
- assert_eq!(linux.label, "Linux");
- let active: Vec<_> = linux
- .options
- .iter()
- .filter(|o| o.active)
- .map(|o| o.id.as_str())
- .collect();
- assert_eq!(active, ["builtin"]);
- // An unknown word reads as Automatic.
- let r = runtimes_section(None, Some("docker"));
- assert_eq!(r.rows[0].id, "linux-runtime");
- assert!(r.rows[0].options[0].active);
- }
-
#[test]
fn hotkeys_need_a_modifier() {
let c = KeyCombo {
@@ -1402,7 +1160,7 @@ mod tests {
fn the_page_lists_account_general_privacy_agents() {
let p = page(&SettingsInput::default());
let ids: Vec<_> = p.sections.iter().map(|s| s.id.as_str()).collect();
- assert_eq!(ids, ["account", "teams", "general", "agents"]);
+ assert_eq!(ids, ["account", "teams", "general", "runtimes", "agents"]);
let p = page(&SettingsInput {
identity: Some("[email protected]".into()),
can_sign_out: true,
@@ -1410,7 +1168,12 @@ mod tests {
..Default::default()
});
let ids: Vec<_> = p.sections.iter().map(|s| s.id.as_str()).collect();
- assert_eq!(ids, ["account", "teams", "general", "privacy", "agents"]);
+ assert_eq!(
+ ids,
+ [
+ "account", "teams", "general", "runtimes", "privacy", "agents"
+ ]
+ );
assert_eq!(p.sections[0].rows[0].button.as_deref(), Some("Sign out"));
let sign_in: SignInPhase =
serde_json::from_str(r#"{"kind":"waiting","userCode":"AB-CD"}"#).unwrap();
@@ -1437,10 +1200,10 @@ mod tests {
assert_eq!(
ids(&p),
[
- "account", "teams", "general", "privacy", "keyvault", "agents"
+ "account", "teams", "general", "runtimes", "privacy", "keyvault", "agents"
]
);
- let kv = &p.sections[4];
+ let kv = &p.sections[5];
assert_eq!(kv.title, "Keyvault");
let toggle = &kv.rows[0];
assert_eq!(
@@ -1615,7 +1378,10 @@ mod tests {
.map(|r| r.label.clone())
};
let off = with_storage(&page(&input), &storage, &input.experiments);
- assert_eq!(ids(&off), ["account", "teams", "general", "agents"]);
+ assert_eq!(
+ ids(&off),
+ ["account", "teams", "general", "runtimes", "agents"]
+ );
assert_eq!(note(&off).as_deref(), Some(NOTE_WITHOUT_VOLUME));
let on = SettingsInput {
experiments: Experiments {
@@ -1627,7 +1393,9 @@ mod tests {
let p = with_storage(&page(&on), &storage, &on.experiments);
assert_eq!(
ids(&p),
- ["account", "teams", "general", "storage", "agents"]
+ [
+ "account", "teams", "general", "storage", "runtimes", "agents"
+ ]
);
assert_eq!(note(&p).as_deref(), Some(NOTE));
// A settings file from before experiments: all off.
diff --git a/libs/cua/crates/cua-spaces-app-core/src/summon.rs b/libs/cua/crates/cua-spaces-app-core/src/summon.rs
new file mode 100644
index 0000000000..8b3d1abd0d
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/summon.rs
@@ -0,0 +1,650 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! @mentioning an agent in a Space's composer: who the picker offers, what
+//! sending does for each @mention, and what the thread says when an agent
+//! can't be woken.
+//!
+//! - **The picker** ([`candidates`]): the agents already in the Space, then
+//! each agent that can start in it (`agent_add`) under a free handle.
+//! - **Sending** ([`plan`]): the message is always posted. Each @mention of
+//! an agent in the Space wakes it (the thread does that); an @mention of an
+//! agent that isn't in the Space yet adds it first, asleep, so the posted
+//! message wakes it. An agent whose app has no sign-in it can use in a
+//! Space is not added: the step says why ([`CantWake`]), and the thread
+//! shows that under the message with Connect.
+//! - **Ask first** ([`first_message`]): the job is posted as `@<handle> <job>`,
+//! the same summon as a message typed in the Space.
+//!
+//! The @mention grammar is the thread's (`cua_spaces_ext::thread::parse_mentions`).
+
+use serde::{Deserialize, Serialize};
+
+use crate::connectors::{self, ConnectorsInput};
+
+/// An agent that can start in a Space (`agent_add`'s harnesses), with the
+/// handle it gets and its name.
+struct Startable {
+ harness: &'static str,
+ handle: &'static str,
+ label: &'static str,
+ /// The setup id its sign-in is checked under (Settings, Connectors).
+ app: &'static str,
+}
+
+const STARTABLE: &[Startable] = &[
+ Startable {
+ harness: "claude-code",
+ handle: "claude",
+ label: "Claude Code",
+ app: "claude-code",
+ },
+ Startable {
+ harness: "openai-codex",
+ handle: "codex",
+ label: "Codex",
+ app: "codex",
+ },
+ Startable {
+ harness: "hermes",
+ handle: "hermes",
+ label: "Hermes",
+ app: "hermes",
+ },
+ Startable {
+ harness: "openclaw",
+ handle: "openclaw",
+ label: "OpenClaw",
+ app: "openclaw",
+ },
+];
+
+/// The harness an agent id runs as in a Space: Ask first's ids are the
+/// harness ids (`openai-codex`); `codex` is the app's setup id for it.
+fn harness_of(id: &str) -> &str {
+ match id {
+ "codex" => "openai-codex",
+ other => other,
+ }
+}
+
+fn startable(harness: &str) -> Option<&'static Startable> {
+ STARTABLE.iter().find(|s| s.harness == harness_of(harness))
+}
+
+/// `@name` tokens in `text` (lowercased, deduplicated, in order), as the
+/// thread reads them: `a-z`, `0-9`, `.`, `_`, `-`; a trailing `.` or `-`
+/// ends the sentence, not the name; an `@` inside a word (an email) is not
+/// a mention.
+pub fn parse_mentions(text: &str) -> Vec<String> {
+ let mut out: Vec<String> = vec![];
+ let chars: Vec<char> = text.chars().collect();
+ let mut i = 0;
+ while i < chars.len() {
+ if chars[i] == '@' && (i == 0 || !(chars[i - 1].is_alphanumeric() || chars[i - 1] == '_')) {
+ let mut j = i + 1;
+ let mut name = String::new();
+ while j < chars.len() {
+ let c = chars[j].to_ascii_lowercase();
+ if c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-') {
+ name.push(c);
+ j += 1;
+ } else {
+ break;
+ }
+ }
+ let name = name.trim_end_matches(['.', '-']).to_string();
+ let valid = !name.is_empty()
+ && name.len() <= 64
+ && name
+ .chars()
+ .next()
+ .is_some_and(|c| c.is_ascii_alphanumeric());
+ if valid && !out.contains(&name) {
+ out.push(name);
+ }
+ i = j.max(i + 1);
+ } else {
+ i += 1;
+ }
+ }
+ out
+}
+
+/// An agent already in the Space.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SummonMember {
+ pub handle: String,
+ /// `claude-code`, `codex`, ... (empty when the thread doesn't say).
+ pub harness: String,
+ pub label: String,
+}
+
+/// What summoning reads.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SummonInput {
+ pub members: Vec<SummonMember>,
+ /// People's handles, so a new agent never takes one.
+ pub people: Vec<String>,
+ /// Agents can be added to this Space (`thread.agentAdd` there, and you may post).
+ pub can_add: bool,
+ /// Coding apps and saved sign-ins (Settings, Connectors).
+ pub connectors: ConnectorsInput,
+}
+
+/// A row in the composer's @ picker.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SummonCandidate {
+ pub handle: String,
+ pub label: String,
+ pub harness: String,
+ /// Already in the Space.
+ pub member: bool,
+ /// "In this Space", "Starts in this Space", "Not connected yet".
+ pub detail: String,
+}
+
+/// A free handle: `base`, else `base-2`, ...
+fn free_handle(base: &str, taken: &[String]) -> String {
+ let taken: Vec<String> = taken.iter().map(|t| t.to_ascii_lowercase()).collect();
+ if !taken.iter().any(|t| t == base) {
+ return base.into();
+ }
+ (2..)
+ .map(|n| format!("{base}-{n}"))
+ .find(|h| !taken.contains(h))
+ .unwrap_or_else(|| base.into())
+}
+
+fn taken(input: &SummonInput) -> Vec<String> {
+ input
+ .members
+ .iter()
+ .map(|m| m.handle.clone())
+ .chain(input.people.iter().cloned())
+ .collect()
+}
+
+/// The handle a new `harness` agent gets in this Space.
+fn new_handle(input: &SummonInput, s: &Startable) -> String {
+ free_handle(s.handle, &taken(input))
+}
+
+/// The agents the picker offers: those in the Space first, then each one
+/// that can start in it (one per kind not already there).
+pub fn candidates(input: &SummonInput) -> Vec<SummonCandidate> {
+ let mut out: Vec<SummonCandidate> = input
+ .members
+ .iter()
+ .map(|m| SummonCandidate {
+ handle: m.handle.clone(),
+ label: m.label.clone(),
+ harness: m.harness.clone(),
+ member: true,
+ detail: "In this Space".into(),
+ })
+ .collect();
+ if input.can_add {
+ for s in STARTABLE {
+ if input.members.iter().any(|m| m.harness == s.harness) {
+ continue;
+ }
+ let ready = connectors::signed_in(&input.connectors, s.app);
+ out.push(SummonCandidate {
+ handle: new_handle(input, s),
+ label: s.label.into(),
+ harness: s.harness.into(),
+ member: false,
+ detail: if ready {
+ "Starts in this Space".into()
+ } else {
+ "Not connected yet".into()
+ },
+ });
+ }
+ }
+ out
+}
+
+/// Why an agent can't be woken, and what the thread offers under the message.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CantWake {
+ /// `not-connected` (no sign-in it can use), `cant-add` (this Space can't
+ /// add agents), `failed` (adding or waking it failed).
+ pub reason: String,
+ pub handle: String,
+ pub harness: String,
+ /// The agent's name ("Claude Code").
+ pub name: String,
+ /// The setup id Connect runs for (Settings, Connectors).
+ pub app: String,
+ /// "Claude Code isn't connected yet".
+ pub text: String,
+ pub detail: String,
+ /// "Connect Claude Code" (absent when Connect can't help).
+ pub connect_label: Option<String>,
+ /// While Connect runs.
+ pub connecting_label: String,
+ /// The app's page in Settings, Connectors ("Claude Code settings").
+ pub open_label: Option<String>,
+ /// Once connected: the message goes again.
+ pub retry_label: String,
+ /// After the retry.
+ pub retried_text: String,
+ /// Only you see it: it is about this device's sign-ins, never posted to the thread.
+ pub only_you: bool,
+ pub only_you_label: String,
+ pub dismiss_label: String,
+}
+
+fn cant_wake(
+ input: &SummonInput,
+ s: &Startable,
+ handle: &str,
+ reason: &str,
+ error: Option<&str>,
+) -> CantWake {
+ let name = s.label;
+ let plan = connectors::connect_plan(&input.connectors, s.app);
+ let providers: Vec<&str> = connectors::app_providers(s.app)
+ .iter()
+ .filter_map(|p| connectors::provider_label(p))
+ .collect();
+ let (text, detail, connect) = match reason {
+ "not-connected" => (
+ format!("{name} isn't connected yet"),
+ if providers.is_empty() {
+ format!("Connect {name} so it can work in your Spaces.")
+ } else {
+ format!(
+ "It needs a sign-in to {} to work in your Spaces. Your message is saved: it goes again once {name} is connected.",
+ providers.join(" or ")
+ )
+ },
+ true,
+ ),
+ "cant-add" => (
+ format!("{name} can't join this Space"),
+ "This Space can't add agents. Ask its owner, or use another Space.".to_string(),
+ false,
+ ),
+ _ => (
+ format!("{name} couldn't start"),
+ error
+ .map(str::to_string)
+ .unwrap_or_else(|| "Something went wrong. Send it again to try once more.".into()),
+ false,
+ ),
+ };
+ let in_settings = input
+ .connectors
+ .apps
+ .iter()
+ .any(|a| a.agent == s.app && a.installed);
+ CantWake {
+ reason: reason.into(),
+ handle: handle.into(),
+ harness: s.harness.into(),
+ name: name.into(),
+ app: s.app.into(),
+ text,
+ detail,
+ connect_label: connect.then(|| format!("Connect {name}")),
+ connecting_label: if plan.app_token {
+ "Approve in your browser…".into()
+ } else if plan.device {
+ "Enter the code in your browser…".into()
+ } else {
+ "Connecting…".into()
+ },
+ open_label: in_settings.then(|| format!("{name} settings")),
+ retry_label: "Send again".into(),
+ retried_text: format!("{name} is connected. Sent again."),
+ only_you: true,
+ only_you_label: ONLY_YOU.into(),
+ dismiss_label: "Dismiss".into(),
+ }
+}
+
+/// The label on everything in a thread that only this device shows.
+pub const ONLY_YOU: &str = "Only visible to you";
+
+/// A line in the thread that only you see (it is never posted): a message
+/// waiting for its Space, or a note about this device.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalNote {
+ pub text: String,
+ pub only_you: bool,
+ pub only_you_label: String,
+ /// Absent where dismissing makes no sense (a queued message goes once the Space is ready).
+ pub dismiss_label: Option<String>,
+}
+
+/// The line under a message written while its Space is being made (`creating`),
+/// or while it is being sent just after.
+pub fn queued_note(creating: bool) -> LocalNote {
+ LocalNote {
+ text: if creating {
+ "Sends when the Space is ready"
+ } else {
+ "Sending…"
+ }
+ .into(),
+ only_you: true,
+ only_you_label: ONLY_YOU.into(),
+ dismiss_label: None,
+ }
+}
+
+/// What sending does for one @mention.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SummonStep {
+ pub handle: String,
+ pub harness: String,
+ /// `wake` (in the Space: the posted message wakes it), `add` (add it
+ /// asleep under `handle` first, then post), `blocked` (post only; see
+ /// `cant_wake`).
+ pub action: String,
+ pub cant_wake: Option<CantWake>,
+}
+
+/// What sending `text` does: the steps before and around posting it, one
+/// per @mentioned agent. People and unknown handles have no step.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SummonPlan {
+ pub steps: Vec<SummonStep>,
+}
+
+/// Resolves an @handle to an agent kind not yet in the Space: its own handle
+/// (`@claude`), or the free handle the picker offered (`@claude-2`).
+fn startable_for(input: &SummonInput, handle: &str) -> Option<&'static Startable> {
+ STARTABLE.iter().find(|s| {
+ !input.members.iter().any(|m| m.harness == s.harness)
+ && (handle == s.handle || handle == new_handle(input, s))
+ })
+}
+
+pub fn plan(input: &SummonInput, text: &str) -> SummonPlan {
+ let steps = parse_mentions(text)
+ .into_iter()
+ .filter_map(|h| {
+ if let Some(m) = input
+ .members
+ .iter()
+ .find(|m| m.handle.eq_ignore_ascii_case(&h))
+ {
+ // In the Space already: the posted message wakes it. It runs on
+ // its owner's keys, which this device can't see, so nothing is
+ // checked here; the thread says if it can't start.
+ return Some(SummonStep {
+ handle: m.handle.clone(),
+ harness: m.harness.clone(),
+ action: "wake".into(),
+ cant_wake: None,
+ });
+ }
+ let s = startable_for(input, &h)?;
+ let blocked = if !input.can_add {
+ Some(cant_wake(input, s, &h, "cant-add", None))
+ } else if !connectors::signed_in(&input.connectors, s.app) {
+ Some(cant_wake(input, s, &h, "not-connected", None))
+ } else {
+ None
+ };
+ Some(SummonStep {
+ handle: h.clone(),
+ harness: s.harness.into(),
+ action: if blocked.is_some() { "blocked" } else { "add" }.into(),
+ cant_wake: blocked,
+ })
+ })
+ .collect();
+ SummonPlan { steps }
+}
+
+/// The note for an agent whose add or wake failed with `error` (the host's words).
+pub fn failed(input: &SummonInput, harness: &str, handle: &str, error: &str) -> Option<CantWake> {
+ let s = startable(harness)?;
+ // `ANTHROPIC_API_KEY is not set` reads as "api key".
+ let e = error.to_ascii_lowercase().replace('_', " ");
+ let reason = if [
+ "api key",
+ "sign in",
+ "signed in",
+ "credential",
+ "unauthorized",
+ "401",
+ "login",
+ "auth",
+ ]
+ .iter()
+ .any(|w| e.contains(w))
+ {
+ "not-connected"
+ } else {
+ "failed"
+ };
+ Some(cant_wake(input, s, handle, reason, Some(error)))
+}
+
+/// Ask first's job, as the Space's first message: `@<handle> <job>`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FirstMessage {
+ /// What is posted.
+ pub text: String,
+ /// The agent's handle in the Space (null: this agent can't join a Space; the job is posted as typed).
+ pub handle: Option<String>,
+ pub harness: String,
+}
+
+/// `agent`'s first message for `prompt` (`agent` is Ask first's id).
+pub fn first_message(input: &SummonInput, agent: &str, prompt: &str) -> FirstMessage {
+ let prompt = prompt.trim();
+ let harness = harness_of(agent).to_string();
+ let handle = input
+ .members
+ .iter()
+ .find(|m| m.harness == harness)
+ .map(|m| m.handle.clone())
+ .or_else(|| startable(&harness).map(|s| new_handle(input, s)));
+ FirstMessage {
+ text: match &handle {
+ Some(h) => format!("@{h} {prompt}"),
+ None => prompt.to_string(),
+ },
+ handle,
+ harness,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::agent_keys::AgentKeyInput;
+ use crate::connectors::ConnectorAppInput;
+
+ fn input(keys: &[&str]) -> SummonInput {
+ SummonInput {
+ members: vec![SummonMember {
+ handle: "hermes".into(),
+ harness: "hermes".into(),
+ label: "Hermes".into(),
+ }],
+ people: vec!["grace".into()],
+ can_add: true,
+ connectors: ConnectorsInput {
+ apps: vec![ConnectorAppInput {
+ agent: "claude-code".into(),
+ name: "Claude Code".into(),
+ installed: true,
+ ..Default::default()
+ }],
+ keys: crate::agent_keys::AgentKeysInput {
+ keys: keys
+ .iter()
+ .map(|e| AgentKeyInput {
+ provider: "other".into(),
+ env: (*e).into(),
+ last4: "abcd".into(),
+ added_ms: 1,
+ })
+ .collect(),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ }
+ }
+
+ #[test]
+ fn mentions_read_as_the_thread_reads_them() {
+ assert_eq!(
+ parse_mentions("@claude run it, then @Codex. cc [email protected] and @x"),
+ vec!["claude", "codex", "x"]
+ );
+ assert_eq!(parse_mentions("@re.view-1."), vec!["re.view-1"]);
+ assert!(parse_mentions("@ @-").is_empty());
+ assert_eq!(parse_mentions("@claude @claude"), vec!["claude"]);
+ }
+
+ #[test]
+ fn picker_lists_members_then_agents_that_can_start() {
+ let c = candidates(&input(&[]));
+ assert_eq!(c[0].handle, "hermes");
+ assert!(c[0].member);
+ let rest: Vec<_> = c[1..].iter().map(|c| c.handle.as_str()).collect();
+ assert_eq!(rest, ["claude", "codex", "openclaw"]);
+ assert_eq!(c[1].label, "Claude Code");
+ assert_eq!(c[1].detail, "Not connected yet");
+ let c = candidates(&input(&["CLAUDE_CODE_OAUTH_TOKEN"]));
+ assert_eq!(c[1].detail, "Starts in this Space");
+ // A Space that can't add agents offers only its members.
+ let mut i = input(&[]);
+ i.can_add = false;
+ assert_eq!(candidates(&i).len(), 1);
+ }
+
+ #[test]
+ fn a_new_agent_never_takes_a_used_handle() {
+ let mut i = input(&[]);
+ i.people.push("claude".into());
+ let c = candidates(&i);
+ assert_eq!(
+ c.iter()
+ .find(|c| c.harness == "claude-code")
+ .unwrap()
+ .handle,
+ "claude-2"
+ );
+ let p = plan(&i, "@claude-2 hi");
+ assert_eq!(p.steps[0].harness, "claude-code");
+ }
+
+ #[test]
+ fn sending_adds_wakes_or_says_why_not() {
+ // Signed in: Claude Code is added, then woken by the message; Hermes,
+ // in the Space, is woken; people and unknown names have no step.
+ let i = input(&["CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY"]);
+ let p = plan(
+ &i,
+ "@claude fix the build, @hermes review, cc @grace @nobody",
+ );
+ let s: Vec<_> = p
+ .steps
+ .iter()
+ .map(|s| (s.handle.as_str(), s.action.as_str()))
+ .collect();
+ assert_eq!(s, [("claude", "add"), ("hermes", "wake")]);
+
+ // No sign-in: blocked, with Connect.
+ let p = plan(&input(&[]), "@claude fix the build");
+ let st = &p.steps[0];
+ assert_eq!(st.action, "blocked");
+ let c = st.cant_wake.as_ref().unwrap();
+ assert_eq!(c.reason, "not-connected");
+ assert_eq!(c.text, "Claude Code isn't connected yet");
+ assert_eq!(c.connect_label.as_deref(), Some("Connect Claude Code"));
+ assert_eq!(c.open_label.as_deref(), Some("Claude Code settings"));
+ assert_eq!(c.retry_label, "Send again");
+ assert_eq!(c.connecting_label, "Approve in your browser…");
+ assert!(c.detail.contains("sign-in to Anthropic"));
+
+ // A member runs on its owner's keys: woken, never checked against this device's.
+ let p = plan(&input(&[]), "@hermes go");
+ assert_eq!(p.steps[0].action, "wake");
+ // A new Hermes needs Anthropic or OpenAI.
+ let mut i = input(&[]);
+ i.members.clear();
+ let c = plan(&i, "@hermes go").steps[0].cant_wake.clone().unwrap();
+ assert!(c.detail.contains("Anthropic or OpenAI"));
+
+ // Codex isn't on This Mac: no settings page to open; Connect still asks for a key.
+ let c = plan(&input(&[]), "@codex go").steps[0]
+ .cant_wake
+ .clone()
+ .unwrap();
+ assert_eq!(c.open_label, None);
+ assert_eq!(c.connecting_label, "Connecting…");
+
+ // A Space that can't add agents says so, without Connect.
+ let mut i = input(&["CLAUDE_CODE_OAUTH_TOKEN"]);
+ i.can_add = false;
+ let c = plan(&i, "@claude go").steps[0].cant_wake.clone().unwrap();
+ assert_eq!(c.reason, "cant-add");
+ assert_eq!(c.connect_label, None);
+ }
+
+ #[test]
+ fn device_notes_say_only_you_see_them() {
+ let c = plan(&input(&[]), "@claude go").steps[0]
+ .cant_wake
+ .clone()
+ .unwrap();
+ assert!(c.only_you);
+ assert_eq!(c.only_you_label, "Only visible to you");
+ assert_eq!(c.dismiss_label, "Dismiss");
+ let q = queued_note(true);
+ assert!(q.only_you);
+ assert_eq!(q.text, "Sends when the Space is ready");
+ assert_eq!(q.dismiss_label, None);
+ assert_eq!(queued_note(false).text, "Sending…");
+ }
+
+ #[test]
+ fn a_failed_add_reads_as_its_reason() {
+ let i = input(&[]);
+ let c = failed(&i, "claude-code", "claude", "ANTHROPIC_API_KEY is not set").unwrap();
+ assert_eq!(c.reason, "not-connected");
+ let c = failed(&i, "claude-code", "claude", "disk full").unwrap();
+ assert_eq!(c.reason, "failed");
+ assert_eq!(c.text, "Claude Code couldn't start");
+ assert_eq!(c.detail, "disk full");
+ assert!(failed(&i, "nope", "x", "e").is_none());
+ }
+
+ #[test]
+ fn ask_first_posts_the_job_with_a_mention() {
+ let i = input(&[]);
+ let m = first_message(&i, "claude-code", " fix the build ");
+ assert_eq!(m.text, "@claude fix the build");
+ assert_eq!(m.handle.as_deref(), Some("claude"));
+ let m = first_message(&i, "openai-codex", "go");
+ assert_eq!(
+ (m.text.as_str(), m.harness.as_str()),
+ ("@codex go", "openai-codex")
+ );
+ // An agent already in the Space keeps its handle.
+ assert_eq!(first_message(&i, "hermes", "go").text, "@hermes go");
+ // An agent that can't join a Space: the job as typed.
+ let m = first_message(&i, "goose", "go");
+ assert_eq!((m.text.as_str(), m.handle), ("go", None));
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
index 6d86a49069..db18b5748c 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
@@ -4197,7 +4197,7 @@ pub const OFFER_NOT_CHECKED: &str = "Still checking this computer.";
pub const MACOS_NEEDS_APPLE_SILICON: &str = "macOS Spaces need a Mac with Apple silicon.";
/// `arm64` or `amd64` for an architecture name (`aarch64`, `x86_64`, `x64`).
-fn arch_word(arch: Option<&str>) -> Option<&'static str> {
+pub(crate) fn arch_word(arch: Option<&str>) -> Option<&'static str> {
match arch?.to_ascii_lowercase().as_str() {
"arm64" | "aarch64" => Some("arm64"),
"amd64" | "x86_64" | "x64" => Some("amd64"),
diff --git a/libs/cua/crates/cua-spaces-app-core/tests/summon_harnesses.rs b/libs/cua/crates/cua-spaces-app-core/tests/summon_harnesses.rs
new file mode 100644
index 0000000000..ef489cb37d
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/tests/summon_harnesses.rs
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Drift guard: every agent the composer's @ picker offers to start in a
+//! Space (`summon.candidates`) is a harness `agent_add` knows, so picking it
+//! adds a member instead of failing with "unknown harness".
+
+use cua_spaces_app_core::connectors::ConnectorsInput;
+use cua_spaces_app_core::summon::{SummonInput, candidates, plan};
+
+fn input() -> SummonInput {
+ SummonInput {
+ members: vec![],
+ people: vec![],
+ can_add: true,
+ connectors: ConnectorsInput::default(),
+ }
+}
+
+#[test]
+fn every_agent_the_picker_starts_is_a_real_harness() {
+ let c = candidates(&input());
+ assert!(!c.is_empty());
+ for c in &c {
+ assert!(
+ cua_agents::harness::harness(&c.harness).is_some(),
+ "@{} starts harness {:?}, which agent_add doesn't know (known: {:?})",
+ c.handle,
+ c.harness,
+ cua_agents::harness::ids()
+ );
+ }
+}
+
+#[test]
+fn mentioning_codex_adds_the_openai_codex_harness() {
+ let p = plan(&input(), "@codex look at this");
+ let step = p
+ .steps
+ .iter()
+ .find(|s| s.handle == "codex")
+ .expect("a step for @codex");
+ assert_eq!(step.harness, "openai-codex");
+}
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
index bc4ecb6cb6..93f2e93cf2 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -2194,6 +2194,25 @@ pub fn app_settings_page(input: AppSettingsInput) -> AppSettingsPage {
core::settings::page(&input)
}
+/// A runtime binary's one line in Settings, Advanced ("Docker 27.3 found",
+/// "Not a Docker or Podman binary").
+#[uniffi::export]
+pub fn app_runtime_path_verdict(check: AppRuntimePathCheck) -> AppRuntimePathVerdict {
+ core::runtimes::path_verdict(&check)
+}
+
+/// The setting a runtime row's choice changes (`runtime.<kind>` or
+/// `runtime.<kind>_path`; a `None` value unsets it), or none for any other
+/// row.
+#[uniffi::export]
+pub fn app_runtimes_choose(
+ input: Option<AppRuntimesInput>,
+ row: String,
+ option: String,
+) -> Option<AppRuntimeSettingChange> {
+ core::runtimes::choose(input.as_ref(), &row, &option)
+}
+
/// The Settings page with Settings, Storage after General while the Cua
/// Volume experiment is on (left out while it is off).
#[uniffi::export]
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.rs
index 99dae7ef08..236195e234 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
@@ -6889,6 +6889,94 @@ pub struct AppExperiments {
pub web_ui: bool,
}
+/// A runtime the host found for one kind (the SDK's `RuntimeDetected`).
+pub type AppDetectedRuntime = core::runtimes::DetectedRuntime;
+#[uniffi::remote(Record)]
+pub struct AppDetectedRuntime {
+ /// `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ pub tool: String,
+ /// As people know it (`Docker`, `Apple container`).
+ pub name: String,
+ pub path: String,
+ /// As its `--version` says it (`27.3.1`).
+ pub version: Option<String>,
+ /// The one guest system it runs, when only one (`macOS`, `Linux`).
+ pub guests: Option<String>,
+}
+
+/// What a binary is for one kind (the SDK's `RuntimePathProbe`).
+pub type AppRuntimePathCheck = core::runtimes::RuntimePathCheck;
+#[uniffi::remote(Record)]
+pub struct AppRuntimePathCheck {
+ pub path: String,
+ /// A file is there.
+ pub exists: bool,
+ /// It can be run.
+ pub executable: bool,
+ /// The tool it is, when it is one the kind takes.
+ pub tool: Option<String>,
+ pub name: Option<String>,
+ pub version: Option<String>,
+ /// The oldest version Cua runs on.
+ pub min_version: Option<String>,
+ /// The tools the kind takes here (`Docker`, `Podman`).
+ pub expected: Vec<String>,
+ pub guests: Option<String>,
+}
+
+/// One kind as the host read it (the SDK's `RuntimeKindState`).
+pub type AppRuntimeKindInput = core::runtimes::RuntimeKindInput;
+#[uniffi::remote(Record)]
+pub struct AppRuntimeKindInput {
+ /// `container`, `vm` or `microvm`.
+ pub kind: String,
+ /// `runtime.<kind>`: `auto`, `builtin`, `system` (none: auto).
+ pub source: Option<String>,
+ /// `runtime.<kind>_path`, when set.
+ pub path: Option<String>,
+ /// What is installed for the kind, the one used first (none: not
+ /// looked for yet).
+ pub detected: Option<Vec<AppDetectedRuntime>>,
+ /// The path in use, probed.
+ pub check: Option<AppRuntimePathCheck>,
+ /// The tools the kind takes on this machine (`Docker`, `Podman`).
+ pub expected: Vec<String>,
+}
+
+/// What Settings knows about this machine's runtimes.
+pub type AppRuntimesInput = core::runtimes::RuntimesInput;
+#[uniffi::remote(Record)]
+pub struct AppRuntimesInput {
+ /// This machine's system (none: not said; every option is offered).
+ pub os: Option<AppSpaceOs>,
+ /// `arm64`, `amd64`.
+ pub host_arch: Option<String>,
+ /// The runtime doctor's ready backends (none: not read yet).
+ pub local_backends: Option<Vec<String>>,
+ /// Why each other backend is not ready.
+ pub local_details: Option<std::collections::HashMap<String, String>>,
+ /// Each kind's setting and what is installed for it (none: not read).
+ pub kinds: Option<Vec<AppRuntimeKindInput>>,
+}
+
+/// A path's one line: whether it can be used, and what it is.
+pub type AppRuntimePathVerdict = core::runtimes::RuntimePathVerdict;
+#[uniffi::remote(Record)]
+pub struct AppRuntimePathVerdict {
+ pub ok: bool,
+ pub line: String,
+}
+
+/// What a row in the section changes: the setting and its new value
+/// (`None`: unset it, back to the default or the detected path).
+pub type AppRuntimeSettingChange = core::runtimes::RuntimeSettingChange;
+#[uniffi::remote(Record)]
+pub struct AppRuntimeSettingChange {
+ /// `runtime.container`, `runtime.vm_path`.
+ pub key: String,
+ pub value: Option<String>,
+}
+
/// Notch island or glass.
pub type AppSwitcherTheme = core::settings::SwitcherTheme;
#[uniffi::remote(Enum)]
@@ -7017,21 +7105,6 @@ pub struct AppTelemetryInput {
pub notice_shown: bool,
}
-/// This machine's runtime doctor, for Settings, Advanced, Runtimes'
-/// MicroVM row (the same facts New Space's MicroVM tile follows).
-pub type AppMicrovmInput = core::settings::MicrovmInput;
-#[uniffi::remote(Record)]
-pub struct AppMicrovmInput {
- /// This machine's system (`macos`, `linux`, `windows`).
- pub os: Option<AppSpaceOs>,
- /// Ready backends (none: not read yet).
- pub local_backends: Option<Vec<String>>,
- /// Why each other backend is not ready, by backend name.
- pub local_details: Option<std::collections::HashMap<String, String>>,
- /// This machine's architecture (`arm64`, `amd64`).
- pub host_arch: Option<String>,
-}
-
/// What the Settings page shows.
pub type AppSettingsInput = core::settings::SettingsInput;
#[uniffi::remote(Record)]
@@ -7078,18 +7151,13 @@ pub struct AppSettingsInput {
/// "Connect to the desktop automatically" (none: no row; a shell
/// without the preview cover leaves it out).
pub auto_connect: Option<bool>,
- /// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,
- /// `system`); none: no Runtimes section.
- pub lume_source: Option<String>,
- /// Which engine local Linux Spaces run on (`runtime.linux`: `auto`,
- /// `builtin`, `system`); none: no Linux row.
- pub linux_source: Option<String>,
/// Overflow into your clouds when this machine is full
/// (`placement.overflow`); none: no row.
pub overflow: Option<bool>,
- /// What this machine's runtime doctor said, for Runtimes' MicroVM row
- /// (whether microVMs run here, and why not); none: no MicroVM row.
- pub microvm: Option<AppMicrovmInput>,
+ /// Settings, Advanced's runtimes: each kind's setting, what is
+ /// installed for it and whether it runs here. None: nothing read yet
+ /// (the rows still show, "Checking…").
+ pub runtimes: Option<AppRuntimesInput>,
/// Settings, General's Show tips switch: tips are on
/// (`!AppSettings.tips.off`). A shell that does not say reads as on.
pub show_tips: bool,
diff --git a/libs/cua/crates/cua-spaces/src/agents/keys.rs b/libs/cua/crates/cua-spaces/src/agents/keys.rs
index 44483783d9..c936ab9586 100644
--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs
+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs
@@ -28,7 +28,85 @@ pub const SECRET_NAME: &str = "agent-keys";
/// The app's settings methods (`SpaceService.CallSpaceTool` names). They are
/// not contract tools: no MCP server lists or calls them, so an agent can
/// never read or change a key.
-pub const APP_METHODS: &[&str] = &["agent_keys.list", "agent_keys.set", "agent_keys.remove"];
+pub const APP_METHODS: &[&str] = &[
+ "agent_keys.list",
+ "agent_keys.set",
+ "agent_keys.remove",
+ "agent_keys.shell",
+ "agent_keys.from_shell",
+];
+
+/// The provider keys Cua may read from your login shell, by name (Settings,
+/// Connectors: "Use ANTHROPIC_API_KEY from your shell"). Nothing else is
+/// ever read there.
+pub const SHELL_NAMES: &[&str] = &[
+ "ANTHROPIC_API_KEY",
+ "OPENAI_API_KEY",
+ "COPILOT_GITHUB_TOKEN",
+];
+
+/// How long the login shell has to answer.
+const SHELL_WAIT: Duration = Duration::from_secs(5);
+
+/// The marker before the value in the shell's answer (anything a profile prints comes before it).
+const SHELL_MARK: &str = "__cua_shell_value__";
+
+/// Your login shell: `$SHELL`, else zsh.
+pub fn login_shell() -> std::path::PathBuf {
+ std::env::var_os("SHELL")
+ .filter(|s| !s.is_empty())
+ .map(std::path::PathBuf::from)
+ .unwrap_or_else(|| "/bin/zsh".into())
+}
+
+/// `name`'s value in a login, interactive `shell` (the profile files your
+/// terminal reads), when it is one of [`SHELL_NAMES`] and set. The shell's
+/// stdin is closed and it is stopped after [`SHELL_WAIT`].
+pub fn shell_value(shell: &std::path::Path, name: &str) -> Option<String> {
+ if !SHELL_NAMES.contains(&name) {
+ return None;
+ }
+ let script = format!("printf '\\n{SHELL_MARK}%s' \"${{{name}-}}\"");
+ let mut child = std::process::Command::new(shell)
+ .args(["-l", "-i", "-c", &script])
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .ok()?;
+ let mut out = child.stdout.take()?;
+ let reader = std::thread::spawn(move || {
+ let mut s = Vec::new();
+ let _ = std::io::Read::read_to_end(&mut out, &mut s);
+ String::from_utf8_lossy(&s).into_owned()
+ });
+ let start = Instant::now();
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => break,
+ Ok(None) if start.elapsed() < SHELL_WAIT => {
+ std::thread::sleep(Duration::from_millis(20))
+ }
+ _ => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return None;
+ }
+ }
+ }
+ let text = reader.join().ok()?;
+ let value = text.rsplit_once(SHELL_MARK)?.1.trim().to_string();
+ (!value.is_empty()).then_some(value)
+}
+
+/// Which of [`SHELL_NAMES`] your login shell has set (names only).
+pub fn shell_names(shell: &std::path::Path) -> Vec<String> {
+ SHELL_NAMES
+ .iter()
+ .filter(|n| shell_value(shell, n).is_some())
+ .map(|n| (*n).to_string())
+ .collect()
+}
/// Whether `name` is one of [`APP_METHODS`].
pub fn is_app_method(name: &str) -> bool {
@@ -250,9 +328,11 @@ struct Blob {
keys: Vec<Stored>,
}
-/// How long a read of the vault item is reused (the app and readiness
-/// checks read often; the daemon is the one writer).
-const CACHE_FOR: Duration = Duration::from_secs(30);
+/// How long a read of the vault item is reused by readiness checks and a
+/// run's env (they read in bursts). Short, because the daemon is not the one
+/// writer: the app saves the sign-ins Connect makes into the same item, and
+/// the next run must see them.
+const CACHE_FOR: Duration = Duration::from_secs(2);
/// The stored agent keys of one credential store.
pub struct AgentKeys {
@@ -360,7 +440,7 @@ impl AgentKeys {
/// The stored keys, without their values.
pub fn list(&self) -> Result<Vec<KeyInfo>> {
let mut g = self.lock();
- Ok(self.read(&mut g, false)?.iter().map(Stored::info).collect())
+ Ok(self.read(&mut g, true)?.iter().map(Stored::info).collect())
}
/// [`AgentKeys::list`] with the providers and availability.
@@ -585,28 +665,67 @@ struct RemoveArgs {
env: String,
}
+#[derive(Serialize)]
+struct ShellReport {
+ /// The provider keys your login shell has set (names; never a value).
+ names: Vec<String>,
+}
+
/// Runs one of [`APP_METHODS`] against `keys`; every answer is the
-/// [`KeysReport`] after the change. `None` for any other name.
+/// [`KeysReport`] after the change, except `agent_keys.shell` (which names
+/// your login shell has set). `None` for any other name. `shell` is the
+/// login shell `agent_keys.shell` and `agent_keys.from_shell` read.
pub fn app_call(
keys: &AgentKeys,
name: &str,
args: serde_json::Value,
-) -> Option<Result<KeysReport>> {
+ shell: &std::path::Path,
+) -> Option<Result<serde_json::Value>> {
let args = if args.is_null() {
serde_json::json!({})
} else {
args
};
+ let report = |r: Result<KeysReport>| {
+ r.and_then(|r| serde_json::to_value(r).map_err(|e| Error::Agent(e.to_string())))
+ };
Some(match name {
- "agent_keys.list" => keys.report(),
- "agent_keys.set" => serde_json::from_value::<SetArgs>(args)
- .map_err(|e| Error::InvalidArgument(format!("agent_keys.set: {}", redact_serde(&e))))
- .and_then(|a| keys.set(&a.provider, a.env.as_deref(), &a.value))
- .and_then(|_| keys.report()),
- "agent_keys.remove" => serde_json::from_value::<RemoveArgs>(args)
- .map_err(|e| Error::InvalidArgument(format!("agent_keys.remove: {e}")))
- .and_then(|a| keys.remove(&a.env))
- .and_then(|_| keys.report()),
+ "agent_keys.list" => report(keys.report()),
+ "agent_keys.set" => report(
+ serde_json::from_value::<SetArgs>(args)
+ .map_err(|e| {
+ Error::InvalidArgument(format!("agent_keys.set: {}", redact_serde(&e)))
+ })
+ .and_then(|a| keys.set(&a.provider, a.env.as_deref(), &a.value))
+ .and_then(|_| keys.report()),
+ ),
+ "agent_keys.remove" => report(
+ serde_json::from_value::<RemoveArgs>(args)
+ .map_err(|e| Error::InvalidArgument(format!("agent_keys.remove: {e}")))
+ .and_then(|a| keys.remove(&a.env))
+ .and_then(|_| keys.report()),
+ ),
+ "agent_keys.shell" => serde_json::to_value(ShellReport {
+ names: shell_names(shell),
+ })
+ .map_err(|e| Error::Agent(e.to_string())),
+ // The value goes straight from your shell into the store; it is never answered.
+ "agent_keys.from_shell" => report(
+ serde_json::from_value::<RemoveArgs>(args)
+ .map_err(|e| Error::InvalidArgument(format!("agent_keys.from_shell: {e}")))
+ .and_then(|a| {
+ let value = shell_value(shell, &a.env).ok_or_else(|| {
+ Error::InvalidArgument(format!("{} isn't set in your shell", a.env))
+ })?;
+ let provider = provider_of(&a.env);
+ keys.set(
+ provider,
+ (provider == "other").then_some(a.env.as_str()),
+ &value,
+ )
+ })
+ .and_then(|_| keys.report()),
+ ),
_ => return None,
})
}
@@ -616,7 +735,7 @@ pub fn app_call(
/// that is not one of [`APP_METHODS`].
#[cfg(feature = "mcp")]
pub fn app_tool(name: &str, args: serde_json::Value) -> Option<crate::mcp::ToolOutcome> {
- app_call(global(), name, args).map(|r| match r {
+ app_call(global(), name, args, &login_shell()).map(|r| match r {
Ok(report) => crate::mcp::ToolOutcome::json(&report),
Err(e) => crate::mcp::ToolOutcome::error(&e),
})
@@ -690,6 +809,38 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[test]
+ fn a_sign_in_the_app_saves_shows_in_the_daemons_next_list_and_run() {
+ // The daemon reads the list (and warms its cache) before Connect.
+ let (daemon, dir) = temp_keys();
+ assert!(daemon.list().unwrap().is_empty());
+ assert!(daemon.names().is_empty());
+ // The app saves the sign-in Connect made into the same item.
+ let app = AgentKeys::new(cua_auth::Store::TestKeychain(dir.clone()));
+ app.import(
+ "codex",
+ "CODEX_AUTH_JSON",
+ "Codex · ChatGPT sign-in",
+ "{\"tokens\":{}}",
+ None,
+ )
+ .unwrap();
+ // Settings' next read sees it right away.
+ let listed = daemon.list().unwrap();
+ assert_eq!(
+ listed.iter().map(|k| k.env.as_str()).collect::<Vec<_>>(),
+ ["CODEX_AUTH_JSON"]
+ );
+ // And a run started a moment later gets it.
+ std::thread::sleep(CACHE_FOR + Duration::from_millis(50));
+ assert!(
+ daemon
+ .values(&["CODEX_AUTH_JSON"])
+ .contains_key("CODEX_AUTH_JSON")
+ );
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[test]
fn a_short_key_shows_no_characters() {
let (keys, dir) = temp_keys();
@@ -755,6 +906,68 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[test]
+ fn a_key_from_your_shell_is_saved_and_only_its_name_is_answered() {
+ let (keys, dir) = temp_keys();
+ // A login shell whose profile prints noise and exports one key; it runs the command it is given.
+ let shell = dir.join("fake-shell");
+ std::fs::write(
+ &shell,
+ "#!/bin/sh\necho 'welcome to your shell'\nANTHROPIC_API_KEY=sk-ant-from-shell-0000-wxyz; export ANTHROPIC_API_KEY\nshift 3\nexec /bin/sh -c \"$1\"\n",
+ )
+ .unwrap();
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ let names = app_call(&keys, "agent_keys.shell", serde_json::json!({}), &shell)
+ .unwrap()
+ .unwrap();
+ assert_eq!(names, serde_json::json!({"names": ["ANTHROPIC_API_KEY"]}));
+ let r = app_call(
+ &keys,
+ "agent_keys.from_shell",
+ serde_json::json!({"env": "ANTHROPIC_API_KEY"}),
+ &shell,
+ )
+ .unwrap()
+ .unwrap();
+ let text = serde_json::to_string(&r).unwrap();
+ assert!(
+ text.contains("wxyz") && !text.contains("sk-ant-from-shell"),
+ "{text}"
+ );
+ assert_eq!(
+ keys.values(&["ANTHROPIC_API_KEY"])
+ .get("ANTHROPIC_API_KEY")
+ .map(String::as_str),
+ Some("sk-ant-from-shell-0000-wxyz")
+ );
+ // Not set there, or not a provider key Cua reads: refused.
+ assert!(
+ app_call(
+ &keys,
+ "agent_keys.from_shell",
+ serde_json::json!({"env": "OPENAI_API_KEY"}),
+ &shell
+ )
+ .unwrap()
+ .is_err()
+ );
+ assert!(
+ app_call(
+ &keys,
+ "agent_keys.from_shell",
+ serde_json::json!({"env": "HOME"}),
+ &shell
+ )
+ .unwrap()
+ .is_err()
+ );
+ assert_eq!(shell_value(&shell, "PATH"), None);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn app_methods_answer_the_report_without_values() {
let (keys, dir) = temp_keys();
@@ -762,16 +975,18 @@ mod tests {
&keys,
"agent_keys.set",
serde_json::json!({"provider": "openai", "value": "sk-test-0000-1234"}),
+ std::path::Path::new("/nonexistent-shell"),
)
.unwrap()
.unwrap();
- assert_eq!(r.keys.len(), 1);
+ assert_eq!(r["keys"].as_array().unwrap().len(), 1);
assert!(!serde_json::to_string(&r).unwrap().contains("sk-test-0000"));
// A malformed call does not echo what it was given.
let e = app_call(
&keys,
"agent_keys.set",
serde_json::json!({"provider": "openai", "value": 12345678}),
+ std::path::Path::new("/nonexistent-shell"),
)
.unwrap()
.unwrap_err();
@@ -780,11 +995,20 @@ mod tests {
&keys,
"agent_keys.remove",
serde_json::json!({"env": "OPENAI_API_KEY"}),
+ std::path::Path::new("/nonexistent-shell"),
)
.unwrap()
.unwrap();
- assert!(r.keys.is_empty());
- assert!(app_call(&keys, "agent_start", serde_json::json!({})).is_none());
+ assert!(r["keys"].as_array().unwrap().is_empty());
+ assert!(
+ app_call(
+ &keys,
+ "agent_start",
+ serde_json::json!({}),
+ std::path::Path::new("/nonexistent-shell")
+ )
+ .is_none()
+ );
for m in APP_METHODS {
assert!(
cua_spaces_contract::tool(m).is_none(),
diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rs
index 5f376b89e2..f125565545 100644
--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs
@@ -2441,8 +2441,8 @@ fn stopped_sharing_reason(e: &Error) -> Option<String> {
/// local Space (2 vCPUs, 4 GiB).
/// How this machine's daemon reaches the machine's own cua-spacesd (the
/// host service): where it listens (the direct listener, `CUA_ENV_LISTEN`,
-/// else loopback on `CUA_ENV_PORT` or the channel's port, 3211 or 3221 for
-/// Cua Spaces Local) and its local env token.
+/// else loopback on `CUA_ENV_PORT`, the port setup chose, or the channel's
+/// port, 3211 or 3221 for Cua Spaces Local) and its local env token.
fn host_spacesd(host: &Host) -> std::result::Result<cua_cluster::machine::HostSpacesd, String> {
host_spacesd_on(host, cua_home::channel::CuaChannel::current())
}
@@ -2451,11 +2451,10 @@ fn host_spacesd_on(
host: &Host,
channel: cua_home::channel::CuaChannel,
) -> std::result::Result<cua_cluster::machine::HostSpacesd, String> {
- let listen = host
- .config()
- .ok()
- .flatten()
- .and_then(|c| c.listen)
+ let config = host.config().ok().flatten();
+ let listen = config
+ .as_ref()
+ .and_then(|c| c.listen.clone())
.filter(|l| !l.is_empty())
.or_else(|| {
std::env::var("CUA_ENV_LISTEN")
@@ -2466,7 +2465,14 @@ fn host_spacesd_on(
let port = std::env::var("CUA_ENV_PORT")
.ok()
.and_then(|p| p.trim().parse::<u16>().ok())
- .unwrap_or(channel.ports().tcp);
+ // The port setup chose (another macOS user's host held
+ // the channel's), else the channel's.
+ .unwrap_or_else(|| {
+ config
+ .as_ref()
+ .map_or(channel.ports(), |c| c.service_ports(channel))
+ .tcp
+ });
format!("127.0.0.1:{port}")
});
// A listener on every interface is reached on loopback.
@@ -4588,6 +4594,14 @@ mod tests {
assert_eq!(on(CuaChannel::Stable).url, "http://127.0.0.1:3211");
assert_eq!(on(CuaChannel::Local).url, "http://127.0.0.1:3221");
assert_eq!(on(CuaChannel::Local).token, "secret");
+ // A host set up beside another macOS user's: the port setup chose.
+ let config = cua_host::HostConfig {
+ mode: "relay".into(),
+ port: Some(3231),
+ ..Default::default()
+ };
+ std::fs::write(host.paths().config(), serde_json::to_vec(&config).unwrap()).unwrap();
+ assert_eq!(on(CuaChannel::Stable).url, "http://127.0.0.1:3231");
// The mesh media port is every channel's, by design: guest Spaces
// and older cua-spacesd serve it there, and it is not an OS port.
for channel in CuaChannel::ALL {
diff --git a/libs/cua/crates/cua-spaces/src/space.rs b/libs/cua/crates/cua-spaces/src/space.rs
index 788aa0627e..510aae59b9 100644
--- a/libs/cua/crates/cua-spaces/src/space.rs
+++ b/libs/cua/crates/cua-spaces/src/space.rs
@@ -148,6 +148,8 @@ pub(crate) struct SpaceInner {
/// Why no cua-spacesd answered when this connected (`endpoint`,
/// `reason`), for a Space connected without one.
pub(crate) spacesd_unavailable: std::sync::OnceLock<(String, String)>,
+ /// When that was noted ([`Space::spacesd_retry_due`]).
+ pub(crate) spacesd_unavailable_at: std::sync::OnceLock<std::time::Instant>,
}
/// A connected Space. Cheap to clone; every clone shares one spacesd
@@ -204,6 +206,7 @@ impl Space {
keepalive: Default::default(),
image_config: Default::default(),
spacesd_unavailable: Default::default(),
+ spacesd_unavailable_at: Default::default(),
}),
}
}
@@ -432,6 +435,24 @@ impl Space {
pub(crate) fn set_spacesd_unavailable(&self, endpoint: String, reason: String) {
let _ = self.inner.spacesd_unavailable.set((endpoint, reason));
+ let _ = self
+ .inner
+ .spacesd_unavailable_at
+ .set(std::time::Instant::now());
+ }
+
+ /// Whether this connection was made without the cua-spacesd its image
+ /// publishes (it didn't answer then: the Space or its runtime was still
+ /// waking, as after a daemon restart) at least `after` ago, so a new
+ /// connection may find it. A Space whose image runs no cua-spacesd is
+ /// never due.
+ pub(crate) fn spacesd_retry_due(&self, after: std::time::Duration) -> bool {
+ self.inner.env.is_none()
+ && self
+ .inner
+ .spacesd_unavailable_at
+ .get()
+ .is_some_and(|at| at.elapsed() >= after)
}
/// When no cua-spacesd answered because this host has no route to a
@@ -824,6 +845,32 @@ fn humantime_rfc3339(at: std::time::SystemTime) -> String {
mod tests {
use super::*;
+ fn no_spacesd() -> Space {
+ Space::new(
+ SpaceId::Local {
+ name: "pipbox".into(),
+ },
+ "pipbox".into(),
+ None,
+ Default::default(),
+ None,
+ None,
+ BTreeMap::new(),
+ )
+ }
+
+ #[test]
+ fn a_space_connected_while_its_spacesd_was_waking_is_dialed_again() {
+ // Its image publishes cua-spacesd, which didn't answer then (the
+ // daemon restarted while the Space was still waking).
+ let s = no_spacesd();
+ s.set_spacesd_unavailable("127.0.0.1:7000".into(), "connection refused".into());
+ assert!(s.spacesd_retry_due(std::time::Duration::ZERO));
+ assert!(!s.spacesd_retry_due(std::time::Duration::from_secs(3600)));
+ // An image that runs no cua-spacesd is never dialed again for it.
+ assert!(!no_spacesd().spacesd_retry_due(std::time::Duration::ZERO));
+ }
+
#[test]
fn versions_compare_against_a_floor() {
assert!(spacesd_older_than("0.1.0", "0.2.2"));
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 88715d4d08..940d96cca7 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -239,6 +239,10 @@ pub struct PendingSpace {
pub phase: &'static str,
}
+/// How long a connection made without the cua-spacesd its image publishes
+/// is kept before the next use dials again.
+const SPACESD_RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(5);
+
/// Builder for [`Spaces`].
#[derive(Default)]
pub struct SpacesBuilder {
@@ -1607,6 +1611,16 @@ impl Spaces {
// Bound first: the cache's guard must be gone before the lock is
// taken again below.
let cached = self.inner.connections.lock().await.get(&key).cloned();
+ // Connected while its cua-spacesd didn't answer (the Space was still
+ // waking, as after a daemon restart): dial again, or the Space stays
+ // without spacesd until it is restarted and agents can't start there.
+ if let Some(s) = &cached
+ && s.spacesd_retry_due(SPACESD_RETRY_AFTER)
+ {
+ tracing::info!(space = %key, "no cua-spacesd answered when this connected; reconnecting");
+ self.inner.connections.lock().await.remove(&key);
+ return None;
+ }
if let Some(s) = cached {
let policy = |provided| {
if provided {
diff --git a/libs/cua/crates/cua-vmm/src/container/engine.rs b/libs/cua/crates/cua-vmm/src/container/engine.rs
index c604b9bd13..92658ba7aa 100644
--- a/libs/cua/crates/cua-vmm/src/container/engine.rs
+++ b/libs/cua/crates/cua-vmm/src/container/engine.rs
@@ -275,6 +275,17 @@ pub fn discover() -> Option<EngineEndpoint> {
source: "DOCKER_HOST".into(),
});
}
+ // `runtime.container_path` (with `runtime.container = system`): the
+ // engine that binary talks to.
+ if let Some(bin) = crate::kinds::configured_bin(crate::kinds::RuntimeKind::Container)
+ && let Some(h) = endpoint_of_binary(&bin)
+ {
+ return Some(EngineEndpoint {
+ kind: classify(&h),
+ uri: h,
+ source: format!("runtime.container_path {}", bin.display()),
+ });
+ }
let docker_dir = docker_config_dir();
let env_ctx = std::env::var("DOCKER_CONTEXT").ok();
if let Some((name, h)) = context_endpoint(&docker_dir, env_ctx.as_deref()) {
@@ -316,10 +327,114 @@ pub fn discover() -> Option<EngineEndpoint> {
})
}
+/// The engine endpoint a `docker` or `podman` binary uses (its current
+/// context, or its machine's socket), asked once per binary (bounded).
+pub fn endpoint_of_binary(bin: &Path) -> Option<String> {
+ use std::sync::Mutex;
+ static CACHE: Mutex<Vec<(PathBuf, Option<String>)>> = Mutex::new(Vec::new());
+ if let Some((_, h)) = CACHE.lock().ok()?.iter().find(|(p, _)| p == bin) {
+ return h.clone();
+ }
+ let podman = bin
+ .file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.contains("podman"));
+ let asks: &[&[&str]] = if podman {
+ &[
+ &[
+ "machine",
+ "inspect",
+ "--format",
+ "{{.ConnectionInfo.PodmanSocket.Path}}",
+ ],
+ &["info", "--format", "{{.Host.RemoteSocket.Path}}"],
+ ]
+ } else {
+ &[&[
+ "context",
+ "inspect",
+ "--format",
+ "{{.Endpoints.docker.Host}}",
+ ]]
+ };
+ let found = asks
+ .iter()
+ .find_map(|args| bounded_output(bin, args))
+ .map(|h| endpoint_uri(&h))
+ .filter(|h| !h.is_empty());
+ if let Ok(mut c) = CACHE.lock() {
+ c.push((bin.to_path_buf(), found.clone()));
+ }
+ found
+}
+
+/// A socket path as a `unix://` URI; anything with a scheme as it is.
+fn endpoint_uri(h: &str) -> String {
+ let h = h.trim().trim_matches('"');
+ if h.starts_with('/') {
+ format!("unix://{h}")
+ } else {
+ h.to_string()
+ }
+}
+
+/// `bin args`'s first line, when it succeeds within a few seconds.
+fn bounded_output(bin: &Path, args: &[&str]) -> Option<String> {
+ use std::process::{Command, Stdio};
+ use std::time::{Duration, Instant};
+ let mut child = Command::new(bin)
+ .args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .ok()?;
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ match child.try_wait().ok()? {
+ Some(status) if status.success() => break,
+ Some(_) => return None,
+ None if Instant::now() > deadline => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return None;
+ }
+ None => std::thread::sleep(Duration::from_millis(20)),
+ }
+ }
+ let mut out = String::new();
+ std::io::Read::read_to_string(&mut child.stdout.take()?, &mut out).ok()?;
+ out.lines()
+ .map(str::trim)
+ .find(|l| !l.is_empty() && !l.starts_with('<'))
+ .map(str::to_string)
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ /// A docker binary's own context names the engine Spaces then use.
+ #[cfg(unix)]
+ #[test]
+ fn a_binary_names_its_engine() {
+ use std::os::unix::fs::PermissionsExt;
+ let d = tempfile::tempdir().unwrap();
+ let bin = d.path().join("docker");
+ std::fs::write(
+ &bin,
+ "#!/bin/sh\n[ \"$1 $2\" = \"context inspect\" ] && echo /Users/me/.orbstack/run/docker.sock\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
+ assert_eq!(
+ endpoint_of_binary(&bin).as_deref(),
+ Some("unix:///Users/me/.orbstack/run/docker.sock")
+ );
+ assert_eq!(endpoint_uri("tcp://1.2.3.4:2375"), "tcp://1.2.3.4:2375");
+ assert_eq!(endpoint_of_binary(&d.path().join("missing")), None);
+ }
+
#[test]
fn classifies_common_engines() {
assert_eq!(
diff --git a/libs/cua/crates/cua-vmm/src/containerization/mod.rs b/libs/cua/crates/cua-vmm/src/containerization/mod.rs
index 6f23f8b361..bd7b9de68d 100644
--- a/libs/cua/crates/cua-vmm/src/containerization/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/containerization/mod.rs
@@ -151,13 +151,25 @@ impl ContainerizationRuntime {
}
/// The `container` binary, if there is one.
+ ///
+ /// With `runtime.microvm = system`, Apple's `container` already on this
+ /// Mac (`runtime.microvm_path`, else the one on `PATH`), never cua's
+ /// own copy.
pub fn bin(&self) -> Option<PathBuf> {
match &self.cfg.bin {
Some(b) => Some(b.clone()),
+ None if Self::uses_installed() => {
+ crate::kinds::system_bin(crate::kinds::RuntimeKind::Microvm)
+ }
None => install::installed_bin(&self.cfg.root),
}
}
+ /// MicroVMs are set to what is already installed (nothing is downloaded).
+ fn uses_installed() -> bool {
+ crate::kinds::source(crate::kinds::RuntimeKind::Microvm) == crate::kinds::KindSource::System
+ }
+
fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
let mut m = self.locks.lock().unwrap_or_else(|e| e.into_inner());
m.entry(name.to_string())
@@ -248,7 +260,16 @@ impl ContainerizationRuntime {
if let Some(why) = install::unsupported_reason() {
return Err(VmmError::other(why));
}
- if install::installed_bin(&self.cfg.root).is_none() {
+ if Self::uses_installed() {
+ if self.bin().is_none() {
+ return Err(VmmError::missing(
+ "Apple container",
+ "MicroVMs are set to use what is already installed, and Apple's container \
+ is not installed on this Mac (Settings, Advanced, or \
+ `cua config set runtime.microvm auto`)",
+ ));
+ }
+ } else if install::installed_bin(&self.cfg.root).is_none() {
if !self.cfg.auto_install {
return Err(VmmError::missing(
"Apple container",
diff --git a/libs/cua/crates/cua-vmm/src/kinds.rs b/libs/cua/crates/cua-vmm/src/kinds.rs
new file mode 100644
index 0000000000..57aa30c685
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/kinds.rs
@@ -0,0 +1,690 @@
+//! Which software runs each kind of Space here: the per-kind runtime
+//! settings (`runtime.container`, `runtime.vm`, `runtime.microvm`, each
+//! `auto`, `builtin` or `system`, and `runtime.<kind>_path`), the runtimes
+//! already installed on this machine for each kind, and what a given
+//! binary is.
+//!
+//! * **One setting per kind.** `runtime.container` was `runtime.linux` and
+//! `runtime.vm` was `runtime.lume`: the old names are still read (the new
+//! ones win), in the config file and the environment.
+//! * **A path overrides detection.** With a kind set to `system`, its
+//! `runtime.<kind>_path` names the binary to use instead of the one
+//! found on `PATH` ([`configured_bin`]); the daemon and `cua` both read
+//! it, so they use the same one.
+//! * **Detection** ([`detect`]) lists, per kind, every runtime this machine
+//! has (name, path, version), in the order the one that is used is
+//! picked; [`probe`] tells what any binary is (it runs `--version`).
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+
+use crate::host::{self, HostOs};
+
+/// A kind of Space with a runtime setting of its own (`--kind`'s words).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum RuntimeKind {
+ Container,
+ Vm,
+ Microvm,
+}
+
+impl RuntimeKind {
+ /// Every kind, in Settings' order.
+ pub const ALL: [RuntimeKind; 3] = [
+ RuntimeKind::Container,
+ RuntimeKind::Vm,
+ RuntimeKind::Microvm,
+ ];
+
+ /// `container`, `vm`, `microvm`.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Container => "container",
+ Self::Vm => "vm",
+ Self::Microvm => "microvm",
+ }
+ }
+
+ /// The kind `word` names (`containers`, `virtual machines` too).
+ pub fn parse(word: &str) -> Option<Self> {
+ match word.trim().to_ascii_lowercase().as_str() {
+ "container" | "containers" => Some(Self::Container),
+ "vm" | "vms" | "virtual machine" | "virtual machines" => Some(Self::Vm),
+ "microvm" | "microvms" => Some(Self::Microvm),
+ _ => None,
+ }
+ }
+
+ /// The per-OS setting this kind's replaced (`[runtime] <name>` and its
+ /// variable), still read when the new one is not set.
+ fn legacy(self) -> Option<(&'static str, &'static str)> {
+ match self {
+ Self::Container => Some(("linux", "CUA_RUNTIME_LINUX")),
+ Self::Vm => Some(("lume", "CUA_RUNTIME_LUME")),
+ Self::Microvm => None,
+ }
+ }
+}
+
+/// What a kind's setting asks for.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum KindSource {
+ /// The best of what is here (the kind's own rules).
+ #[default]
+ Auto,
+ /// Cua's own (set up on first use).
+ Builtin,
+ /// Only what is already installed here (nothing is downloaded).
+ System,
+}
+
+impl KindSource {
+ /// `auto`, `builtin` (`built-in`) or `system`.
+ pub fn parse(word: &str) -> Option<Self> {
+ match word.trim().to_ascii_lowercase().as_str() {
+ "auto" | "" => Some(Self::Auto),
+ "builtin" | "built-in" | "cua" => Some(Self::Builtin),
+ "system" | "installed" => Some(Self::System),
+ _ => None,
+ }
+ }
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Auto => "auto",
+ Self::Builtin => "builtin",
+ Self::System => "system",
+ }
+ }
+}
+
+/// `runtime.<kind><suffix>` now: its variable (`CUA_RUNTIME_<KIND><SUFFIX>`,
+/// then the old per-OS one), else the config file (the new name, then the
+/// old one). Read on every use, so a change in Settings applies at once.
+fn setting(kind: RuntimeKind, suffix: &str, config: &Path) -> Option<String> {
+ let name = format!("{}{suffix}", kind.as_str());
+ let legacy = kind.legacy().filter(|_| suffix.is_empty());
+ let env = std::iter::once(format!("CUA_RUNTIME_{}", name.to_ascii_uppercase()))
+ .chain(legacy.map(|(_, e)| e.to_string()))
+ .find_map(|e| std::env::var(e).ok().filter(|v| !v.trim().is_empty()));
+ env.or_else(|| {
+ let doc = std::fs::read_to_string(config)
+ .ok()?
+ .parse::<toml_edit::DocumentMut>()
+ .ok()?;
+ let table = doc.get("runtime")?;
+ std::iter::once(name.as_str())
+ .chain(legacy.map(|(n, _)| n))
+ .find_map(|n| table.get(n)?.as_str().map(str::to_string))
+ })
+ .map(|v| v.trim().to_string())
+ .filter(|v| !v.is_empty())
+}
+
+fn config_file() -> PathBuf {
+ host::cua_home().join("config.toml")
+}
+
+/// `runtime.<kind>` now (auto when unset or unreadable).
+pub fn source(kind: RuntimeKind) -> KindSource {
+ source_in(kind, &config_file())
+}
+
+/// [`source`] with the config file at `config`.
+pub fn source_in(kind: RuntimeKind, config: &Path) -> KindSource {
+ setting(kind, "", config)
+ .and_then(|v| KindSource::parse(&v))
+ .unwrap_or_default()
+}
+
+/// `runtime.<kind>_path` now, whatever the source says.
+pub fn custom_path(kind: RuntimeKind) -> Option<PathBuf> {
+ custom_path_in(kind, &config_file())
+}
+
+/// [`custom_path`] with the config file at `config`.
+pub fn custom_path_in(kind: RuntimeKind, config: &Path) -> Option<PathBuf> {
+ setting(kind, "_path", config).map(PathBuf::from)
+}
+
+/// The binary the settings pin for `kind`: its custom path, when the kind
+/// is set to `system` (Automatic and Cua's own pick their own). This
+/// overrides detection everywhere the kind's binary is looked up.
+pub fn configured_bin(kind: RuntimeKind) -> Option<PathBuf> {
+ (source(kind) == KindSource::System)
+ .then(|| custom_path(kind))
+ .flatten()
+}
+
+/// With `kind` set to `system`, the binary to run: its custom path, else
+/// the first of its tools installed here (never one cua set up itself).
+/// `None` for Automatic and Cua's own, and when nothing is installed.
+pub fn system_bin(kind: RuntimeKind) -> Option<PathBuf> {
+ if source(kind) != KindSource::System {
+ return None;
+ }
+ custom_path(kind).or_else(|| first_installed(kind))
+}
+
+/// The first of `kind`'s tools on `PATH` here (not cua's own copies).
+pub fn first_installed(kind: RuntimeKind) -> Option<PathBuf> {
+ tools_for(kind, HostOs::current())
+ .into_iter()
+ .flat_map(program_names)
+ .filter_map(|n| host::which(&n))
+ .find(|p| !p.starts_with(host::cua_home()))
+}
+
+/// A runtime program a kind can use.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Tool {
+ /// `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ pub id: &'static str,
+ /// As people know it (`Docker`, `Apple container`).
+ pub name: &'static str,
+ pub kind: RuntimeKind,
+ /// The systems it runs on.
+ pub hosts: &'static [HostOs],
+ /// The guest systems it runs, when only one ("macOS", "Linux").
+ pub guests: Option<&'static str>,
+ /// The oldest version cua runs on.
+ pub min_version: Option<&'static str>,
+}
+
+/// `lume::builtin::MIN_VERSION` (a test keeps them equal; this module
+/// builds without the `lume` feature too).
+const LUME_MIN_VERSION: &str = "0.6.0";
+
+const MAC: &[HostOs] = &[HostOs::Macos];
+const LINUX: &[HostOs] = &[HostOs::Linux];
+const MAC_LINUX: &[HostOs] = &[HostOs::Macos, HostOs::Linux];
+
+/// Every tool, per kind in the order detection prefers them.
+pub const TOOLS: &[Tool] = &[
+ Tool {
+ id: "docker",
+ name: "Docker",
+ kind: RuntimeKind::Container,
+ hosts: MAC_LINUX,
+ guests: None,
+ min_version: None,
+ },
+ Tool {
+ id: "podman",
+ name: "Podman",
+ kind: RuntimeKind::Container,
+ hosts: MAC_LINUX,
+ guests: None,
+ min_version: None,
+ },
+ Tool {
+ id: "lume",
+ name: "Lume",
+ kind: RuntimeKind::Vm,
+ hosts: MAC,
+ guests: Some("macOS"),
+ min_version: Some(LUME_MIN_VERSION),
+ },
+ Tool {
+ id: "qemu",
+ name: "QEMU",
+ kind: RuntimeKind::Vm,
+ hosts: LINUX,
+ guests: None,
+ min_version: None,
+ },
+ Tool {
+ id: "container",
+ name: "Apple container",
+ kind: RuntimeKind::Microvm,
+ hosts: MAC,
+ guests: Some("Linux"),
+ min_version: None,
+ },
+ Tool {
+ id: "firecracker",
+ name: "Firecracker",
+ kind: RuntimeKind::Microvm,
+ hosts: LINUX,
+ guests: None,
+ min_version: None,
+ },
+];
+
+/// The tools `kind` can use on `os`.
+pub fn tools_for(kind: RuntimeKind, os: HostOs) -> Vec<&'static Tool> {
+ TOOLS
+ .iter()
+ .filter(|t| t.kind == kind && t.hosts.contains(&os))
+ .collect()
+}
+
+/// The program names a tool is looked up by on `PATH`.
+fn program_names(tool: &Tool) -> Vec<String> {
+ match tool.id {
+ "lume" => vec![
+ cua_home::channel::CuaChannel::current()
+ .lume_bin_name()
+ .to_string(),
+ ],
+ "qemu" => vec![format!("qemu-system-{}", crate::types::Arch::host().qemu())],
+ id => vec![id.to_string()],
+ }
+}
+
+/// A runtime found on this machine.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Detected {
+ /// [`Tool::id`].
+ pub tool: String,
+ /// [`Tool::name`].
+ pub name: String,
+ pub path: PathBuf,
+ /// As `--version` says it (`27.3.1`), when it says.
+ pub version: Option<String>,
+ /// [`Tool::guests`].
+ pub guests: Option<String>,
+}
+
+/// What a binary is, for the path a person typed (or the one in use).
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PathProbe {
+ pub path: PathBuf,
+ /// A file is there.
+ pub exists: bool,
+ /// It can be run.
+ pub executable: bool,
+ /// The tool it is ([`Tool::id`]), when it is one of the kind's.
+ pub tool: Option<String>,
+ /// [`Tool::name`].
+ pub name: Option<String>,
+ pub version: Option<String>,
+ /// The tool's [`Tool::min_version`].
+ pub min_version: Option<String>,
+ /// The names of the tools the kind takes here ("Docker", "Podman").
+ pub expected: Vec<String>,
+ /// [`Tool::guests`].
+ pub guests: Option<String>,
+}
+
+/// The first `x.y` or `x.y.z` in `text` (`Docker version 27.3.1, build
+/// ce12230` is `27.3.1`; `Firecracker v1.10.1` is `1.10.1`).
+pub fn version_in(text: &str) -> Option<String> {
+ text.split(|c: char| c.is_whitespace() || c == ',' || c == '(' || c == ')')
+ .map(|w| w.trim_start_matches('v'))
+ .find(|w| {
+ let parts: Vec<&str> = w.split('.').collect();
+ parts.len() >= 2
+ && parts.len() <= 4
+ && parts
+ .iter()
+ .take(2)
+ .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()))
+ })
+ .map(|w| {
+ w.trim_end_matches(|c: char| !c.is_ascii_digit())
+ .to_string()
+ })
+}
+
+/// Which of the tools `text` (a `--version` answer) comes from, judged by
+/// what each one prints and, for Lume (it prints only its version), the
+/// file's name.
+pub fn identify(file_name: &str, text: &str) -> Option<&'static Tool> {
+ let t = text.to_ascii_lowercase();
+ let by = |id: &str| TOOLS.iter().find(|x| x.id == id);
+ if t.contains("docker version") {
+ by("docker")
+ } else if t.contains("podman version") {
+ by("podman")
+ } else if t.contains("qemu emulator version") {
+ by("qemu")
+ } else if t.contains("container cli version")
+ || t.contains("container version") && t.contains("apple")
+ {
+ by("container")
+ } else if t.contains("firecracker") {
+ by("firecracker")
+ } else if file_name.to_ascii_lowercase().starts_with("lume") && version_in(text).is_some() {
+ by("lume")
+ } else {
+ None
+ }
+}
+
+/// How long `--version` may take.
+const VERSION_TIMEOUT: Duration = Duration::from_secs(5);
+
+/// `<bin> --version`'s answer (stdout, else stderr), when it answers in time.
+async fn version_output(bin: &Path) -> Option<String> {
+ let mut cmd = version_command(bin);
+ let out = tokio::time::timeout(
+ VERSION_TIMEOUT,
+ cmd.arg("--version")
+ .stdin(std::process::Stdio::null())
+ .kill_on_drop(true)
+ .output(),
+ )
+ .await
+ .ok()?
+ .ok()?;
+ let text = [&out.stdout, &out.stderr]
+ .iter()
+ .map(|b| String::from_utf8_lossy(b).trim().to_string())
+ .find(|s| !s.is_empty())?;
+ Some(text)
+}
+
+/// The command a binary's `--version` runs as: a Lume as its channel runs
+/// it (Local's keeps its own config), anything else as it is.
+fn version_command(bin: &Path) -> tokio::process::Command {
+ #[cfg(feature = "lume")]
+ if bin
+ .file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with("lume"))
+ && let Ok(l) = crate::lume::builtin::LumeCmd::new(
+ cua_home::channel::CuaChannel::current(),
+ &host::cua_home().join("vmm").join("lume"),
+ bin.to_path_buf(),
+ )
+ {
+ return l.tokio_command();
+ }
+ tokio::process::Command::new(bin)
+}
+
+fn executable(p: &Path) -> bool {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ p.metadata()
+ .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
+ .unwrap_or(false)
+ }
+ #[cfg(not(unix))]
+ {
+ p.is_file()
+ }
+}
+
+/// What `path` is, for `kind` on this machine: there, runnable, which tool
+/// (only the kind's own count) and its version. Runs `path --version`
+/// (bounded); never anything else.
+pub async fn probe(kind: RuntimeKind, path: &Path) -> PathProbe {
+ probe_on(kind, path, HostOs::current()).await
+}
+
+async fn probe_on(kind: RuntimeKind, path: &Path, os: HostOs) -> PathProbe {
+ let tools = tools_for(kind, os);
+ let mut p = PathProbe {
+ path: path.to_path_buf(),
+ exists: path.exists(),
+ expected: tools.iter().map(|t| t.name.to_string()).collect(),
+ ..Default::default()
+ };
+ p.executable = p.exists && executable(path);
+ if !p.executable {
+ return p;
+ }
+ let Some(text) = version_output(path).await else {
+ return p;
+ };
+ let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ if let Some(tool) = identify(file, &text).filter(|t| tools.iter().any(|x| x.id == t.id)) {
+ p.tool = Some(tool.id.into());
+ p.name = Some(tool.name.into());
+ p.min_version = tool.min_version.map(str::to_string);
+ p.guests = tool.guests.map(str::to_string);
+ p.version = version_in(&text);
+ }
+ p
+}
+
+/// The runtimes installed here for `kind`, in the order the one used is
+/// picked (the first is what Automatic and "Already installed" use when no
+/// path is set). Never anything cua set up itself (its own Lume, its own
+/// `container`, its own Firecracker).
+pub async fn detect(kind: RuntimeKind) -> Vec<Detected> {
+ let mut out: Vec<Detected> = Vec::new();
+ for tool in tools_for(kind, HostOs::current()) {
+ for name in program_names(tool) {
+ let Some(path) = host::which(&name) else {
+ continue;
+ };
+ if path.starts_with(host::cua_home()) || out.iter().any(|d| d.path == path) {
+ continue;
+ }
+ let version = version_output(&path).await.and_then(|t| version_in(&t));
+ out.push(Detected {
+ tool: tool.id.into(),
+ name: tool.name.into(),
+ path,
+ version,
+ guests: tool.guests.map(str::to_string),
+ });
+ }
+ }
+ out
+}
+
+/// One kind as Settings shows it: its setting, its custom path, what is
+/// installed here and what the path in use is.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct KindReport {
+ pub kind: RuntimeKind,
+ pub source: KindSource,
+ /// `runtime.<kind>_path`, when set.
+ pub path: Option<PathBuf>,
+ pub detected: Vec<Detected>,
+ /// [`probe`] of the path in use (the custom one, else the first
+ /// detected), when there is one.
+ pub check: Option<PathProbe>,
+ /// The names of the tools the kind takes here (`Docker`, `Podman`).
+ pub expected: Vec<String>,
+}
+
+/// [`KindReport`] for every kind, read now.
+pub async fn report() -> Vec<KindReport> {
+ let mut out = Vec::new();
+ for kind in RuntimeKind::ALL {
+ let detected = detect(kind).await;
+ let path = custom_path(kind);
+ let in_use = path
+ .clone()
+ .or_else(|| detected.first().map(|d| d.path.clone()));
+ let check = match in_use {
+ Some(p) => Some(probe(kind, &p).await),
+ None => None,
+ };
+ out.push(KindReport {
+ kind,
+ source: source(kind),
+ path,
+ detected,
+ check,
+ expected: tools_for(kind, HostOs::current())
+ .iter()
+ .map(|t| t.name.to_string())
+ .collect(),
+ });
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn versions_and_tools_are_read_from_version_answers() {
+ assert_eq!(
+ version_in("Docker version 27.3.1, build ce12230").as_deref(),
+ Some("27.3.1")
+ );
+ assert_eq!(version_in("podman version 5.2.1").as_deref(), Some("5.2.1"));
+ assert_eq!(
+ version_in("Firecracker v1.10.1\n\nSupported snapshot data format versions: v1.0.0")
+ .as_deref(),
+ Some("1.10.1")
+ );
+ assert_eq!(
+ version_in("QEMU emulator version 9.1.0").as_deref(),
+ Some("9.1.0")
+ );
+ assert_eq!(
+ version_in("container CLI version 0.6.0 (build: release, commit: 1a2b3c4)").as_deref(),
+ Some("0.6.0")
+ );
+ assert_eq!(version_in("0.6.0").as_deref(), Some("0.6.0"));
+ assert_eq!(version_in("no version here"), None);
+ let id = |f: &str, t: &str| identify(f, t).map(|t| t.id);
+ assert_eq!(
+ id("docker", "Docker version 27.3.1, build ce12230"),
+ Some("docker")
+ );
+ assert_eq!(id("podman", "podman version 5.2.1"), Some("podman"));
+ assert_eq!(
+ id("container", "container CLI version 0.6.0 (build: release)"),
+ Some("container")
+ );
+ assert_eq!(
+ id("firecracker", "Firecracker v1.10.1"),
+ Some("firecracker")
+ );
+ assert_eq!(
+ id("qemu-system-aarch64", "QEMU emulator version 9.1.0"),
+ Some("qemu")
+ );
+ assert_eq!(id("lume", "0.6.0"), Some("lume"));
+ // Only a Lume answers with a bare version.
+ assert_eq!(id("sh", "0.6.0"), None);
+ assert_eq!(id("ls", "ls: illegal option -- -"), None);
+ }
+
+ #[cfg(feature = "lume")]
+ #[test]
+ fn lume_s_oldest_version_is_the_one_cua_runs_on() {
+ assert_eq!(LUME_MIN_VERSION, crate::lume::builtin::MIN_VERSION);
+ }
+
+ #[test]
+ fn each_kind_takes_its_own_tools_per_system() {
+ let ids = |k, os| tools_for(k, os).iter().map(|t| t.id).collect::<Vec<_>>();
+ assert_eq!(
+ ids(RuntimeKind::Container, HostOs::Macos),
+ ["docker", "podman"]
+ );
+ assert_eq!(
+ ids(RuntimeKind::Container, HostOs::Linux),
+ ["docker", "podman"]
+ );
+ assert_eq!(ids(RuntimeKind::Vm, HostOs::Macos), ["lume"]);
+ assert_eq!(ids(RuntimeKind::Vm, HostOs::Linux), ["qemu"]);
+ assert_eq!(ids(RuntimeKind::Microvm, HostOs::Macos), ["container"]);
+ assert_eq!(ids(RuntimeKind::Microvm, HostOs::Linux), ["firecracker"]);
+ assert_eq!(
+ RuntimeKind::parse("Virtual machines"),
+ Some(RuntimeKind::Vm)
+ );
+ assert_eq!(KindSource::parse("Built-in"), Some(KindSource::Builtin));
+ }
+
+ /// The new name wins; the old per-OS name still counts; a path is read
+ /// whatever the source.
+ #[test]
+ fn settings_read_new_then_old_names() {
+ let d = tempfile::tempdir().unwrap();
+ let config = d.path().join("config.toml");
+ std::fs::write(
+ &config,
+ "[runtime]\nlinux = \"builtin\"\nlume = \"system\"\n",
+ )
+ .unwrap();
+ assert_eq!(
+ source_in(RuntimeKind::Container, &config),
+ KindSource::Builtin
+ );
+ assert_eq!(source_in(RuntimeKind::Vm, &config), KindSource::System);
+ assert_eq!(source_in(RuntimeKind::Microvm, &config), KindSource::Auto);
+ std::fs::write(
+ &config,
+ "[runtime]\nlinux = \"builtin\"\ncontainer = \"system\"\ncontainer_path = \"/opt/homebrew/bin/podman\"\n",
+ )
+ .unwrap();
+ assert_eq!(
+ source_in(RuntimeKind::Container, &config),
+ KindSource::System
+ );
+ assert_eq!(
+ custom_path_in(RuntimeKind::Container, &config),
+ Some(PathBuf::from("/opt/homebrew/bin/podman"))
+ );
+ assert_eq!(custom_path_in(RuntimeKind::Vm, &config), None);
+ }
+
+ /// A fake Docker: what it is and its version; a script that is not one;
+ /// a file that cannot run; nothing there.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_path_is_probed_for_what_it_is() {
+ use std::os::unix::fs::PermissionsExt;
+ let d = tempfile::tempdir().unwrap();
+ let script = |name: &str, body: &str, mode: u32| {
+ let p = d.path().join(name);
+ std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode)).unwrap();
+ p
+ };
+ let docker = script(
+ "docker",
+ "echo 'Docker version 27.3.1, build ce12230'",
+ 0o755,
+ );
+ let p = probe_on(RuntimeKind::Container, &docker, HostOs::Macos).await;
+ assert!(p.exists && p.executable);
+ assert_eq!(
+ (p.tool.as_deref(), p.version.as_deref()),
+ (Some("docker"), Some("27.3.1"))
+ );
+ assert_eq!(p.expected, ["Docker", "Podman"]);
+ // A Docker is not a microVM runtime.
+ let p = probe_on(RuntimeKind::Microvm, &docker, HostOs::Macos).await;
+ assert_eq!(
+ (p.tool, p.expected),
+ (None, vec!["Apple container".to_string()])
+ );
+ let other = script("tool", "echo 'something else 1.0'", 0o755);
+ assert_eq!(
+ probe_on(RuntimeKind::Container, &other, HostOs::Macos)
+ .await
+ .tool,
+ None
+ );
+ let plain = script("plain", "true", 0o644);
+ let p = probe_on(RuntimeKind::Container, &plain, HostOs::Macos).await;
+ assert!(p.exists && !p.executable);
+ let p = probe_on(
+ RuntimeKind::Container,
+ &d.path().join("missing"),
+ HostOs::Macos,
+ )
+ .await;
+ assert!(!p.exists && !p.executable);
+ let lume = script("lume", "echo 0.5.3", 0o755);
+ let p = probe_on(RuntimeKind::Vm, &lume, HostOs::Macos).await;
+ assert_eq!(
+ (
+ p.tool.as_deref(),
+ p.version.as_deref(),
+ p.min_version.as_deref(),
+ p.guests.as_deref()
+ ),
+ (Some("lume"), Some("0.5.3"), Some("0.6.0"), Some("macOS"))
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/src/lib.rs b/libs/cua/crates/cua-vmm/src/lib.rs
index d0499c7ce7..43087aa630 100644
--- a/libs/cua/crates/cua-vmm/src/lib.rs
+++ b/libs/cua/crates/cua-vmm/src/lib.rs
@@ -42,6 +42,7 @@ pub mod host;
pub mod hostvms;
pub mod identity_gate;
pub mod inject;
+pub mod kinds;
pub mod local_network;
#[cfg(feature = "lume")]
pub mod lume;
diff --git a/libs/cua/crates/cua-vmm/src/lume/builtin.rs b/libs/cua/crates/cua-vmm/src/lume/builtin.rs
index 8fd5166466..3c8a719be1 100644
--- a/libs/cua/crates/cua-vmm/src/lume/builtin.rs
+++ b/libs/cua/crates/cua-vmm/src/lume/builtin.rs
@@ -80,27 +80,21 @@ impl LumeSource {
/// The setting now: the environment, else the config file, else auto.
/// Read on every use, so a change in Settings applies at once.
pub fn current() -> Self {
- if let Some(s) = std::env::var(SETTING_ENV)
- .ok()
- .and_then(|v| Self::parse(&v))
- {
- return s;
- }
- Self::from_config(&host::cua_home().join("config.toml"))
+ Self::of(crate::kinds::source(crate::kinds::RuntimeKind::Vm))
}
- /// `[runtime] lume = "..."` in `path` (auto when absent or unreadable).
+ /// `[runtime] vm` (or the older `lume`) in `path` (auto when
+ /// absent or unreadable).
pub fn from_config(path: &Path) -> Self {
- std::fs::read_to_string(path)
- .ok()
- .and_then(|t| t.parse::<toml_edit::DocumentMut>().ok())
- .and_then(|d| {
- d.get("runtime")?
- .get("lume")?
- .as_str()
- .and_then(Self::parse)
- })
- .unwrap_or_default()
+ Self::of(crate::kinds::source_in(crate::kinds::RuntimeKind::Vm, path))
+ }
+
+ fn of(s: crate::kinds::KindSource) -> Self {
+ match s {
+ crate::kinds::KindSource::Auto => Self::Auto,
+ crate::kinds::KindSource::Builtin => Self::Builtin,
+ crate::kinds::KindSource::System => Self::System,
+ }
}
/// Whether the built-in Lume may be used (and downloaded).
@@ -151,7 +145,10 @@ pub fn resolve(source: LumeSource) -> Option<PathBuf> {
pub fn resolve_for(channel: CuaChannel, source: LumeSource) -> Option<PathBuf> {
let system = || system_lume(channel, host::which, &root());
match source {
- LumeSource::System => system(),
+ // `runtime.vm_path` overrides the one found on PATH.
+ LumeSource::System => crate::kinds::custom_path(crate::kinds::RuntimeKind::Vm)
+ .filter(|p| p.is_file())
+ .or_else(system),
LumeSource::Builtin => installed(),
LumeSource::Auto => system()
.filter(|p| system_binary_usable(source, binary_version_for(channel, p).as_deref()))
diff --git a/libs/cua/crates/cua-vmm/src/managed.rs b/libs/cua/crates/cua-vmm/src/managed.rs
index db05322707..fd6a1f4b77 100644
--- a/libs/cua/crates/cua-vmm/src/managed.rs
+++ b/libs/cua/crates/cua-vmm/src/managed.rs
@@ -200,27 +200,24 @@ impl LinuxSource {
/// The setting now: the environment, else the config file, else auto.
/// Read on every use, so a change in Settings applies at once.
pub fn current() -> Self {
- if let Some(s) = std::env::var(SETTING_ENV)
- .ok()
- .and_then(|v| Self::parse(&v))
- {
- return s;
- }
- Self::from_config(&host::cua_home().join("config.toml"))
+ Self::of(crate::kinds::source(crate::kinds::RuntimeKind::Container))
}
- /// `[runtime] linux = "..."` in `path` (auto when absent or unreadable).
+ /// `[runtime] container` (or the older `linux`) in `path` (auto when
+ /// absent or unreadable).
pub fn from_config(path: &Path) -> Self {
- std::fs::read_to_string(path)
- .ok()
- .and_then(|t| t.parse::<toml_edit::DocumentMut>().ok())
- .and_then(|d| {
- d.get("runtime")?
- .get("linux")?
- .as_str()
- .and_then(Self::parse)
- })
- .unwrap_or_default()
+ Self::of(crate::kinds::source_in(
+ crate::kinds::RuntimeKind::Container,
+ path,
+ ))
+ }
+
+ fn of(s: crate::kinds::KindSource) -> Self {
+ match s {
+ crate::kinds::KindSource::Auto => Self::Auto,
+ crate::kinds::KindSource::Builtin => Self::Builtin,
+ crate::kinds::KindSource::System => Self::System,
+ }
}
/// Whether the built-in runtime may be used (and downloaded).
diff --git a/libs/cua/crates/cua-vmm/src/microvm/assets.rs b/libs/cua/crates/cua-vmm/src/microvm/assets.rs
index 78be36e644..93d19ae74d 100644
--- a/libs/cua/crates/cua-vmm/src/microvm/assets.rs
+++ b/libs/cua/crates/cua-vmm/src/microvm/assets.rs
@@ -50,7 +50,8 @@ fn firecracker_url(arch: Arch) -> String {
)
}
-/// The `firecracker` binary: `$CUA_FIRECRACKER`, then `~/.cua/bin`, then
+/// The `firecracker` binary: `$CUA_FIRECRACKER`, then (with
+/// `runtime.microvm = system`) the installed one, else `~/.cua/bin`, then
/// `PATH`.
pub fn firecracker_bin() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("CUA_FIRECRACKER").map(PathBuf::from)
@@ -58,6 +59,12 @@ pub fn firecracker_bin() -> Option<PathBuf> {
{
return Some(p);
}
+ // `runtime.microvm = system`: the one already installed (its custom
+ // path, else the one on PATH), never cua's own.
+ if crate::kinds::source(crate::kinds::RuntimeKind::Microvm) == crate::kinds::KindSource::System
+ {
+ return crate::kinds::system_bin(crate::kinds::RuntimeKind::Microvm);
+ }
let own = host::cua_home().join("bin").join("firecracker");
if own.is_file() {
return Some(own);
diff --git a/libs/cua/crates/cua-vmm/src/qemu/mod.rs b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
index 8a37f08a8c..3393b3fd59 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
@@ -496,6 +496,13 @@ impl QemuRuntime {
pub async fn binary(&self, arch: Arch) -> Result<PathBuf> {
let name = format!("qemu-system-{}", arch.qemu());
+ // `runtime.vm_path` (with `runtime.vm = system`), when it is this
+ // arch's QEMU.
+ if let Some(p) = crate::kinds::configured_bin(crate::kinds::RuntimeKind::Vm)
+ .filter(|p| p.file_name().is_some_and(|n| n == name.as_str()))
+ {
+ return Ok(p);
+ }
if let Some(p) = host::which(&name) {
return Ok(p);
}
diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
index 8d6e01b827..856c4e0543 100644
--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
@@ -919,8 +919,14 @@ external fun uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json(
): Short
external fun uniffi_cua_sdk_checksum_method_agentsetup_detect(
): Short
+external fun uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json(
+): Short
+external fun uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json(
+): Short
external fun uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json(
): Short
+external fun uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json(
+): Short
external fun uniffi_cua_sdk_checksum_method_agentsetup_install_skills(
): Short
external fun uniffi_cua_sdk_checksum_method_agentsetup_onboarding_declined(
@@ -1097,6 +1103,10 @@ external fun uniffi_cua_sdk_checksum_method_local_pull_image(
): Short
external fun uniffi_cua_sdk_checksum_method_local_push_image(
): Short
+external fun uniffi_cua_sdk_checksum_method_local_runtime_check_path(
+): Short
+external fun uniffi_cua_sdk_checksum_method_local_runtime_kinds(
+): Short
external fun uniffi_cua_sdk_checksum_method_local_setup(
): Short
external fun uniffi_cua_sdk_checksum_method_local_storage(
@@ -1826,8 +1836,14 @@ external fun uniffi_cua_sdk_fn_method_agentsetup_connection_status_json(`ptr`: L
): RustBuffer.ByValue
external fun uniffi_cua_sdk_fn_method_agentsetup_detect(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
+external fun uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(`ptr`: Long,`agent`: RustBuffer.ByValue,
+): Long
+external fun uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(`ptr`: Long,`id`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_agentsetup_disconnect_json(`ptr`: Long,`agents`: RustBuffer.ByValue,`signIn`: Byte,
): Long
+external fun uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(`ptr`: Long,`agents`: RustBuffer.ByValue,`skills`: Byte,`mcp`: Byte,`signIn`: Byte,
+): Long
external fun uniffi_cua_sdk_fn_method_agentsetup_install_skills(`ptr`: Long,`agents`: RustBuffer.ByValue,`skills`: RustBuffer.ByValue,`force`: Byte,
): Long
external fun uniffi_cua_sdk_fn_method_agentsetup_onboarding_declined(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus,
@@ -2056,6 +2072,10 @@ external fun uniffi_cua_sdk_fn_method_local_pull_image(`ptr`: Long,`reference`:
): Long
external fun uniffi_cua_sdk_fn_method_local_push_image(`ptr`: Long,`reference`: RustBuffer.ByValue,`destination`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_local_runtime_check_path(`ptr`: Long,`kind`: RustBuffer.ByValue,`path`: RustBuffer.ByValue,
+): Long
+external fun uniffi_cua_sdk_fn_method_local_runtime_kinds(`ptr`: Long,
+): Long
external fun uniffi_cua_sdk_fn_method_local_setup(`ptr`: Long,`components`: RustBuffer.ByValue,`dryRun`: Byte,
): Long
external fun uniffi_cua_sdk_fn_method_local_storage(`ptr`: Long,
@@ -3255,9 +3275,18 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_agentsetup_detect() != 59369.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json() != 18365.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json() != 39143.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json() != 14363.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json() != 37278.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_agentsetup_install_skills() != 40049.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -3522,6 +3551,12 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_local_push_image() != 29472.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_local_runtime_check_path() != 59009.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cua_sdk_checksum_method_local_runtime_kinds() != 34595.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_local_setup() != 57791.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -5707,6 +5742,19 @@ public interface AgentSetupInterface {
*/
fun `detect`(): List<AgentInfo>
+ /**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+ suspend fun `deviceSignInStartJson`(`agent`: kotlin.String): kotlin.String
+
+ /**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+ suspend fun `deviceSignInWaitJson`(`id`: kotlin.String): kotlin.String
+
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
@@ -5714,6 +5762,13 @@ public interface AgentSetupInterface {
*/
suspend fun `disconnectJson`(`agents`: List<kotlin.String>, `signIn`: kotlin.Boolean): kotlin.String
+ /**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+ suspend fun `disconnectPartsJson`(`agents`: List<kotlin.String>, `skills`: kotlin.Boolean, `mcp`: kotlin.Boolean, `signIn`: kotlin.Boolean): kotlin.String
+
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -5962,6 +6017,57 @@ open class AgentSetup: Disposable, AutoCloseable, AgentSetupInterface
+ /**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `deviceSignInStartJson`(`agent`: kotlin.String) : kotlin.String {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(
+ uniffiHandle,
+ FfiConverterString.lower(`agent`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterString.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
+ /**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `deviceSignInWaitJson`(`id`: kotlin.String) : kotlin.String {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(
+ uniffiHandle,
+ FfiConverterString.lower(`id`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterString.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
@@ -5988,6 +6094,32 @@ open class AgentSetup: Disposable, AutoCloseable, AgentSetupInterface
}
+ /**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `disconnectPartsJson`(`agents`: List<kotlin.String>, `skills`: kotlin.Boolean, `mcp`: kotlin.Boolean, `signIn`: kotlin.Boolean) : kotlin.String {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(
+ uniffiHandle,
+ FfiConverterSequenceString.lower(`agents`),FfiConverterBoolean.lower(`skills`),FfiConverterBoolean.lower(`mcp`),FfiConverterBoolean.lower(`signIn`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterString.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -11018,6 +11150,22 @@ public interface LocalInterface {
*/
suspend fun `pushImage`(`reference`: kotlin.String, `destination`: kotlin.String): kotlin.String
+ /**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+ suspend fun `runtimeCheckPath`(`kind`: kotlin.String, `path`: kotlin.String): RuntimePathProbe
+
+ /**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+ suspend fun `runtimeKinds`(): List<RuntimeKindState>
+
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -11236,6 +11384,60 @@ open class Local: Disposable, AutoCloseable, LocalInterface
}
+ /**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `runtimeCheckPath`(`kind`: kotlin.String, `path`: kotlin.String) : RuntimePathProbe {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_check_path(
+ uniffiHandle,
+ FfiConverterString.lower(`kind`),FfiConverterString.lower(`path`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeRuntimePathProbe.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
+ /**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `runtimeKinds`() : List<RuntimeKindState> {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_kinds(
+ uniffiHandle,
+
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterSequenceTypeRuntimeKindState.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -31901,8 +32103,9 @@ public object FfiConverterTypeComputerResources: FfiConverterRustBuffer<Computer
*/
data class ConfigEntry (
/**
- * `default.on`, `default.kind`, `default.runtime`, `runtime.lume`,
- * `runtime.linux` or `telemetry.enabled`.
+ * `default.on`, `default.kind`, `default.runtime`, `runtime.container`,
+ * `runtime.vm`, `runtime.microvm` (and their `_path`) or
+ * `telemetry.enabled`.
*/
var `key`: kotlin.String
,
@@ -40550,6 +40753,244 @@ public object FfiConverterTypeRuntimeCheck: FfiConverterRustBuffer<RuntimeCheck>
+/**
+ * A runtime installed on this machine for one kind of Space.
+ */
+data class RuntimeDetected (
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */
+ var `tool`: kotlin.String
+ ,
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */
+ var `name`: kotlin.String
+ ,
+ var `path`: kotlin.String
+ ,
+ /**
+ * As `--version` says it (`27.3.1`).
+ */
+ var `version`: kotlin.String?
+ ,
+ /**
+ * The guest system it runs, when only one (`macOS`, `Linux`).
+ */
+ var `guests`: kotlin.String?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeRuntimeDetected: FfiConverterRustBuffer<RuntimeDetected> {
+ override fun read(buf: ByteBuffer): RuntimeDetected {
+ return RuntimeDetected(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: RuntimeDetected) = (
+ FfiConverterString.allocationSize(value.`tool`) +
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterString.allocationSize(value.`path`) +
+ FfiConverterOptionalString.allocationSize(value.`version`) +
+ FfiConverterOptionalString.allocationSize(value.`guests`)
+ )
+
+ override fun write(value: RuntimeDetected, buf: ByteBuffer) {
+ FfiConverterString.write(value.`tool`, buf)
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterString.write(value.`path`, buf)
+ FfiConverterOptionalString.write(value.`version`, buf)
+ FfiConverterOptionalString.write(value.`guests`, buf)
+ }
+}
+
+
+
+/**
+ * One kind of Space's runtime, as Settings shows it.
+ */
+data class RuntimeKindState (
+ /**
+ * `container`, `vm` or `microvm`.
+ */
+ var `kind`: kotlin.String
+ ,
+ /**
+ * `runtime.<kind>`: `auto`, `builtin` or `system`.
+ */
+ var `source`: kotlin.String
+ ,
+ /**
+ * `runtime.<kind>_path`, when set.
+ */
+ var `path`: kotlin.String?
+ ,
+ /**
+ * What is installed here for the kind, the one used first.
+ */
+ var `detected`: List<RuntimeDetected>
+ ,
+ /**
+ * The path in use (the custom one, else the first detected), probed.
+ */
+ var `check`: RuntimePathProbe?
+ ,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ var `expected`: List<kotlin.String>
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeRuntimeKindState: FfiConverterRustBuffer<RuntimeKindState> {
+ override fun read(buf: ByteBuffer): RuntimeKindState {
+ return RuntimeKindState(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterSequenceTypeRuntimeDetected.read(buf),
+ FfiConverterOptionalTypeRuntimePathProbe.read(buf),
+ FfiConverterSequenceString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: RuntimeKindState) = (
+ FfiConverterString.allocationSize(value.`kind`) +
+ FfiConverterString.allocationSize(value.`source`) +
+ FfiConverterOptionalString.allocationSize(value.`path`) +
+ FfiConverterSequenceTypeRuntimeDetected.allocationSize(value.`detected`) +
+ FfiConverterOptionalTypeRuntimePathProbe.allocationSize(value.`check`) +
+ FfiConverterSequenceString.allocationSize(value.`expected`)
+ )
+
+ override fun write(value: RuntimeKindState, buf: ByteBuffer) {
+ FfiConverterString.write(value.`kind`, buf)
+ FfiConverterString.write(value.`source`, buf)
+ FfiConverterOptionalString.write(value.`path`, buf)
+ FfiConverterSequenceTypeRuntimeDetected.write(value.`detected`, buf)
+ FfiConverterOptionalTypeRuntimePathProbe.write(value.`check`, buf)
+ FfiConverterSequenceString.write(value.`expected`, buf)
+ }
+}
+
+
+
+/**
+ * What a binary is, for one kind of Space (`runtime_check_path`).
+ */
+data class RuntimePathProbe (
+ var `path`: kotlin.String
+ ,
+ /**
+ * A file is there.
+ */
+ var `exists`: kotlin.Boolean
+ ,
+ /**
+ * It can be run.
+ */
+ var `executable`: kotlin.Boolean
+ ,
+ /**
+ * The tool it is, when it is one the kind takes.
+ */
+ var `tool`: kotlin.String?
+ ,
+ var `name`: kotlin.String?
+ ,
+ var `version`: kotlin.String?
+ ,
+ /**
+ * The oldest version cua runs on.
+ */
+ var `minVersion`: kotlin.String?
+ ,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ var `expected`: List<kotlin.String>
+ ,
+ var `guests`: kotlin.String?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeRuntimePathProbe: FfiConverterRustBuffer<RuntimePathProbe> {
+ override fun read(buf: ByteBuffer): RuntimePathProbe {
+ return RuntimePathProbe(
+ FfiConverterString.read(buf),
+ FfiConverterBoolean.read(buf),
+ FfiConverterBoolean.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: RuntimePathProbe) = (
+ FfiConverterString.allocationSize(value.`path`) +
+ FfiConverterBoolean.allocationSize(value.`exists`) +
+ FfiConverterBoolean.allocationSize(value.`executable`) +
+ FfiConverterOptionalString.allocationSize(value.`tool`) +
+ FfiConverterOptionalString.allocationSize(value.`name`) +
+ FfiConverterOptionalString.allocationSize(value.`version`) +
+ FfiConverterOptionalString.allocationSize(value.`minVersion`) +
+ FfiConverterSequenceString.allocationSize(value.`expected`) +
+ FfiConverterOptionalString.allocationSize(value.`guests`)
+ )
+
+ override fun write(value: RuntimePathProbe, buf: ByteBuffer) {
+ FfiConverterString.write(value.`path`, buf)
+ FfiConverterBoolean.write(value.`exists`, buf)
+ FfiConverterBoolean.write(value.`executable`, buf)
+ FfiConverterOptionalString.write(value.`tool`, buf)
+ FfiConverterOptionalString.write(value.`name`, buf)
+ FfiConverterOptionalString.write(value.`version`, buf)
+ FfiConverterOptionalString.write(value.`minVersion`, buf)
+ FfiConverterSequenceString.write(value.`expected`, buf)
+ FfiConverterOptionalString.write(value.`guests`, buf)
+ }
+}
+
+
+
/**
* Options for [`Sandboxes::create`].
*/
@@ -50715,6 +51156,38 @@ public object FfiConverterOptionalTypePtySize: FfiConverterRustBuffer<PtySize?>
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeRuntimePathProbe: FfiConverterRustBuffer<RuntimePathProbe?> {
+ override fun read(buf: ByteBuffer): RuntimePathProbe? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeRuntimePathProbe.read(buf)
+ }
+
+ override fun allocationSize(value: RuntimePathProbe?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeRuntimePathProbe.allocationSize(value)
+ }
+ }
+
+ override fun write(value: RuntimePathProbe?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeRuntimePathProbe.write(value, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
@@ -53523,6 +53996,62 @@ public object FfiConverterSequenceTypeRuntimeCheck: FfiConverterRustBuffer<List<
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeRuntimeDetected: FfiConverterRustBuffer<List<RuntimeDetected>> {
+ override fun read(buf: ByteBuffer): List<RuntimeDetected> {
+ val len = buf.getInt()
+ return List<RuntimeDetected>(len) {
+ FfiConverterTypeRuntimeDetected.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<RuntimeDetected>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeRuntimeDetected.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<RuntimeDetected>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeRuntimeDetected.write(it, buf)
+ }
+ }
+}
+
+
+
+
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeRuntimeKindState: FfiConverterRustBuffer<List<RuntimeKindState>> {
+ override fun read(buf: ByteBuffer): List<RuntimeKindState> {
+ val len = buf.getInt()
+ return List<RuntimeKindState>(len) {
+ FfiConverterTypeRuntimeKindState.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<RuntimeKindState>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeRuntimeKindState.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<RuntimeKindState>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeRuntimeKindState.write(it, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.py
index 5b60a09ac3..9d944336bc 100644
--- a/libs/cua/python/src/cua/_native.py
+++ b/libs/cua/python/src/cua/_native.py
@@ -617,8 +617,14 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_agentsetup_detect() != 59369:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json() != 18365:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json() != 39143:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json() != 14363:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json() != 37278:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_agentsetup_install_skills() != 40049:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_agentsetup_onboarding_declined() != 55051:
@@ -781,6 +787,10 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_local_push_image() != 29472:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_local_runtime_check_path() != 59009:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_local_runtime_kinds() != 34595:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_local_setup() != 57791:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_local_storage() != 42598:
@@ -2563,12 +2573,30 @@ _UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_detect.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_detect.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_disconnect_json.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
ctypes.c_int8,
)
_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_disconnect_json.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.c_int8,
+ ctypes.c_int8,
+ ctypes.c_int8,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_install_skills.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -2993,6 +3021,16 @@ _UniffiLib.uniffi_cua_sdk_fn_method_local_push_image.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_local_push_image.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_check_path.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_check_path.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_kinds.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_kinds.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_local_setup.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -5042,9 +5080,18 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json.rest
_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_detect.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_detect.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_install_skills.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_agentsetup_install_skills.restype = ctypes.c_uint16
@@ -5288,6 +5335,12 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_local_pull_image.restype = ctypes.c_ui
_UniffiLib.uniffi_cua_sdk_checksum_method_local_push_image.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_local_push_image.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_local_runtime_check_path.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_local_runtime_check_path.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_local_runtime_kinds.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_local_runtime_kinds.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_local_setup.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_local_setup.restype = ctypes.c_uint16
@@ -21364,6 +21417,255 @@ class _UniffiFfiConverterTypeRoutineInfo(_UniffiConverterRustBuffer):
_UniffiFfiConverterOptionalString.write(value.last_outcome, buf)
_UniffiFfiConverterOptionalString.write(value.last_run_id, buf)
+@dataclass
+class RuntimeDetected:
+ """
+ A runtime installed on this machine for one kind of Space.
+"""
+ def __init__(self, *, tool:str, name:str, path:str, version:typing.Optional[str], guests:typing.Optional[str]):
+ self.tool = tool
+ self.name = name
+ self.path = path
+ self.version = version
+ self.guests = guests
+
+
+
+
+ def __str__(self):
+ return "RuntimeDetected(tool={}, name={}, path={}, version={}, guests={})".format(self.tool, self.name, self.path, self.version, self.guests)
+ def __eq__(self, other):
+ if self.tool != other.tool:
+ return False
+ if self.name != other.name:
+ return False
+ if self.path != other.path:
+ return False
+ if self.version != other.version:
+ return False
+ if self.guests != other.guests:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeRuntimeDetected(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return RuntimeDetected(
+ tool=_UniffiFfiConverterString.read(buf),
+ name=_UniffiFfiConverterString.read(buf),
+ path=_UniffiFfiConverterString.read(buf),
+ version=_UniffiFfiConverterOptionalString.read(buf),
+ guests=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.tool)
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterString.check_lower(value.path)
+ _UniffiFfiConverterOptionalString.check_lower(value.version)
+ _UniffiFfiConverterOptionalString.check_lower(value.guests)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.tool, buf)
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterString.write(value.path, buf)
+ _UniffiFfiConverterOptionalString.write(value.version, buf)
+ _UniffiFfiConverterOptionalString.write(value.guests, buf)
+
+class _UniffiFfiConverterSequenceTypeRuntimeDetected(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeRuntimeDetected.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeRuntimeDetected.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeRuntimeDetected.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class RuntimePathProbe:
+ """
+ What a binary is, for one kind of Space (`runtime_check_path`).
+"""
+ def __init__(self, *, path:str, exists:bool, executable:bool, tool:typing.Optional[str], name:typing.Optional[str], version:typing.Optional[str], min_version:typing.Optional[str], expected:typing.List[str], guests:typing.Optional[str]):
+ self.path = path
+ self.exists = exists
+ self.executable = executable
+ self.tool = tool
+ self.name = name
+ self.version = version
+ self.min_version = min_version
+ self.expected = expected
+ self.guests = guests
+
+
+
+
+ def __str__(self):
+ return "RuntimePathProbe(path={}, exists={}, executable={}, tool={}, name={}, version={}, min_version={}, expected={}, guests={})".format(self.path, self.exists, self.executable, self.tool, self.name, self.version, self.min_version, self.expected, self.guests)
+ def __eq__(self, other):
+ if self.path != other.path:
+ return False
+ if self.exists != other.exists:
+ return False
+ if self.executable != other.executable:
+ return False
+ if self.tool != other.tool:
+ return False
+ if self.name != other.name:
+ return False
+ if self.version != other.version:
+ return False
+ if self.min_version != other.min_version:
+ return False
+ if self.expected != other.expected:
+ return False
+ if self.guests != other.guests:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeRuntimePathProbe(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return RuntimePathProbe(
+ path=_UniffiFfiConverterString.read(buf),
+ exists=_UniffiFfiConverterBoolean.read(buf),
+ executable=_UniffiFfiConverterBoolean.read(buf),
+ tool=_UniffiFfiConverterOptionalString.read(buf),
+ name=_UniffiFfiConverterOptionalString.read(buf),
+ version=_UniffiFfiConverterOptionalString.read(buf),
+ min_version=_UniffiFfiConverterOptionalString.read(buf),
+ expected=_UniffiFfiConverterSequenceString.read(buf),
+ guests=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.path)
+ _UniffiFfiConverterBoolean.check_lower(value.exists)
+ _UniffiFfiConverterBoolean.check_lower(value.executable)
+ _UniffiFfiConverterOptionalString.check_lower(value.tool)
+ _UniffiFfiConverterOptionalString.check_lower(value.name)
+ _UniffiFfiConverterOptionalString.check_lower(value.version)
+ _UniffiFfiConverterOptionalString.check_lower(value.min_version)
+ _UniffiFfiConverterSequenceString.check_lower(value.expected)
+ _UniffiFfiConverterOptionalString.check_lower(value.guests)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.path, buf)
+ _UniffiFfiConverterBoolean.write(value.exists, buf)
+ _UniffiFfiConverterBoolean.write(value.executable, buf)
+ _UniffiFfiConverterOptionalString.write(value.tool, buf)
+ _UniffiFfiConverterOptionalString.write(value.name, buf)
+ _UniffiFfiConverterOptionalString.write(value.version, buf)
+ _UniffiFfiConverterOptionalString.write(value.min_version, buf)
+ _UniffiFfiConverterSequenceString.write(value.expected, buf)
+ _UniffiFfiConverterOptionalString.write(value.guests, buf)
+
+class _UniffiFfiConverterOptionalTypeRuntimePathProbe(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeRuntimePathProbe.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeRuntimePathProbe.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeRuntimePathProbe.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class RuntimeKindState:
+ """
+ One kind of Space's runtime, as Settings shows it.
+"""
+ def __init__(self, *, kind:str, source:str, path:typing.Optional[str], detected:typing.List[RuntimeDetected], check:typing.Optional[RuntimePathProbe], expected:typing.List[str]):
+ self.kind = kind
+ self.source = source
+ self.path = path
+ self.detected = detected
+ self.check = check
+ self.expected = expected
+
+
+
+
+ def __str__(self):
+ return "RuntimeKindState(kind={}, source={}, path={}, detected={}, check={}, expected={})".format(self.kind, self.source, self.path, self.detected, self.check, self.expected)
+ def __eq__(self, other):
+ if self.kind != other.kind:
+ return False
+ if self.source != other.source:
+ return False
+ if self.path != other.path:
+ return False
+ if self.detected != other.detected:
+ return False
+ if self.check != other.check:
+ return False
+ if self.expected != other.expected:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeRuntimeKindState(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return RuntimeKindState(
+ kind=_UniffiFfiConverterString.read(buf),
+ source=_UniffiFfiConverterString.read(buf),
+ path=_UniffiFfiConverterOptionalString.read(buf),
+ detected=_UniffiFfiConverterSequenceTypeRuntimeDetected.read(buf),
+ check=_UniffiFfiConverterOptionalTypeRuntimePathProbe.read(buf),
+ expected=_UniffiFfiConverterSequenceString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.kind)
+ _UniffiFfiConverterString.check_lower(value.source)
+ _UniffiFfiConverterOptionalString.check_lower(value.path)
+ _UniffiFfiConverterSequenceTypeRuntimeDetected.check_lower(value.detected)
+ _UniffiFfiConverterOptionalTypeRuntimePathProbe.check_lower(value.check)
+ _UniffiFfiConverterSequenceString.check_lower(value.expected)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.kind, buf)
+ _UniffiFfiConverterString.write(value.source, buf)
+ _UniffiFfiConverterOptionalString.write(value.path, buf)
+ _UniffiFfiConverterSequenceTypeRuntimeDetected.write(value.detected, buf)
+ _UniffiFfiConverterOptionalTypeRuntimePathProbe.write(value.check, buf)
+ _UniffiFfiConverterSequenceString.write(value.expected, buf)
+
class _UniffiFfiConverterSequenceTypeReadinessProbe(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -29509,6 +29811,19 @@ class AgentSetupProtocol(typing.Protocol):
def detect(self, ) -> typing.List[AgentInfo]:
"""
Every supported agent, installed or not (read-only).
+"""
+ raise NotImplementedError
+ async def device_sign_in_start_json(self, agent: str) -> str:
+ """
+ Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ link and the code, then wait with [`Self::device_sign_in_wait_json`].
+"""
+ raise NotImplementedError
+ async def device_sign_in_wait_json(self, id: str) -> str:
+ """
+ Waits for a device sign-in to be approved and saves it into Keyvault on
+ This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
"""
raise NotImplementedError
async def disconnect_json(self, agents: typing.List[str],sign_in: bool) -> str:
@@ -29516,6 +29831,13 @@ class AgentSetupProtocol(typing.Protocol):
Disconnect: what Connect did, undone (the previous config entry back
from Cua's record, the skills, and with `sign_in` the copy in
Keyvault). JSON `{outcomes, removed_sign_ins}`.
+"""
+ raise NotImplementedError
+ async def disconnect_parts_json(self, agents: typing.List[str],skills: bool,mcp: bool,sign_in: bool) -> str:
+ """
+ Disconnect of some parts only (an app's page's switches): Cua's skills
+ and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ `{outcomes, removed_sign_ins}`.
"""
raise NotImplementedError
async def install_skills(self, agents: typing.List[str],skills: typing.List[str],force: bool) -> typing.List[AgentSetupOutcome]:
@@ -29709,6 +30031,49 @@ class AgentSetup(AgentSetupProtocol):
*_uniffi_lowered_args,
)
return _uniffi_lift_return(_uniffi_ffi_result)
+ async def device_sign_in_start_json(self, agent: str) -> str:
+ """
+ Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ link and the code, then wait with [`Self::device_sign_in_wait_json`].
+"""
+
+ _UniffiFfiConverterString.check_lower(agent)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(agent),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterString.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def device_sign_in_wait_json(self, id: str) -> str:
+ """
+ Waits for a device sign-in to be approved and saves it into Keyvault on
+ This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+"""
+
+ _UniffiFfiConverterString.check_lower(id)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(id),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterString.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def disconnect_json(self, agents: typing.List[str],sign_in: bool) -> str:
"""
Disconnect: what Connect did, undone (the previous config entry back
@@ -29734,6 +30099,37 @@ class AgentSetup(AgentSetupProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def disconnect_parts_json(self, agents: typing.List[str],skills: bool,mcp: bool,sign_in: bool) -> str:
+ """
+ Disconnect of some parts only (an app's page's switches): Cua's skills
+ and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ `{outcomes, removed_sign_ins}`.
+"""
+
+ _UniffiFfiConverterSequenceString.check_lower(agents)
+
+ _UniffiFfiConverterBoolean.check_lower(skills)
+
+ _UniffiFfiConverterBoolean.check_lower(mcp)
+
+ _UniffiFfiConverterBoolean.check_lower(sign_in)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterSequenceString.lower(agents),
+ _UniffiFfiConverterBoolean.lower(skills),
+ _UniffiFfiConverterBoolean.lower(mcp),
+ _UniffiFfiConverterBoolean.lower(sign_in),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterString.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def install_skills(self, agents: typing.List[str],skills: typing.List[str],force: bool) -> typing.List[AgentSetupOutcome]:
"""
Installs `skills` (empty: all bundled) for `agents`. Folders cua did
@@ -31603,6 +31999,29 @@ class _UniffiFfiConverterTypeBuildListener:
def write(cls, value: BuildListener, buf: _UniffiRustBuffer):
buf.write_u64(cls.lower(value))
+class _UniffiFfiConverterSequenceTypeRuntimeKindState(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeRuntimeKindState.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeRuntimeKindState.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeRuntimeKindState.read(buf) for i in range(count)
+ ]
+
class _UniffiFfiConverterSequenceTypeSetupStep(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -31655,6 +32074,22 @@ class LocalProtocol(typing.Protocol):
"""
Copies an image (host architecture) to `destination`; returns the
pushed manifest digest.
+"""
+ raise NotImplementedError
+ async def runtime_check_path(self, kind: str,path: str) -> RuntimePathProbe:
+ """
+ What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ runnable, which runtime and its version. Settings checks a typed path
+ with it before it is saved (`runtime.<kind>_path`).
+"""
+ raise NotImplementedError
+ async def runtime_kinds(self, ) -> typing.List[RuntimeKindState]:
+ """
+ Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ setting (`runtime.<kind>`), the runtimes installed on this machine
+ for it and what the path in use is. Read-only: runs each runtime's
+ `--version`, nothing else; probed in this process (the daemon runs
+ on the same host).
"""
raise NotImplementedError
async def setup(self, components: typing.List[str],dry_run: bool) -> typing.List[SetupStep]:
@@ -31797,6 +32232,52 @@ class Local(LocalProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def runtime_check_path(self, kind: str,path: str) -> RuntimePathProbe:
+ """
+ What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ runnable, which runtime and its version. Settings checks a typed path
+ with it before it is saved (`runtime.<kind>_path`).
+"""
+
+ _UniffiFfiConverterString.check_lower(kind)
+
+ _UniffiFfiConverterString.check_lower(path)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(kind),
+ _UniffiFfiConverterString.lower(path),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeRuntimePathProbe.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_check_path(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def runtime_kinds(self, ) -> typing.List[RuntimeKindState]:
+ """
+ Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ setting (`runtime.<kind>`), the runtimes installed on this machine
+ for it and what the path in use is. Read-only: runs each runtime's
+ `--version`, nothing else; probed in this process (the daemon runs
+ on the same host).
+"""
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypeRuntimeKindState.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_local_runtime_kinds(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def setup(self, components: typing.List[str],dry_run: bool) -> typing.List[SetupStep]:
"""
Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
@@ -46859,6 +47340,9 @@ __all__ = [
"ResourcesSnapshot",
"ResourcesUpdate",
"RoutineInfo",
+ "RuntimeDetected",
+ "RuntimePathProbe",
+ "RuntimeKindState",
"SandboxCreateOptions",
"SandboxInfo",
"SandboxListing",
diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.py
index f3cdf2c9b4..520eff3cbc 100644
--- a/libs/cua/scripts/generate-app-core-ffi.py
+++ b/libs/cua/scripts/generate-app-core-ffi.py
@@ -54,7 +54,8 @@ TYPES = [
("login_item.rs", "login_item", ["LoginItemStatus", "LoginItemInput", "LoginItemPlan"]),
("local_network.rs", "local_network", ["LocalNetworkAccess", "LocalNetworkInput", "LocalNetworkStepKind", "LocalNetworkStep"]),
("experiments.rs", "experiments", ["Experiments"]),
- ("settings.rs", "settings", ["SwitcherTheme", "AppSettings", "KeyCombo", "SignInPhase", "TelemetryInput", "MicrovmInput", "SettingsInput", "SettingsRowKind", "SettingsOption", "SettingsRow", "SettingsSection", "SettingsPage"]),
+ ("runtimes.rs", "runtimes", ["DetectedRuntime", "RuntimePathCheck", "RuntimeKindInput", "RuntimesInput", "RuntimePathVerdict", "RuntimeSettingChange"]),
+ ("settings.rs", "settings", ["SwitcherTheme", "AppSettings", "KeyCombo", "SignInPhase", "TelemetryInput", "SettingsInput", "SettingsRowKind", "SettingsOption", "SettingsRow", "SettingsSection", "SettingsPage"]),
("sign_in.rs", "sign_in", ["SignInFailure", "SignInFooterState", "SignInFooterInput", "SignInToast", "SignInFooter"]),
("window.rs", "window", ["ChromeInput", "MainChrome", "MenuItemId", "MenuItem", "MenuInput"]),
("host.rs", "host", ["HostSummaryInput", "HostSetupRequest", "HostClient", "HostAccess", "HostPermissionInput", "HostProvidedSpace", "HostSpacesAudit", "HostState", "HostAccount", "HostAccountStep", "HostActionId", "HostSettingChange", "HostToggle", "HostConfirm", "HostAction", "HostAccessRow", "PermissionRow", "HostSetupChoice", "HostPanelView", "HostFormState", "HostFormAction", "HostFormChoice", "HostFormField", "HostFormView"]),
diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
index 9076fdf775..b06b51a0b6 100644
--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
@@ -1007,6 +1007,19 @@ public protocol AgentSetupProtocol: AnyObject, Sendable {
*/
func detect() -> [AgentInfo]
+ /**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+ func deviceSignInStartJson(agent: String) async throws -> String
+
+ /**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+ func deviceSignInWaitJson(id: String) async throws -> String
+
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
@@ -1014,6 +1027,13 @@ public protocol AgentSetupProtocol: AnyObject, Sendable {
*/
func disconnectJson(agents: [String], signIn: Bool) async throws -> String
+ /**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+ func disconnectPartsJson(agents: [String], skills: Bool, mcp: Bool, signIn: Bool) async throws -> String
+
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -1200,6 +1220,49 @@ open func detect() -> [AgentInfo] {
})
}
+ /**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+open func deviceSignInStartJson(agent: String)async throws -> String {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(agent)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterString.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
+ /**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+open func deviceSignInWaitJson(id: String)async throws -> String {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(id)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterString.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
@@ -1222,6 +1285,28 @@ open func disconnectJson(agents: [String], signIn: Bool)async throws -> String
)
}
+ /**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+open func disconnectPartsJson(agents: [String], skills: Bool, mcp: Bool, signIn: Bool)async throws -> String {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(
+ self.uniffiCloneHandle(),
+ FfiConverterSequenceString.lower(agents),FfiConverterBool.lower(skills),FfiConverterBool.lower(mcp),FfiConverterBool.lower(signIn)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterString.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -4479,6 +4564,22 @@ public protocol LocalProtocol: AnyObject, Sendable {
*/
func pushImage(reference: String, destination: String) async throws -> String
+ /**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+ func runtimeCheckPath(kind: String, path: String) async throws -> RuntimePathProbe
+
+ /**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+ func runtimeKinds() async throws -> [RuntimeKindState]
+
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -4635,6 +4736,52 @@ open func pushImage(reference: String, destination: String)async throws -> Stri
)
}
+ /**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+open func runtimeCheckPath(kind: String, path: String)async throws -> RuntimePathProbe {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_local_runtime_check_path(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(kind),FfiConverterString.lower(path)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeRuntimePathProbe_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
+ /**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+open func runtimeKinds()async throws -> [RuntimeKindState] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_local_runtime_kinds(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeRuntimeKindState.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -22453,8 +22600,9 @@ public func FfiConverterTypeComputerResources_lower(_ value: ComputerResources)
*/
public struct ConfigEntry: Equatable, Hashable {
/**
- * `default.on`, `default.kind`, `default.runtime`, `runtime.lume`,
- * `runtime.linux` or `telemetry.enabled`.
+ * `default.on`, `default.kind`, `default.runtime`, `runtime.container`,
+ * `runtime.vm`, `runtime.microvm` (and their `_path`) or
+ * `telemetry.enabled`.
*/
public var key: String
/**
@@ -22487,8 +22635,9 @@ public struct ConfigEntry: Equatable, Hashable {
// declare one manually.
public init(
/**
- * `default.on`, `default.kind`, `default.runtime`, `runtime.lume`,
- * `runtime.linux` or `telemetry.enabled`.
+ * `default.on`, `default.kind`, `default.runtime`, `runtime.container`,
+ * `runtime.vm`, `runtime.microvm` (and their `_path`) or
+ * `telemetry.enabled`.
*/key: String,
/**
* The effective value.
@@ -34076,6 +34225,323 @@ public func FfiConverterTypeRuntimeCheck_lower(_ value: RuntimeCheck) -> RustBuf
}
+/**
+ * A runtime installed on this machine for one kind of Space.
+ */
+public struct RuntimeDetected: Equatable, Hashable {
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */
+ public var tool: String
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */
+ public var name: String
+ public var path: String
+ /**
+ * As `--version` says it (`27.3.1`).
+ */
+ public var version: String?
+ /**
+ * The guest system it runs, when only one (`macOS`, `Linux`).
+ */
+ public var guests: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */tool: String,
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */name: String, path: String,
+ /**
+ * As `--version` says it (`27.3.1`).
+ */version: String?,
+ /**
+ * The guest system it runs, when only one (`macOS`, `Linux`).
+ */guests: String?) {
+ self.tool = tool
+ self.name = name
+ self.path = path
+ self.version = version
+ self.guests = guests
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension RuntimeDetected: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeRuntimeDetected: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> RuntimeDetected {
+ return
+ try RuntimeDetected(
+ tool: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ path: FfiConverterString.read(from: &buf),
+ version: FfiConverterOptionString.read(from: &buf),
+ guests: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: RuntimeDetected, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.tool, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.path, into: &buf)
+ FfiConverterOptionString.write(value.version, into: &buf)
+ FfiConverterOptionString.write(value.guests, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimeDetected_lift(_ buf: RustBuffer) throws -> RuntimeDetected {
+ return try FfiConverterTypeRuntimeDetected.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimeDetected_lower(_ value: RuntimeDetected) -> RustBuffer {
+ return FfiConverterTypeRuntimeDetected.lower(value)
+}
+
+
+/**
+ * One kind of Space's runtime, as Settings shows it.
+ */
+public struct RuntimeKindState: Equatable, Hashable {
+ /**
+ * `container`, `vm` or `microvm`.
+ */
+ public var kind: String
+ /**
+ * `runtime.<kind>`: `auto`, `builtin` or `system`.
+ */
+ public var source: String
+ /**
+ * `runtime.<kind>_path`, when set.
+ */
+ public var path: String?
+ /**
+ * What is installed here for the kind, the one used first.
+ */
+ public var detected: [RuntimeDetected]
+ /**
+ * The path in use (the custom one, else the first detected), probed.
+ */
+ public var check: RuntimePathProbe?
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ public var expected: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `container`, `vm` or `microvm`.
+ */kind: String,
+ /**
+ * `runtime.<kind>`: `auto`, `builtin` or `system`.
+ */source: String,
+ /**
+ * `runtime.<kind>_path`, when set.
+ */path: String?,
+ /**
+ * What is installed here for the kind, the one used first.
+ */detected: [RuntimeDetected],
+ /**
+ * The path in use (the custom one, else the first detected), probed.
+ */check: RuntimePathProbe?,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */expected: [String]) {
+ self.kind = kind
+ self.source = source
+ self.path = path
+ self.detected = detected
+ self.check = check
+ self.expected = expected
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension RuntimeKindState: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeRuntimeKindState: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> RuntimeKindState {
+ return
+ try RuntimeKindState(
+ kind: FfiConverterString.read(from: &buf),
+ source: FfiConverterString.read(from: &buf),
+ path: FfiConverterOptionString.read(from: &buf),
+ detected: FfiConverterSequenceTypeRuntimeDetected.read(from: &buf),
+ check: FfiConverterOptionTypeRuntimePathProbe.read(from: &buf),
+ expected: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: RuntimeKindState, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.kind, into: &buf)
+ FfiConverterString.write(value.source, into: &buf)
+ FfiConverterOptionString.write(value.path, into: &buf)
+ FfiConverterSequenceTypeRuntimeDetected.write(value.detected, into: &buf)
+ FfiConverterOptionTypeRuntimePathProbe.write(value.check, into: &buf)
+ FfiConverterSequenceString.write(value.expected, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimeKindState_lift(_ buf: RustBuffer) throws -> RuntimeKindState {
+ return try FfiConverterTypeRuntimeKindState.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimeKindState_lower(_ value: RuntimeKindState) -> RustBuffer {
+ return FfiConverterTypeRuntimeKindState.lower(value)
+}
+
+
+/**
+ * What a binary is, for one kind of Space (`runtime_check_path`).
+ */
+public struct RuntimePathProbe: Equatable, Hashable {
+ public var path: String
+ /**
+ * A file is there.
+ */
+ public var exists: Bool
+ /**
+ * It can be run.
+ */
+ public var executable: Bool
+ /**
+ * The tool it is, when it is one the kind takes.
+ */
+ public var tool: String?
+ public var name: String?
+ public var version: String?
+ /**
+ * The oldest version cua runs on.
+ */
+ public var minVersion: String?
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ public var expected: [String]
+ public var guests: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(path: String,
+ /**
+ * A file is there.
+ */exists: Bool,
+ /**
+ * It can be run.
+ */executable: Bool,
+ /**
+ * The tool it is, when it is one the kind takes.
+ */tool: String?, name: String?, version: String?,
+ /**
+ * The oldest version cua runs on.
+ */minVersion: String?,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */expected: [String], guests: String?) {
+ self.path = path
+ self.exists = exists
+ self.executable = executable
+ self.tool = tool
+ self.name = name
+ self.version = version
+ self.minVersion = minVersion
+ self.expected = expected
+ self.guests = guests
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension RuntimePathProbe: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeRuntimePathProbe: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> RuntimePathProbe {
+ return
+ try RuntimePathProbe(
+ path: FfiConverterString.read(from: &buf),
+ exists: FfiConverterBool.read(from: &buf),
+ executable: FfiConverterBool.read(from: &buf),
+ tool: FfiConverterOptionString.read(from: &buf),
+ name: FfiConverterOptionString.read(from: &buf),
+ version: FfiConverterOptionString.read(from: &buf),
+ minVersion: FfiConverterOptionString.read(from: &buf),
+ expected: FfiConverterSequenceString.read(from: &buf),
+ guests: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: RuntimePathProbe, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.path, into: &buf)
+ FfiConverterBool.write(value.exists, into: &buf)
+ FfiConverterBool.write(value.executable, into: &buf)
+ FfiConverterOptionString.write(value.tool, into: &buf)
+ FfiConverterOptionString.write(value.name, into: &buf)
+ FfiConverterOptionString.write(value.version, into: &buf)
+ FfiConverterOptionString.write(value.minVersion, into: &buf)
+ FfiConverterSequenceString.write(value.expected, into: &buf)
+ FfiConverterOptionString.write(value.guests, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimePathProbe_lift(_ buf: RustBuffer) throws -> RuntimePathProbe {
+ return try FfiConverterTypeRuntimePathProbe.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRuntimePathProbe_lower(_ value: RuntimePathProbe) -> RustBuffer {
+ return FfiConverterTypeRuntimePathProbe.lower(value)
+}
+
+
/**
* Options for [`Sandboxes::create`].
*/
@@ -46709,6 +47175,30 @@ fileprivate struct FfiConverterOptionTypePtySize: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeRuntimePathProbe: FfiConverterRustBuffer {
+ typealias SwiftType = RuntimePathProbe?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeRuntimePathProbe.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeRuntimePathProbe.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -49111,6 +49601,56 @@ fileprivate struct FfiConverterSequenceTypeRuntimeCheck: FfiConverterRustBuffer
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeRuntimeDetected: FfiConverterRustBuffer {
+ typealias SwiftType = [RuntimeDetected]
+
+ public static func write(_ value: [RuntimeDetected], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeRuntimeDetected.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [RuntimeDetected] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [RuntimeDetected]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeRuntimeDetected.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeRuntimeKindState: FfiConverterRustBuffer {
+ typealias SwiftType = [RuntimeKindState]
+
+ public static func write(_ value: [RuntimeKindState], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeRuntimeKindState.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [RuntimeKindState] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [RuntimeKindState]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeRuntimeKindState.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -50711,9 +51251,18 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_agentsetup_detect() != 59369) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json() != 18365) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json() != 39143) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json() != 14363) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json() != 37278) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_agentsetup_install_skills() != 40049) {
return InitializationResult.apiChecksumMismatch
}
@@ -50978,6 +51527,12 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_local_push_image() != 29472) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_local_runtime_check_path() != 59009) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_sdk_checksum_method_local_runtime_kinds() != 34595) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_local_setup() != 57791) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
index fd30524d3c..967d56aa0b 100644
--- a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
+++ b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
@@ -393,11 +393,26 @@ RustBuffer uniffi_cua_sdk_fn_method_agentsetup_connection_status_json(uint64_t p
RustBuffer uniffi_cua_sdk_fn_method_agentsetup_detect(uint64_t ptr, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DEVICE_SIGN_IN_START_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DEVICE_SIGN_IN_START_JSON
+uint64_t uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(uint64_t ptr, RustBuffer agent
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DEVICE_SIGN_IN_WAIT_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DEVICE_SIGN_IN_WAIT_JSON
+uint64_t uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(uint64_t ptr, RustBuffer id
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DISCONNECT_JSON
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DISCONNECT_JSON
uint64_t uniffi_cua_sdk_fn_method_agentsetup_disconnect_json(uint64_t ptr, RustBuffer agents, int8_t sign_in
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DISCONNECT_PARTS_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_DISCONNECT_PARTS_JSON
+uint64_t uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(uint64_t ptr, RustBuffer agents, int8_t skills, int8_t mcp, int8_t sign_in
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_INSTALL_SKILLS
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_AGENTSETUP_INSTALL_SKILLS
uint64_t uniffi_cua_sdk_fn_method_agentsetup_install_skills(uint64_t ptr, RustBuffer agents, RustBuffer skills, int8_t force
@@ -969,6 +984,16 @@ uint64_t uniffi_cua_sdk_fn_method_local_pull_image(uint64_t ptr, RustBuffer refe
uint64_t uniffi_cua_sdk_fn_method_local_push_image(uint64_t ptr, RustBuffer reference, RustBuffer destination
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_LOCAL_RUNTIME_CHECK_PATH
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_LOCAL_RUNTIME_CHECK_PATH
+uint64_t uniffi_cua_sdk_fn_method_local_runtime_check_path(uint64_t ptr, RustBuffer kind, RustBuffer path
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_LOCAL_RUNTIME_KINDS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_LOCAL_RUNTIME_KINDS
+uint64_t uniffi_cua_sdk_fn_method_local_runtime_kinds(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_LOCAL_SETUP
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_LOCAL_SETUP
uint64_t uniffi_cua_sdk_fn_method_local_setup(uint64_t ptr, RustBuffer components, int8_t dry_run
@@ -3863,12 +3888,30 @@ uint16_t uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DETECT
uint16_t uniffi_cua_sdk_checksum_method_agentsetup_detect(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DEVICE_SIGN_IN_START_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DEVICE_SIGN_IN_START_JSON
+uint16_t uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DEVICE_SIGN_IN_WAIT_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DEVICE_SIGN_IN_WAIT_JSON
+uint16_t uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DISCONNECT_JSON
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DISCONNECT_JSON
uint16_t uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DISCONNECT_PARTS_JSON
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_DISCONNECT_PARTS_JSON
+uint16_t uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_AGENTSETUP_INSTALL_SKILLS
@@ -4397,6 +4440,18 @@ uint16_t uniffi_cua_sdk_checksum_method_local_pull_image(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_LOCAL_PUSH_IMAGE
uint16_t uniffi_cua_sdk_checksum_method_local_push_image(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_LOCAL_RUNTIME_CHECK_PATH
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_LOCAL_RUNTIME_CHECK_PATH
+uint16_t uniffi_cua_sdk_checksum_method_local_runtime_check_path(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_LOCAL_RUNTIME_KINDS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_LOCAL_RUNTIME_KINDS
+uint16_t uniffi_cua_sdk_checksum_method_local_runtime_kinds(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_LOCAL_SETUP
diff --git a/libs/cua/typescript/src/native/cua_sdk-ffi.ts b/libs/cua/typescript/src/native/cua_sdk-ffi.ts
index 09975e0a66..7b9e355508 100644
--- a/libs/cua/typescript/src/native/cua_sdk-ffi.ts
+++ b/libs/cua/typescript/src/native/cua_sdk-ffi.ts
@@ -1013,11 +1013,26 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_agentsetup_disconnect_json": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8, FfiType.Int8, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_agentsetup_install_skills": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
@@ -1423,6 +1438,16 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_local_runtime_check_path": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_fn_method_local_runtime_kinds": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_local_setup": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
ret: FfiType.Handle,
@@ -3483,11 +3508,26 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_agentsetup_install_skills": {
args: [],
ret: FfiType.UInt16,
@@ -3893,6 +3933,16 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_local_runtime_check_path": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_sdk_checksum_method_local_runtime_kinds": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_local_setup": {
args: [],
ret: FfiType.UInt16,
@@ -5977,7 +6027,10 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_agentsetup_connect_json(uniffiSelf: bigint, agents: Uint8Array, server: Uint8Array, skills: number, mcp: number, signIn: number): bigint;
uniffi_cua_sdk_fn_method_agentsetup_connection_status_json(uniffiSelf: bigint, expected: Uint8Array, refresh: number, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_sdk_fn_method_agentsetup_detect(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(uniffiSelf: bigint, agent: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(uniffiSelf: bigint, id: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_agentsetup_disconnect_json(uniffiSelf: bigint, agents: Uint8Array, signIn: number): bigint;
+ uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(uniffiSelf: bigint, agents: Uint8Array, skills: number, mcp: number, signIn: number): bigint;
uniffi_cua_sdk_fn_method_agentsetup_install_skills(uniffiSelf: bigint, agents: Uint8Array, skills: Uint8Array, force: number): bigint;
uniffi_cua_sdk_fn_method_agentsetup_onboarding_declined(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_sdk_fn_method_agentsetup_remove(uniffiSelf: bigint, agents: Uint8Array, skills: number, mcp: number): bigint;
@@ -6059,6 +6112,8 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_local_doctor(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_local_pull_image(uniffiSelf: bigint, reference: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_local_push_image(uniffiSelf: bigint, reference: Uint8Array, destination: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_local_runtime_check_path(uniffiSelf: bigint, kind: Uint8Array, path: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_local_runtime_kinds(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_local_setup(uniffiSelf: bigint, components: Uint8Array, dryRun: number): bigint;
uniffi_cua_sdk_fn_method_local_storage(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_loginattempt_method(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -6471,7 +6526,10 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_agentsetup_connect_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_detect(): number;
+ uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json(): number;
+ uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json(): number;
+ uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json(): number;
uniffi_cua_sdk_checksum_method_agentsetup_install_skills(): number;
uniffi_cua_sdk_checksum_method_agentsetup_onboarding_declined(): number;
uniffi_cua_sdk_checksum_method_agentsetup_remove(): number;
@@ -6553,6 +6611,8 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_local_doctor(): number;
uniffi_cua_sdk_checksum_method_local_pull_image(): number;
uniffi_cua_sdk_checksum_method_local_push_image(): number;
+ uniffi_cua_sdk_checksum_method_local_runtime_check_path(): number;
+ uniffi_cua_sdk_checksum_method_local_runtime_kinds(): number;
uniffi_cua_sdk_checksum_method_local_setup(): number;
uniffi_cua_sdk_checksum_method_local_storage(): number;
uniffi_cua_sdk_checksum_method_loginattempt_method(): number;
diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.ts
index 14555b6d2e..a2aa8457d2 100644
--- a/libs/cua/typescript/src/native/cua_sdk.ts
+++ b/libs/cua/typescript/src/native/cua_sdk.ts
@@ -6776,8 +6776,9 @@ const FfiConverterTypeComputerResources = (() => {
*/
export type ConfigEntry = {
/**
- * `default.on`, `default.kind`, `default.runtime`, `runtime.lume`,
- * `runtime.linux` or `telemetry.enabled`.
+ * `default.on`, `default.kind`, `default.runtime`, `runtime.container`,
+ * `runtime.vm`, `runtime.microvm` (and their `_path`) or
+ * `telemetry.enabled`.
*/
key: string,
/**
@@ -16257,6 +16258,245 @@ const FfiConverterTypeRoutineInfo = (() => {
return new FFIConverter();
})();
+/**
+ * A runtime installed on this machine for one kind of Space.
+ */
+export type RuntimeDetected = {
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */
+ tool: string,
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */
+ name: string,
+ path: string,
+ /**
+ * As `--version` says it (`27.3.1`).
+ */
+ version?: string,
+ /**
+ * The guest system it runs, when only one (`macOS`, `Linux`).
+ */
+ guests?: string
+}
+
+/**
+ * Generated factory for {@link RuntimeDetected} record objects.
+ */
+export const RuntimeDetected = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<RuntimeDetected, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<RuntimeDetected>,
+ });
+})();
+
+const FfiConverterTypeRuntimeDetected = (() => {
+ type TypeName = RuntimeDetected;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ tool: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ path: FfiConverterString.read(from),
+ version: FfiConverterOptionalString.read(from),
+ guests: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.tool, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.path, into);
+ FfiConverterOptionalString.write(value.version, into);
+ FfiConverterOptionalString.write(value.guests, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.tool) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.path) +
+ FfiConverterOptionalString.allocationSize(value.version) +
+ FfiConverterOptionalString.allocationSize(value.guests);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * What a binary is, for one kind of Space (`runtime_check_path`).
+ */
+export type RuntimePathProbe = {
+ path: string,
+ /**
+ * A file is there.
+ */
+ exists: boolean,
+ /**
+ * It can be run.
+ */
+ executable: boolean,
+ /**
+ * The tool it is, when it is one the kind takes.
+ */
+ tool?: string,
+ name?: string,
+ version?: string,
+ /**
+ * The oldest version cua runs on.
+ */
+ minVersion?: string,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ expected: Array<string>,
+ guests?: string
+}
+
+/**
+ * Generated factory for {@link RuntimePathProbe} record objects.
+ */
+export const RuntimePathProbe = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<RuntimePathProbe, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<RuntimePathProbe>,
+ });
+})();
+
+const FfiConverterTypeRuntimePathProbe = (() => {
+ type TypeName = RuntimePathProbe;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ path: FfiConverterString.read(from),
+ exists: FfiConverterBool.read(from),
+ executable: FfiConverterBool.read(from),
+ tool: FfiConverterOptionalString.read(from),
+ name: FfiConverterOptionalString.read(from),
+ version: FfiConverterOptionalString.read(from),
+ minVersion: FfiConverterOptionalString.read(from),
+ expected: FfiConverterSequenceString.read(from),
+ guests: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.path, into);
+ FfiConverterBool.write(value.exists, into);
+ FfiConverterBool.write(value.executable, into);
+ FfiConverterOptionalString.write(value.tool, into);
+ FfiConverterOptionalString.write(value.name, into);
+ FfiConverterOptionalString.write(value.version, into);
+ FfiConverterOptionalString.write(value.minVersion, into);
+ FfiConverterSequenceString.write(value.expected, into);
+ FfiConverterOptionalString.write(value.guests, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.path) +
+ FfiConverterBool.allocationSize(value.exists) +
+ FfiConverterBool.allocationSize(value.executable) +
+ FfiConverterOptionalString.allocationSize(value.tool) +
+ FfiConverterOptionalString.allocationSize(value.name) +
+ FfiConverterOptionalString.allocationSize(value.version) +
+ FfiConverterOptionalString.allocationSize(value.minVersion) +
+ FfiConverterSequenceString.allocationSize(value.expected) +
+ FfiConverterOptionalString.allocationSize(value.guests);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * One kind of Space's runtime, as Settings shows it.
+ */
+export type RuntimeKindState = {
+ /**
+ * `container`, `vm` or `microvm`.
+ */
+ kind: string,
+ /**
+ * `runtime.<kind>`: `auto`, `builtin` or `system`.
+ */
+ source: string,
+ /**
+ * `runtime.<kind>_path`, when set.
+ */
+ path?: string,
+ /**
+ * What is installed here for the kind, the one used first.
+ */
+ detected: Array<RuntimeDetected>,
+ /**
+ * The path in use (the custom one, else the first detected), probed.
+ */
+ check?: RuntimePathProbe,
+ /**
+ * The names of the tools the kind takes here (`Docker`, `Podman`).
+ */
+ expected: Array<string>
+}
+
+/**
+ * Generated factory for {@link RuntimeKindState} record objects.
+ */
+export const RuntimeKindState = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<RuntimeKindState, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<RuntimeKindState>,
+ });
+})();
+
+const FfiConverterTypeRuntimeKindState = (() => {
+ type TypeName = RuntimeKindState;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ kind: FfiConverterString.read(from),
+ source: FfiConverterString.read(from),
+ path: FfiConverterOptionalString.read(from),
+ detected: FfiConverterSequenceTypeRuntimeDetected.read(from),
+ check: FfiConverterOptionalTypeRuntimePathProbe.read(from),
+ expected: FfiConverterSequenceString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.kind, into);
+ FfiConverterString.write(value.source, into);
+ FfiConverterOptionalString.write(value.path, into);
+ FfiConverterSequenceTypeRuntimeDetected.write(value.detected, into);
+ FfiConverterOptionalTypeRuntimePathProbe.write(value.check, into);
+ FfiConverterSequenceString.write(value.expected, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.kind) +
+ FfiConverterString.allocationSize(value.source) +
+ FfiConverterOptionalString.allocationSize(value.path) +
+ FfiConverterSequenceTypeRuntimeDetected.allocationSize(value.detected) +
+ FfiConverterOptionalTypeRuntimePathProbe.allocationSize(value.check) +
+ FfiConverterSequenceString.allocationSize(value.expected);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
// Enum: RegistrySecret
export enum RegistrySecret_Tags {
@@ -25503,12 +25743,29 @@ export interface AgentSetupLike {
* Every supported agent, installed or not (read-only).
*/
detect(): Array<AgentInfo>;
+/**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+ deviceSignInStartJson(agent: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+ deviceSignInWaitJson(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
* Keyvault). JSON `{outcomes, removed_sign_ins}`.
*/
disconnectJson(agents: Array<string>, signIn: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+ disconnectPartsJson(agents: Array<string>, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -25701,6 +25958,79 @@ private constructor(pointer: UniffiHandle) {
));
}
+/**
+ * Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login
+ * --device-auth` in a folder Cua owns). JSON `{id, url, code}`: show the
+ * link and the code, then wait with [`Self::device_sign_in_wait_json`].
+ */
+ async deviceSignInStartJson(agent: string, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_start_json(
+ uniffiTypeAgentSetupObjectFactory.clonePointer(this),FfiConverterString.lower(agent, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Waits for a device sign-in to be approved and saves it into Keyvault on
+ * This Mac. JSON: `{imported, refused, line}` (as Connect's `sign_in`).
+ */
+ async deviceSignInWaitJson(id: string, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_agentsetup_device_sign_in_wait_json(
+ uniffiTypeAgentSetupObjectFactory.clonePointer(this),FfiConverterString.lower(id, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Disconnect: what Connect did, undone (the previous config entry back
* from Cua's record, the skills, and with `sign_in` the copy in
@@ -25738,6 +26068,43 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Disconnect of some parts only (an app's page's switches): Cua's skills
+ * and/or its MCP entry, and with `sign_in` the copy in Keyvault. JSON
+ * `{outcomes, removed_sign_ins}`.
+ */
+ async disconnectPartsJson(agents: Array<string>, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_agentsetup_disconnect_parts_json(
+ uniffiTypeAgentSetupObjectFactory.clonePointer(this),FfiConverterSequenceString.lower(agents, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(skills, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(mcp, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(signIn, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Installs `skills` (empty: all bundled) for `agents`. Folders cua did
* not write are skipped unless `force`.
@@ -28150,6 +28517,20 @@ export interface LocalLike {
* pushed manifest digest.
*/
pushImage(reference: string, destination: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+/**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+ runtimeCheckPath(kind: string, path: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RuntimePathProbe>;
+/**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+ runtimeKinds(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<RuntimeKindState>>;
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -28332,6 +28713,82 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * What `path` is for `kind` (`container`, `vm`, `microvm`): there,
+ * runnable, which runtime and its version. Settings checks a typed path
+ * with it before it is saved (`runtime.<kind>_path`).
+ */
+ async runtimeCheckPath(kind: string, path: string, asyncOpts_?: { signal: AbortSignal }): Promise<RuntimePathProbe> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_local_runtime_check_path(
+ uniffiTypeLocalObjectFactory.clonePointer(this),FfiConverterString.lower(kind, nativeModule().rustbuffer_alloc),FfiConverterString.lower(path, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeRuntimePathProbe.lift.bind(FfiConverterTypeRuntimePathProbe),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Each kind of Space (`container`, `vm`, `microvm`) with its runtime
+ * setting (`runtime.<kind>`), the runtimes installed on this machine
+ * for it and what the path in use is. Read-only: runs each runtime's
+ * `--version`, nothing else; probed in this process (the daemon runs
+ * on the same host).
+ */
+ async runtimeKinds(asyncOpts_?: { signal: AbortSignal }): Promise<Array<RuntimeKindState>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_local_runtime_kinds(
+ uniffiTypeLocalObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeRuntimeKindState.lift.bind(FfiConverterSequenceTypeRuntimeKindState),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Provisions `components` (`qemu`, `lume`; `runsc` reports its plan).
* Empty = everything provisionable. `dry_run` only reports.
@@ -45656,6 +46113,12 @@ const FfiConverterSequenceTypeComputerResources = new FfiConverterArray(FfiConve
// FfiConverter for ComputerResources | undefined
const FfiConverterOptionalTypeComputerResources = new FfiConverterOptional(FfiConverterTypeComputerResources);
+// FfiConverter for Array<RuntimeDetected>
+const FfiConverterSequenceTypeRuntimeDetected = new FfiConverterArray(FfiConverterTypeRuntimeDetected);
+
+// FfiConverter for RuntimePathProbe | undefined
+const FfiConverterOptionalTypeRuntimePathProbe = new FfiConverterOptional(FfiConverterTypeRuntimePathProbe);
+
// FfiConverter for Array<ReadinessProbe>
const FfiConverterSequenceTypeReadinessProbe = new FfiConverterArray(FfiConverterTypeReadinessProbe);
@@ -45767,6 +46230,9 @@ const FfiConverterOptionalTypeAgentRunOptions = new FfiConverterOptional(FfiConv
// FfiConverter for Array<PairingCode>
const FfiConverterSequenceTypePairingCode = new FfiConverterArray(FfiConverterTypePairingCode);
+// FfiConverter for Array<RuntimeKindState>
+const FfiConverterSequenceTypeRuntimeKindState = new FfiConverterArray(FfiConverterTypeRuntimeKindState);
+
// FfiConverter for Array<SetupStep>
const FfiConverterSequenceTypeSetupStep = new FfiConverterArray(FfiConverterTypeSetupStep);
@@ -46158,9 +46624,18 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_detect() !== 59369) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_detect");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json() !== 18365) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_start_json");
+ }
+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json() !== 39143) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_device_sign_in_wait_json");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json() !== 14363) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_disconnect_json");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json() !== 37278) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_disconnect_parts_json");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_install_skills() !== 40049) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_install_skills");
}
@@ -46404,6 +46879,12 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_local_push_image() !== 29472) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_push_image");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_local_runtime_check_path() !== 59009) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_runtime_check_path");
+ }
+ if (nativeModule().uniffi_cua_sdk_checksum_method_local_runtime_kinds() !== 34595) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_runtime_kinds");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_local_setup() !== 57791) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_local_setup");
}
@@ -47646,6 +48127,9 @@ export default Object.freeze({
FfiConverterTypeRoutineInfo,
FfiConverterTypeRuntimeCheck,
FfiConverterTypeRuntimeCheckStatus,
+ FfiConverterTypeRuntimeDetected,
+ FfiConverterTypeRuntimeKindState,
+ FfiConverterTypeRuntimePathProbe,
FfiConverterTypeSandbox,
FfiConverterTypeSandboxCreateOptions,
FfiConverterTypeSandboxInfo,
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 06785407e7..1d8529ca75 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -12802,6 +12802,96 @@ public func FfiConverterTypeAppDetailCopy_lower(_ value: AppDetailCopy) -> RustB
}
+public struct AppDetectedRuntime: Equatable, Hashable {
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */
+ public var tool: String
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */
+ public var name: String
+ public var path: String
+ /**
+ * As its `--version` says it (`27.3.1`).
+ */
+ public var version: String?
+ /**
+ * The one guest system it runs, when only one (`macOS`, `Linux`).
+ */
+ public var guests: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `docker`, `podman`, `lume`, `qemu`, `container`, `firecracker`.
+ */tool: String,
+ /**
+ * As people know it (`Docker`, `Apple container`).
+ */name: String, path: String,
+ /**
+ * As its `--version` says it (`27.3.1`).
+ */version: String?,
+ /**
+ * The one guest system it runs, when only one (`macOS`, `Linux`).
+ */guests: String?) {
+ self.tool = tool
+ self.name = name
+ self.path = path
+ self.version = version
+ self.guests = guests
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppDetectedRuntime: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppDetectedRuntime: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppDetectedRuntime {
+ return
+ try AppDetectedRuntime(
+ tool: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ path: FfiConverterString.read(from: &buf),
+ version: FfiConverterOptionString.read(from: &buf),
+ guests: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppDetectedRuntime, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.tool, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.path, into: &buf)
+ FfiConverterOptionString.write(value.version, into: &buf)
+ FfiConverterOptionString.write(value.guests, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppDetectedRuntime_lift(_ buf: RustBuffer) throws -> AppDetectedRuntime {
+ return try FfiConverterTypeAppDetectedRuntime.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppDetectedRuntime_lower(_ value: AppDetectedRuntime) -> RustBuffer {
+ return FfiConverterTypeAppDetectedRuntime.lower(value)
+}
+
+
public struct AppDeviceBanner: Equatable, Hashable {
/**
* Tone.
@@ -25492,92 +25582,6 @@ public func FfiConverterTypeAppMenuPreviewRow_lower(_ value: AppMenuPreviewRow)
}
-public struct AppMicrovmInput: Equatable, Hashable {
- /**
- * This machine's system (`macos`, `linux`, `windows`).
- */
- public var os: AppSpaceOs?
- /**
- * Ready backends (none: not read yet).
- */
- public var localBackends: [String]?
- /**
- * Why each other backend is not ready, by backend name.
- */
- public var localDetails: [String: String]?
- /**
- * This machine's architecture (`arm64`, `amd64`).
- */
- public var hostArch: String?
-
- // Default memberwise initializers are never public by default, so we
- // declare one manually.
- public init(
- /**
- * This machine's system (`macos`, `linux`, `windows`).
- */os: AppSpaceOs?,
- /**
- * Ready backends (none: not read yet).
- */localBackends: [String]?,
- /**
- * Why each other backend is not ready, by backend name.
- */localDetails: [String: String]?,
- /**
- * This machine's architecture (`arm64`, `amd64`).
- */hostArch: String?) {
- self.os = os
- self.localBackends = localBackends
- self.localDetails = localDetails
- self.hostArch = hostArch
- }
-
-
-
-
-}
-
-#if compiler(>=6)
-extension AppMicrovmInput: Sendable {}
-#endif
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public struct FfiConverterTypeAppMicrovmInput: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppMicrovmInput {
- return
- try AppMicrovmInput(
- os: FfiConverterOptionTypeAppSpaceOs.read(from: &buf),
- localBackends: FfiConverterOptionSequenceString.read(from: &buf),
- localDetails: FfiConverterOptionDictionaryStringString.read(from: &buf),
- hostArch: FfiConverterOptionString.read(from: &buf)
- )
- }
-
- public static func write(_ value: AppMicrovmInput, into buf: inout [UInt8]) {
- FfiConverterOptionTypeAppSpaceOs.write(value.os, into: &buf)
- FfiConverterOptionSequenceString.write(value.localBackends, into: &buf)
- FfiConverterOptionDictionaryStringString.write(value.localDetails, into: &buf)
- FfiConverterOptionString.write(value.hostArch, into: &buf)
- }
-}
-
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeAppMicrovmInput_lift(_ buf: RustBuffer) throws -> AppMicrovmInput {
- return try FfiConverterTypeAppMicrovmInput.lift(buf)
-}
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeAppMicrovmInput_lower(_ value: AppMicrovmInput) -> RustBuffer {
- return FfiConverterTypeAppMicrovmInput.lower(value)
-}
-
-
public struct AppModeChoice: Equatable, Hashable {
/**
* What it means.
@@ -34384,6 +34388,340 @@ public func FfiConverterTypeAppRoutineInput_lower(_ value: AppRoutineInput) -> R
}
+public struct AppRuntimeKindInput: Equatable, Hashable {
+ /**
+ * `container`, `vm` or `microvm`.
+ */
+ public var kind: String
+ /**
+ * `runtime.<kind>`: `auto`, `builtin`, `system` (none: auto).
+ */
+ public var source: String?
+ /**
+ * `runtime.<kind>_path`, when set.
+ */
+ public var path: String?
+ /**
+ * What is installed for the kind, the one used first (none: not
+ * looked for yet).
+ */
+ public var detected: [AppDetectedRuntime]?
+ /**
+ * The path in use, probed.
+ */
+ public var check: AppRuntimePathCheck?
+ /**
+ * The tools the kind takes on this machine (`Docker`, `Podman`).
+ */
+ public var expected: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `container`, `vm` or `microvm`.
+ */kind: String,
+ /**
+ * `runtime.<kind>`: `auto`, `builtin`, `system` (none: auto).
+ */source: String?,
+ /**
+ * `runtime.<kind>_path`, when set.
+ */path: String?,
+ /**
+ * What is installed for the kind, the one used first (none: not
+ * looked for yet).
+ */detected: [AppDetectedRuntime]?,
+ /**
+ * The path in use, probed.
+ */check: AppRuntimePathCheck?,
+ /**
+ * The tools the kind takes on this machine (`Docker`, `Podman`).
+ */expected: [String]) {
+ self.kind = kind
+ self.source = source
+ self.path = path
+ self.detected = detected
+ self.check = check
+ self.expected = expected
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppRuntimeKindInput: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppRuntimeKindInput: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppRuntimeKindInput {
+ return
+ try AppRuntimeKindInput(
+ kind: FfiConverterString.read(from: &buf),
+ source: FfiConverterOptionString.read(from: &buf),
+ path: FfiConverterOptionString.read(from: &buf),
+ detected: FfiConverterOptionSequenceTypeAppDetectedRuntime.read(from: &buf),
+ check: FfiConverterOptionTypeAppRuntimePathCheck.read(from: &buf),
+ expected: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppRuntimeKindInput, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.kind, into: &buf)
+ FfiConverterOptionString.write(value.source, into: &buf)
+ FfiConverterOptionString.write(value.path, into: &buf)
+ FfiConverterOptionSequenceTypeAppDetectedRuntime.write(value.detected, into: &buf)
+ FfiConverterOptionTypeAppRuntimePathCheck.write(value.check, into: &buf)
+ FfiConverterSequenceString.write(value.expected, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimeKindInput_lift(_ buf: RustBuffer) throws -> AppRuntimeKindInput {
+ return try FfiConverterTypeAppRuntimeKindInput.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimeKindInput_lower(_ value: AppRuntimeKindInput) -> RustBuffer {
+ return FfiConverterTypeAppRuntimeKindInput.lower(value)
+}
+
+
+public struct AppRuntimePathCheck: Equatable, Hashable {
+ public var path: String
+ /**
+ * A file is there.
+ */
+ public var exists: Bool
+ /**
+ * It can be run.
+ */
+ public var executable: Bool
+ /**
+ * The tool it is, when it is one the kind takes.
+ */
+ public var tool: String?
+ public var name: String?
+ public var version: String?
+ /**
+ * The oldest version Cua runs on.
+ */
+ public var minVersion: String?
+ /**
+ * The tools the kind takes here (`Docker`, `Podman`).
+ */
+ public var expected: [String]
+ public var guests: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(path: String,
+ /**
+ * A file is there.
+ */exists: Bool,
+ /**
+ * It can be run.
+ */executable: Bool,
+ /**
+ * The tool it is, when it is one the kind takes.
+ */tool: String?, name: String?, version: String?,
+ /**
+ * The oldest version Cua runs on.
+ */minVersion: String?,
+ /**
+ * The tools the kind takes here (`Docker`, `Podman`).
+ */expected: [String], guests: String?) {
+ self.path = path
+ self.exists = exists
+ self.executable = executable
+ self.tool = tool
+ self.name = name
+ self.version = version
+ self.minVersion = minVersion
+ self.expected = expected
+ self.guests = guests
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppRuntimePathCheck: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppRuntimePathCheck: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppRuntimePathCheck {
+ return
+ try AppRuntimePathCheck(
+ path: FfiConverterString.read(from: &buf),
+ exists: FfiConverterBool.read(from: &buf),
+ executable: FfiConverterBool.read(from: &buf),
+ tool: FfiConverterOptionString.read(from: &buf),
+ name: FfiConverterOptionString.read(from: &buf),
+ version: FfiConverterOptionString.read(from: &buf),
+ minVersion: FfiConverterOptionString.read(from: &buf),
+ expected: FfiConverterSequenceString.read(from: &buf),
+ guests: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppRuntimePathCheck, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.path, into: &buf)
+ FfiConverterBool.write(value.exists, into: &buf)
+ FfiConverterBool.write(value.executable, into: &buf)
+ FfiConverterOptionString.write(value.tool, into: &buf)
+ FfiConverterOptionString.write(value.name, into: &buf)
+ FfiConverterOptionString.write(value.version, into: &buf)
+ FfiConverterOptionString.write(value.minVersion, into: &buf)
+ FfiConverterSequenceString.write(value.expected, into: &buf)
+ FfiConverterOptionString.write(value.guests, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimePathCheck_lift(_ buf: RustBuffer) throws -> AppRuntimePathCheck {
+ return try FfiConverterTypeAppRuntimePathCheck.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimePathCheck_lower(_ value: AppRuntimePathCheck) -> RustBuffer {
+ return FfiConverterTypeAppRuntimePathCheck.lower(value)
+}
+
+
+public struct AppRuntimePathVerdict: Equatable, Hashable {
+ public var ok: Bool
+ public var line: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(ok: Bool, line: String) {
+ self.ok = ok
+ self.line = line
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppRuntimePathVerdict: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppRuntimePathVerdict: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppRuntimePathVerdict {
+ return
+ try AppRuntimePathVerdict(
+ ok: FfiConverterBool.read(from: &buf),
+ line: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppRuntimePathVerdict, into buf: inout [UInt8]) {
+ FfiConverterBool.write(value.ok, into: &buf)
+ FfiConverterString.write(value.line, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimePathVerdict_lift(_ buf: RustBuffer) throws -> AppRuntimePathVerdict {
+ return try FfiConverterTypeAppRuntimePathVerdict.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimePathVerdict_lower(_ value: AppRuntimePathVerdict) -> RustBuffer {
+ return FfiConverterTypeAppRuntimePathVerdict.lower(value)
+}
+
+
+public struct AppRuntimeSettingChange: Equatable, Hashable {
+ /**
+ * `runtime.container`, `runtime.vm_path`.
+ */
+ public var key: String
+ public var value: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `runtime.container`, `runtime.vm_path`.
+ */key: String, value: String?) {
+ self.key = key
+ self.value = value
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppRuntimeSettingChange: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppRuntimeSettingChange: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppRuntimeSettingChange {
+ return
+ try AppRuntimeSettingChange(
+ key: FfiConverterString.read(from: &buf),
+ value: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppRuntimeSettingChange, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterOptionString.write(value.value, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimeSettingChange_lift(_ buf: RustBuffer) throws -> AppRuntimeSettingChange {
+ return try FfiConverterTypeAppRuntimeSettingChange.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimeSettingChange_lower(_ value: AppRuntimeSettingChange) -> RustBuffer {
+ return FfiConverterTypeAppRuntimeSettingChange.lower(value)
+}
+
+
public struct AppRuntimeSwitch: Equatable, Hashable {
/**
* The `cua config` setting: `runtime.lume`.
@@ -34470,6 +34808,102 @@ public func FfiConverterTypeAppRuntimeSwitch_lower(_ value: AppRuntimeSwitch) ->
}
+public struct AppRuntimesInput: Equatable, Hashable {
+ /**
+ * This machine's system (none: not said; every option is offered).
+ */
+ public var os: AppSpaceOs?
+ /**
+ * `arm64`, `amd64`.
+ */
+ public var hostArch: String?
+ /**
+ * The runtime doctor's ready backends (none: not read yet).
+ */
+ public var localBackends: [String]?
+ /**
+ * Why each other backend is not ready.
+ */
+ public var localDetails: [String: String]?
+ /**
+ * Each kind's setting and what is installed for it (none: not read).
+ */
+ public var kinds: [AppRuntimeKindInput]?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * This machine's system (none: not said; every option is offered).
+ */os: AppSpaceOs?,
+ /**
+ * `arm64`, `amd64`.
+ */hostArch: String?,
+ /**
+ * The runtime doctor's ready backends (none: not read yet).
+ */localBackends: [String]?,
+ /**
+ * Why each other backend is not ready.
+ */localDetails: [String: String]?,
+ /**
+ * Each kind's setting and what is installed for it (none: not read).
+ */kinds: [AppRuntimeKindInput]?) {
+ self.os = os
+ self.hostArch = hostArch
+ self.localBackends = localBackends
+ self.localDetails = localDetails
+ self.kinds = kinds
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppRuntimesInput: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppRuntimesInput: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppRuntimesInput {
+ return
+ try AppRuntimesInput(
+ os: FfiConverterOptionTypeAppSpaceOs.read(from: &buf),
+ hostArch: FfiConverterOptionString.read(from: &buf),
+ localBackends: FfiConverterOptionSequenceString.read(from: &buf),
+ localDetails: FfiConverterOptionDictionaryStringString.read(from: &buf),
+ kinds: FfiConverterOptionSequenceTypeAppRuntimeKindInput.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppRuntimesInput, into buf: inout [UInt8]) {
+ FfiConverterOptionTypeAppSpaceOs.write(value.os, into: &buf)
+ FfiConverterOptionString.write(value.hostArch, into: &buf)
+ FfiConverterOptionSequenceString.write(value.localBackends, into: &buf)
+ FfiConverterOptionDictionaryStringString.write(value.localDetails, into: &buf)
+ FfiConverterOptionSequenceTypeAppRuntimeKindInput.write(value.kinds, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimesInput_lift(_ buf: RustBuffer) throws -> AppRuntimesInput {
+ return try FfiConverterTypeAppRuntimesInput.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRuntimesInput_lower(_ value: AppRuntimesInput) -> RustBuffer {
+ return FfiConverterTypeAppRuntimesInput.lower(value)
+}
+
+
public struct AppSandboxImage: Equatable, Hashable {
/**
* OCI ref.
@@ -35249,26 +35683,17 @@ public struct AppSettingsInput: Equatable, Hashable {
* without the preview cover leaves it out).
*/
public var autoConnect: Bool?
- /**
- * Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,
- * `system`); none: no Runtimes section.
- */
- public var lumeSource: String?
- /**
- * Which engine local Linux Spaces run on (`runtime.linux`: `auto`,
- * `builtin`, `system`); none: no Linux row.
- */
- public var linuxSource: String?
/**
* Overflow into your clouds when this machine is full
* (`placement.overflow`); none: no row.
*/
public var overflow: Bool?
/**
- * What this machine's runtime doctor said, for Runtimes' MicroVM row
- * (whether microVMs run here, and why not); none: no MicroVM row.
+ * Settings, Advanced's runtimes: each kind's setting, what is
+ * installed for it and whether it runs here. None: nothing read yet
+ * (the rows still show, "Checking…").
*/
- public var microvm: AppMicrovmInput?
+ public var runtimes: AppRuntimesInput?
/**
* Settings, General's Show tips switch: tips are on
* (`!AppSettings.tips.off`). A shell that does not say reads as on.
@@ -35337,22 +35762,15 @@ public struct AppSettingsInput: Equatable, Hashable {
* "Connect to the desktop automatically" (none: no row; a shell
* without the preview cover leaves it out).
*/autoConnect: Bool?,
- /**
- * Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,
- * `system`); none: no Runtimes section.
- */lumeSource: String?,
- /**
- * Which engine local Linux Spaces run on (`runtime.linux`: `auto`,
- * `builtin`, `system`); none: no Linux row.
- */linuxSource: String?,
/**
* Overflow into your clouds when this machine is full
* (`placement.overflow`); none: no row.
*/overflow: Bool?,
/**
- * What this machine's runtime doctor said, for Runtimes' MicroVM row
- * (whether microVMs run here, and why not); none: no MicroVM row.
- */microvm: AppMicrovmInput?,
+ * Settings, Advanced's runtimes: each kind's setting, what is
+ * installed for it and whether it runs here. None: nothing read yet
+ * (the rows still show, "Checking…").
+ */runtimes: AppRuntimesInput?,
/**
* Settings, General's Show tips switch: tips are on
* (`!AppSettings.tips.off`). A shell that does not say reads as on.
@@ -35374,10 +35792,8 @@ public struct AppSettingsInput: Equatable, Hashable {
self.keyvaultSiteIcons = keyvaultSiteIcons
self.keyvaultProtection = keyvaultProtection
self.autoConnect = autoConnect
- self.lumeSource = lumeSource
- self.linuxSource = linuxSource
self.overflow = overflow
- self.microvm = microvm
+ self.runtimes = runtimes
self.showTips = showTips
}
@@ -35414,10 +35830,8 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {
keyvaultSiteIcons: FfiConverterBool.read(from: &buf),
keyvaultProtection: FfiConverterSequenceTypeAppFact.read(from: &buf),
autoConnect: FfiConverterOptionBool.read(from: &buf),
- lumeSource: FfiConverterOptionString.read(from: &buf),
- linuxSource: FfiConverterOptionString.read(from: &buf),
overflow: FfiConverterOptionBool.read(from: &buf),
- microvm: FfiConverterOptionTypeAppMicrovmInput.read(from: &buf),
+ runtimes: FfiConverterOptionTypeAppRuntimesInput.read(from: &buf),
showTips: FfiConverterBool.read(from: &buf)
)
}
@@ -35440,10 +35854,8 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {
FfiConverterBool.write(value.keyvaultSiteIcons, into: &buf)
FfiConverterSequenceTypeAppFact.write(value.keyvaultProtection, into: &buf)
FfiConverterOptionBool.write(value.autoConnect, into: &buf)
- FfiConverterOptionString.write(value.lumeSource, into: &buf)
- FfiConverterOptionString.write(value.linuxSource, into: &buf)
FfiConverterOptionBool.write(value.overflow, into: &buf)
- FfiConverterOptionTypeAppMicrovmInput.write(value.microvm, into: &buf)
+ FfiConverterOptionTypeAppRuntimesInput.write(value.runtimes, into: &buf)
FfiConverterBool.write(value.showTips, into: &buf)
}
}
@@ -70038,30 +70450,6 @@ fileprivate struct FfiConverterOptionTypeAppMenuPreview: FfiConverterRustBuffer
}
}
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-fileprivate struct FfiConverterOptionTypeAppMicrovmInput: FfiConverterRustBuffer {
- typealias SwiftType = AppMicrovmInput?
-
- public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
- guard let value = value else {
- writeInt(&buf, Int8(0))
- return
- }
- writeInt(&buf, Int8(1))
- FfiConverterTypeAppMicrovmInput.write(value, into: &buf)
- }
-
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
- switch try readInt(&buf) as Int8 {
- case 0: return nil
- case 1: return try FfiConverterTypeAppMicrovmInput.read(from: &buf)
- default: throw UniffiInternalError.unexpectedOptionalTag
- }
- }
-}
-
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -70566,6 +70954,54 @@ fileprivate struct FfiConverterOptionTypeAppReviewView: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppRuntimePathCheck: FfiConverterRustBuffer {
+ typealias SwiftType = AppRuntimePathCheck?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppRuntimePathCheck.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppRuntimePathCheck.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppRuntimeSettingChange: FfiConverterRustBuffer {
+ typealias SwiftType = AppRuntimeSettingChange?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppRuntimeSettingChange.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppRuntimeSettingChange.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -70590,6 +71026,30 @@ fileprivate struct FfiConverterOptionTypeAppRuntimeSwitch: FfiConverterRustBuffe
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppRuntimesInput: FfiConverterRustBuffer {
+ typealias SwiftType = AppRuntimesInput?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppRuntimesInput.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppRuntimesInput.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -71958,6 +72418,30 @@ fileprivate struct FfiConverterOptionSequenceTypeAppCatalogEntry: FfiConverterRu
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionSequenceTypeAppDetectedRuntime: FfiConverterRustBuffer {
+ typealias SwiftType = [AppDetectedRuntime]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterSequenceTypeAppDetectedRuntime.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterSequenceTypeAppDetectedRuntime.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -72030,6 +72514,30 @@ fileprivate struct FfiConverterOptionSequenceTypeAppRemoteWindow: FfiConverterRu
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionSequenceTypeAppRuntimeKindInput: FfiConverterRustBuffer {
+ typealias SwiftType = [AppRuntimeKindInput]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterSequenceTypeAppRuntimeKindInput.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterSequenceTypeAppRuntimeKindInput.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -73129,6 +73637,31 @@ fileprivate struct FfiConverterSequenceTypeAppDetailAction: FfiConverterRustBuff
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeAppDetectedRuntime: FfiConverterRustBuffer {
+ typealias SwiftType = [AppDetectedRuntime]
+
+ public static func write(_ value: [AppDetectedRuntime], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeAppDetectedRuntime.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppDetectedRuntime] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [AppDetectedRuntime]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeAppDetectedRuntime.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -75129,6 +75662,31 @@ fileprivate struct FfiConverterSequenceTypeAppRoutineInput: FfiConverterRustBuff
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeAppRuntimeKindInput: FfiConverterRustBuffer {
+ typealias SwiftType = [AppRuntimeKindInput]
+
+ public static func write(_ value: [AppRuntimeKindInput], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeAppRuntimeKindInput.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppRuntimeKindInput] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [AppRuntimeKindInput]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeAppRuntimeKindInput.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -79239,6 +79797,31 @@ public func appRowsToSpaces(rows: [AppSpaceRow], nowMs: Int64) -> [AppSpace] {
)
})
}
+/**
+ * A runtime binary's one line in Settings, Advanced ("Docker 27.3 found",
+ * "Not a Docker or Podman binary").
+ */
+public func appRuntimePathVerdict(check: AppRuntimePathCheck) -> AppRuntimePathVerdict {
+ return try! FfiConverterTypeAppRuntimePathVerdict_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_runtime_path_verdict(
+ FfiConverterTypeAppRuntimePathCheck_lower(check),$0
+ )
+})
+}
+/**
+ * The setting a runtime row's choice changes (`runtime.<kind>` or
+ * `runtime.<kind>_path`; a `None` value unsets it), or none for any other
+ * row.
+ */
+public func appRuntimesChoose(input: AppRuntimesInput?, row: String, option: String) -> AppRuntimeSettingChange? {
+ return try! FfiConverterOptionTypeAppRuntimeSettingChange.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_runtimes_choose(
+ FfiConverterOptionTypeAppRuntimesInput.lower(input),
+ FfiConverterString.lower(row),
+ FfiConverterString.lower(option),$0
+ )
+})
+}
/**
* The SDK's plan-option group for a picker group.
*/
@@ -81412,6 +81995,12 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_rows_to_spaces() != 20688) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_app_runtime_path_verdict() != 38898) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_app_runtimes_choose() != 22513) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_app_sensitive_group_sdk() != 32734) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
index 04c58a7bbc..3bc25312ee 100644
--- a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
+++ b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
@@ -1697,6 +1697,16 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_roster_reduce(RustBuffer state, Rus
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_rows_to_spaces(RustBuffer rows, int64_t now_ms, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_RUNTIME_PATH_VERDICT
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_RUNTIME_PATH_VERDICT
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_runtime_path_verdict(RustBuffer check, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_RUNTIMES_CHOOSE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_RUNTIMES_CHOOSE
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_runtimes_choose(RustBuffer input, RustBuffer row, RustBuffer option, RustCallStatus *_Nonnull out_status
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SENSITIVE_GROUP_SDK
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SENSITIVE_GROUP_SDK
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_sensitive_group_sdk(RustBuffer group, RustCallStatus *_Nonnull out_status
@@ -3868,6 +3878,18 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_roster_reduce(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ROWS_TO_SPACES
uint16_t uniffi_cua_spaces_ffi_checksum_func_app_rows_to_spaces(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_RUNTIME_PATH_VERDICT
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_RUNTIME_PATH_VERDICT
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_runtime_path_verdict(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_RUNTIMES_CHOOSE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_RUNTIMES_CHOOSE
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_runtimes_choose(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SENSITIVE_GROUP_SDK
diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.json
index 40986a5ff3..c503eee100 100644
--- a/scripts/docs-generators/cli-specs/cua.json
+++ b/scripts/docs-generators/cli-specs/cua.json
@@ -455,7 +455,7 @@
"aliases": [],
"default_value": false,
"env": null,
- "help": "Also copy each agent's sign-in to Keyvault on This Mac, so its runs in your Spaces use it: Codex's ChatGPT sign-in (`~/.codex/auth.json`), Claude Code's `claude setup-token` (one browser approval), Hermes' provider key (`~/.hermes/.env`). The agent's own sign-in is never changed",
+ "help": "Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed",
"hidden": false,
"name": "sign-in",
"repeatable": false,
@@ -729,7 +729,7 @@
"aliases": [],
"default_value": false,
"env": null,
- "help": "Also copy each agent's sign-in to Keyvault on This Mac, so its runs in your Spaces use it: Codex's ChatGPT sign-in (`~/.codex/auth.json`), Claude Code's `claude setup-token` (one browser approval), Hermes' provider key (`~/.hermes/.env`). The agent's own sign-in is never changed",
+ "help": "Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed",
"hidden": false,
"name": "sign-in",
"repeatable": false,
diff --git a/scripts/docs-generators/cua-sdk.ts b/scripts/docs-generators/cua-sdk.ts
index 3273ad030e..8776497ded 100644
--- a/scripts/docs-generators/cua-sdk.ts
+++ b/scripts/docs-generators/cua-sdk.ts
@@ -482,6 +482,15 @@ export const PAGES: PageSpec[] = [
modules: ['local'],
python: [['`cua_sandbox` runtimes', `${PY}/runtimes`]],
},
+ {
+ slug: 'runtime-kinds',
+ title: 'Runtime per kind',
+ description: 'Which program runs containers, virtual machines and microVMs on this machine, and what a given binary is.',
+ intro:
+ 'Each kind of Space has its own setting, `runtime.container`, `runtime.vm` and `runtime.microvm` (`auto`, `builtin` or `system`), and with `system` a `runtime.<kind>_path` naming the program to use. `runtime_kinds` reads them with what is installed for each kind; `runtime_check_path` tells what a binary is before it is saved. The Cua app\'s Settings, Advanced shows the same, and `cua` and the daemon use the same program.',
+ members: [{ object: 'Local', title: 'Runtime per kind methods', methods: ['runtime_kinds', 'runtime_check_path'] }],
+ items: ['RuntimeKindState', 'RuntimeDetected', 'RuntimePathProbe'],
+ },
{
slug: 'spaces',
title: 'Spaces',
@@ -991,7 +1000,7 @@ const TELEMETRY_CONCEPTS = ['../concepts/telemetry', '../concepts/telemetry-even
/** Groups of the reference sidebar; folders other generators own are listed by name. */
const NAV: Array<[label: string, pages: string[]]> = [
- ['Sandboxes', ['cua', 'sandbox', 'share', 'image', 'os-image-catalog', 'image-software', 'services', 'runtime-support']],
+ ['Sandboxes', ['cua', 'runtime-kinds', 'sandbox', 'share', 'image', 'os-image-catalog', 'image-software', 'services', 'runtime-support']],
['Inside a sandbox', ['spacesd', 'agents', 'agent-setup']],
['Spaces', ['spaces']],
['Account', ['auth']],