Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces): join with a code and a cua://add deep link (CUA-1772) (#5316)
Francesco Bonaccic195318010ab
diff --git a/apps/cua-spaces-desktop/electron-builder.config.cjs b/apps/cua-spaces-desktop/electron-builder.config.cjsindex af3b49aec7..f5e6a73f9d 100644--- a/apps/cua-spaces-desktop/electron-builder.config.cjs+++ b/apps/cua-spaces-desktop/electron-builder.config.cjs@@ -184,6 +184,10 @@ module.exports = {electronLanguages: ["en", "en-US"],electronFuses: env.CUA_SPACES_NO_FUSES === "1" ? null : electronFuses({ resetAdHocSignature: !macSigning }),+ // `cua://add/<code>` (the add-machine link) opens this app: Info.plist on macOS, the desktop+ // entry's MIME type on Linux. Windows registers it when the app first runs (src/main.ts).+ protocols: [{ name: "Cua", schemes: ["cua"] }],+mac: {appId: "com.trycua.spaces.macos",category: "public.app-category.developer-tools",diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.tsindex c20e9fcfed..90e5c01999 100644--- a/apps/cua-spaces-desktop/src/bridge/index.ts+++ b/apps/cua-spaces-desktop/src/bridge/index.ts@@ -19,6 +19,7 @@ import { devicesMethods } from "./devices";import { filesMethods } from "./files";import { BridgeEvents, BridgeRegistry } from "./host";import { hostSetupMethods } from "./host-setup";+import { joinMethods } from "./join-with-code";import { keyvaultMethods } from "./keyvault";import { hostStatus, machinesMethods } from "./machines";import { ELECTRON_METHODS, METHODS } from "./methods";@@ -59,6 +60,7 @@ export const AREAS = [spaceDetailMethods,filesMethods,hostSetupMethods,+ joinMethods,settingsMethods,keyvaultMethods,windowMethods,diff --git a/apps/cua-spaces-desktop/src/bridge/join-with-code.ts b/apps/cua-spaces-desktop/src/bridge/join-with-code.tsnew file mode 100644index 0000000000..5c98270903--- /dev/null+++ b/apps/cua-spaces-desktop/src/bridge/join-with-code.ts@@ -0,0 +1,114 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// "Join with a code" (`host.joinWithCode`): sets this computer up with a+// one-time pairing code made on another device, by running the bundled+// `cua host setup --pair <code>`, as the install script does. The page+// confirms first; nothing here runs on a link alone. The Swift host answers+// the same method (`JoinWithCode.swift`).+import { spawn } from "node:child_process";++import { string } from "./args";+import type { BridgeContext } from "./context";+import { Failure, type Handlers } from "./host";+import { hostStatus } from "./machines";++/** Long enough for the driver download and the service start; the relay answers in seconds. */+export const JOIN_TIMEOUT_MS = 180_000;++const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";++/** The 12-character code in what was typed or pasted (`cua_host::normalize_pairing_code`), or null. */+export function normalizeCode(input: string): string | null {+ let s = input.trim();+ const at = s.indexOf("/add/");+ if (at >= 0) s = s.slice(at + 5).split(/[?#/]/)[0] ?? "";+ if (s.startsWith("cpc_")) s = s.slice(4);+ let out = "";+ for (const raw of s) {+ const c = raw.toUpperCase();+ if (c === "-" || c === " ") continue;+ const m = c === "I" || c === "L" ? "1" : c === "O" ? "0" : c;+ if (m.length !== 1 || !ALPHABET.includes(m)) return null;+ out += m;+ }+ return out.length === 12 ? out : null;+}++/** The relay another than the production one that a link names (`?relay=`), when it is an http(s) URL. */+export function linkRelay(input: string): string | null {+ try {+ const v = new URL(input.trim()).searchParams.get("relay")?.trim();+ return v && /^https?:\/\//i.test(v) ? v : null;+ } catch {+ return null;+ }+}++/** `cua`'s arguments for joining with `code` (the canonical code, so nothing typed reaches the command line as is). */+export function joinArgs(code: string, relay: string | null): string[] {+ return ["host", "setup", "--pair", code, ...(relay ? ["--relay", relay] : [])];+}++/** The line to show for a failed run: the last one the command wrote to stderr, else the exit status. */+export function failureText(stderr: string, status: string): string {+ const lines = stderr+ .split(/\r?\n/)+ .map((l) => l.trim())+ .filter(Boolean);+ return lines.length ? lines[lines.length - 1]! : `cua host setup ${status}`;+}++export interface CuaRun {+ ok: boolean;+ stderr: string;+ status: string;+}++/** Runs `cua` with `args` and waits for it (stopped after `timeoutMs`). */+export function runCua(cua: string, args: string[], env: NodeJS.ProcessEnv, timeoutMs = JOIN_TIMEOUT_MS): Promise<CuaRun> {+ return new Promise((resolve) => {+ let stderr = "";+ let settled = false;+ const done = (r: CuaRun) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(r);+ };+ let child;+ try {+ child = spawn(cua, args, { env, stdio: ["ignore", "ignore", "pipe"], windowsHide: true });+ } catch (e) {+ resolve({ ok: false, stderr: "", status: `could not start: ${e instanceof Error ? e.message : String(e)}` });+ return;+ }+ const timer = setTimeout(() => {+ child.kill("SIGKILL");+ done({ ok: false, stderr, status: "timed out" });+ }, timeoutMs);+ child.stderr?.on("data", (d: Buffer) => {+ stderr = (stderr + d.toString()).slice(-4000);+ });+ child.on("error", (e) => done({ ok: false, stderr: "", status: `could not start: ${e.message}` }));+ child.on("exit", (code, signal) => done({ ok: code === 0, stderr, status: signal ? `stopped by ${signal}` : `exited with ${code}` }));+ });+}++export function joinMethods(ctx: BridgeContext, run: typeof runCua = runCua): Handlers {+ const { model, supervisor, env } = ctx;+ return {+ "host.joinWithCode": async (args) => {+ const input = string(args, "code");+ const code = normalizeCode(input);+ if (!code) throw Failure.badArgs("code: 12 letters and digits, like K7QM-4XPB-2RHD");+ const named = typeof args.relay === "string" && args.relay.trim() ? args.relay.trim() : null;+ if (named && !/^https?:\/\//i.test(named)) throw Failure.badArgs("relay: an http(s) URL");+ if (!supervisor) throw Failure.unsupported("This build has no bundled cua to join with a code. Use the install command on this computer.");+ const result = await run(supervisor.cua, joinArgs(code, named ?? linkRelay(input)), { ...env });+ if (!result.ok) throw Failure.failed(failureText(result.stderr, result.status));+ await model.host.refresh();+ return hostStatus(model);+ },+ };+}diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 4d4b3e4511..c8762cacce 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -34,7 +34,7 @@ export const METHODS = ["telemetry.track", "spaces.usage", "spaces.windows", "stream.pip","spaces.thumbnail","spaces.chooseFiles", "spaces.droppedFiles", "spaces.sendFiles",- "host.setUp", "host.action", "host.openSettings",+ "host.setUp", "host.joinWithCode", "host.action", "host.openSettings","settings.get", "settings.choose","keyvault.get", "keyvault.lock", "keyvault.unlock","keyvault.unlockVault", "keyvault.setup", "keyvault.setDisabled",diff --git a/apps/cua-spaces-desktop/src/deep-link.ts b/apps/cua-spaces-desktop/src/deep-link.tsnew file mode 100644index 0000000000..47a7c31b2f--- /dev/null+++ b/apps/cua-spaces-desktop/src/deep-link.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// `cua://add/<code>`: the add-machine link (https://cua.ai/add/<code>)+// opened in this app. It brings the app forward on Machines with Join with a+// code filled in. It never joins on its own: the page asks first.+import { normalizeCode } from "./bridge/join-with-code";++export const DEEP_LINK_SCHEME = "cua";++/**+ * The app's route for a `cua://add/<code>[?relay=<url>]` link (also+ * `cua://add?code=<code>`), or null for any other URL or a malformed code.+ */+export function routeForDeepLink(raw: string): string | null {+ let url: URL;+ try {+ url = new URL(raw.trim());+ } catch {+ return null;+ }+ if (url.protocol !== `${DEEP_LINK_SCHEME}:` || url.hostname.toLowerCase() !== "add") return null;+ const fromPath = decodeURIComponent(url.pathname.replace(/^\/+/, "").split("/")[0] ?? "");+ const code = normalizeCode(fromPath || url.searchParams.get("code") || "");+ if (!code) return null;+ const relay = url.searchParams.get("relay")?.trim();+ const query = new URLSearchParams({ join: code });+ if (relay && /^https?:\/\//i.test(relay)) query.set("relay", relay);+ return `/machines?${query.toString()}`;+}++/** The first `cua://` argument of a command line (Windows and Linux start a second copy with the link as an argument). */+export function deepLinkInArgv(argv: readonly string[]): string | null {+ return argv.find((a) => a.toLowerCase().startsWith(`${DEEP_LINK_SCHEME}://`)) ?? null;+}diff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.tsindex 9ffc0d1aa1..4063a93ead 100644--- a/apps/cua-spaces-desktop/src/main.ts+++ b/apps/cua-spaces-desktop/src/main.ts@@ -28,6 +28,7 @@ import { createPipWindows } from "./pip";import { electronKeyvaultPrompts } from "./prompts";import { APP_ORIGIN, handleAppProtocol, registerSchemePrivileges } from "./protocol";import { readSettings, writeSettings } from "./settings";+import { DEEP_LINK_SCHEME, deepLinkInArgv, routeForDeepLink } from "./deep-link";import { makeSystem } from "./system";import { initTheme, setThemeSource } from "./theme";import { closesToTray, installTray, isQuitting } from "./tray";@@ -306,7 +307,33 @@ if (!app.requestSingleInstanceLock()) {const openSettings = () => tellMain("settings.openRequested");const gettingStarted = () => tellMain("checklist.openRequested");- app.on("second-instance", showMain);+ // A `cua://add/<code>` link: the app on Machines, Join with a code filled in. Links that+ // arrive before the app is ready wait for it.+ let ready = false;+ const pendingLinks: string[] = [];+ const openLink = (link: string) => {+ if (!ready) {+ pendingLinks.push(link);+ return;+ }+ const route = routeForDeepLink(link);+ if (route) {+ app.focus({ steal: true });+ showRoute(route);+ }+ };+ // Windows and Linux start a second copy with the link as an argument; macOS sends open-url.+ app.on("second-instance", (_event, argv) => {+ const link = deepLinkInArgv(argv);+ if (link) openLink(link);+ else showMain();+ });+ app.on("open-url", (event, url) => {+ event.preventDefault();+ openLink(url);+ });+ const firstLink = deepLinkInArgv(process.argv);+ if (firstLink) pendingLinks.push(firstLink);app.whenReady().then(async () => {// Docker was installed and the user added to its group after this session began: start again with the group, so no logout or reboot is needed.@@ -382,6 +409,12 @@ if (!app.requestSingleInstanceLock()) {});app.on("activate", showMain);++ // Make this app the one `cua://` links open (the installer registers it on macOS and in the Linux+ // package; Windows only learns it here). A development run is not an installed app: leave links alone.+ if (app.isPackaged) app.setAsDefaultProtocolClient(DEEP_LINK_SCHEME);+ ready = true;+ for (const link of pendingLinks.splice(0)) openLink(link);});app.on("window-all-closed", () => {diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.tsindex 4a7a50bfd0..79c62a4cad 100644--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts@@ -209,7 +209,8 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()for (const [method, args] of cases) problems.push(...shapeProblems(method, await call(method, args)));expect(problems).toEqual([]);// Every method of this area has its case (the Electron-only ones are checked below).- const electronOnly = new Set(["onboarding.get", "onboarding.complete"]);+ // (host.joinWithCode runs the bundled cua: join-with-code.test.ts.)+ const electronOnly = new Set(["onboarding.get", "onboarding.complete", "host.joinWithCode"]);expect(HOST_METHODS.filter((m) => !electronOnly.has(m) && !cases.some(([c]) => c === m))).toEqual([]);expect(HOST_METHODS.filter((m) => NOT_YET.includes(m))).toEqual([]);});@@ -249,7 +250,7 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()});expect(mine.filter((op) => !HOST_OPS.includes(op))).toEqual([]);const problems: string[] = [];- for (const op of HOST_OPS as OpName[]) {+ for (const op of (HOST_OPS as OpName[]).filter((o) => o !== "host.joinWithCode")) {try {const result = await adapter.call(op, (args[op] ?? {}) as never);problems.push(...validate(OP_SHAPES[op], result, SHAPE_DEFS).map((e) => `${op} ${e}`));diff --git a/apps/cua-spaces-desktop/test/host-fixtures.ts b/apps/cua-spaces-desktop/test/host-fixtures.tsindex 5c1e3a06cc..9306098127 100644--- a/apps/cua-spaces-desktop/test/host-fixtures.ts+++ b/apps/cua-spaces-desktop/test/host-fixtures.ts@@ -307,7 +307,7 @@ export const HOST_METHODS = ["devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine","devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode", "teams.list","storage.get", "storage.run", "notifications.list", "notifications.markAllRead", "notifications.markRead",- "host.setUp", "host.action", "host.openSettings", "settings.get", "settings.choose",+ "host.setUp", "host.joinWithCode", "host.action", "host.openSettings", "settings.get", "settings.choose","onboarding.get", "onboarding.complete",];@@ -319,5 +319,5 @@ export const HOST_OPS = ["devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine","devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode", "teams.list","storage.get", "storage.run", "notifications.list", "notifications.markAllRead", "notifications.markRead",- "host.setUp", "host.action", "host.openSettings", "settings.get", "settings.set", "settings.choose", "experiments.set", "session.completeOnboarding",+ "host.setUp", "host.joinWithCode", "host.action", "host.openSettings", "settings.get", "settings.set", "settings.choose", "experiments.set", "session.completeOnboarding",];diff --git a/apps/cua-spaces-desktop/test/join-with-code.test.ts b/apps/cua-spaces-desktop/test/join-with-code.test.tsnew file mode 100644index 0000000000..370df9746d--- /dev/null+++ b/apps/cua-spaces-desktop/test/join-with-code.test.ts@@ -0,0 +1,139 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// "Join with a code" (`host.joinWithCode`) and the `cua://add/<code>` link+// (the SwiftUI app's JoinWithCodeTests, ported).+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import * as path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import type { BridgeContext } from "../src/bridge/context";+import { Failure } from "../src/bridge/host";+import { failureText, joinArgs, joinMethods, linkRelay, normalizeCode, runCua, type CuaRun } from "../src/bridge/join-with-code";+import { deepLinkInArgv, routeForDeepLink } from "../src/deep-link";++describe("pairing codes", () => {+ it("reads any case, with or without dashes, I/L as 1 and O as 0, and an add-machine link", () => {+ expect(normalizeCode("k7qm-4xpb-2rhd")).toBe("K7QM4XPB2RHD");+ expect(normalizeCode(" K7QM 4XPB 2RHD ")).toBe("K7QM4XPB2RHD");+ expect(normalizeCode("IL0O-IL0O-IL0O")).toBe("110011001100");+ expect(normalizeCode("https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fr.example")).toBe("K7QM4XPB2RHD");+ });+ it("rejects what is not a code", () => {+ for (const bad of ["", "K7QM-4XPB", "K7QM-4XPB-2RHD-9", "U7QM-4XPB-2RHD", "K7QM-4XPB-2RH!", "; rm -rf ~"]) expect(normalizeCode(bad)).toBeNull();+ });+ it("finds the relay a link names, http(s) only", () => {+ expect(linkRelay("https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fr.example")).toBe("https://r.example");+ expect(linkRelay("https://cua.ai/add/K7QM-4XPB-2RHD?relay=file%3A%2F%2F%2Fetc")).toBeNull();+ expect(linkRelay("K7QM-4XPB-2RHD")).toBeNull();+ });+});++describe("the command", () => {+ it("passes the canonical code, and the relay when one is named", () => {+ expect(joinArgs("K7QM4XPB2RHD", null)).toEqual(["host", "setup", "--pair", "K7QM4XPB2RHD"]);+ expect(joinArgs("K7QM4XPB2RHD", "https://r.example")).toEqual(["host", "setup", "--pair", "K7QM4XPB2RHD", "--relay", "https://r.example"]);+ });+ it("shows the last line cua wrote, else the exit status", () => {+ expect(failureText("warning: x\nerror: this pairing code was already used\n\n", "exited with 1")).toBe("error: this pairing code was already used");+ expect(failureText("", "exited with 1")).toBe("cua host setup exited with 1");+ });+});++describe.skipIf(process.platform === "win32")("running cua", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "join-cua-"));+ afterAll(() => rmSync(dir, { recursive: true, force: true }));+ const script = (name: string, body: string) => {+ const file = path.join(dir, name);+ writeFileSync(file, `#!/bin/sh\n${body}\n`);+ chmodSync(file, 0o755);+ return file;+ };+ it("succeeds on exit 0 and receives the arguments", async () => {+ const out = path.join(dir, "args.txt");+ const cua = script("ok", `printf '%s\\n' "$@" > "${out}"`);+ expect((await runCua(cua, joinArgs("K7QM4XPB2RHD", null), {})).ok).toBe(true);+ expect((await import("node:fs")).readFileSync(out, "utf8").trim().split("\n")).toEqual(["host", "setup", "--pair", "K7QM4XPB2RHD"]);+ });+ it("fails with what cua said on stderr", async () => {+ const cua = script("bad", `echo "host setup failed at register: the pairing code expired" >&2; exit 1`);+ const r = await runCua(cua, [], {});+ expect(r.ok).toBe(false);+ expect(failureText(r.stderr, r.status)).toBe("host setup failed at register: the pairing code expired");+ });+ it("stops a run that takes too long", async () => {+ const cua = script("slow", "sleep 5");+ expect(await runCua(cua, [], {}, 100)).toMatchObject({ ok: false, status: "timed out" });+ });+ it("reports a cua that cannot start", async () => {+ expect((await runCua(path.join(dir, "missing"), [], {})).ok).toBe(false);+ });+});++describe("host.joinWithCode", () => {+ const status = { configured: true };+ const make = (run: (cua: string, args: string[]) => Promise<CuaRun>, supervisor: unknown = { cua: "/app/cua" }) => {+ const calls: { cua: string; args: string[] }[] = [];+ let refreshed = 0;+ const ctx = {+ model: { host: { refresh: async () => void refreshed++, state: status, machineId: "m1", progress: "" } },+ supervisor,+ env: { HOME: "/h" },+ } as unknown as BridgeContext;+ const method = joinMethods(ctx, async (cua, args) => (calls.push({ cua, args }), run(cua, args)))["host.joinWithCode"]!;+ const handler = (args: Record<string, unknown>) => Promise.resolve(method(args as never, null as never));+ return { handler, calls, refreshed: () => refreshed };+ };+ const code = async (p: Promise<unknown>) => ((await p.then(() => null, (e: unknown) => e)) as Failure | null)?.code;++ it("runs the bundled cua with the canonical code, refreshes the host and answers its status", async () => {+ const t = make(async () => ({ ok: true, stderr: "", status: "exited with 0" }));+ const answer = (await t.handler({ code: "k7qm-4xpb-2rhd" })) as Record<string, unknown>;+ expect(t.calls).toEqual([{ cua: "/app/cua", args: ["host", "setup", "--pair", "K7QM4XPB2RHD"] }]);+ expect(t.refreshed()).toBe(1);+ expect(answer).toMatchObject({ configured: true, machineId: "m1" });+ });+ it("passes a relay from the page, or from a pasted link", async () => {+ const t = make(async () => ({ ok: true, stderr: "", status: "" }));+ await t.handler({ code: "K7QM4XPB2RHD", relay: "https://r.example" });+ await t.handler({ code: "https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fs.example" });+ expect(t.calls.map((c) => c.args.slice(4))).toEqual([["--relay", "https://r.example"], ["--relay", "https://s.example"]]);+ });+ it("rejects a bad code or relay without running anything", async () => {+ const t = make(async () => ({ ok: true, stderr: "", status: "" }));+ expect(await code(t.handler({ code: "nope" }))).toBe("bad_args");+ expect(await code(t.handler({}))).toBe("bad_args");+ expect(await code(t.handler({ code: "K7QM4XPB2RHD", relay: "ftp://x" }))).toBe("bad_args");+ expect(t.calls).toEqual([]);+ });+ it("fails with cua's own words, and does not refresh", async () => {+ const t = make(async () => ({ ok: false, stderr: "this pairing code was already used\n", status: "exited with 1" }));+ await expect(t.handler({ code: "K7QM4XPB2RHD" })).rejects.toMatchObject({ code: "failed", message: "this pairing code was already used" });+ expect(t.refreshed()).toBe(0);+ });+ it("is unsupported in a build without the bundled cua", async () => {+ const t = make(async () => ({ ok: true, stderr: "", status: "" }), null);+ expect(await code(t.handler({ code: "K7QM4XPB2RHD" }))).toBe("unsupported");+ });+});++describe("cua:// links", () => {+ it("opens Machines with the code", () => {+ expect(routeForDeepLink("cua://add/K7QM-4XPB-2RHD")).toBe("/machines?join=K7QM4XPB2RHD");+ expect(routeForDeepLink("cua://add/k7qm4xpb2rhd")).toBe("/machines?join=K7QM4XPB2RHD");+ expect(routeForDeepLink("cua://add?code=K7QM-4XPB-2RHD")).toBe("/machines?join=K7QM4XPB2RHD");+ });+ it("carries an http(s) relay", () => {+ expect(routeForDeepLink("cua://add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fr.example")).toBe("/machines?join=K7QM4XPB2RHD&relay=https%3A%2F%2Fr.example");+ expect(routeForDeepLink("cua://add/K7QM-4XPB-2RHD?relay=javascript%3Aalert(1)")).toBe("/machines?join=K7QM4XPB2RHD");+ });+ it("ignores anything else", () => {+ for (const bad of ["cua://keyvault", "cua://add", "cua://add/short", "cua://add/K7QM-4XPB-2RH!", "https://cua.ai/add/K7QM-4XPB-2RHD", "cua-spaces://app/machines", "not a url"]) {+ expect(routeForDeepLink(bad)).toBeNull();+ }+ });+ it("finds the link among a command line's arguments", () => {+ expect(deepLinkInArgv(["/app/Cua Spaces.exe", "--flag", "cua://add/K7QM-4XPB-2RHD"])).toBe("cua://add/K7QM-4XPB-2RHD");+ expect(deepLinkInArgv(["/app/Cua Spaces.exe"])).toBeNull();+ });+});diff --git a/apps/cua-spaces-macos/README.md b/apps/cua-spaces-macos/README.mdindex ababa9a819..520fc61ca1 100644--- a/apps/cua-spaces-macos/README.md+++ b/apps/cua-spaces-macos/README.md@@ -15,6 +15,7 @@ render and do platform glue.| Devices | Settings → Devices: this Mac's enrollment (enrolled until, grace ends, needs enrollment), the account's devices with Rename and Revoke, Recent Access; the Enroll sheet (sign in again, or a one-time code approved from an enrolled device), the approval sheet for a device asking to join (a notification too; Approve asks for Touch ID or the login password), and a banner in the main window when this Mac needs enrolling || Menu bar | The Cua mark (template); status line, Open, New Space, Settings, Quit || Launch at login | Settings → General: `SMAppService.mainApp`, showing what macOS reports (on, off, waiting for approval with a button to Login Items, not found); the first run's Done page ticks it. A login launch opens without the main window, and the app's daemon (host Spaces, persistent agents, Cua Volume) starts with it |+| Join with a code | `host.joinWithCode` runs the bundled `cua host setup --pair <code>` (3 minute limit); `cua://add/<CODE>` opens Machines at `?join=<CODE>` and the page asks before joining || Notch panel | The "N Spaces" tab, Space tiles with live thumbnails, and the Teleport prompt; hover opens it after 300 ms, a dragged window or file drops on a tile. Window drags need Accessibility; the panel says so with an Open Settings button |Keyboard in the live desktop (main window and floating viewer): once youdiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swiftindex a48b0397c1..5cfc6903f9 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift@@ -284,6 +284,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {return false}+ /// `cua://add/<CODE>` links: the page's Machines at the code, which it+ /// confirms before joining. Never joins by itself.+ func application(_ application: NSApplication, open urls: [URL]) {+ guard let route = urls.lazy.compactMap(JoinWithCode.route(for:)).first else { return }+ NSApp.activate()+ WebUIWindowController.show(model: Self.model, at: .path(route))+ }+func start(_ model: AppModel) {guard !started else { return }started = truediff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/JoinWithCode.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/JoinWithCode.swiftnew file mode 100644index 0000000000..b72caf58c0--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/JoinWithCode.swift@@ -0,0 +1,110 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation++/// "Join with a code": the pairing code a machine joins with, as the+/// `host.joinWithCode` bridge method and the `cua://add/<CODE>` link carry it.+/// Pure parts only; the Process runs in `WebUIBridge+Pages.swift`.+enum JoinWithCode {+ /// Crockford base32, the pairing code's alphabet.+ static let alphabet = Set("0123456789ABCDEFGHJKMNPQRSTVWXYZ")+ static let codeLength = 12+ /// How long `cua host setup --pair` may run.+ static let timeout: TimeInterval = 180++ /// The code as `XXXX-XXXX-XXXX`, from any case, with dashes and spaces+ /// ignored; `nil` unless it is 12 Crockford base32 characters.+ static func normalizeCode(_ raw: String) -> String? {+ let chars = raw.uppercased().filter { $0 != "-" && !$0.isWhitespace }+ guard chars.count == codeLength, chars.allSatisfy({ alphabet.contains($0) }) else { return nil }+ let s = Array(chars)+ return [s[0..<4], s[4..<8], s[8..<12]].map { String($0) }.joined(separator: "-")+ }++ /// A code or an add-machine link (`https://cua.ai/add/<code>?relay=...`)+ /// as the user pasted it: the trimmed text and the link's relay, if any.+ /// Other text passes through, for the CLI to judge.+ static func splitInput(code raw: String, relay: String?) -> (code: String, relay: String?) {+ let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ var relay = relay?.trimmingCharacters(in: .whitespacesAndNewlines)+ if relay?.isEmpty == true { relay = nil }+ if let url = URL(string: text), let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http" || scheme == "cua" {+ let parts = url.pathComponents.filter { $0 != "/" }+ var found: String?+ if let i = parts.firstIndex(of: "add"), i + 1 < parts.count { found = parts[i + 1] }+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []+ if found == nil { found = items.first { $0.name == "code" }?.value }+ if relay == nil, let r = items.first(where: { $0.name == "relay" })?.value, !r.isEmpty { relay = r }+ if let found { return (found, relay) }+ }+ return (text, relay)+ }++ /// The arguments after `cua`; `nil` when there is no code.+ static func arguments(code raw: String, relay: String?) -> [String]? {+ let (text, relay) = splitInput(code: raw, relay: relay)+ guard !text.isEmpty else { return nil }+ let code = normalizeCode(text) ?? text+ var args = ["host", "setup", "--pair", code]+ if let relay { args += ["--relay", relay] }+ return args+ }++ /// The last non-empty line of the CLI's stderr, for the error message.+ static func failureMessage(stderr: String, status: Int32) -> String {+ let line = stderr.split(whereSeparator: \.isNewline)+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .last { !$0.isEmpty }+ return line ?? "cua host setup exited with status \(status)"+ }++ /// What `cua://add/<CODE>`, `cua://add/<CODE>?relay=<url>` and+ /// `cua://add?code=<CODE>` ask for: the page's route, or `nil` for any+ /// other link or a code that is not well formed.+ static func route(for url: URL) -> String? {+ guard url.scheme?.lowercased() == "cua",+ let parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }+ let segments = ([parts.host] + parts.path.split(separator: "/").map(String.init))+ .compactMap { $0 }.filter { !$0.isEmpty }+ guard segments.first?.lowercased() == "add" else { return nil }+ let items = parts.queryItems ?? []+ let raw = segments.count > 1 ? segments[1] : items.first { $0.name == "code" }?.value+ guard segments.count <= 2, let raw, let code = normalizeCode(raw) else { return nil }+ var route = "/machines?join=\(code)"+ if let relay = items.first(where: { $0.name == "relay" })?.value, !relay.isEmpty {+ route += "&relay=\(MainUIRoute.encodeComponent(relay))"+ }+ return route+ }++ /// Runs `cua <args>` off the main thread; throws the failure message on+ /// a non-zero exit, and after `timeout` seconds (the process is stopped).+ static func run(cua: String, args: [String], timeout: TimeInterval = JoinWithCode.timeout) async throws {+ let (status, err) = await Task.detached { () -> (Int32, String) in+ let process = Process()+ process.executableURL = URL(fileURLWithPath: cua)+ process.arguments = args+ process.environment = ProcessInfo.processInfo.environment+ process.standardInput = FileHandle.nullDevice+ process.standardOutput = FileHandle.nullDevice+ let pipe = Pipe()+ process.standardError = pipe+ do { try process.run() } catch { return (-1, "Could not start cua: \(error.localizedDescription)") }+ let timer = DispatchSource.makeTimerSource(queue: .global())+ nonisolated(unsafe) var timedOut = false+ timer.schedule(deadline: .now() + timeout)+ timer.setEventHandler { timedOut = true; process.terminate() }+ timer.resume()+ // Reads to EOF, so a chatty child never blocks on a full pipe.+ let data = pipe.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()+ timer.cancel()+ if timedOut { return (-1, "Joining timed out after \(Int(timeout)) seconds") }+ return (process.terminationStatus, String(decoding: data, as: UTF8.self))+ }.value+ if status != 0 { throw FailedRun(message: failureMessage(stderr: err, status: status)) }+ }++ struct FailedRun: Error { let message: String }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swiftindex f95cc8e1a6..1cf8a08fef 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/MainUIRoute.swift@@ -22,6 +22,8 @@ public enum MainUIRoute: Equatable, Sendable {case machinescase agentscase keyvault+ /// A page path as given (`/machines?join=<CODE>` from a `cua://add` link).+ case path(String)/// The page's path, query included.var webPath: String {@@ -33,6 +35,7 @@ public enum MainUIRoute: Equatable, Sendable {case .machines: return "/machines"case .agents: return "/agents"case .keyvault: return "/keyvault"+ case let .path(path): return pathcase let .space(id, dropped):let path = "/spaces/\(Self.encodeComponent(id))"let names = dropped.map(\.lastPathComponent)diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 72c7095d25..29c8d63048 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -202,6 +202,22 @@ extension WebUIBridge {: HostSetupFailure.presenting(LiveSpacesBackend.words(error)))}return hostStatus()+ case "host.joinWithCode":+ let relay = args["relay"] as? String+ guard let code = args["code"] as? String,+ let cliArgs = JoinWithCode.arguments(code: code, relay: relay) else {+ throw Failure.badArgs("code: string")+ }+ guard let cua = AppEnvironment.bundledCuaPath else {+ throw Failure.unsupported("This build has no bundled cua to join with")+ }+ do {+ try await JoinWithCode.run(cua: cua, args: cliArgs)+ } catch let failed as JoinWithCode.FailedRun {+ throw Failure(code: "failed", message: failed.message)+ }+ await model.host.refresh()+ return hostStatus()case "host.action":guard model.host.host != nil else { throw Failure.unsupported("This Mac can't be set up for access in this build") }let id = try hostAction(try string(args, "action"))diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex b59ec31a68..d4ee30c5cc 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -95,7 +95,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"spaces.thumbnail",// A Space's drop well: Send file… and dropped files (WebUIBridge+Files.swift)."spaces.chooseFiles", "spaces.droppedFiles", "spaces.sendFiles",- "host.setUp", "host.action", "host.openSettings",+ "host.setUp", "host.joinWithCode", "host.action", "host.openSettings","settings.get", "settings.choose","keyvault.get", "keyvault.lock", "keyvault.unlock","keyvault.unlockVault", "keyvault.setup", "keyvault.setDisabled",diff --git a/apps/cua-spaces-macos/Support/Info.plist b/apps/cua-spaces-macos/Support/Info.plistindex 9ff5ce001d..87e0008789 100644--- a/apps/cua-spaces-macos/Support/Info.plist+++ b/apps/cua-spaces-macos/Support/Info.plist@@ -20,6 +20,17 @@<string>APPL</string><key>CFBundleShortVersionString</key><string>0.9.2</string>+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLName</key>+ <string>com.trycua.spaces.macos</string>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>cua</string>+ </array>+ </dict>+ </array><key>CFBundleVersion</key><string>1</string><key>LSMinimumSystemVersion</key>diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex 95d7d5e485..2200260806 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -261,6 +261,7 @@ struct BridgeContractTests {"spaces.add": "needs a running cua-spacesd at the address","host.setUp": "installs the host service", "host.action": "changes the host service","host.openSettings": "opens System Settings",+ "host.joinWithCode": "runs the bundled cua; JoinWithCodeTests covers the arguments and bad args","agents.events": "needs the daemon's agent_events; WebUIHostTests checks it is unsupported without it","agents.pause": "changes the fake's state for agents.list", "agents.resume": "as agents.pause","agents.setupDriver": "writes the coding agents' configs on the fixture setup",diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/JoinWithCodeTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/JoinWithCodeTests.swiftnew file mode 100644index 0000000000..dc27847674--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/JoinWithCodeTests.swift@@ -0,0 +1,77 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import AppKit+@testable import CuaSpacesMacKit+import Foundation+import Testing++@Suite("Join with a code")+struct JoinWithCodeTests {+ @Test func normalizesCodes() {+ #expect(JoinWithCode.normalizeCode("abcd-efgh-jkmn") == "ABCD-EFGH-JKMN")+ #expect(JoinWithCode.normalizeCode(" 0123 4567 89ab ") == "0123-4567-89AB")+ #expect(JoinWithCode.normalizeCode("ABCDEFGHJKMN") == "ABCD-EFGH-JKMN")+ #expect(JoinWithCode.normalizeCode("ABCD-EFGH-JKM") == nil)+ #expect(JoinWithCode.normalizeCode("ABCD-EFGH-JKMNP") == nil)+ #expect(JoinWithCode.normalizeCode("ABCD-EFGH-JKMI") == nil, "I is not in the alphabet")+ #expect(JoinWithCode.normalizeCode("ABCD-EFGH-JKMU") == nil, "U is not in the alphabet")+ #expect(JoinWithCode.normalizeCode("") == nil)+ }++ @Test func buildsArguments() {+ #expect(JoinWithCode.arguments(code: "abcd-efgh-jkmn", relay: nil)+ == ["host", "setup", "--pair", "ABCD-EFGH-JKMN"])+ #expect(JoinWithCode.arguments(code: "ABCDEFGHJKMN", relay: "https://relay.example.com")+ == ["host", "setup", "--pair", "ABCD-EFGH-JKMN", "--relay", "https://relay.example.com"])+ #expect(JoinWithCode.arguments(code: "ABCDEFGHJKMN", relay: " ")+ == ["host", "setup", "--pair", "ABCD-EFGH-JKMN"])+ #expect(JoinWithCode.arguments(code: "https://cua.ai/add/abcd-efgh-jkmn?relay=https%3A%2F%2Fr.example.com", relay: nil)+ == ["host", "setup", "--pair", "ABCD-EFGH-JKMN", "--relay", "https://r.example.com"])+ #expect(JoinWithCode.arguments(code: "https://cua.ai/add/ABCDEFGHJKMN?relay=https%3A%2F%2Fr.example.com", relay: "https://mine.example.com")+ == ["host", "setup", "--pair", "ABCD-EFGH-JKMN", "--relay", "https://mine.example.com"])+ #expect(JoinWithCode.arguments(code: "", relay: nil) == nil)+ #expect(JoinWithCode.arguments(code: " ", relay: "https://r") == nil)+ }++ @Test func picksTheLastStderrLine() {+ #expect(JoinWithCode.failureMessage(stderr: "warming up\ncode expired\n\n \n", status: 1) == "code expired")+ #expect(JoinWithCode.failureMessage(stderr: "", status: 3) == "cua host setup exited with status 3")+ }++ @Test func parsesLinks() {+ func route(_ s: String) -> String? { URL(string: s).flatMap(JoinWithCode.route(for:)) }+ #expect(route("cua://add/abcd-efgh-jkmn") == "/machines?join=ABCD-EFGH-JKMN")+ #expect(route("cua://add/ABCDEFGHJKMN?relay=https%3A%2F%2Fr.example.com%2Fx")+ == "/machines?join=ABCD-EFGH-JKMN&relay=https%3A%2F%2Fr.example.com%2Fx")+ #expect(route("cua://add?code=abcdefghjkmn") == "/machines?join=ABCD-EFGH-JKMN")+ #expect(route("cua://add/ABCDEFGHJKMN/extra") == nil)+ #expect(route("cua://add/ABCD-EFGH-JKM") == nil)+ #expect(route("cua://add/ABCD-EFGH-JKMI") == nil)+ #expect(route("cua://add") == nil)+ #expect(route("cua://open/ABCDEFGHJKMN") == nil)+ #expect(route("https://cua.ai/add/ABCDEFGHJKMN") == nil)+ }++ @Test func linkRouteIsThePath() {+ #expect(MainUIRoute.path("/machines?join=ABCD-EFGH-JKMN").webPath == "/machines?join=ABCD-EFGH-JKMN")+ }++ @Test @MainActor func emptyCodeIsBadArgs() async throws {+ _ = NSApplication.shared+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-join-\(UUID().uuidString)")+ let model = AppModel(backend: FixtureSpacesBackend(), keyvault: KeyvaultModel(client: nil),+ onboarding: OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path),+ settingsPath: dir.appendingPathComponent("settings.json").path,+ telemetry: FixtureTelemetry())+ let bridge = WebUIBridge(model: model, allowedOrigins: [])+ for args: [String: Any] in [[:], ["code": ""], ["code": " "], ["code": 5]] {+ do {+ _ = try await bridge.handle("host.joinWithCode", args)+ Issue.record("expected bad_args for \(args)")+ } catch let f as WebUIBridge.Failure {+ #expect(f.code == "bad_args")+ }+ }+ }+}diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.mdindex 8db40dc8a8..a2ccd3835a 100644--- a/apps/cua-spaces-web/src/bridge/README.md+++ b/apps/cua-spaces-web/src/bridge/README.md@@ -33,6 +33,7 @@ import { BridgeProvider, useSpaces } from "@/bridge";| `useSpaces()` | `Space[]` with pending creates, power changes and deletes overlaid by the core. Actions: `createSpace(req)`, `cancelCreate(pendingId)`, `dismissCreate(pendingId)`, `startSpace(id)`, `stopSpace(id)`, `deleteSpace(id)`, `openSpace(id)`. || `useMachines()` | `Machine[]`, this machine first, each with `spaceIds`, `connection` (`relay`, `direct`, or null before host setup), `detail`, `lastSeen` and, for this machine, `panel` (the core's `host.panel`). Also `setupGuide`: host setup in the core's words (`host.panel` choices, `host.formView`), for the Add a machine explainer. || `usePairingCode({ open, enabled, team? })` | "Add a machine" by link or QR code: makes a code on opening (`devices.createPairingCode`), reads `devices.pairingCodes` every 3 s until it is `used`, `revoked` or `expired`, and `revoke()` / `renew()`. `phase` is `idle`, `minting`, `ready`, `used`, `revoked`, `expired` or `error` (`error.unsupported` when the host or relay can't make codes). |+| `useJoinWithCode({ onJoined? })` | "Join with a code": `{ phase, error, join(codeOrLink, relay?), reset() }`. `join` reads the code the way `cua host setup --pair` does (`pairing-code.ts`), then asks the host to run the bundled `cua host setup --pair` (`host.joinWithCode`). Opening the app with a `cua://add/<code>` link lands on `/machines?join=<code>`, which fills the dialog and waits for Join. || `useSettings()` | `{ values, telemetry, defaultLocation, page }`, where `page` is the core's Settings layout. Action: `updateSetting(key, value)` for `theme`, `menuBar`, `hotkey`, `telemetry`, `defaultLocation`, `launchAtLogin` or `updateChannel`. The last two are `null` when the host can't offer them, and the Settings page hides their rows. `globalShortcut` is the host's ⌘⇧Space (macOS) with whether the system gave it to the app; absent or `null` where the host has none. || `useKeyvault()` | `{ overview, groups, views, vaultState }`. `views` holds the core's `page`, `sidebar` and `vault` (the list grouped by app, then site). Actions: `unlock(passphrase?)`, `lockItem(id)`, `lockItems(ids)`, `unlockItems(ids)`, `setDisabled`, `approve`, `deny`, `revokeGrant`, `vaultAction(action)` (search, select, open), and `pane(selection)`. || `useSession()` | `{ fleet, onboarding, daemon, signedIn, identity, signIn }`, where `signIn` is the sign-in phase. Actions: `signIn()`, `signOut()`, `completeOnboarding(mode)`, `openExternal(url)`. |diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex f7c8ce2de9..8aad6faeff 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -134,6 +134,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"spaces.droppedFiles": { names: ["notes.txt"] },"spaces.sendFiles": { spaceId: SPACE, paths: ["/tmp/cua-contract-notes.txt"] },"host.setUp": { request: { mode: "relay" } },+ "host.joinWithCode": { code: "K7QM-4XPB-2RHD" },"host.action": { action: "stop-sharing" },"host.openSettings": { url: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" },"startup.get": {},diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 1cb6ce1aa8..20449223d6 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -118,6 +118,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"spaces.droppedFiles": { names: ["notes.txt"] },"spaces.sendFiles": { spaceId: "s1", paths: ["/tmp/notes.txt"] },"host.setUp": { request: { mode: "relay" } },+ "host.joinWithCode": { code: "K7QM-4XPB-2RHD" },"host.action": { action: "stop-sharing" },"host.openSettings": { url: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" },"startup.get": {},@@ -161,6 +162,7 @@ function webkitResult(method: string): unknown {return { completed: true, mode: "client" };case "host.status":case "host.setUp":+ case "host.joinWithCode":case "host.action":return { configured: false, sharing: false, serviceInstalled: false, serviceRunning: false, serviceKind: "process", clients: [], permissions: [], shareDesktop: true, provideSpaces: false, maxSpaces: 0 };case "keyvault.approve":diff --git a/apps/cua-spaces-web/src/bridge/__tests__/pairing-code.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/pairing-code.test.tsnew file mode 100644index 0000000000..ac672c3499--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/__tests__/pairing-code.test.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";++import { displayPairingCode, normalizePairingCode, pairingLinkRelay } from "../pairing-code";++// The same cases as `cua_host::pairing` (libs/cua/crates/cua-host/src/pairing.rs).+describe("pairing codes", () => {+ it("reads a code in any case, with or without dashes and spaces", () => {+ for (const typed of ["K7QM-4XPB-2RHD", "k7qm-4xpb-2rhd", "K7QM4XPB2RHD", " k7qm 4xpb 2rhd ", "cpc_K7QM4XPB2RHD"]) {+ expect(normalizePairingCode(typed)).toBe("K7QM4XPB2RHD");+ }+ });++ it("reads I and L as 1, and O as 0", () => {+ expect(normalizePairingCode("IL0O-IL0O-IL0O")).toBe("110011001100");+ });++ it("reads an add-machine link", () => {+ expect(normalizePairingCode("https://cua.ai/add/K7QM-4XPB-2RHD")).toBe("K7QM4XPB2RHD");+ expect(normalizePairingCode("https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Frelay.example")).toBe("K7QM4XPB2RHD");+ });++ it("rejects what cannot be a code", () => {+ for (const typed of ["", "K7QM-4XPB", "K7QM-4XPB-2RHD-9", "K7QM-4XPB-2RH!", "U7QM-4XPB-2RHD", "https://cua.ai/add/"]) {+ expect(normalizePairingCode(typed)).toBeNull();+ }+ });++ it("shows a code as XXXX-XXXX-XXXX and leaves other input alone", () => {+ expect(displayPairingCode("k7qm4xpb2rhd")).toBe("K7QM-4XPB-2RHD");+ expect(displayPairingCode("nope")).toBe("nope");+ });++ it("finds the relay a link names", () => {+ expect(pairingLinkRelay("https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Frelay.example")).toBe("https://relay.example");+ expect(pairingLinkRelay("https://cua.ai/add/K7QM-4XPB-2RHD")).toBeNull();+ expect(pairingLinkRelay("K7QM-4XPB-2RHD")).toBeNull();+ });+});diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.tsindex 597abb2009..cc7cafc4a4 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/host-setup.ts@@ -7,6 +7,7 @@import { HostError } from "../../adapter";import type { HostStatus } from "../../contracts/host";import { HOST_SETTING_CHANGE, isSettingsPane } from "../../ops/host-setup";+import { normalizePairingCode } from "../../pairing-code";import { demoHostStatus } from "../demo-data";import type { DemoContext, DemoHandlers } from "./context";@@ -17,7 +18,7 @@ export interface DemoHostSetupState {export const demoHostSetupState = (now: number, firstRun: boolean): DemoHostSetupState => ({ host: demoHostStatus(now, firstRun) });-export function demoHostSetupHandlers({ state, now, wait, emit, stepMs }: DemoContext): DemoHandlers<"host.setUp" | "host.action" | "host.openSettings"> {+export function demoHostSetupHandlers({ state, now, wait, emit, stepMs }: DemoContext): DemoHandlers<"host.setUp" | "host.joinWithCode" | "host.action" | "host.openSettings"> {const set = (host: HostStatus) => {state.host = host;emit({ type: "machines.changed" });@@ -41,6 +42,12 @@ export function demoHostSetupHandlers({ state, now, wait, emit, stepMs }: DemoCorecentAccess: [],});},+ // The demo has no relay: any well-formed code joins, a bad one fails as the CLI does.+ "host.joinWithCode": async ({ code }) => {+ if (!normalizePairingCode(code)) throw new HostError(`${code.trim() || "That"} is not a pairing code (12 letters and digits, like K7QM-4XPB-2RHD)`, "bad_args");+ await wait(stepMs * 2);+ return set({ ...demoHostStatus(now()), name: "This Mac", permissions: state.host.permissions, clients: [], recentAccess: [] });+ },"host.action": async ({ action }) => {await wait(stepMs);const h = state.host;diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex e8b8ad005e..050e9e608e 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -85,6 +85,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = ["settings.choose","agents.events","agents.setupDriver",+ "host.joinWithCode",...TELEPORT_TAURI_UNSUPPORTED,...KEYVAULT_MANAGE_TAURI_UNSUPPORTED,...TAURI_SETTINGS_UNSUPPORTED,diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex ccdb0f9ea4..61402fbdce 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -4463,6 +4463,9 @@"host.action": {"$ref": "#/$defs/HostStatus"},+ "host.joinWithCode": {+ "$ref": "#/$defs/HostStatus"+ },"host.openSettings": {"type": "null"},@@ -5966,6 +5969,16 @@}]},+ "host.joinWithCode": {+ "anyOf": [+ {+ "$ref": "#/$defs/WkHostState"+ },+ {+ "type": "null"+ }+ ]+ },"host.openSettings": {"type": "null"},diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex fc9cdca586..eac0c57408 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -875,6 +875,7 @@ export const OP_SHAPES: Record<OpName, Schema> = {"spaces.droppedFiles": strings,"spaces.sendFiles": list(obj<SentFileInfo>()({ name: str, dest: str, bytes: num })),"host.setUp": HostStatusShape,+ "host.joinWithCode": HostStatusShape,"host.action": HostStatusShape,"host.openSettings": nul,"startup.get": StartupShape,@@ -1103,6 +1104,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"machines.list": WkMachinesShape,"host.status": nullable(WkHostShape),"host.setUp": nullable(WkHostShape),+ "host.joinWithCode": nullable(WkHostShape),"host.action": nullable(WkHostShape),"agents.list": OP_SHAPES["agents.list"],"agents.runs": OP_SHAPES["agents.runs"],diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex fbe99b30e3..8e77f79dc8 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -117,6 +117,8 @@ export type { HostFormAction, HostSetupRequest } from "./ops/host-setup";export type { TelemetrySignal } from "./ops/telemetry";export { useStartup, type StartupHook } from "./startup";export { defaultTeam, eligibleTeams, teamName, useTeamChoices, type TeamChoices } from "./teams";+export { joinFailureText, useJoinWithCode, type JoinHook, type JoinPhase } from "./join";+export { displayPairingCode, normalizePairingCode, pairingLinkRelay } from "./pairing-code";export { expiresInText, FINISHING_SETUP, PAIRING_POLL_MS, pairingUnsupported, usePairingCode, type PairingHook, type PairingPhase } from "./pairing";export { READY_STARTUP, type StartupAction, type StartupPhase, type StartupState } from "./ops/startup";export {diff --git a/apps/cua-spaces-web/src/bridge/join.ts b/apps/cua-spaces-web/src/bridge/join.tsnew file mode 100644index 0000000000..050670979d--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/join.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * "Join with a code": sets this computer up with a one-time pairing code+ * (or the add-machine link) made on another device, the in-app way of+ * `cua host setup --pair <code>`. The host runs the bundled `cua`+ * (`host.joinWithCode`) and answers once the machine has joined.+ */++import { useCallback, useState } from "react";++import { isUnsupported } from "./adapter";+import { useBridge } from "./hooks";+import { normalizePairingCode, pairingLinkRelay } from "./pairing-code";++export type JoinPhase = "idle" | "joining" | "joined" | "failed";++export interface JoinHook {+ phase: JoinPhase;+ /** Why it failed, in words for people. */+ error: string | null;+ /** Joins with `input` (a code or an add-machine link); `relay` overrides the link's own. Resolves to whether it worked. */+ join(input: string, relay?: string | null): Promise<boolean>;+ reset(): void;+}++/** What the page says for a failure: the host's own words, or a plain line. */+export function joinFailureText(e: unknown): string {+ if (isUnsupported(e)) return "This version of Cua Spaces can't join with a code. Update the app, or run the install command on this computer.";+ const text = e instanceof Error ? e.message : String(e);+ return text.trim() || "Couldn't join with that code.";+}++export function useJoinWithCode({ onJoined }: { onJoined?: () => void } = {}): JoinHook {+ const { data: adapter } = useBridge();+ const [phase, setPhase] = useState<JoinPhase>("idle");+ const [error, setError] = useState<string | null>(null);++ const join = useCallback(+ async (input: string, relay?: string | null) => {+ const code = normalizePairingCode(input);+ if (!code) {+ setPhase("failed");+ setError("That doesn't look like a code. It has 12 letters and digits, like K7QM-4XPB-2RHD.");+ return false;+ }+ if (!adapter) return false;+ setPhase("joining");+ setError(null);+ try {+ await adapter.call("host.joinWithCode", { code, relay: relay ?? pairingLinkRelay(input) });+ setPhase("joined");+ onJoined?.();+ return true;+ } catch (e) {+ setPhase("failed");+ setError(joinFailureText(e));+ return false;+ }+ },+ [adapter, onJoined],+ );++ return { phase, error, join, reset: useCallback(() => (setPhase("idle"), setError(null)), []) };+}diff --git a/apps/cua-spaces-web/src/bridge/ops/host-setup.ts b/apps/cua-spaces-web/src/bridge/ops/host-setup.tsindex 0dd7142569..cb10bad3e1 100644--- a/apps/cua-spaces-web/src/bridge/ops/host-setup.ts+++ b/apps/cua-spaces-web/src/bridge/ops/host-setup.ts@@ -11,6 +11,7 @@* | Operation | Tauri | SwiftUI |* |---|---|---|* | `host.setUp {request}` | `host_setup` | `HostModel.submit` |+ * | `host.joinWithCode {code, relay?}` | none | runs the bundled `cua host setup --pair` |* | `host.action {action}` | `host_stop_sharing`, `host_start_sharing`, `host_remove`, `host_configure` | `HostModel.run(action)` (`sign-in`: the inline sign-in, then sharing follows it) |* | `host.openSettings {url}` | `host_open_settings` | `PermissionRows.open` |*/@@ -63,6 +64,12 @@ export type HostRunAction = Exclude<HostActionId, "set-up">;export interface HostSetupOps {/** Sets this machine up for access; answers its status after. */"host.setUp": { args: { request: HostSetupRequest }; result: HostStatus };+ /**+ * Joins the account that made a one-time pairing code (or add-machine+ * link) by running the bundled `cua host setup --pair`; answers the status+ * after. `relay` names a relay other than the production one.+ */+ "host.joinWithCode": { args: { code: string; relay?: string | null }; result: HostStatus };/** Runs a This machine button; answers the status after. */"host.action": { args: { action: HostRunAction }; result: HostStatus };/** Opens a System Settings privacy pane (`x-apple.systempreferences:` only). */@@ -113,6 +120,11 @@ export function tauriHostSetupOps(invoke: Invoke) {export const HOST_SETUP_COVERAGE = {"host.setUp": { webkit: { methods: ["host.setUp"] }, tauri: ["host_setup"] },+ "host.joinWithCode": {+ webkit: { methods: ["host.joinWithCode"] },+ tauri: [],+ unsupported: { tauri: "the Tauri app has no bundled `cua` to run, and its Windows and Linux builds are not shipped" },+ },"host.action": {webkit: { methods: ["host.action"] },tauri: ["host_stop_sharing", "host_start_sharing", "host_remove", "host_status", "host_configure"],diff --git a/apps/cua-spaces-web/src/bridge/ops/space-detail.ts b/apps/cua-spaces-web/src/bridge/ops/space-detail.tsindex fceedb1c4d..80100de8fd 100644--- a/apps/cua-spaces-web/src/bridge/ops/space-detail.ts+++ b/apps/cua-spaces-web/src/bridge/ops/space-detail.ts@@ -333,6 +333,7 @@ export const DETAIL_ARGS = {"spaces.droppedFiles": { names: ["notes.txt"] },"spaces.sendFiles": { spaceId: "local:design-review", paths: ["/Users/demo/notes.txt"] },"host.setUp": { request: { mode: "relay" } },+ "host.joinWithCode": { code: "K7QM-4XPB-2RHD" },"host.action": { action: "stop-sharing" as const },"host.openSettings": { url: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" },};diff --git a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.tsindex 72010aa364..deddcb4539 100644--- a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts+++ b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts@@ -95,6 +95,7 @@ export const WEBKIT_PAGE_OPS = ["spaces.droppedFiles","spaces.sendFiles","host.setUp",+ "host.joinWithCode","host.action","host.openSettings",] as const satisfies readonly OpName[];@@ -283,6 +284,7 @@ export function webkitPageOps(request: Request, toHostStatus: (h: WkHostState) ="spaces.sendFiles": list("spaces.sendFiles"),"host.setUp": host("host.setUp"),+ "host.joinWithCode": ({ code, relay }) => request("host.joinWithCode", { code, relay: relay ?? null }),"host.action": host("host.action"),"host.openSettings": async ({ url }) => {if (!isSettingsPane(url)) throw new HostError("Only System Settings panes open here", "bad_args");diff --git a/apps/cua-spaces-web/src/bridge/pairing-code.ts b/apps/cua-spaces-web/src/bridge/pairing-code.tsnew file mode 100644index 0000000000..7f58c97c5f--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/pairing-code.ts@@ -0,0 +1,46 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Reading a pairing code from what a person typed, pasted or scanned. The+ * same rules as `cua_host::normalize_pairing_code`, so the page accepts+ * what `cua host setup --pair` accepts: 12 Crockford base32 characters in+ * any case, with or without dashes and spaces, `I`/`L` read as `1` and `O`+ * as `0`, or an add-machine link (`https://cua.ai/add/<code>`).+ */++const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";+const CODE_LEN = 12;++/** The code in canonical form (12 upper-case characters), or null when `input` can't be a code. */+export function normalizePairingCode(input: string): string | null {+ let s = input.trim();+ const at = s.indexOf("/add/");+ if (at >= 0) s = s.slice(at + "/add/".length).split(/[?#/]/)[0] ?? "";+ if (s.startsWith("cpc_")) s = s.slice(4);+ let out = "";+ for (const raw of s) {+ const c = raw.toUpperCase();+ if (c === "-" || c === " ") continue;+ const mapped = c === "I" || c === "L" ? "1" : c === "O" ? "0" : c;+ if (mapped.length !== 1 || !ALPHABET.includes(mapped)) return null;+ out += mapped;+ }+ return out.length === CODE_LEN ? out : null;+}++/** `XXXX-XXXX-XXXX`; input that is not a code comes back as typed. */+export function displayPairingCode(input: string): string {+ const c = normalizePairingCode(input);+ return c ? `${c.slice(0, 4)}-${c.slice(4, 8)}-${c.slice(8)}` : input;+}++/** The relay an add-machine link names (`?relay=<url>`), or null. */+export function pairingLinkRelay(input: string): string | null {+ try {+ const v = new URL(input.trim()).searchParams.get("relay")?.trim();+ return v ? v : null;+ } catch {+ return null;+ }+}diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex 5ea913e9ad..a7b030c4c4 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -304,6 +304,7 @@ export const OPERATIONS = ["spaces.droppedFiles","spaces.sendFiles","host.setUp",+ "host.joinWithCode","host.action","host.openSettings",...STARTUP_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 31aef655ed..5813a1f919 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -131,6 +131,7 @@ export const WEBKIT_METHODS = ["spaces.droppedFiles","spaces.sendFiles","host.setUp",+ "host.joinWithCode","host.action","host.openSettings","settings.get",diff --git a/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx b/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsxindex b349fa3c5d..8edaa9c6ed 100644--- a/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx+++ b/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx@@ -62,6 +62,9 @@ describe("Add a machine by link or QR code", () => {expect(document.querySelector("[data-pairing-qr] path")?.getAttribute("d")).toMatch(/^M\d/);expect(screen.getByText(/^https:\/\/cua\.ai\/add\/K7QM-4XPB-/)).toBeTruthy();expect(screen.getByText(/sh -s -- --pair K7QM-4XPB-/)).toBeTruthy();+ // The bare code too, for Join with a code on a computer that has the app.+ expect(document.querySelector("[data-pairing-code] code")?.textContent).toMatch(/^K7QM-4XPB-[0-9A-Z]{4}$/);+ expect(screen.getByLabelText("Copy code")).toBeTruthy();expect(screen.getByText("Waiting for the computer…")).toBeTruthy();expect(document.querySelector("[data-pairing-expires]")?.textContent).toBe("Works once. Expires in 30 min");diff --git a/apps/cua-spaces-web/src/components/__tests__/join-with-code-dialog.test.tsx b/apps/cua-spaces-web/src/components/__tests__/join-with-code-dialog.test.tsxnew file mode 100644index 0000000000..261f7d6667--- /dev/null+++ b/apps/cua-spaces-web/src/components/__tests__/join-with-code-dialog.test.tsx@@ -0,0 +1,103 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { BridgeProvider } from "@/bridge";+import { HostError, type DataAdapter } from "@/bridge/adapter";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import { unavailableCore } from "@/bridge/core";+import { JoinWithCodeDialog } from "@/components/join-with-code-dialog";++afterEach(cleanup);++/** The demo host, recording `host.joinWithCode` and optionally answering it differently. */+function host(override?: (args: Record<string, unknown>) => Promise<unknown>) {+ const base = createDemoAdapter({ latencyMs: 0, stepMs: 0, signedIn: true, onboarded: true });+ const joins: Record<string, unknown>[] = [];+ const adapter = Object.assign(Object.create(base) as DataAdapter, {+ call: ((op: string, args: Record<string, unknown>) => {+ if (op === "host.joinWithCode") {+ joins.push(args);+ if (override) return override(args);+ }+ return (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);+ }) as DataAdapter["call"],+ });+ return { adapter, joins };+}++async function mount(adapter: DataAdapter, props: { initialCode?: string; initialRelay?: string | null } = {}) {+ render(+ <BridgeProvider adapter={adapter} core={unavailableCore("test: no core")}>+ <JoinWithCodeDialog open onOpenChange={() => {}} {...props} />+ </BridgeProvider>,+ );+ await act(() => new Promise((r) => setTimeout(r, 10)));+}++const state = () => document.querySelector("[data-join-with-code]")?.getAttribute("data-join-with-code");+const field = () => screen.getByLabelText("Pairing code") as HTMLInputElement;+const join = () => screen.getByRole("button", { name: "Join" }) as HTMLButtonElement;++describe("Join with a code", () => {+ it("keeps Join off until the text is a code, then joins with the canonical code", async () => {+ const { adapter, joins } = host();+ await mount(adapter);+ expect(join().disabled).toBe(true);+ fireEvent.change(field(), { target: { value: "k7qm-4xpb" } });+ expect(join().disabled).toBe(true);+ fireEvent.change(field(), { target: { value: "k7qm-4xpb-2rhd" } });+ expect(join().disabled).toBe(false);+ fireEvent.click(join());+ await waitFor(() => expect(state()).toBe("joined"));+ expect(joins).toEqual([{ code: "K7QM4XPB2RHD", relay: null }]);+ expect(document.querySelector("[data-join-joined]")?.textContent).toContain("joined");+ });++ it("fills a code that came from a link and waits for Join", async () => {+ const { adapter, joins } = host();+ await mount(adapter, { initialCode: "K7QM4XPB2RHD", initialRelay: "https://relay.example" });+ expect(field().value).toBe("K7QM-4XPB-2RHD");+ expect(document.querySelector("[data-join-relay]")?.textContent).toContain("https://relay.example");+ expect(joins).toEqual([]);+ fireEvent.click(join());+ await waitFor(() => expect(state()).toBe("joined"));+ expect(joins).toEqual([{ code: "K7QM4XPB2RHD", relay: "https://relay.example" }]);+ });++ it("takes the relay from a pasted link", async () => {+ const { adapter, joins } = host();+ await mount(adapter);+ fireEvent.change(field(), { target: { value: "https://cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Frelay.example" } });+ fireEvent.click(join());+ await waitFor(() => expect(state()).toBe("joined"));+ expect(joins).toEqual([{ code: "K7QM4XPB2RHD", relay: "https://relay.example" }]);+ });++ it("shows why a code failed and lets the person try again", async () => {+ let n = 0;+ const { adapter } = host(async () => {+ if (n++ === 0) throw new HostError("this pairing code was already used", "failed");+ return null;+ });+ await mount(adapter, { initialCode: "K7QM4XPB2RHD" });+ fireEvent.click(join());+ await waitFor(() => expect(state()).toBe("failed"));+ expect(document.querySelector("[data-join-error]")?.textContent).toBe("this pairing code was already used");+ expect(field().disabled).toBe(false);+ fireEvent.click(join());+ await waitFor(() => expect(state()).toBe("joined"));+ });++ it("says plainly when the host can't join with a code", async () => {+ const { adapter } = host(async () => {+ throw new HostError("no such method", "unsupported");+ });+ await mount(adapter, { initialCode: "K7QM4XPB2RHD" });+ fireEvent.click(join());+ await waitFor(() => expect(state()).toBe("failed"));+ expect(document.querySelector("[data-join-error]")?.textContent).toContain("Update the app");+ });+});diff --git a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx b/apps/cua-spaces-web/src/components/add-machine-dialog.tsxindex 4f405fecec..1ba0293fcf 100644--- a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx+++ b/apps/cua-spaces-web/src/components/add-machine-dialog.tsx@@ -200,6 +200,13 @@ function PairingPanel({ pairing, machines }: { pairing: PairingHook; machines: M<div className="mb-1 text-xs font-medium text-muted-foreground">Link</div>{code.url ? <CopyField text={code.url} label="Copy link" /> : null}</div>+ {code.code ? (+ <div data-pairing-code>+ <div className="mb-1 text-xs font-medium text-muted-foreground">Code</div>+ <CopyField text={code.code} label="Copy code" mono />+ <p className="mt-1.5 text-xs text-muted-foreground">Already have Cua Spaces there? Open Machines, choose Join with a code and enter it.</p>+ </div>+ ) : null}<div><Segmented aria-label="The other computer's system" value={shell} options={SHELLS} onValueChange={setShell} />{command ? <CopyField text={command} label="Copy command" mono /> : null}diff --git a/apps/cua-spaces-web/src/components/join-with-code-dialog.tsx b/apps/cua-spaces-web/src/components/join-with-code-dialog.tsxnew file mode 100644index 0000000000..cbcef61a64--- /dev/null+++ b/apps/cua-spaces-web/src/components/join-with-code-dialog.tsx@@ -0,0 +1,115 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { CheckIcon, LoaderCircleIcon } from "lucide-react";+import { useEffect, useState, type FormEvent } from "react";++import { displayPairingCode, normalizePairingCode, pairingLinkRelay, useJoinWithCode, useMachines } from "@/bridge";+import { Button } from "@/components/ui/button";+import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";++/**+ * "Join with a code": adds this computer to the account that made a+ * one-time code in "Add a machine" on another device. Meant for a computer+ * that has Cua Spaces but is not signed in to that account (a team machine,+ * or a computer you don't want to sign in on). `initialCode` is a code that+ * arrived by a `cua://add/<code>` link; it fills the field, and nothing+ * joins until the person presses Join.+ */+export function JoinWithCodeDialog({+ open,+ onOpenChange,+ initialCode = "",+ initialRelay = null,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ initialCode?: string;+ initialRelay?: string | null;+}) {+ const { refresh } = useMachines();+ const joining = useJoinWithCode({ onJoined: () => void refresh().catch(() => {}) });+ const [text, setText] = useState(initialCode);+ const { reset } = joining;+ useEffect(() => {+ if (open) {+ setText(initialCode ? displayPairingCode(initialCode) : "");+ reset();+ }+ }, [open, initialCode, reset]);++ const busy = joining.phase === "joining";+ const joined = joining.phase === "joined";+ const ready = normalizePairingCode(text) !== null;+ const relay = initialRelay ?? pairingLinkRelay(text);+ const submit = (e: FormEvent) => {+ e.preventDefault();+ if (!busy && !joined && ready) void joining.join(text, relay);+ };++ return (+ <Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>+ <DialogPopup className="top-[14vh] w-[min(460px,calc(100vw-2rem))]" data-join-with-code={joining.phase}>+ <form onSubmit={submit} className="px-6 pt-5 pb-4">+ <DialogTitle className="text-[15px] font-semibold">Join with a code</DialogTitle>+ <DialogDescription className="mt-1 text-[13px] text-muted-foreground">+ Paste the code from Add a machine on your other device. This computer is added to the account that made it, and that account can then reach it. Only use a code you made yourself or got from someone you trust.+ </DialogDescription>+ {relay ? (+ <p className="mt-2 text-xs text-muted-foreground" data-join-relay>+ This code uses its own relay: <span className="font-medium text-foreground">{relay}</span>+ </p>+ ) : null}+ {joined ? (+ <div className="mt-4 flex items-center gap-2.5 rounded-lg border bg-card px-3 py-3 text-[13px]" data-join-joined>+ <CheckIcon className="size-4 shrink-0 text-success" aria-hidden />+ <span>This computer joined. It shows in your machines.</span>+ </div>+ ) : (+ <>+ <Input+ autoFocus+ aria-label="Pairing code"+ placeholder="XXXX-XXXX-XXXX"+ className="mt-4 font-mono tracking-wider"+ value={text}+ disabled={busy}+ spellCheck={false}+ autoCapitalize="characters"+ autoComplete="off"+ onChange={(e) => setText(e.target.value)}+ />+ {joining.error ? (+ <p role="alert" className="mt-2 text-xs text-destructive" data-join-error>+ {joining.error}+ </p>+ ) : null}+ {busy ? (+ <p className="mt-3 flex items-center gap-2 text-xs text-muted-foreground" data-join-busy>+ <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> Setting this computer up…+ </p>+ ) : null}+ </>+ )}+ <div className="mt-4 flex justify-end gap-2">+ {joined ? (+ <Button type="button" onClick={() => onOpenChange(false)}>+ Done+ </Button>+ ) : (+ <>+ <Button type="button" variant="outline" disabled={busy} onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button type="submit" disabled={busy || !ready}>+ Join+ </Button>+ </>+ )}+ </div>+ </form>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/cua-spaces-web/src/components/onboarding-mode.tsx b/apps/cua-spaces-web/src/components/onboarding-mode.tsxindex 74f1a21916..d04ed8b562 100644--- a/apps/cua-spaces-web/src/components/onboarding-mode.tsx+++ b/apps/cua-spaces-web/src/components/onboarding-mode.tsx@@ -1,7 +1,10 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.+import { useState } from "react";+import { useMachines, useThisMachine, type OnboardingHook, type OnboardingView } from "@/bridge";+import { JoinWithCodeDialog } from "@/components/join-with-code-dialog";import { HostSetupForm } from "@/components/this-machine";import { cn } from "@/lib/utils";@@ -15,6 +18,7 @@ type HostSetup = ReturnType<typeof useThisMachine>;*/export function ModeCard({ flow, view, host }: { flow: OnboardingHook; view: OnboardingView; host: HostSetup }) {const { data: machines } = useMachines();+ const [joining, setJoining] = useState(false);if (host.formView) {const done = (ok: boolean) => {if (ok) flow.send({ type: "mode-chosen", mode: "host" });@@ -59,6 +63,19 @@ export function ModeCard({ flow, view, host }: { flow: OnboardingHook; view: Onb</button>);})}+ {flow.hostConfigured ? null : (+ <>+ <button+ type="button"+ onClick={() => setJoining(true)}+ data-testid="onboarding-join-with-code"+ className="self-start px-1 pt-1 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:text-foreground"+ >+ Have a code from another device? Join with a code+ </button>+ <JoinWithCodeDialog open={joining} onOpenChange={setJoining} />+ </>+ )}</div>);}diff --git a/apps/cua-spaces-web/src/routes/machines/index.tsx b/apps/cua-spaces-web/src/routes/machines/index.tsxindex 8b2172e2a3..4ba7880ef8 100644--- a/apps/cua-spaces-web/src/routes/machines/index.tsx+++ b/apps/cua-spaces-web/src/routes/machines/index.tsx@@ -8,6 +8,7 @@ import { useEffect, useState, type ReactNode } from "react";import { useBridge, useExperiments, useMachines, useSpaces, type Machine, type Space, type SpaceDetailView } from "@/bridge";import { spaceDetail } from "@/bridge/space-detail";import { AddMachineDialog } from "@/components/add-machine-dialog";+import { JoinWithCodeDialog } from "@/components/join-with-code-dialog";import { ThisMachine } from "@/components/this-machine";import { OsIcon } from "@/components/os-icon";import { EmptyState, Page, PageHeader } from "@/components/page";@@ -22,7 +23,13 @@ import { cn, relativeTime } from "@/lib/utils";export const Route = createFileRoute("/machines/")({component: MachinesPage,// `?add=1` opens "Add a machine" (the getting-started checklist links here).- validateSearch: (s: Record<string, unknown>): { add?: true } => (s.add === 1 || s.add === "1" || s.add === true ? { add: true } : {}),+ // `?join=<code>` opens "Join with a code" with the code filled in (a `cua://add/<code>` link+ // opened on this computer); `relay` names a relay other than the production one.+ validateSearch: (s: Record<string, unknown>): { add?: true; join?: string; relay?: string } => ({+ ...(s.add === 1 || s.add === "1" || s.add === true ? { add: true as const } : {}),+ ...(typeof s.join === "string" && s.join ? { join: s.join.slice(0, 200) } : {}),+ ...(typeof s.relay === "string" && s.relay ? { relay: s.relay.slice(0, 300) } : {}),+ }),});function MachinesPage() {@@ -32,7 +39,7 @@ function MachinesPage() {const exp = useExperiments();const experiments = exp.unsupported ? undefined : (exp.data?.experiments ?? {});const [selectedId, setSelectedId] = useState<string | null>(null);- const { add } = Route.useSearch();+ const { add, join, relay } = Route.useSearch();const navigate = Route.useNavigate();const [adding, setAddingState] = useState(add === true);const setAdding = (open: boolean) => {@@ -42,6 +49,14 @@ function MachinesPage() {useEffect(() => {if (add) setAddingState(true);}, [add]);+ const [joining, setJoiningState] = useState(join !== undefined);+ const setJoining = (open: boolean) => {+ setJoiningState(open);+ if (!open && join) void navigate({ search: {}, replace: true });+ };+ useEffect(() => {+ if (join) setJoiningState(true);+ }, [join]);const selected = selectedMachine(machines, selectedId);// Reachable from here: a machine whose owner stopped sharing it is not.const online = machines.filter(reachable).length;@@ -62,9 +77,14 @@ function MachinesPage() {isLoading ? "Loading machines…" : machines.length ? machinesSummary(machines.length, online) : "Computers that can run your Spaces."}actions={- <Button variant="outline" onClick={() => setAdding(true)}>- <PlusIcon /> Add a machine- </Button>+ <div className="flex items-center gap-2">+ <Button variant="ghost" onClick={() => setJoining(true)} data-join-with-code-open>+ Join with a code+ </Button>+ <Button variant="outline" onClick={() => setAdding(true)}>+ <PlusIcon /> Add a machine+ </Button>+ </div>}/>{error ? (@@ -118,6 +138,7 @@ function MachinesPage() {</div>)}<AddMachineDialog open={adding} onOpenChange={setAdding} guide={setupGuide} />+ <JoinWithCodeDialog open={joining} onOpenChange={setJoining} initialCode={join ?? ""} initialRelay={relay ?? null} /></Page>);}diff --git a/docs/content/docs/spaces/guides/teams/machines.mdx b/docs/content/docs/spaces/guides/teams/machines.mdxindex 81f8fed428..6c4c2d4784 100644--- a/docs/content/docs/spaces/guides/teams/machines.mdx+++ b/docs/content/docs/spaces/guides/teams/machines.mdx@@ -35,6 +35,12 @@ Pairing needs Cua Spaces 0.8.0 or later. An owner or admin does this.cua host setup --pair K7QM-4XPB-2RHD```+If the computer already has the Cua Spaces app, you don't need the command.+Opening the link in a browser offers to open the app, and the app shows **Join+with a code** with the code filled in. You can also open **Machines** in the+app, choose **Join with a code**, and paste the code or the link. The app asks+before it joins.+The machine joins the team that made the code, with no sign-in on thatcomputer. A code works once and expires after 30 minutes. Revoke an unused onefrom the same dialog.