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.

fix(spaces): start never pulls a moved image, pending first message for a new home, pet-name default names (#6707)

ddupont8ef19f259a99
diff --git a/apps/cua-spaces-mobile/core/Cargo.lock b/apps/cua-spaces-mobile/core/Cargo.lock
index efc8a8cd7e..16e4083b22 100644
--- a/apps/cua-spaces-mobile/core/Cargo.lock
+++ b/apps/cua-spaces-mobile/core/Cargo.lock
@@ -271,6 +271,16 @@ dependencies = [
"cua-connections",
"cua-create-failure",
"cua-home",
+ "cua-spaces-contract",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "cua-spaces-contract"
+version = "0.11.0"
+dependencies = [
+ "schemars",
"serde",
"serde_json",
]
@@ -307,6 +317,12 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "dyn-clone"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -1022,6 +1038,26 @@ dependencies = [
"bitflags",
]
+[[package]]
+name = "ref-cast"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
+dependencies = [
+ "ref-cast-impl",
+]
+
+[[package]]
+name = "ref-cast-impl"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -1161,6 +1197,31 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "schemars"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"
+dependencies = [
+ "dyn-clone",
+ "ref-cast",
+ "schemars_derive",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "schemars_derive"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde_derive_internals",
+ "syn 3.0.9",
+]
+
[[package]]
name = "scopeguard"
version = "1.2.0"
@@ -1233,6 +1294,17 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "serde_derive_internals"
+version = "0.30.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
[[package]]
name = "serde_json"
version = "1.0.154"
diff --git a/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx
index e101c159a7..35783b88c0 100644
--- a/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx
@@ -75,7 +75,7 @@ describe.skipIf(!wasmBuilt)("the box with an agent home", () => {
return c!;
});
const config = (create.args as { config: Record<string, unknown> }).config;
- expect(config).toMatchObject({ image: AGENT_HOME_IMAGE, children: true, name: expect.stringMatching(/^home-/) });
+ expect(config).toMatchObject({ image: AGENT_HOME_IMAGE, children: true, name: expect.stringMatching(/^[a-z]+-[a-z]+$/) });
expect(config.labels).toMatchObject({ "cua.home": "1", "cua.home.agent": "openai-codex" });
expect(AGENT_HOME_IMAGE).toBe("ghcr.io/trycua/linux:24.04-slim");
expect(config).not.toHaveProperty("headless");
@@ -119,7 +119,7 @@ describe.skipIf(!wasmBuilt)("the box with an agent home", () => {
await act(async () => {
fireEvent.keyDown(box2, { key: "Enter" });
});
- await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\/local%3A(home-run-the-tests|agent-home-demo)/));
+ await waitFor(() => expect(router.state.location.pathname).toMatch(/^\/spaces\/local%3A([a-z]+-[a-z]+|agent-home-demo)/));
expect(calls.some((c) => c.op === "spaces.create")).toBe(false);
await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@claude run the tests again")).toBe(true), { timeout: 15000 });
});
diff --git a/apps/cua-spaces-web/src/__tests__/new-space-nits.test.tsx b/apps/cua-spaces-web/src/__tests__/new-space-nits.test.tsx
index 8fa1e5eedf..52f98510e3 100644
--- a/apps/cua-spaces-web/src/__tests__/new-space-nits.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/new-space-nits.test.tsx
@@ -84,7 +84,7 @@ describe.skipIf(!wasmBuilt)("New Space nits", () => {
await next(dialog);
const name = await waitFor(() => dialog.querySelector<HTMLInputElement>("[data-name-input]")!);
const generated = name.placeholder;
- expect(generated).toMatch(/^space-[0-9a-f]{10}$/);
+ expect(generated).toMatch(/^[a-z]+-[a-z]+$/);
await next(dialog);
await waitFor(() => expect(dialog.textContent).toContain(`Name${generated}`));
// The create uses it: the row while it is created carries the name.
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 5ceaa3521d..a7d8070cf0 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
@@ -7,29 +7,18 @@ import { firstMessage, newPendingId, useAgents, useBridge, useFeatureRecorder, u
import type { SpaceCreateConfig } from "@/bridge/contracts/host";
import { useChildren } from "@/components/children/use-children";
import { useSummonIn } from "@/components/ask-first/use-summon-in";
-import { enqueue, flushQueue, resolveQueue } from "@/components/space-thread/queued";
+import { dropQueue, enqueue, flushQueue, resolveQueue } from "@/components/space-thread/queued";
import { useConnectors } from "@/hooks/use-connectors";
import { containerHome } from "@/lib/agent-home/container";
import { grantsFor, homeGrantsArg, homeMentionsArg } from "@/lib/agent-home/grants";
import { homeForRequest, rememberHome } from "@/lib/agent-home/home-space";
+import { petName } from "@/lib/pet-name";
import { parseMentions } from "@/lib/agent-home/mentions";
import { homeBrief, homePrompt } from "@/lib/agent-home/prompt";
import type { AskRepo } from "@/lib/ask-first-repo";
import { getDriver } from "@/lib/prepare/store";
import { addAskTask, askTask, HOST_NOT_SHARED, hostSpaceId, postToSpaceThread, retryTarget, taskTarget, updateAskTask, whereOs, type AskTask, type TaskTarget, type TaskWhere } from "@/lib/ask-first";
-/** The home's name: short, and readable in the Spaces list. */
-export const homeName = (prompt: string, now = Date.now()) => {
- const slug = prompt
- .toLowerCase()
- .replace(/https?:\/\/\S+/g, " ")
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-+|-+$/g, "")
- .slice(0, 24)
- .replace(/-+$/g, "");
- return `home-${slug || "task"}-${now.toString(36).slice(-3)}`;
-};
-
/** The job as the agent is told it: the repo the person picked is a line of it, said once in plain words. */
export const withRepo = (prompt: string, repo?: { url: string } | null) => (repo ? `${prompt.trim()}\n\nRepo: ${repo.url}` : prompt);
@@ -127,7 +116,7 @@ export function useStartTask(): {
if (isHome && children) {
// The agent home: a slim Linux Space, the root of this person's tree (the agent decides where the work runs).
const agent = task0?.agent ?? "";
- const config: SpaceCreateConfig = containerHome.create(setupFor(agent, task0?.prompt ?? ""), homeName(task0?.prompt ?? ""));
+ const config: SpaceCreateConfig = containerHome.create(setupFor(agent, task0?.prompt ?? ""), petName((n) => (spaces ?? []).some((x) => x.name === n)));
space = await createSpace({ ...config, os: "linux" }, pendingId);
// The spawn capability, whatever the host did with `children` in the config.
children.setChildrenOn(space.id, true);
@@ -141,6 +130,8 @@ export function useStartTask(): {
spaceId = space.id;
updateAskTask(id, { spaceId, pendingId: null });
place?.onCreated?.(spaceId);
+ // A home's message was shown while it was made; it is posted below with its briefing.
+ if (isHome) resolveQueue(pendingId, spaceId);
if (place?.queued) {
// The job (and anything typed meanwhile) waited in the Space's thread: send it now.
resolveQueue(pendingId, spaceId);
@@ -163,7 +154,10 @@ export function useStartTask(): {
homeText = homePrompt(task?.prompt ?? "", setupFor(agent, task?.prompt ?? ""), containerHome.abilities(), task?.repo ?? undefined);
// A home takes the job through its member (a new one too): the chosen repo is a line of the message.
const brief = homeBrief(setupFor(agent, task?.prompt ?? ""), containerHome.abilities());
- if ((await reuseHome(spaceId, agent, prompt, task?.model, brief)) === "posted") {
+ const outcome = await reuseHome(spaceId, agent, prompt, task?.model, brief);
+ // Posted for real now (or not at all): the pending copy does not stay.
+ if (place?.pendingId) dropQueue(place.pendingId);
+ if (outcome === "posted") {
updateAskTask(id, { inSpace: true });
return;
}
@@ -181,6 +175,7 @@ export function useStartTask(): {
const started = await startRun({ spaceId, agent, prompt: homeText ?? prompt, ...(task?.model ? { model: task.model } : {}) });
updateAskTask(id, { runId: started.run_id, inSpace: true });
} catch (e) {
+ if (place?.pendingId) dropQueue(place.pendingId);
updateAskTask(id, { error: e instanceof Error ? e.message : String(e), pendingId: null });
}
})();
@@ -234,6 +229,11 @@ export function useStartTask(): {
// The job shows in the Space's thread at once, queued until the Space is ready (a home gets it with its briefing instead).
const first = !home && canSummon() ? firstMessage(core, { members: [], people: [], canAdd: true, connectors }, agent, withRepo(prompt, repo)) : null;
if (first?.handle) enqueue(pendingId, first.text);
+ // A new home is made first: the message shows in its thread right away, pending until the home can take it.
+ else if (home && canSummon()) {
+ const shown = firstMessage(core, { members: [], people: [], canAdd: true, connectors }, agent, withRepo(prompt, repo));
+ if (shown?.handle) enqueue(pendingId, shown.text);
+ }
run(task.id, target, { pendingId, onCreated, queued: Boolean(first?.handle) });
go(pendingId);
} else {
diff --git a/apps/cua-spaces-web/src/components/space-thread/queued.test.ts b/apps/cua-spaces-web/src/components/space-thread/queued.test.ts
new file mode 100644
index 0000000000..bd5c97bbb7
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/space-thread/queued.test.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// A message typed for a home that is still being made shows in its thread at once and leaves when really posted.
+
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { dropQueue, enqueue, resetQueued, resolveQueue, useQueued } from "./queued";
+
+describe("pending messages of a Space being made", () => {
+ beforeEach(() => resetQueued());
+
+ it("shows the message at once, keeps it when the create finishes, and drops it once posted", () => {
+ enqueue("pending-1", "@claude hi");
+ const early = renderHook(() => useQueued("pending-1"));
+ expect(early.result.current.map((q) => q.text)).toEqual(["@claude hi"]);
+
+ resolveQueue("pending-1", "local:brave-otter");
+ const created = renderHook(() => useQueued("local:brave-otter"));
+ expect(created.result.current.map((q) => q.text)).toEqual(["@claude hi"]);
+
+ dropQueue("pending-1");
+ const after = renderHook(() => useQueued("local:brave-otter"));
+ expect(after.result.current).toEqual([]);
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/space-thread/queued.ts b/apps/cua-spaces-web/src/components/space-thread/queued.ts
index 54337d74ec..b0aa201015 100644
--- a/apps/cua-spaces-web/src/components/space-thread/queued.ts
+++ b/apps/cua-spaces-web/src/components/space-thread/queued.ts
@@ -52,6 +52,17 @@ export function resolveQueue(pendingId: string, spaceId: string): void {
useQueue.setState((s) => ({ resolved: { ...s.resolved, [pendingId]: spaceId } }));
}
+/**
+ * Drops what `pendingId` shows without sending it: the message was posted by another path (a home's briefed
+ * first message), so it is in the thread for real now.
+ */
+export function dropQueue(pendingId: string): void {
+ useQueue.setState((s) => {
+ const { [pendingId]: _gone, ...rest } = s.byPending;
+ return { byPending: rest };
+ });
+}
+
/** 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 (;;) {
diff --git a/apps/cua-spaces-web/src/lib/pet-name.test.ts b/apps/cua-spaces-web/src/lib/pet-name.test.ts
new file mode 100644
index 0000000000..841c9a08ba
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/pet-name.test.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The friendly default names: the same lists as the core's (the core test fails when they drift).
+
+import { describe, expect, it } from "vitest";
+
+import { petName } from "./pet-name";
+import { PET_ADJECTIVES, PET_ANIMALS } from "./pet-names.generated";
+
+describe("petName", () => {
+ it("is a lowercase adjective-animal, DNS-safe", () => {
+ for (let i = 0; i < 200; i++) expect(petName(() => false)).toMatch(/^[a-z]+-[a-z]+$/);
+ });
+
+ it("retries another pair when taken, with a suffix only as the last resort", () => {
+ const seen: string[] = [];
+ const n = petName((c) => {
+ seen.push(c);
+ return seen.length === 1;
+ });
+ expect(n).not.toBe(seen[0]);
+ expect(n.split("-")).toHaveLength(2);
+ expect(petName((c) => c.split("-").length === 2).split("-")).toHaveLength(3);
+ });
+
+ it("lists are long enough and have no duplicates", () => {
+ for (const l of [PET_ADJECTIVES, PET_ANIMALS]) {
+ expect(l.length).toBeGreaterThanOrEqual(100);
+ expect(new Set(l).size).toBe(l.length);
+ for (const w of l) expect(w).toMatch(/^[a-z]+$/);
+ }
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/pet-name.ts b/apps/cua-spaces-web/src/lib/pet-name.ts
new file mode 100644
index 0000000000..89f64e51d0
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/pet-name.ts
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { PET_ADJECTIVES, PET_ANIMALS } from "./pet-names.generated";
+
+/**
+ * A friendly default name (`brave-otter`), as the daemon makes for a Space created without one. The page names a
+ * home before the daemon replies, so it carries the same lists (generated from the core's, with a drift test).
+ * A taken name is retried with another pair; a short suffix is the last resort.
+ */
+export function petName(taken: (name: string) => boolean, random: () => number = Math.random): string {
+ const pick = <T,>(l: readonly T[]) => l[Math.floor(random() * l.length)]!;
+ for (let i = 0; i < 64; i++) {
+ const n = `${pick(PET_ADJECTIVES)}-${pick(PET_ANIMALS)}`;
+ if (!taken(n)) return n;
+ }
+ for (;;) {
+ const n = `${pick(PET_ADJECTIVES)}-${pick(PET_ANIMALS)}-${Math.floor(random() * 0x10000)
+ .toString(16)
+ .padStart(4, "0")}`;
+ if (!taken(n)) return n;
+ }
+}
diff --git a/apps/cua-spaces-web/src/lib/pet-names.generated.ts b/apps/cua-spaces-web/src/lib/pet-names.generated.ts
new file mode 100644
index 0000000000..f2f893d0b0
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/pet-names.generated.ts
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Generated from libs/cua/crates/cua-spaces-contract/src/names.rs (CUA_UPDATE_PET_NAMES=1 cargo test -p cua-spaces-contract pet_names). Do not edit.
+export const PET_ADJECTIVES = ["agile", "amber", "ample", "bold", "brave", "breezy", "bright", "brisk", "calm", "candid", "careful", "clever", "cosmic", "cozy", "crisp", "curious", "dapper", "daring", "dewy", "deft", "eager", "early", "easy", "epic", "fair", "fancy", "fast", "fine", "fleet", "fond", "frosty", "gentle", "giant", "glad", "golden", "grand", "happy", "hardy", "honest", "humble", "jolly", "jovial", "keen", "kind", "lively", "lucky", "lunar", "mellow", "merry", "mighty", "mild", "misty", "modest", "nifty", "nimble", "noble", "novel", "open", "patient", "peppy", "placid", "plucky", "polite", "proud", "quick", "quiet", "rapid", "ready", "rosy", "royal", "rustic", "sandy", "serene", "shiny", "silent", "silver", "simple", "sleek", "smart", "smooth", "snowy", "solar", "solid", "spry", "steady", "stellar", "sunny", "super", "swift", "tidy", "tiny", "topaz", "true", "trusty", "upbeat", "vivid", "warm", "wise", "witty", "zesty", "zippy", "balmy", "lush", "azure", "ivory", "jade", "coral", "olive", "velvet"] as const;
+export const PET_ANIMALS = ["alpaca", "badger", "bat", "bear", "beaver", "bee", "bison", "bobcat", "camel", "cat", "civet", "cobra", "condor", "coyote", "crane", "crow", "deer", "dingo", "dolphin", "dove", "dragonfly", "eagle", "egret", "elk", "falcon", "ferret", "finch", "fox", "frog", "gecko", "gibbon", "goat", "goose", "gopher", "gull", "hare", "hawk", "hedgehog", "heron", "horse", "hound", "ibis", "iguana", "jackal", "jaguar", "jay", "kestrel", "kiwi", "koala", "lark", "lemur", "llama", "lynx", "magpie", "mallard", "marten", "meerkat", "mink", "mole", "moose", "moth", "mouse", "newt", "ocelot", "orca", "osprey", "otter", "owl", "panda", "parrot", "pelican", "penguin", "pika", "plover", "pony", "puffin", "puma", "quail", "rabbit", "raven", "robin", "salmon", "seal", "shrew", "skink", "sloth", "sparrow", "squid", "stoat", "stork", "swan", "tapir", "tern", "tiger", "toad", "trout", "turtle", "viper", "vole", "walrus", "weasel", "whale", "wolf", "wombat", "wren", "yak", "zebra"] as const;
diff --git a/apps/cua-spaces/core-wasm/Cargo.lock b/apps/cua-spaces/core-wasm/Cargo.lock
index 790098f2df..83c95c2e32 100644
--- a/apps/cua-spaces/core-wasm/Cargo.lock
+++ b/apps/cua-spaces/core-wasm/Cargo.lock
@@ -45,6 +45,16 @@ dependencies = [
"cua-connections",
"cua-create-failure",
"cua-home",
+ "cua-spaces-contract",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "cua-spaces-contract"
+version = "0.11.0"
+dependencies = [
+ "schemars",
"serde",
"serde_json",
]
@@ -59,6 +69,12 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "dyn-clone"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -164,12 +180,57 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "ref-cast"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
+dependencies = [
+ "ref-cast-impl",
+]
+
+[[package]]
+name = "ref-cast-impl"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "schemars"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"
+dependencies = [
+ "dyn-clone",
+ "ref-cast",
+ "schemars_derive",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "schemars_derive"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde_derive_internals",
+ "syn 3.0.6",
+]
+
[[package]]
name = "serde"
version = "1.0.229"
@@ -200,6 +261,17 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "serde_derive_internals"
+version = "0.30.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
[[package]]
name = "serde_json"
version = "1.0.151"
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index fb711ae77d..c35c147546 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -2330,6 +2330,7 @@ dependencies = [
"cua-create-failure",
"cua-home",
"cua-keyvault",
+ "cua-spaces-contract",
"cua-telemetry",
"serde",
"serde_json",
diff --git a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx
index 9adc2bb12c..35fa7f8fd5 100644
--- a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx
+++ b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx
@@ -15,7 +15,7 @@ import { MainWindow } from "./MainWindow";
import { createFakeCloudBridge, type CloudBridge } from '../../native/cloud';
/** A Space created unnamed: the name the wizard generated and showed. */
-const GENERATED = /space-[0-9a-f]{10}/;
+const GENERATED = /(?<![\w-])[a-z]{3,}-[a-z]{3,}(?![\w-])/;
const ROWS: SpaceRow[] = [
{ id: "relay:aurora", name: "aurora", provider: "relay", spacesdVersion: "0.4.0", features: [], os: "linux", reachable: true },
@@ -110,7 +110,7 @@ describe("MainWindow", () => {
on: "local",
kind: "vm",
runtime: "auto",
- name: expect.stringMatching(/^space-[0-9a-f]{10}$/),
+ name: expect.stringMatching(/^[a-z]+-[a-z]+$/),
cpus: 2,
memoryMb: 4096,
spacesd: true,
diff --git a/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx b/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx
index 287d2442e9..41cf5c1f59 100644
--- a/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx
+++ b/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx
@@ -166,7 +166,7 @@ describe("New Space wizard", () => {
fireEvent.change(screen.getByRole("slider", { name: "CPU cores" }), { target: { value: "3" } });
fireEvent.change(screen.getByRole("slider", { name: "Memory" }), { target: { value: "6" } });
next();
- fireEvent.change(screen.getByPlaceholderText(/^space-[0-9a-f]{10}$/), {
+ fireEvent.change(screen.getByPlaceholderText(/^[a-z]+-[a-z]+$/), {
target: { value: "cua-e2e-vm" },
});
next();
@@ -273,7 +273,7 @@ describe("New Space wizard", () => {
renderWizard();
next();
next();
- fireEvent.change(screen.getByPlaceholderText(/^space-[0-9a-f]{10}$/), { target: { value: "Bad Name" } });
+ fireEvent.change(screen.getByPlaceholderText(/^[a-z]+-[a-z]+$/), { target: { value: "Bad Name" } });
expect(screen.getByRole("button", { name: "Continue" })).toBeDisabled();
});
diff --git a/docs/content/docs/spaces/reference/spaces.mdx b/docs/content/docs/spaces/reference/spaces.mdx
index 5425a636da..0d9d13edd8 100644
--- a/docs/content/docs/spaces/reference/spaces.mdx
+++ b/docs/content/docs/spaces/reference/spaces.mdx
@@ -147,7 +147,7 @@ Creates a new sandbox where `on` says (local: this computer, free; aws, azure, g
| `instance_type` | `string` | none | With `on` a linked cloud (`aws`, `hetzner`, ...): the machine type its host must be (`c7g.xlarge`, `cax41`). Default: the elastic pool picks the cheapest that fits (cloud_plan shows it). |
| `kind` | `"auto" \| "container" \| "vm" \| "microvm"` | `auto` | What kind of computer. Default `auto` (from the image). `auto`: From the image: macOS and Windows images are VMs, an image with a container rootfs is a container, a disk-only image is a VM. `container`: A container (gVisor, or runc locally). `vm`: A virtual machine (QEMU or Lume locally, KubeVirt in the cloud). `microvm`: A microVM: the image's container rootfs booted with its own kernel (Firecracker on Linux with KVM; on a Mac, Virtualization.framework or Apple's Containerization). |
| `labels` | `map of string` | none | Labels kept with the Space and shown by `list_spaces` (`labels`): up to 64 pairs; keys and values are not empty; keys up to 63 bytes, values up to 256. Not with `durable` or `reuse`. |
-| `name` | `string` | none | Name. Default: a generated `space-<hex>`. |
+| `name` | `string` | none | Name. Default: a generated friendly name such as `brave-otter`. |
| `network` | `string` | none | Its network: `internet` (default: the internet and its own tree; this computer, the local network, cloud metadata and other trees are blocked), `none`, or `custom` / `custom:none` with `allow` and `deny`. Presets that open more (`localhost:<ports>`, `lan`, `unprotected`) are the user's to choose: refused here. |
| `on` | `string` | none | Where it runs: `local` (this computer, free), `auto` (the least-loaded of the user's computers that can take it: this one and the ones signed in to the user's account that provide Spaces, Modal only when connected and no computer has room), `aws`, `gcp` or `modal` (your own cloud account, billed there), or `host:<computer>`: one of the user's own computers that provides Spaces (`cua host setup --share both` on it), named by id or by words from its name ("host:spare mac mini" matches "Mac mini (spare)" or `dillons-mac-mini`). Default: the user's default location (`cua config set default.on`, `CUA_DEFAULT_ON`), else `local`; never `auto` unless asked. Not `direct:<addr>`: that is one already-running Space at a fixed address, attached with `add_space`, not a host this can create on. An existing computer is added with `add_space`, not created. |
| `parent` | `string` | none | Create it as a child of this Space (id or name): it joins the parent's tree, and its network is no more open than the parent's. |
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 1b75100493..ed824c286e 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -3301,6 +3301,7 @@ dependencies = [
"cua-host",
"cua-keyvault",
"cua-sandbox-core",
+ "cua-spaces-contract",
"cua-telemetry",
"serde",
"serde_json",
diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rs
index 6b29fa0e75..56da430aa4 100644
--- a/libs/cua/crates/cua-daemon/src/local.rs
+++ b/libs/cua/crates/cua-daemon/src/local.rs
@@ -579,6 +579,9 @@ pub struct VmmLocal {
/// host and refreshed in the background, so a create never waits on a
/// registry for a tag it resolved before.
resolved: Arc<std::sync::Mutex<HashMap<ResolveKey, (std::time::Instant, Resolved)>>>,
+ /// A newer image of a kept-warm request than the one creates are served
+ /// ([`hold_refresh`]), until a warm member of it is ready.
+ pending: Arc<std::sync::Mutex<HashMap<ResolveKey, Resolved>>>,
}
/// What an image placement is resolved for: image, OS, kind, runtime.
@@ -588,6 +591,29 @@ type ResolveKey = (String, String, String, String);
/// background; the create uses the cached one).
const RESOLVE_REFRESH: std::time::Duration = std::time::Duration::from_secs(60);
+/// What a refreshed placement does to the one creates are served.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Refresh {
+ /// Creates are served this one from now on.
+ Serve(Resolved),
+ /// Creates keep the current one; `next` is made ready first.
+ Hold { next: Resolved },
+}
+
+/// A request whose shape is kept warm must not move to a newer image
+/// (another digest) until a warm member of it is ready: a create would
+/// otherwise miss the pool and pull the image itself.
+pub(crate) fn hold_refresh(current: &Resolved, fresh: Resolved, kept_warm: bool) -> Refresh {
+ if kept_warm && fresh.placement.image != current.placement.image {
+ Refresh::Hold { next: fresh }
+ } else {
+ Refresh::Serve(fresh)
+ }
+}
+
+/// The source of the pool entry that makes the next image ready.
+const NEXT_SOURCE: &str = "warm-pools-next";
+
/// The container engine [`VmmLocal`] uses.
#[derive(Clone)]
enum Engine {
@@ -631,6 +657,7 @@ impl VmmLocal {
pool: std::sync::OnceLock::new(),
named_state: Default::default(),
resolved: Default::default(),
+ pending: Default::default(),
}
}
@@ -775,6 +802,9 @@ impl VmmLocal {
match self.keep_warm_space(pool).await {
Ok(()) => {
sources.insert(crate::pool::WARM_SOURCE.to_string());
+ if !self.pending.lock().unwrap().is_empty() {
+ sources.insert(NEXT_SOURCE.to_string());
+ }
}
Err(e) => tracing::warn!("warm-pools: {e}"),
}
@@ -804,7 +834,8 @@ impl VmmLocal {
pool.retain_explicit(|src| {
!(src.starts_with("warm:")
|| src.starts_with("pool:")
- || src == crate::pool::WARM_SOURCE)
+ || src == crate::pool::WARM_SOURCE
+ || src == NEXT_SOURCE)
|| sources.contains(src)
});
}
@@ -854,9 +885,77 @@ impl VmmLocal {
pool.set_prepare_first(&key, first);
pool.note_request(&p.spec, p.backend, spacesd, requested_words(&spec));
tracing::debug!(shape = %key, "warm-pools: keeping one Linux Space ready");
+ self.make_next_ready(pool, &spec, &image).await;
Ok(())
}
+ /// The image of the kept-warm request moved: pulls it and prepares a
+ /// member of it in the background, beside the one creates are served,
+ /// and serves creates the new image once that member is ready. The old
+ /// member stays claimable meanwhile, so no create pulls an image.
+ async fn make_next_ready(
+ &self,
+ pool: &crate::pool::WarmPool,
+ spec: &LocalStartSpec,
+ image: &str,
+ ) {
+ let keys: Vec<ResolveKey> = self
+ .pending
+ .lock()
+ .unwrap()
+ .keys()
+ .filter(|k| k.0 == image.trim())
+ .cloned()
+ .collect();
+ for key in keys {
+ let Some(next) = self.pending.lock().unwrap().get(&key).cloned() else {
+ continue;
+ };
+ let outcome = async {
+ let p = self
+ .prepare_with(spec, Some(next.clone()))
+ .await
+ .map_err(|e| e.to_string())?;
+ let spacesd = p.image.as_ref().and_then(|i| i.spacesd) == Some(true);
+ let (harnesses, first) = warm_pools_ordered();
+ let k = pool
+ .set_explicit_prepared(
+ NEXT_SOURCE,
+ &p.spec,
+ p.backend,
+ spacesd,
+ p.rt,
+ 1,
+ Some(1),
+ None,
+ Some(WARM_POOLS_IDLE),
+ Some(harnesses),
+ )
+ .ok_or_else(|| "this shape does not pool".to_string())?;
+ pool.set_prepare_first(&k, first);
+ Ok::<String, String>(k)
+ }
+ .await;
+ match outcome {
+ Ok(k) if pool.shape_status(&k).is_some_and(|(ready, _, _)| ready > 0) => {
+ tracing::info!(shape = %k, "warm-pools: the new image has a warm Space; creates use it");
+ self.resolved
+ .lock()
+ .unwrap()
+ .insert(key.clone(), (std::time::Instant::now(), next));
+ self.pending.lock().unwrap().remove(&key);
+ }
+ Ok(k) => {
+ tracing::debug!(shape = %k, "warm-pools: the new image is being made ready")
+ }
+ Err(e) => {
+ tracing::warn!("warm-pools: cannot prepare the new image: {e}");
+ self.pending.lock().unwrap().remove(&key);
+ }
+ }
+ }
+ }
+
/// Keeps `min` (at most `max`) members of `spec`'s shape for explicit
/// pool `source`; the shape key, or why it does not pool here.
async fn explicit(
@@ -926,15 +1025,30 @@ impl VmmLocal {
if let Some((at, r)) = cached {
if at.elapsed() >= RESOLVE_REFRESH {
let cache = self.resolved.clone();
+ let pending = self.pending.clone();
let (image, os, runtime) = (image.to_string(), os.to_string(), runtime.clone());
+ let served = r.clone();
tokio::spawn(async move {
- if let Ok(r) = resolve_placement_for(&image, &os, kind, &runtime, None).await
- && r.image.is_some()
+ if let Ok(fresh) =
+ resolve_placement_for(&image, &os, kind, &runtime, None).await
+ && fresh.image.is_some()
{
+ // The image of a kept-warm request moved: creates keep
+ // the one they were served until a warm member of the
+ // new one is ready, so none waits on its pull.
+ let kept = key.0 == warm_pools_image()
+ && cua_vmm::experiments::enabled(cua_vmm::experiments::Gate::WarmPools);
+ let next = match hold_refresh(&served, fresh, kept) {
+ Refresh::Serve(r) => r,
+ Refresh::Hold { next } => {
+ pending.lock().unwrap().insert(key.clone(), next);
+ served
+ }
+ };
cache
.lock()
.unwrap()
- .insert(key, (std::time::Instant::now(), r));
+ .insert(key, (std::time::Instant::now(), next));
}
});
}
@@ -1942,6 +2056,17 @@ impl VmmLocal {
/// Resolves `spec` (image placement, backend, runtime) into the
/// [`StartSpec`] its backend starts.
async fn prepare(&self, spec: &LocalStartSpec) -> RuntimeResult<Prepared> {
+ self.prepare_with(spec, None).await
+ }
+
+ /// [`Self::prepare`], with the placement given (`Some`) instead of read
+ /// from the registry or the cache: how the next image is made ready
+ /// before creates are served it.
+ async fn prepare_with(
+ &self,
+ spec: &LocalStartSpec,
+ forced: Option<Resolved>,
+ ) -> RuntimeResult<Prepared> {
use cua_sandbox_core::placement::{Kind, PlacementError, Runtime};
let kind = spec
.kind
@@ -1957,34 +2082,38 @@ impl VmmLocal {
.transpose()
.map_err(RuntimeError::InvalidPlacement)?
.unwrap_or_default();
- let mut r = self
- .resolve_cached(
- &spec.image,
- &spec.os,
- kind,
- &runtime,
- spec.registry_credentials.as_ref(),
- )
- .await
- .map_err(|e| match e {
- Error::Unsupported(m) => RuntimeError::UnsupportedImage(m),
- Error::InvalidPlacement {
- message,
- axis,
- valid,
- } => RuntimeError::InvalidPlacement(PlacementError {
- axis: match axis.as_str() {
- "on" => cua_sandbox_core::placement::Axis::On,
- "kind" => cua_sandbox_core::placement::Axis::Kind,
- "runtime" => cua_sandbox_core::placement::Axis::Runtime,
- _ => cua_sandbox_core::placement::Axis::Image,
- },
- given: spec.image.clone(),
- message,
- valid,
- }),
- other => RuntimeError::Other(other.to_string()),
- })?;
+ let resolved = match forced {
+ Some(r) => Ok(r),
+ None => {
+ self.resolve_cached(
+ &spec.image,
+ &spec.os,
+ kind,
+ &runtime,
+ spec.registry_credentials.as_ref(),
+ )
+ .await
+ }
+ };
+ let mut r = resolved.map_err(|e| match e {
+ Error::Unsupported(m) => RuntimeError::UnsupportedImage(m),
+ Error::InvalidPlacement {
+ message,
+ axis,
+ valid,
+ } => RuntimeError::InvalidPlacement(PlacementError {
+ axis: match axis.as_str() {
+ "on" => cua_sandbox_core::placement::Axis::On,
+ "kind" => cua_sandbox_core::placement::Axis::Kind,
+ "runtime" => cua_sandbox_core::placement::Axis::Runtime,
+ _ => cua_sandbox_core::placement::Axis::Image,
+ },
+ given: spec.image.clone(),
+ message,
+ valid,
+ }),
+ other => RuntimeError::Other(other.to_string()),
+ })?;
if missing_fallback_allowed(
kind,
&runtime,
@@ -3641,6 +3770,36 @@ fn claim_delivers_token(backend: BackendKind) -> bool {
#[cfg(test)]
mod tests {
+ use super::*;
+
+ fn resolved(reference: &str) -> Resolved {
+ Resolved {
+ placement: Placement {
+ backend: BackendKind::Container,
+ image: ImageSource::oci(reference),
+ },
+ arch: None,
+ image: None,
+ }
+ }
+
+ /// A moved image of a kept-warm request is held until a warm member of
+ /// it is ready, so a create never pulls; anything else follows at once.
+ #[test]
+ fn a_moved_image_of_a_kept_warm_request_is_held_until_ready() {
+ let old = resolved("ghcr.io/trycua/linux@sha256:aaa");
+ let new = resolved("ghcr.io/trycua/linux@sha256:bbb");
+ assert_eq!(
+ hold_refresh(&old, new.clone(), true),
+ Refresh::Hold { next: new.clone() }
+ );
+ assert_eq!(hold_refresh(&old, new.clone(), false), Refresh::Serve(new));
+ // The same digest again changes nothing.
+ assert_eq!(
+ hold_refresh(&old, old.clone(), true),
+ Refresh::Serve(old.clone())
+ );
+ }
#[test]
fn members_are_prepared_where_the_conformance_table_says() {
use crate::pool::PoolHost as _;
@@ -4010,8 +4169,6 @@ mod tests {
);
}
- use super::*;
-
#[test]
fn missing_fallback_requires_auto_linux_source() {
use cua_sandbox_core::placement::{Kind, Runtime};
diff --git a/libs/cua/crates/cua-spaces-app-core/Cargo.toml b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
index 62a498ba6c..14ae7aeeaf 100644
--- a/libs/cua/crates/cua-spaces-app-core/Cargo.toml
+++ b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
@@ -27,6 +27,8 @@ cua-home.workspace = true
# A failed create's cause as a fixed telemetry word (no dependencies, so
# also in the wasm build).
cua-create-failure.workspace = true
+# The friendly default names a Space gets (lists only; also in the wasm build).
+cua-spaces-contract.workspace = true
serde.workspace = true
serde_json.workspace = true
cua-keyvault = { workspace = true, optional = true }
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-gpu.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-gpu.json
index 903d3177ee..4425679303 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-gpu.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-gpu.json
@@ -342,7 +342,7 @@
"cpusText": "4 cores",
"disk": "150 GB (150-1024) ~Uses about 33 GB on this Mac at first, up to 150 GB as the Space fills it. ?A VM disk cannot shrink below the image's 150 GB.",
"fields": [
- "name: Name [space-000000002a]",
+ "name: Name [dapper-mole]",
"open-when-ready: Open when ready"
],
"gpu": "GPU acceleration (Experimental) [x] Learn more -> https://cua.ai/docs/lume/guides/gpu-passthrough",
@@ -439,12 +439,12 @@
"image": "ghcr.io/trycua/macos:26",
"kind": "vm",
"memoryMb": 8192,
- "name": "space-000000002a",
+ "name": "dapper-mole",
"on": "local",
"runtime": "auto",
"spacesd": true
},
- "creating": "Creating space-000000002a. It appears in the list when it is ready.",
+ "creating": "Creating dapper-mole. It appears in the list when it is ready.",
"failed": "Could not create the Space: no macOS image is configured",
"openDesktop": true,
"summary": [
@@ -456,7 +456,7 @@
"Runtime: Lume virtual machine (Apple silicon)",
"Resources: 4 cores, 8 GB memory, 150 GB disk",
"GPU: GPU acceleration (Experimental)",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
]
}
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-microvm.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-microvm.json
index cac830f5d5..64463c87a1 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-microvm.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-microvm.json
@@ -478,7 +478,7 @@
"cpusText": "2 cores",
"disk": null,
"fields": [
- "name: Name [space-000000002a]",
+ "name: Name [dapper-mole]",
"open-when-ready: Open when ready"
],
"gpu": null,
@@ -580,12 +580,12 @@
"image": "ghcr.io/trycua/linux:24.04",
"kind": "microvm",
"memoryMb": 4096,
- "name": "space-000000002a",
+ "name": "dapper-mole",
"on": "local",
"runtime": "containerization",
"spacesd": true
},
- "creating": "Creating space-000000002a. It appears in the list when it is ready.",
+ "creating": "Creating dapper-mole. It appears in the list when it is ready.",
"failed": "Could not create the Space: Apple's container services did not start",
"openDesktop": true,
"summary": [
@@ -597,7 +597,7 @@
"Runtime: Apple Containerization microVM on this Mac",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB ?2.9–6.9 GB initially; grows with use",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
]
}
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-resources.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-resources.json
index 8719a714ee..1bd60302aa 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-resources.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-resources.json
@@ -2348,7 +2348,7 @@
"cpusText": "4 cores",
"disk": "200 GB (150-500) [Reset] ~The disk will be resized to 200 GB after downloading. Uses about 33 GB on this Mac at first, up to 200 GB as the Space fills it. ?A VM disk cannot shrink below the image's 150 GB.",
"fields": [
- "name: Name [space-000000002a]",
+ "name: Name [dapper-mole]",
"open-when-ready: Open when ready"
],
"gpu": null,
@@ -2449,12 +2449,12 @@
"image": "ghcr.io/trycua/macos:26",
"kind": "vm",
"memoryMb": 8192,
- "name": "space-000000002a",
+ "name": "dapper-mole",
"on": "local",
"runtime": "auto",
"spacesd": true
},
- "creating": "Creating space-000000002a. It appears in the list when it is ready.",
+ "creating": "Creating dapper-mole. It appears in the list when it is ready.",
"failed": "Could not create the Space: Not enough disk space for this Space. Free up space on this Mac (or run `cua cache prune` in Terminal), then try again.",
"openDesktop": true,
"summary": [
@@ -2465,7 +2465,7 @@
"Architecture: ARM",
"Runtime: Lume virtual machine (Apple silicon)",
"Resources: 4 cores, 8 GB memory, 200 GB disk",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
]
}
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-space.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-space.json
index 01694f73ce..238ca56f34 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/create-space.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/create-space.json
@@ -1674,7 +1674,7 @@
"cpusText": "4 cores",
"disk": null,
"fields": [
- "name: Name [space-000000002a]",
+ "name: Name [dapper-mole]",
"open-when-ready: Open when ready"
],
"gpu": null,
@@ -1727,7 +1727,7 @@
"cpusText": "4 cores",
"disk": null,
"fields": [
- "name: Name [space-000000002a] !Lowercase letters, digits and dashes",
+ "name: Name [dapper-mole] !Lowercase letters, digits and dashes",
"open-when-ready: Open when ready"
],
"gpu": null,
@@ -1780,7 +1780,7 @@
"cpusText": "4 cores",
"disk": null,
"fields": [
- "name: Name [space-000000002a] !Lowercase letters, digits and dashes",
+ "name: Name [dapper-mole] !Lowercase letters, digits and dashes",
"open-when-ready: Open when ready"
],
"gpu": null,
@@ -1833,7 +1833,7 @@
"cpusText": "4 cores",
"disk": null,
"fields": [
- "name: Name [space-000000002a]",
+ "name: Name [dapper-mole]",
"open-when-ready: Open when ready"
],
"gpu": null,
@@ -1886,7 +1886,7 @@
"cpusText": "4 cores",
"disk": null,
"fields": [
- "name: Name [space-000000002a]",
+ "name: Name [dapper-mole]",
"open-when-ready: Open when ready"
],
"gpu": null,
@@ -1989,7 +1989,7 @@
"cpusText": "4 cores",
"disk": null,
"fields": [
- "name: Name [space-000000002a]",
+ "name: Name [dapper-mole]",
"open-when-ready: Open when ready"
],
"gpu": null,
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/placement-picker.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/placement-picker.json
index b61626315e..8d3a364f02 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/placement-picker.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/placement-picker.json
@@ -47,7 +47,7 @@
"Runtime: Container on this Mac (gVisor when installed)",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -101,7 +101,7 @@
"Runtime: Container on this Mac (gVisor when installed)",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -152,7 +152,7 @@
"Kind: Container",
"Runtime: Container on Mac mini",
"Resources: 2 cores, 4 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -204,7 +204,7 @@
"Kind: Virtual machine",
"Runtime: Virtual machine on Mac mini",
"Resources: 4 cores, 8 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -255,7 +255,7 @@
"Kind: Container",
"Runtime: Container on Mac mini",
"Resources: 2 cores, 4 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -306,7 +306,7 @@
"Kind: Container",
"Runtime: Container on lab",
"Resources: 2 cores, 4 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -360,7 +360,7 @@
"Runtime: Container on t4g.medium",
"Cost: About $0.04/hour",
"Deletes itself: After 2 hours",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -412,7 +412,7 @@
"Kind: Container",
"Runtime: Container on Mac mini",
"Resources: 2 cores, 4 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -459,7 +459,7 @@
"Kind: Container",
"Runtime: Container on Mac mini",
"Resources: 2 cores, 4 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -506,7 +506,7 @@
"Kind: Container",
"Runtime: Container on Mac mini",
"Resources: 2 cores, 4 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -550,7 +550,7 @@
"Kind: Container",
"Runtime: Container on Mac mini",
"Resources: 2 cores, 4 GB memory",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -591,7 +591,7 @@
"Runtime: Container on this Mac (gVisor when installed)",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -632,7 +632,7 @@
"Runtime: Container on this Mac (gVisor when installed)",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/your-cloud.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/your-cloud.json
index 8b55f4e890..45a4623974 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/your-cloud.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/your-cloud.json
@@ -39,7 +39,7 @@
"Runtime: Container on this Mac (gVisor when installed)",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -85,7 +85,7 @@
"Runtime: Container on this Mac (gVisor when installed)",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -722,7 +722,7 @@
"Runtime: Container on t4g.medium",
"Cost: About $0.04/hour",
"Deletes itself: After 2 hours",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -764,7 +764,7 @@
"Runtime: Container on t4g.medium",
"Cost: About $0.04/hour",
"Deletes itself: After 2 hours",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -809,7 +809,7 @@
"Runtime: Container on t4g.medium",
"Cost: About $0.04/hour",
"Deletes itself: After 2 hours",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -851,7 +851,7 @@
"Runtime: Container on t4g.medium",
"Cost: About $0.04/hour",
"Deletes itself: After 2 hours",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -897,7 +897,7 @@
"Runtime: Container on t4g.medium",
"Cost: About $0.04/hour",
"Deletes itself: After 2 hours",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -943,7 +943,7 @@
"Runtime: Container on 2 CPU, 4 GiB",
"Cost: About $0.10/hour",
"Deletes itself: After 2 hours",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
@@ -989,7 +989,7 @@
"Runtime: Container on this Mac (gVisor when installed)",
"Resources: 2 cores, 4 GB memory",
"Disk: About 3–7 GB",
- "Name: space-000000002a",
+ "Name: dapper-mole",
"When ready: Open the desktop"
],
"systemsOff": [
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 28c9380285..d396ef32e3 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
@@ -1901,17 +1901,15 @@ pub struct ResourceEdit {
pub text: String,
}
-/// The name an unnamed Space gets: `space-` and ten hex digits, the form
-/// the SDK gives one it names itself (`cua_spaces::Spaces::create`). The
-/// wizard picks it when it opens, shows it, and creates the Space with it.
+/// The name an unnamed Space gets: a friendly `adjective-animal`
+/// (`cua_spaces_contract::names`), the form the SDK gives one it names
+/// itself. The wizard picks it when it opens, shows it, and creates the
+/// Space with it.
pub fn generated_space_name(seed: Option<u64>) -> String {
- let n = seed.unwrap_or_else(|| {
- use std::hash::{BuildHasher, Hasher};
- std::collections::hash_map::RandomState::new()
- .build_hasher()
- .finish()
- });
- format!("space-{:010x}", n & 0xff_ffff_ffff)
+ match seed {
+ Some(s) => cua_spaces_contract::names::pet_name_seeded(s, |_| false),
+ None => cua_spaces_contract::names::pet_name(|_| false),
+ }
}
/// An input to the wizard.
@@ -7099,10 +7097,10 @@ mod tests {
fn an_unnamed_space_shows_and_gets_its_generated_name() {
let e = env();
let s = initial(&e);
- assert_eq!(s.generated_name, "space-000000002a");
- assert_eq!(generated_space_name(Some(u64::MAX)), "space-ffffffffff");
+ assert_eq!(s.generated_name, generated_space_name(Some(42)));
+ assert!(cua_spaces_contract::names::is_pet_name(&s.generated_name));
let other = generated_space_name(None);
- assert!(other.starts_with("space-") && other.len() == 16 && valid_space_name(&other));
+ assert!(cua_spaces_contract::names::is_pet_name(&other) && valid_space_name(&other));
let mut s = s;
for _ in 0..2 {
s = reduce(&s, &WizardAction::Next, &e);
@@ -7113,22 +7111,19 @@ mod tests {
.iter()
.find(|f| f.id == "name")
.and_then(|f| f.placeholder.clone());
- assert_eq!(placeholder.as_deref(), Some("space-000000002a"));
- assert_eq!(v.space_name, "space-000000002a");
+ assert_eq!(placeholder.as_deref(), Some("dapper-mole"));
+ assert_eq!(v.space_name, "dapper-mole");
let name_row = |v: &WizardView| {
v.summary
.iter()
.find(|f| f.label == "Name")
.map(|f| f.value.clone())
};
- assert_eq!(name_row(&v).as_deref(), Some("space-000000002a"));
- assert_eq!(
- create_args(&v.plan).name.as_deref(),
- Some("space-000000002a")
- );
+ assert_eq!(name_row(&v).as_deref(), Some("dapper-mole"));
+ assert_eq!(create_args(&v.plan).name.as_deref(), Some("dapper-mole"));
assert_eq!(
creating_text(&v.plan),
- "Creating space-000000002a. It appears in the list when it is ready."
+ "Creating dapper-mole. It appears in the list when it is ready."
);
let named = view(
&reduce(
diff --git a/libs/cua/crates/cua-spaces-contract/src/inputs.rs b/libs/cua/crates/cua-spaces-contract/src/inputs.rs
index 9b56e1bd40..a0e3d051c7 100644
--- a/libs/cua/crates/cua-spaces-contract/src/inputs.rs
+++ b/libs/cua/crates/cua-spaces-contract/src/inputs.rs
@@ -173,7 +173,7 @@ pub struct CreateSpace {
/// else fails with `invalid_placement`, listing the valid values.
#[serde(default)]
pub runtime: Option<String>,
- /// Name. Default: a generated `space-<hex>`.
+ /// Name. Default: a generated friendly name such as `brave-otter`.
#[serde(default)]
pub name: Option<String>,
/// Return a reachable registered Space in the same location that has
diff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rs
index 1ad698256f..3baf253307 100644
--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs
@@ -16,6 +16,7 @@
//! are derived from.
pub mod inputs;
+pub mod names;
use serde::Serialize;
diff --git a/libs/cua/crates/cua-spaces-contract/src/names.rs b/libs/cua/crates/cua-spaces-contract/src/names.rs
new file mode 100644
index 0000000000..36d64eed10
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-contract/src/names.rs
@@ -0,0 +1,319 @@
+//! Friendly default names for Spaces: `brave-otter`, `quiet-heron`.
+//!
+//! One generator for every surface (the SDK, the CLI, MCP `create_space`,
+//! the app and a Home start), so a Space made without a name reads the same
+//! everywhere. A name is an adjective and an animal from two curated lists
+//! (short, lowercase, DNS-safe, nothing a person could take badly). Names
+//! the caller gives are never touched, and Spaces that exist keep theirs.
+//!
+//! The web app has the same lists as a generated file
+//! (`apps/cua-spaces-web/src/lib/pet-names.generated.ts`), written by the
+//! `pet_names_lists_match_the_web_copy` test's `CUA_UPDATE_PET_NAMES=1`
+//! mode; the test fails when the two drift.
+
+/// Adjectives: short, kind, neutral.
+pub const ADJECTIVES: &[&str] = &[
+ "agile", "amber", "ample", "bold", "brave", "breezy", "bright", "brisk", "calm", "candid",
+ "careful", "clever", "cosmic", "cozy", "crisp", "curious", "dapper", "daring", "dewy", "deft",
+ "eager", "early", "easy", "epic", "fair", "fancy", "fast", "fine", "fleet", "fond", "frosty",
+ "gentle", "giant", "glad", "golden", "grand", "happy", "hardy", "honest", "humble", "jolly",
+ "jovial", "keen", "kind", "lively", "lucky", "lunar", "mellow", "merry", "mighty", "mild",
+ "misty", "modest", "nifty", "nimble", "noble", "novel", "open", "patient", "peppy", "placid",
+ "plucky", "polite", "proud", "quick", "quiet", "rapid", "ready", "rosy", "royal", "rustic",
+ "sandy", "serene", "shiny", "silent", "silver", "simple", "sleek", "smart", "smooth", "snowy",
+ "solar", "solid", "spry", "steady", "stellar", "sunny", "super", "swift", "tidy", "tiny",
+ "topaz", "true", "trusty", "upbeat", "vivid", "warm", "wise", "witty", "zesty", "zippy",
+ "balmy", "lush", "azure", "ivory", "jade", "coral", "olive", "velvet",
+];
+
+/// Animals: short, familiar.
+pub const ANIMALS: &[&str] = &[
+ "alpaca",
+ "badger",
+ "bat",
+ "bear",
+ "beaver",
+ "bee",
+ "bison",
+ "bobcat",
+ "camel",
+ "cat",
+ "civet",
+ "cobra",
+ "condor",
+ "coyote",
+ "crane",
+ "crow",
+ "deer",
+ "dingo",
+ "dolphin",
+ "dove",
+ "dragonfly",
+ "eagle",
+ "egret",
+ "elk",
+ "falcon",
+ "ferret",
+ "finch",
+ "fox",
+ "frog",
+ "gecko",
+ "gibbon",
+ "goat",
+ "goose",
+ "gopher",
+ "gull",
+ "hare",
+ "hawk",
+ "hedgehog",
+ "heron",
+ "horse",
+ "hound",
+ "ibis",
+ "iguana",
+ "jackal",
+ "jaguar",
+ "jay",
+ "kestrel",
+ "kiwi",
+ "koala",
+ "lark",
+ "lemur",
+ "llama",
+ "lynx",
+ "magpie",
+ "mallard",
+ "marten",
+ "meerkat",
+ "mink",
+ "mole",
+ "moose",
+ "moth",
+ "mouse",
+ "newt",
+ "ocelot",
+ "orca",
+ "osprey",
+ "otter",
+ "owl",
+ "panda",
+ "parrot",
+ "pelican",
+ "penguin",
+ "pika",
+ "plover",
+ "pony",
+ "puffin",
+ "puma",
+ "quail",
+ "rabbit",
+ "raven",
+ "robin",
+ "salmon",
+ "seal",
+ "shrew",
+ "skink",
+ "sloth",
+ "sparrow",
+ "squid",
+ "stoat",
+ "stork",
+ "swan",
+ "tapir",
+ "tern",
+ "tiger",
+ "toad",
+ "trout",
+ "turtle",
+ "viper",
+ "vole",
+ "walrus",
+ "weasel",
+ "whale",
+ "wolf",
+ "wombat",
+ "wren",
+ "yak",
+ "zebra",
+];
+
+/// A random 64-bit seed (the standard library's hasher keys are random).
+fn random_seed() -> u64 {
+ use std::hash::{BuildHasher, Hasher};
+ std::collections::hash_map::RandomState::new()
+ .build_hasher()
+ .finish()
+}
+
+/// The next value of a splitmix64 stream.
+fn next(state: &mut u64) -> u64 {
+ *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
+ let mut z = *state;
+ z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
+ z ^ (z >> 31)
+}
+
+fn pair(state: &mut u64) -> String {
+ let a = ADJECTIVES[(next(state) % ADJECTIVES.len() as u64) as usize];
+ let b = ANIMALS[(next(state) % ANIMALS.len() as u64) as usize];
+ format!("{a}-{b}")
+}
+
+/// How many other pairs are tried before a suffix is added.
+const PAIR_TRIES: usize = 64;
+
+/// A friendly name that `taken` does not claim: a few other pairs are tried
+/// first, and only a name that every try collided on gets a short suffix.
+pub fn pet_name(taken: impl Fn(&str) -> bool) -> String {
+ pet_name_seeded(random_seed(), taken)
+}
+
+/// [`pet_name`] from a given seed: the same seed and `taken` give the same
+/// name (tests; a host that picks the name when a form opens).
+pub fn pet_name_seeded(seed: u64, taken: impl Fn(&str) -> bool) -> String {
+ let mut st = seed;
+ for _ in 0..PAIR_TRIES {
+ let name = pair(&mut st);
+ if !taken(&name) {
+ return name;
+ }
+ }
+ loop {
+ let name = format!("{}-{:04x}", pair(&mut st), next(&mut st) & 0xffff);
+ if !taken(&name) {
+ return name;
+ }
+ }
+}
+
+/// Whether `name` is in the form [`pet_name`] makes (with or without its
+/// last-resort suffix): one the SDK, or an app on its behalf, generated.
+pub fn is_pet_name(name: &str) -> bool {
+ let mut parts = name.split('-');
+ let (Some(a), Some(b), rest) = (parts.next(), parts.next(), parts.next()) else {
+ return false;
+ };
+ if !ADJECTIVES.contains(&a) || !ANIMALS.contains(&b) {
+ return false;
+ }
+ match rest {
+ None => true,
+ Some(s) => {
+ parts.next().is_none()
+ && s.len() == 4
+ && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
+ }
+ }
+}
+
+/// The lists as the web app's generated module.
+pub fn web_module() -> String {
+ let list = |v: &[&str]| {
+ v.iter()
+ .map(|w| format!("\"{w}\""))
+ .collect::<Vec<_>>()
+ .join(", ")
+ };
+ format!(
+ "// SPDX-License-Identifier: FSL-1.1-MIT\n// Copyright (c) 2026 Cua AI, Inc.\n\n// Generated from libs/cua/crates/cua-spaces-contract/src/names.rs (CUA_UPDATE_PET_NAMES=1 cargo test -p cua-spaces-contract pet_names). Do not edit.\n\
+ export const PET_ADJECTIVES = [{}] as const;\n\
+ export const PET_ANIMALS = [{}] as const;\n",
+ list(ADJECTIVES),
+ list(ANIMALS)
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::HashSet;
+
+ #[test]
+ fn pet_names_are_adjective_animal_and_dns_safe() {
+ for _ in 0..500 {
+ let n = pet_name(|_| false);
+ assert!(is_pet_name(&n), "{n}");
+ assert!(n.len() <= 24, "{n} is not short");
+ assert!(
+ n.bytes().all(|c| c.is_ascii_lowercase() || c == b'-')
+ && !n.starts_with('-')
+ && !n.ends_with('-'),
+ "{n}"
+ );
+ }
+ }
+
+ #[test]
+ fn pet_name_lists_are_sane() {
+ for (what, l) in [("adjectives", ADJECTIVES), ("animals", ANIMALS)] {
+ assert!(l.len() >= 100, "{what}: only {}", l.len());
+ let set: HashSet<_> = l.iter().collect();
+ assert_eq!(set.len(), l.len(), "{what} has duplicates");
+ for w in l {
+ assert!(
+ !w.is_empty() && w.len() <= 10 && w.bytes().all(|c| c.is_ascii_lowercase()),
+ "{what}: {w:?}"
+ );
+ }
+ }
+ // A word may not be both: `swift-swift` and `a-b` parse the same.
+ for a in ADJECTIVES {
+ assert!(!ANIMALS.contains(a), "{a} is in both lists");
+ }
+ }
+
+ #[test]
+ fn a_taken_name_is_retried_with_another_pair_before_any_suffix() {
+ let first = std::cell::RefCell::new(None::<String>);
+ let n = pet_name(|c| {
+ let mut f = first.borrow_mut();
+ if f.is_none() {
+ *f = Some(c.to_string());
+ true
+ } else {
+ false
+ }
+ });
+ assert_ne!(Some(n.clone()), *first.borrow());
+ assert_eq!(n.matches('-').count(), 1, "no suffix yet: {n}");
+ }
+
+ #[test]
+ fn a_suffix_is_the_last_resort_when_every_pair_is_taken() {
+ let n = pet_name(|c| c.matches('-').count() == 1);
+ assert!(is_pet_name(&n) && n.matches('-').count() == 2, "{n}");
+ }
+
+ #[test]
+ fn only_generated_forms_count_as_pet_names() {
+ assert!(is_pet_name("brave-otter"));
+ assert!(is_pet_name("brave-otter-00ff"));
+ for no in [
+ "my-space",
+ "brave-otter-xyz1",
+ "brave",
+ "brave-otter-00ff-1",
+ "Brave-Otter",
+ "space-0123456789",
+ ] {
+ assert!(!is_pet_name(no), "{no}");
+ }
+ }
+
+ /// The web app's copy of the lists is generated; it may not drift.
+ #[test]
+ fn pet_names_lists_match_the_web_copy() {
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../../../apps/cua-spaces-web/src/lib/pet-names.generated.ts");
+ let want = web_module();
+ if std::env::var_os("CUA_UPDATE_PET_NAMES").is_some() {
+ std::fs::write(&path, &want).unwrap();
+ }
+ assert_eq!(
+ std::fs::read_to_string(&path).unwrap_or_default(),
+ want,
+ "run CUA_UPDATE_PET_NAMES=1 cargo test -p cua-spaces-contract pet_names"
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs
index bb7fbb411d..9135d5755c 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs
@@ -116,35 +116,10 @@ fn startable(id: &str) -> Option<&'static Startable> {
AGENTS.iter().find(|a| a.harness == id)
}
-/// The home's name: short, readable in the Spaces list.
-pub fn home_name(prompt: &str, now_ms: u64) -> String {
- let lower = prompt.to_lowercase();
- // Links are not part of a name.
- let no_links: Vec<&str> = lower
- .split_whitespace()
- .filter(|w| !w.starts_with("http://") && !w.starts_with("https://"))
- .collect();
- let mut slug = String::new();
- let mut dash = true;
- for c in no_links.join(" ").chars() {
- if c.is_ascii_alphanumeric() {
- slug.push(c);
- dash = false;
- } else if !dash {
- slug.push('-');
- dash = true;
- }
- }
- let slug: String = slug.trim_matches('-').chars().take(24).collect();
- let slug = slug.trim_end_matches('-');
- let slug = if slug.is_empty() { "task" } else { slug };
- let mut n = now_ms;
- let mut suffix = String::new();
- for _ in 0..3 {
- suffix.insert(0, char::from_digit((n % 36) as u32, 36).unwrap_or('0'));
- n /= 36;
- }
- format!("home-{slug}-{suffix}")
+/// The home's name: a friendly pair (`brave-otter`) no Space has yet. The
+/// task is not part of it: a prompt rarely reads well as a name.
+pub fn home_name(taken: impl Fn(&str) -> bool) -> String {
+ cua_spaces::names::pet_name(taken)
}
/// Where the job runs, as the phone asks.
@@ -529,7 +504,6 @@ pub(crate) async fn task_start(
agent,
model,
text,
- prompt,
place,
fresh,
};
@@ -554,7 +528,6 @@ struct Job {
agent: &'static Startable,
model: Option<String>,
text: String,
- prompt: String,
place: Where,
fresh: bool,
}
@@ -644,7 +617,12 @@ impl Job {
image: Some(HOME_IMAGE.to_string()),
on,
kind,
- name: Some(home_name(&self.prompt, now_ms())),
+ name: Some(home_name(|n| {
+ self.spaces
+ .list()
+ .map(|v| v.iter().any(|i| i.name == n))
+ .unwrap_or(false)
+ })),
cpus: Some(1),
memory_mb: Some(1024),
wait: Some(true),
@@ -758,17 +736,18 @@ mod tests {
use super::*;
#[test]
- fn a_home_is_named_from_the_job() {
- assert_eq!(
- home_name("Fix the retry backoff!", 0),
- "home-fix-the-retry-backoff-000"
- );
- assert!(
- home_name("see https://example.com/x now", 36 * 36 * 36 + 1)
- .starts_with("home-see-now-")
- );
- assert_eq!(home_name(" ", 1), "home-task-001");
- assert!(home_name(&"word ".repeat(40), 5).len() <= "home--xxx".len() + 24);
+ fn a_home_gets_a_friendly_name_no_space_has() {
+ let n = home_name(|_| false);
+ assert!(cua_spaces::names::is_pet_name(&n), "{n}");
+ // A name that is taken is not handed out again.
+ let first = std::cell::RefCell::new(String::new());
+ let m = home_name(|c| {
+ if first.borrow().is_empty() {
+ *first.borrow_mut() = c.to_string();
+ }
+ c == first.borrow().as_str()
+ });
+ assert_ne!(m, *first.borrow());
}
#[test]
diff --git a/libs/cua/crates/cua-spaces/src/cloud.rs b/libs/cua/crates/cua-spaces/src/cloud.rs
index a41d99ffe3..0015ab81f4 100644
--- a/libs/cua/crates/cua-spaces/src/cloud.rs
+++ b/libs/cua/crates/cua-spaces/src/cloud.rs
@@ -126,7 +126,7 @@ impl Spaces {
.clone()
.filter(|n| !n.trim().is_empty())
.map(|n| crate::spaces::sanitize_label(&n))
- .unwrap_or_else(|| format!("space-{}", crate::spaces::random_suffix())),
+ .unwrap_or_else(|| self.fresh_name()),
);
if opts.kind != Kind::Auto {
create.kind = opts.kind;
diff --git a/libs/cua/crates/cua-spaces/src/lib.rs b/libs/cua/crates/cua-spaces/src/lib.rs
index ebb27cb7f3..2b457cd0c2 100644
--- a/libs/cua/crates/cua-spaces/src/lib.rs
+++ b/libs/cua/crates/cua-spaces/src/lib.rs
@@ -87,6 +87,7 @@ pub mod list_watch;
pub mod listing;
mod local_load;
pub mod mesh;
+pub use cua_spaces_contract::names;
pub mod named_volumes;
pub mod network;
pub mod operator;
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 72a12ead82..397e5bc115 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -36,7 +36,7 @@ pub struct SpaceCreate {
pub kind: Kind,
/// Which engine (`Auto`: the safest one for the kind).
pub runtime: Runtime,
- /// Name. Default `space-<hex>`.
+ /// Name. Default a friendly `adjective-animal` (`brave-otter`).
pub name: Option<String>,
/// vCPUs. Local default 2.
pub cpus: Option<u32>,
@@ -218,7 +218,7 @@ pub(crate) struct LocalProvision {
pub kind: Kind,
/// Which engine.
pub runtime: Runtime,
- /// Instance name. Default `space-<hex>`.
+ /// Instance name. Default a friendly `adjective-animal`.
pub name: Option<String>,
/// vCPUs. Default 2.
pub cpus: Option<u32>,
@@ -597,14 +597,15 @@ pub(crate) fn random_suffix() -> String {
format!("{:010x}", rand::random::<u64>() & 0xff_ffff_ffff)
}
-/// A name in the form [`SpaceCreate::name`] defaults to (`space-` and ten
-/// lowercase hex digits): one the SDK, or an app on its behalf, generated.
+/// A name in the form [`SpaceCreate::name`] defaults to (`adjective-animal`,
+/// or the older `space-` and ten lowercase hex digits): one the SDK, or an app on its behalf, generated.
/// A create under such a name cleans up after a failed start, as one with
/// no name does.
pub fn is_generated_name(name: &str) -> bool {
- name.strip_prefix("space-").is_some_and(|hex| {
- hex.len() == 10 && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
- })
+ cua_spaces_contract::names::is_pet_name(name)
+ || name.strip_prefix("space-").is_some_and(|hex| {
+ hex.len() == 10 && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
+ })
}
pub(crate) struct Inner {
@@ -743,6 +744,18 @@ impl Spaces {
// ------------------------------------------------------------ registry
+ /// A friendly name (`brave-otter`) that no registered Space has
+ /// ([`cua_spaces_contract::names::pet_name`]): the default of a create without one.
+ pub fn fresh_name(&self) -> String {
+ let taken: std::collections::HashSet<String> = self
+ .inner
+ .registry
+ .list()
+ .map(|v| v.into_iter().map(|s| s.name).collect())
+ .unwrap_or_default();
+ cua_spaces_contract::names::pet_name(|n| taken.contains(n))
+ }
+
/// Every registered Space, plus the relay machines of the last
/// [`Spaces::relay_machines`] listing (see [`Spaces::list_all`]).
pub fn list(&self) -> Result<Vec<SpaceInfo>> {
@@ -2578,7 +2591,7 @@ impl Spaces {
.name
.clone()
.filter(|n| !n.trim().is_empty())
- .unwrap_or_else(|| format!("space-{}", random_suffix())),
+ .unwrap_or_else(|| self.fresh_name()),
);
opts.name = Some(name.clone());
name
@@ -2980,11 +2993,7 @@ impl Spaces {
{
return Ok(SpaceCreated::Ready { info, reused: true });
}
- let name = sanitize_label(
- &opts
- .name
- .unwrap_or_else(|| format!("space-{}", random_suffix())),
- );
+ let name = sanitize_label(&opts.name.unwrap_or_else(|| self.fresh_name()));
let local = LocalProvision {
image: opts.image,
kind: opts.kind,
@@ -3029,12 +3038,7 @@ impl Spaces {
"no local runtime passed to SpacesBuilder; using the sandbox manager's"
);
}
- let name = sanitize_label(
- &opts
- .name
- .clone()
- .unwrap_or_else(|| format!("space-{}", random_suffix())),
- );
+ let name = sanitize_label(&opts.name.clone().unwrap_or_else(|| self.fresh_name()));
let expect_env = expects_spacesd(opts.image.as_deref(), opts.spacesd);
// An alias (`linux`, `macos:26`, `macos:26-slim`) names a canonical
// image, as it does for a cloud or host Space; the local runtime
@@ -4561,8 +4565,9 @@ mod tests {
#[test]
fn generated_names_are_the_sdks_own_form() {
- let name = format!("space-{}", random_suffix());
+ let name = cua_spaces_contract::names::pet_name(|_| false);
assert!(is_generated_name(&name), "{name}");
+ assert!(is_generated_name(&format!("space-{}", random_suffix())));
assert!(is_generated_name("space-000000002a"));
for other in [
"space-2a",
diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.json
index be7e69af92..1243db448f 100644
--- a/libs/cua/spaces-contract/manifest.json
+++ b/libs/cua/spaces-contract/manifest.json
@@ -541,7 +541,7 @@
"type": "object"
},
"name": {
- "description": "Name. Default: a generated `space-<hex>`.",
+ "description": "Name. Default: a generated friendly name such as `brave-otter`.",
"type": "string"
},
"network": {