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): add a machine by link or QR code in the app (CUA-1358) (#5006)
Francesco Bonaccia10b91323d70
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 44de6a8a86..4803e64ff2 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -86,6 +86,7 @@ generated by `node scripts/licenses/notices.mjs`; do not edit it by hand.- [`tailwind-merge`](https://github.com/dcastil/tailwind-merge) 3.7.0: MIT (cua-spaces-web)- [`tiny-typed-emitter`](https://github.com/binier/tiny-typed-emitter) 2.1.0: MIT (cua-spaces-desktop)- [`universalify`](https://github.com/RyanZim/universalify) 2.0.1: MIT (cua-spaces-desktop)+- [`uqr`](https://github.com/unjs/uqr) 0.1.3: MIT (cua-spaces-web)- [`use-sync-external-store`](https://github.com/react/react) 1.7.0: MIT (cua-spaces-web)- [`zustand`](https://github.com/pmndrs/zustand) 5.0.15: MIT (cua-spaces-web)diff --git a/apps/cua-spaces-desktop/src/bridge/devices.ts b/apps/cua-spaces-desktop/src/bridge/devices.tsindex 278467347c..f4358edc6d 100644--- a/apps/cua-spaces-desktop/src/bridge/devices.ts+++ b/apps/cua-spaces-desktop/src/bridge/devices.ts@@ -2,7 +2,8 @@// Copyright (c) 2026 Cua AI, Inc.// Settings → Devices (`devices.*`): enrolling this machine, approving,-// renaming and revoking devices, confirming machines (the SwiftUI host's+// renaming and revoking devices, confirming machines, and the one-time+// codes that add a machine by link or QR code (the SwiftUI host's// WebUIBridge+Pages `devices`, over `model/devices.ts`). Approving asks the// person at this machine first, as the native sheet does.import { computerName, DevicesUnavailable } from "../model/devices";@@ -70,5 +71,15 @@ export function devicesMethods(ctx: BridgeContext): Handlers {await run(() => devices.confirmMachine(id));return null;},+ "devices.createPairingCode": async (args) => {+ const team = optionalString(args, "team");+ return encode(await run(() => devices.createPairingCode(team)));+ },+ "devices.pairingCodes": async () => encode(await run(() => devices.pairingCodes())),+ "devices.revokePairingCode": async (args) => {+ const id = string(args, "id");+ await run(() => devices.revokePairingCode(id));+ return null;+ },};}diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 6ae66d2541..4c216ef485 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -26,7 +26,8 @@ export const METHODS = ["agents.setupDriver","about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings","devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",- "devices.revoke", "devices.confirmMachine", "storage.get", "storage.run",+ "devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",+ "devices.revokePairingCode", "storage.get", "storage.run","notifications.list", "notifications.markAllRead","telemetry.track", "spaces.usage", "spaces.windows", "stream.pip","spaces.thumbnail",diff --git a/apps/cua-spaces-desktop/src/model/devices.ts b/apps/cua-spaces-desktop/src/model/devices.tsindex add9c3d05f..acce1ec511 100644--- a/apps/cua-spaces-desktop/src/model/devices.ts+++ b/apps/cua-spaces-desktop/src/model/devices.ts@@ -12,7 +12,7 @@import { execFileSync } from "node:child_process";import * as os from "node:os";import type { Native } from "../native/load";-import type { AppApprovalPrompt, AppDevicesInput, AppDevicesView, AppMachineAccessNotice, DevicesLike, DevicesSnapshot, RelayDevice } from "../native/generated/index";+import type { AppApprovalPrompt, AppDevicesInput, AppDevicesView, AppMachineAccessNotice, DevicesLike, DevicesSnapshot, PairingCode, RelayDevice } from "../native/generated/index";import { words } from "./errors";/** What this machine is called on the relay: macOS's computer name ("Dana's MacBook Pro"), else the hostname. */@@ -179,6 +179,21 @@ export class DevicesModel {await this.relay().confirmMachine(id);await this.refresh();}++ /** A one-time link, QR code and install commands that add another computer to the account (or to `team`). */+ createPairingCode(team: string | null): Promise<PairingCode> {+ return this.relay().createPairingCode(team ?? undefined, undefined);+ }++ /** The account's pairing codes, newest first (without the codes). */+ pairingCodes(): Promise<PairingCode[]> {+ return this.relay().pairingCodes();+ }++ /** Revokes an unused pairing code (`pc_…`). */+ revokePairingCode(id: string): Promise<void> {+ return this.relay().revokePairingCode(id);+ }}/** Devices need a signed-in Cua account. */diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.tsindex 3ef9388e47..fe354b25b2 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts@@ -1144,6 +1144,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_devices_create_pairing_code": {+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_devices_device_id": {args: [FfiType.Handle],ret: FfiType.RustBuffer,@@ -1154,6 +1159,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_devices_pairing_codes": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_devices_relay_url": {args: [FfiType.Handle],ret: FfiType.RustBuffer,@@ -1169,6 +1179,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_devices_revoke_pairing_code": {+ args: [FfiType.Handle, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_devices_snapshot": {args: [FfiType.Handle, FfiType.UInt32],ret: FfiType.Handle,@@ -3359,6 +3374,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_devices_create_pairing_code": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_devices_device_id": {args: [],ret: FfiType.UInt16,@@ -3369,6 +3389,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_devices_pairing_codes": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_devices_relay_url": {args: [],ret: FfiType.UInt16,@@ -3384,6 +3409,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_devices_snapshot": {args: [],ret: FfiType.UInt16,@@ -5360,11 +5390,14 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_method_devices_approve(uniffiSelf: bigint, code: Uint8Array, deviceId: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_check_enrolled(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_devices_confirm_machine(uniffiSelf: bigint, machineId: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_devices_create_pairing_code(uniffiSelf: bigint, team: Uint8Array, ttlSecs: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_device_id(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_method_devices_enroll(uniffiSelf: bigint): bigint;+ uniffi_cua_sdk_fn_method_devices_pairing_codes(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_devices_relay_url(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_method_devices_rename(uniffiSelf: bigint, id: Uint8Array, name: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_revoke(uniffiSelf: bigint, id: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(uniffiSelf: bigint, id: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_snapshot(uniffiSelf: bigint, auditLimit: number): bigint;uniffi_cua_sdk_fn_method_fleet_acquire(uniffiSelf: bigint, pool: Uint8Array, name: Uint8Array, ttlSeconds: Uint8Array): bigint;uniffi_cua_sdk_fn_method_fleet_acquire_with(uniffiSelf: bigint, pool: Uint8Array, options: Uint8Array): bigint;@@ -5803,11 +5836,14 @@ interface NativeModuleInterface {uniffi_cua_sdk_checksum_method_devices_approve(): number;uniffi_cua_sdk_checksum_method_devices_check_enrolled(): number;uniffi_cua_sdk_checksum_method_devices_confirm_machine(): number;+ uniffi_cua_sdk_checksum_method_devices_create_pairing_code(): number;uniffi_cua_sdk_checksum_method_devices_device_id(): number;uniffi_cua_sdk_checksum_method_devices_enroll(): number;+ uniffi_cua_sdk_checksum_method_devices_pairing_codes(): number;uniffi_cua_sdk_checksum_method_devices_relay_url(): number;uniffi_cua_sdk_checksum_method_devices_rename(): number;uniffi_cua_sdk_checksum_method_devices_revoke(): number;+ uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code(): number;uniffi_cua_sdk_checksum_method_devices_snapshot(): number;uniffi_cua_sdk_checksum_method_fleet_acquire(): number;uniffi_cua_sdk_checksum_method_fleet_acquire_with(): number;diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.tsindex 1bb0f9b20e..35382c2851 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts@@ -10989,6 +10989,123 @@ const FfiConverterTypeOverlayResult = (() => {return new FFIConverter();})();+/**+ * A one-time code that adds a machine to the account ("Add a machine"+ * by link or QR code).+ */+export type PairingCode = {+ /**+ * `pc_…` (to revoke it).+ */+ id: string,+ /**+ * `XXXX-XXXX-XXXX`: only when just made.+ */+ code?: string,+ /**+ * `https://spaces.cua.ai/add/<code>` (the link and the QR code): only+ * when just made.+ */+ url?: string,+ /**+ * `curl … | sh -s -- --pair <code>` (macOS, Linux): only when just made.+ */+ installSh?: string,+ /**+ * The PowerShell one-liner (Windows): only when just made.+ */+ installPowershell?: string,+ /**+ * `active`, `used`, `revoked` or `expired`.+ */+ state: string,+ /**+ * Team the machine is added for.+ */+ team?: string,+ /**+ * Unix seconds.+ */+ createdAt: bigint,+ /**+ * Unix seconds.+ */+ expiresAt: bigint,+ /**+ * When a machine used it.+ */+ usedAt?: bigint,+ /**+ * The machine it added (relay machine id).+ */+ machine?: string+}++/**+ * Generated factory for {@link PairingCode} record objects.+ */+export const PairingCode = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<PairingCode, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<PairingCode>,+ });+})();++const FfiConverterTypePairingCode = (() => {+ type TypeName = PairingCode;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ id: FfiConverterString.read(from),+ code: FfiConverterOptionalString.read(from),+ url: FfiConverterOptionalString.read(from),+ installSh: FfiConverterOptionalString.read(from),+ installPowershell: FfiConverterOptionalString.read(from),+ state: FfiConverterString.read(from),+ team: FfiConverterOptionalString.read(from),+ createdAt: FfiConverterUInt64.read(from),+ expiresAt: FfiConverterUInt64.read(from),+ usedAt: FfiConverterOptionalUInt64.read(from),+ machine: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.id, into);+ FfiConverterOptionalString.write(value.code, into);+ FfiConverterOptionalString.write(value.url, into);+ FfiConverterOptionalString.write(value.installSh, into);+ FfiConverterOptionalString.write(value.installPowershell, into);+ FfiConverterString.write(value.state, into);+ FfiConverterOptionalString.write(value.team, into);+ FfiConverterUInt64.write(value.createdAt, into);+ FfiConverterUInt64.write(value.expiresAt, into);+ FfiConverterOptionalUInt64.write(value.usedAt, into);+ FfiConverterOptionalString.write(value.machine, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.id) ++ FfiConverterOptionalString.allocationSize(value.code) ++ FfiConverterOptionalString.allocationSize(value.url) ++ FfiConverterOptionalString.allocationSize(value.installSh) ++ FfiConverterOptionalString.allocationSize(value.installPowershell) ++ FfiConverterString.allocationSize(value.state) ++ FfiConverterOptionalString.allocationSize(value.team) ++ FfiConverterUInt64.allocationSize(value.createdAt) ++ FfiConverterUInt64.allocationSize(value.expiresAt) ++ FfiConverterOptionalUInt64.allocationSize(value.usedAt) ++ FfiConverterOptionalString.allocationSize(value.machine);++ }+ };+ return new FFIConverter();+})();+/*** A persistent agent: a named harness whose memory (its home in the Cua* Drive) outlives its runs and its Space.@@ -20878,6 +20995,12 @@ export interface DevicesLike {* member, not just this device.*/confirmMachine(machineId: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RelayMachine>;+/**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+ createPairingCode(team: string | undefined, ttlSecs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<PairingCode>;/*** This device's id, when it has a key (no network).*/@@ -20889,6 +21012,10 @@ export interface DevicesLike {* code to approve from an enrolled device.*/enroll(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DeviceEnrollment>;+/**+ * The account's pairing codes, newest first (without the codes).+ */+ pairingCodes(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<PairingCode>>;/*** The relay base URL.*/@@ -20902,6 +21029,10 @@ export interface DevicesLike {* also deletes its key.*/revoke(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RelayDevice>;+/**+ * Revokes an unused pairing code (`pc_…`).+ */+ revokePairingCode(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -21046,6 +21177,43 @@ private constructor(pointer: UniffiHandle) {}}+/**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+ async createPairingCode(team: string | undefined, ttlSecs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<PairingCode> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_devices_create_pairing_code(+ uniffiTypeDevicesObjectFactory.clonePointer(this),FfiConverterOptionalString.lower(team, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(ttlSecs, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypePairingCode.lift.bind(FfiConverterTypePairingCode),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** This device's id, when it has a key (no network).*/@@ -21105,6 +21273,41 @@ private constructor(pointer: UniffiHandle) {}}+/**+ * The account's pairing codes, newest first (without the codes).+ */+ async pairingCodes(asyncOpts_?: { signal: AbortSignal }): Promise<Array<PairingCode>> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_devices_pairing_codes(+ uniffiTypeDevicesObjectFactory.clonePointer(this)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterSequenceTypePairingCode.lift.bind(FfiConverterSequenceTypePairingCode),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** The relay base URL.*/@@ -21196,6 +21399,36 @@ private constructor(pointer: UniffiHandle) {}}+/**+ * Revokes an unused pairing code (`pc_…`).+ */+ async revokePairingCode(id: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(+ uniffiTypeDevicesObjectFactory.clonePointer(this),FfiConverterString.lower(id, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,+ /*liftFunc:*/ (_v) => {},+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -36610,6 +36843,9 @@ const FfiConverterSequenceTypeAgentRunInfo = new FfiConverterArray(FfiConverterT// FfiConverter for AgentRunOptions | undefinedconst FfiConverterOptionalTypeAgentRunOptions = new FfiConverterOptional(FfiConverterTypeAgentRunOptions);+// FfiConverter for Array<PairingCode>+const FfiConverterSequenceTypePairingCode = new FfiConverterArray(FfiConverterTypePairingCode);+// FfiConverter for Array<FleetClaim>const FfiConverterSequenceTypeFleetClaim = new FfiConverterArray(FfiConverterTypeFleetClaim);@@ -37091,12 +37327,18 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_devices_confirm_machine() !== 44995) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_confirm_machine");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_create_pairing_code() !== 19274) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_create_pairing_code");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_devices_device_id() !== 58064) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_device_id");}if (nativeModule().uniffi_cua_sdk_checksum_method_devices_enroll() !== 25682) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_enroll");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_pairing_codes() !== 10069) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_pairing_codes");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_devices_relay_url() !== 39774) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_relay_url");}@@ -37106,6 +37348,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_devices_revoke() !== 27802) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_revoke");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() !== 3143) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_devices_snapshot() !== 26132) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_snapshot");}@@ -38235,6 +38480,7 @@ export default Object.freeze({FfiConverterTypeNotificationInfo,FfiConverterTypeOverlay,FfiConverterTypeOverlayResult,+ FfiConverterTypePairingCode,FfiConverterTypePersistentAgentInfo,FfiConverterTypePersistentAgentOptions,FfiConverterTypePoint,diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.tsindex 4da692007f..8df5186030 100644--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts@@ -185,6 +185,9 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()["devices.rename", { id: "dev_old", name: "Old box" }],["devices.revoke", { id: "dev_old" }],["devices.confirmMachine", { id: "m2" }],+ ["devices.createPairingCode", { team: null }],+ ["devices.pairingCodes", {}],+ ["devices.revokePairingCode", { id: "pc_fixture1" }],["storage.get", {}],["storage.run", { request: { kind: "clear-cache" } }],["notifications.list", {}],@@ -220,6 +223,8 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()"devices.rename": { id: "dev_old", name: "Old box" },"devices.revoke": { id: "dev_old" },"devices.confirmMachine": { id: "m2" },+ "devices.createPairingCode": { team: null },+ "devices.revokePairingCode": { id: "pc_fixture1" },"storage.run": { request: { kind: "clear-cache" } } as never,"host.setUp": { request: { mode: "direct", direct: "0.0.0.0:3211" } } as never,"host.action": { action: "provide-spaces" } as never,@@ -442,6 +447,16 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()expect(relay.calls.slice(-2)).toEqual(["revoke:dev_old", "confirm-machine:m2"]);});+ it("makes, lists and revokes the codes that add a machine", async () => {+ const made = (await call("devices.createPairingCode", { team: null })) as Record<string, unknown>;+ expect(made).toMatchObject({ id: "pc_fixture1", state: "active", team: null, url: expect.stringContaining("/add/"), installSh: expect.stringContaining("--pair") });+ expect(typeof made.expiresAt).toBe("number");+ const listed = (await call("devices.pairingCodes", {})) as Record<string, unknown>[];+ expect(listed).toEqual([expect.objectContaining({ id: "pc_fixture1", code: null, url: null })]);+ expect(await call("devices.revokePairingCode", { id: "pc_fixture1" })).toBeNull();+ expect(relay.calls.slice(-3)).toEqual(["create-pairing-code:", "pairing-codes", "revoke-pairing-code:pc_fixture1"]);+ });+it("announces a device asking to join once per launch", async () => {const started = startHost(bridge.context, { onboarded: () => true });await model.devices.refresh();diff --git a/apps/cua-spaces-desktop/test/host-fixtures.ts b/apps/cua-spaces-desktop/test/host-fixtures.tsindex df3126f28b..cc50382df3 100644--- a/apps/cua-spaces-desktop/test/host-fixtures.ts+++ b/apps/cua-spaces-desktop/test/host-fixtures.ts@@ -5,7 +5,7 @@// SwiftUI app's FixtureHost, ScriptedHost, FakeAccountTokens,// FixtureDevices, FixturePresence and FixtureLoginItem). In memory: no// service, launchd, network, notification, login item or keychain.-import type { DeviceEnrollment, DevicesLike, DevicesSnapshot, HostLike, HostSettingsChange, HostSetupOptions, HostStatus, RelayDevice } from "../src/native/generated/index";+import type { DeviceEnrollment, DevicesLike, DevicesSnapshot, HostLike, HostSettingsChange, HostSetupOptions, HostStatus, PairingCode, RelayDevice } from "../src/native/generated/index";import type { SystemNote, SystemServices } from "../src/bridge/system";import type { HostModel } from "../src/model/host";import { FixtureLoginItem } from "../src/model/login-item";@@ -233,6 +233,41 @@ export class FixtureDevices {this.current = { ...this.current, machines: this.current.machines.map((m) => (m.id === id ? { ...m, confirmed: true } : m)) };return this.current.machines.find((m) => m.id === id)!;}++ /** The account's pairing codes as the relay keeps them (with the codes). */+ pairing: PairingCode[] = [];++ async createPairingCode(team: string | undefined): Promise<PairingCode> {+ this.calls.push(`create-pairing-code:${team ?? ""}`);+ const now = BigInt(Math.floor(Date.now() / 1000));+ const n = this.pairing.length + 1;+ const code = `K7QM-4XPB-${String(n).padStart(4, "0")}`;+ const made: PairingCode = {+ id: `pc_fixture${n}`,+ code,+ url: `https://spaces.cua.ai/add/${code}`,+ installSh: `curl -fsSL https://cua.ai/install.sh | sh -s -- --pair ${code}`,+ installPowershell: `& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair ${code}`,+ state: "active",+ team,+ createdAt: now,+ expiresAt: now + 1800n,+ usedAt: undefined,+ machine: undefined,+ };+ this.pairing = [made, ...this.pairing];+ return made;+ }++ async pairingCodes(): Promise<PairingCode[]> {+ this.calls.push("pairing-codes");+ return this.pairing.map((p) => ({ ...p, code: undefined, url: undefined, installSh: undefined, installPowershell: undefined }));+ }++ async revokePairingCode(id: string): Promise<void> {+ this.calls.push(`revoke-pairing-code:${id}`);+ this.pairing = this.pairing.map((p) => (p.id === id ? { ...p, state: "revoked" } : p));+ }}/** The system in memory: what was opened, shown, posted and asked. */@@ -266,6 +301,7 @@ export const HOST_METHODS = ["volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal","about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings","devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine",+ "devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode","storage.get", "storage.run", "notifications.list", "notifications.markAllRead","host.setUp", "host.action", "host.openSettings", "settings.get", "settings.choose","onboarding.get", "onboarding.complete",@@ -277,6 +313,7 @@ export const HOST_OPS = ["volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal","about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings","devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine",+ "devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode","storage.get", "storage.run", "notifications.list", "notifications.markAllRead","host.setUp", "host.action", "host.openSettings", "settings.get", "settings.set", "settings.choose", "experiments.set", "session.completeOnboarding",];diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swiftindex df42f4d2a6..0497cf742c 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift@@ -735,6 +735,11 @@ public final class PendingDevices: DevicesRunning, @unchecked Sendable {public func rename(id: String, name: String) async throws { try await d().rename(id: id, name: name) }public func revoke(id: String) async throws { try await d().revoke(id: id) }public func confirmMachine(id: String) async throws { try await d().confirmMachine(id: id) }+ public func createPairingCode(team: String?) async throws -> PairingCode {+ try await d().createPairingCode(team: team)+ }+ public func pairingCodes() async throws -> [PairingCode] { try await d().pairingCodes() }+ public func revokePairingCode(id: String) async throws { try await d().revokePairingCode(id: id) }}/// This machine's host service until the SDK is in.diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swiftindex 06190e73f6..e619a9c69b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift@@ -21,6 +21,13 @@ public protocol DevicesRunning: AnyObject, Sendable {/// Vouches for a machine that registered without an enrolled device's/// proof (S5), from this enrolled device.func confirmMachine(id: String) async throws+ /// A one-time link, QR code and install commands that add another+ /// computer to the account (or to `team`), from this enrolled device.+ func createPairingCode(team: String?) async throws -> PairingCode+ /// The account's pairing codes, newest first (without the codes).+ func pairingCodes() async throws -> [PairingCode]+ /// Revokes an unused pairing code (`pc_…`).+ func revokePairingCode(id: String) async throws}/// The SDK's `Devices` for the signed-in session (key in the session's vault,@@ -56,6 +63,11 @@ public final class LiveDevices: DevicesRunning, @unchecked Sendable {public func rename(id: String, name: String) async throws { _ = try await inner.rename(id: id, name: name) }public func revoke(id: String) async throws { _ = try await inner.revoke(id: id) }public func confirmMachine(id: String) async throws { _ = try await inner.confirmMachine(machineId: id) }+ public func createPairingCode(team: String?) async throws -> PairingCode {+ try await inner.createPairingCode(team: team, ttlSecs: nil)+ }+ public func pairingCodes() async throws -> [PairingCode] { try await inner.pairingCodes() }+ public func revokePairingCode(id: String) async throws { try await inner.revokePairingCode(id: id) }}/// An in-memory account on a relay (fixtures, tests): this Mac enrolled,@@ -156,6 +168,39 @@ public final class FixtureDevices: DevicesRunning, @unchecked Sendable {calls.append("confirm-machine:\(id)")for i in current.machines.indices where current.machines[i].id == id { current.machines[i].confirmed = true }}++ /// The account's pairing codes as the relay keeps them (with the codes).+ public var pairing: [PairingCode] = []++ public func createPairingCode(team: String?) async throws -> PairingCode {+ calls.append("create-pairing-code:\(team ?? "")")+ let now = UInt64(Date().timeIntervalSince1970)+ let code = "K7QM-4XPB-\(String(format: "%04d", pairing.count + 1))"+ let made = PairingCode(+ id: "pc_fixture\(pairing.count + 1)", code: code, url: "https://spaces.cua.ai/add/\(code)",+ installSh: "curl -fsSL https://cua.ai/install.sh | sh -s -- --pair \(code)",+ installPowershell: "& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair \(code)",+ state: "active", team: team, createdAt: now, expiresAt: now + 1800, usedAt: nil, machine: nil)+ pairing.insert(made, at: 0)+ return made+ }++ public func pairingCodes() async throws -> [PairingCode] {+ calls.append("pairing-codes")+ return pairing.map {+ var listed = $0+ listed.code = nil+ listed.url = nil+ listed.installSh = nil+ listed.installPowershell = nil+ return listed+ }+ }++ public func revokePairingCode(id: String) async throws {+ calls.append("revoke-pairing-code:\(id)")+ for i in pairing.indices where pairing[i].id == id { pairing[i].state = "revoked" }+ }}/// Presence before approving a device: Touch ID, an Apple Watch or thediff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 1b592e85a6..6d53bf81c2 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -104,7 +104,8 @@ extension WebUIBridge {// Settings, Devicescase "devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",- "devices.revoke", "devices.confirmMachine":+ "devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",+ "devices.revokePairingCode":return try await devices(method, args)// Settings, Storage@@ -326,6 +327,15 @@ extension WebUIBridge {try await relay.revoke(id: try string(args, "id"))case "devices.confirmMachine":try await relay.confirmMachine(id: try string(args, "id"))+ // "Add a machine" by link or QR code: the relay keeps the code.+ case "devices.createPairingCode":+ let team = (args["team"] as? String).flatMap { $0.isEmpty ? nil : $0 }+ return BridgeValue.encode(try await relay.createPairingCode(team: team))+ case "devices.pairingCodes":+ return BridgeValue.encode(try await relay.pairingCodes())+ case "devices.revokePairingCode":+ try await relay.revokePairingCode(id: try string(args, "id"))+ return NSNull()default:throw Failure.unimplemented(method)}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 1b77ae4e33..452447bc80 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -81,7 +81,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"agents.setupDriver","about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings","devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",- "devices.revoke", "devices.confirmMachine", "storage.get", "storage.run",+ "devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",+ "devices.revokePairingCode", "storage.get", "storage.run","notifications.list", "notifications.markAllRead","telemetry.track", "spaces.usage", "spaces.windows", "stream.pip",// A Space's thumbnail (WebUIBridge+Thumbnails.swift).diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex 787f3c590c..df6032f656 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -215,6 +215,8 @@ struct BridgeContractTests {("about.get", [:]), ("about.set", ["channel": "beta"]), ("about.checkNow", [:]),("loginItem.get", [:]), ("loginItem.set", ["on": true]),("devices.get", [:]), ("devices.enroll", [:]), ("devices.checkEnrolled", [:]),+ ("devices.createPairingCode", ["team": NSNull()]), ("devices.pairingCodes", [:]),+ ("devices.revokePairingCode", ["id": "pc_fixture1"]),("storage.get", [:]), ("storage.run", ["request": ["kind": "clear-cache"]]),("notifications.list", [:]), ("notifications.markAllRead", [:]),("telemetry.track", ["signals": [["type": "step", "step": "app_launched", "ok": true]]]),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swiftindex c6e1f92679..c75a83e98a 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift@@ -228,4 +228,7 @@ final class RelayAnswering: DevicesRunning, @unchecked Sendable {func rename(id: String, name: String) async throws { try await fixture.rename(id: id, name: name) }func revoke(id: String) async throws { try await fixture.revoke(id: id) }func confirmMachine(id: String) async throws { try await fixture.confirmMachine(id: id) }+ func createPairingCode(team: String?) async throws -> PairingCode { try await fixture.createPairingCode(team: team) }+ func pairingCodes() async throws -> [PairingCode] { try await fixture.pairingCodes() }+ func revokePairingCode(id: String) async throws { try await fixture.revokePairingCode(id: id) }}diff --git a/apps/cua-spaces-web/package.json b/apps/cua-spaces-web/package.jsonindex 46f64cadb9..712b3b8863 100644--- a/apps/cua-spaces-web/package.json+++ b/apps/cua-spaces-web/package.json@@ -30,6 +30,7 @@"react": "^19.3.0","react-dom": "^19.3.0","tailwind-merge": "^3.7.0",+ "uqr": "^0.1.3","zustand": "^5.0.15"},"devDependencies": {diff --git a/apps/cua-spaces-web/pnpm-lock.yaml b/apps/cua-spaces-web/pnpm-lock.yamlindex a69b01795b..0b5f552e06 100644--- a/apps/cua-spaces-web/pnpm-lock.yaml+++ b/apps/cua-spaces-web/pnpm-lock.yaml@@ -35,6 +35,9 @@ importers:tailwind-merge:specifier: ^3.7.0version: 3.7.0+ uqr:+ specifier: ^0.1.3+ version: 0.1.3zustand:specifier: ^5.0.15@@ -1315,6 +1318,9 @@ packages:peerDependencies:browserslist: '>= 4.21.0'+ resolution: {integrity: sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==}+resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==}peerDependencies:@@ -2455,6 +2461,8 @@ snapshots:escalade: 3.2.0picocolors: 1.1.1+ [email protected]: {}+dependencies:react: 19.3.0diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.mdindex da45e269ea..bc2a3d6778 100644--- a/apps/cua-spaces-web/src/bridge/README.md+++ b/apps/cua-spaces-web/src/bridge/README.md@@ -32,6 +32,7 @@ import { BridgeProvider, useSpaces } from "@/bridge";| `useBridge()` | `{ mode: "tauri" \| "electron" \| "webkit" \| "demo", core, data }`. `core.status` is `loading`, `ready` or `unavailable`; `data` is the `DataAdapter`. || `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). || `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. || `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)`. |@@ -404,6 +405,9 @@ mechanism. Types are in `contracts/settings.ts`, `contracts/devices.ts` and| `devices.enroll` / `.checkEnrolled` | `{}` | `{ enrolled, code }` / `boolean` | `devices_enroll` / `devices_check_enrolled` | `devices.enroll()` / `checkEnrolled()` || `devices.approve` | `{ code, deviceId }` | `null` | `devices_approve` (presence in the shell) | `presence.confirm` then `devices.approve` || `devices.rename` / `.revoke` / `.confirmMachine` | `{ id, name? }` | `null` | `devices_rename` / `devices_revoke` / `devices_confirm_machine` | same calls on `DevicesRunning` |+| `devices.createPairingCode` | `{ team? }` | `PairingCode` (camelCase: `id`, `code`, `url`, `installSh`, `installPowershell`, `state`, `team`, `createdAt`, `expiresAt`, `usedAt`, `machine`) | `devices_create_pairing_code` | `DevicesRunning.createPairingCode` (the SDK's `Devices.createPairingCode`) |+| `devices.pairingCodes` | `{}` | `PairingCode[]`, newest first, without `code`, `url` and the commands | `devices_pairing_codes` | `DevicesRunning.pairingCodes` |+| `devices.revokePairingCode` | `{ id }` | `null` | `devices_revoke_pairing_code` | `DevicesRunning.revokePairingCode` || `storage.get` | `{}` | `StorageInput` (`volume_storage`, `volume_mount_status`, `volume_cache_stats` as the tools answer) | `agents_tool` | `StorageModel.load` inputs || `storage.run` | `{ request: StorageRequest }` | `DriveCheckInput` for test, save and adopt; else `null` | `agents_tool` (`volume_*`), `drive_reveal`, `host_open_settings` | `StorageModel`'s request runner || `notifications.list` | `{}` | `NotificationInput[]` (camelCase) | `agents_tool` `notifications_list` | `PersistentModel.feed` |diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex c429a05b2a..51c4877153 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -102,6 +102,9 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"devices.rename": { id: "dev_studio", name: "Studio" },"devices.revoke": { id: "dev_old" },"devices.confirmMachine": { id: "m1" },+ "devices.createPairingCode": { team: null },+ "devices.pairingCodes": {},+ "devices.revokePairingCode": { id: "pc_demo0" },"storage.get": {},"storage.run": { request: { kind: "clear-cache" } },"notifications.list": {},diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 45c1cea425..704ad1abb6 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -95,6 +95,9 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"devices.rename": { id: "dev_p", name: "Work laptop" },"devices.revoke": { id: "dev_p" },"devices.confirmMachine": { id: "m1" },+ "devices.createPairingCode": { team: null },+ "devices.pairingCodes": {},+ "devices.revokePairingCode": { id: "pc_demo0" },"storage.get": {},"storage.run": { request: { kind: "clear-cache" } },"notifications.list": {},diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 8254e79b16..866d157068 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -9,7 +9,7 @@import { Emitter, HostError, UnsupportedOperationError, type DataAdapter } from "../adapter";import type { AgentSetupRow, PersistentAgent } from "../contracts/agents";-import type { OnboardingState } from "../contracts/host";+import type { MachineRow, OnboardingState } from "../contracts/host";import type { KvItem } from "../contracts/keyvault";import type { SpaceOs, SpaceRow } from "../contracts/spaces";import {@@ -113,6 +113,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reruns: demoRunRecords(now()),agentSetup: demoAgentSetup(),platform: options.platform ?? MAC_DEMO_PLATFORM,+ paired: [],volume: demoVolumeState(now(), options.onboarded !== false, options.platform),...demoTelemetryState(),...demoRelayUsageState(),@@ -271,7 +272,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { rereturn null;},- "machines.list": () => demoMachineRows(now(), state.host, state.platform),+ "machines.list": () => [...demoMachineRows(now(), state.host, state.platform), ...state.paired.map((m) => ({ ...m, limits: [...m.limits] }))],"host.status": () => ({ ...state.host }),"settings.get": () => settingsSnapshot(),@@ -433,7 +434,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...demoShareHandlers({ wait, stepMs: step }),...demoAgentKeysHandlers({ wait, stepMs: step, now }),...demoVolumeHandlers({ state: state.volume, now, wait, step, emit, platform: state.platform }),- ...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })) }),+ ...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })), addMachine: (m) => ((state.paired = [...state.paired, m]), emit({ type: "machines.changed" })) }),...demoTelemetryHandlers(ctx),...demoRelayUsageHandlers(ctx),...demoSpaceDetailHandlers(ctx),@@ -478,4 +479,6 @@ export interface DemoState extends DemoTelemetryState, DemoRelayUsageState, DemoagentSetup: AgentSetupRow[];volume: DemoVolumeState;platform: DemoPlatform;+ /** Machines added with a pairing code ("Add a machine"). */+ paired: MachineRow[];}diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.tsindex 4cf2d100bc..ec889211cf 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts@@ -8,7 +8,8 @@*/import { HostError } from "../../adapter";-import type { DevicesInput } from "../../contracts/devices";+import type { DevicesInput, PairingCode } from "../../contracts/devices";+import type { MachineRow } from "../../contracts/host";import type { NotificationInput } from "../../contracts/notifications";import type { AboutInput, DriveCheckInput, Experiments, LoginItemReport, StorageInput } from "../../contracts/settings";import { NO_EXPERIMENTS } from "../../contracts/volume";@@ -31,8 +32,25 @@ export interface DemoSettingsContext {experiments?: Experiments;/** The machine the demo runs on (a Mac unless the shell says). */platform?: DemoPlatform;+ /** A machine joined with a pairing code: the host lists it from now on. */+ addMachine?: (machine: MachineRow) => void;}+/** How many times "Add a machine" reads the codes before the demo's other+ * computer runs the command (about ten seconds at its three-second poll). */+export const DEMO_PAIRING_POLLS = 3;++/** The computer the demo adds with a pairing code. */+export const DEMO_PAIRED_MACHINE: MachineRow = {+ id: "m_pair_demo",+ name: "Office PC",+ via: "relay",+ online: true,+ os: "linux",+ model: "Ubuntu 24.04",+ limits: [],+};+type Ops = SettingsOperations & NotificationsOperations;type Handlers = { [K in keyof Ops]: (args: Ops[K]["args"]) => Promise<Ops[K]["result"]> | Ops[K]["result"] };@@ -103,6 +121,17 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {let autoInstall = false;let experiments: Experiments = { ...NO_EXPERIMENTS, ...ctx.experiments };let devices = demoDevices(now());+ // One code made earlier (`cua host pair`) that nobody used yet; only the+ // codes made here join a computer.+ const t0 = Math.floor(now() / 1000);+ let pairing: { code: PairingCode; polls: number; joins: boolean }[] = [+ {+ code: { id: "pc_demo0", code: null, url: null, installSh: null, installPowershell: null, state: "active", team: null, createdAt: t0 - 600, expiresAt: t0 + 1200, usedAt: null, machine: null },+ polls: 0,+ joins: false,+ },+ ];+ let pairingSeq = 0;let feed = demoNotifications(feedEpoch(now()));const platform = ctx.platform ?? MAC_DEMO_PLATFORM;const machine = demoMachine(platform);@@ -211,6 +240,52 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {return null;},+ // Works like the relay: one code per machine, 30 minutes, shown once.+ // The demo's other computer runs the command after a few reads.+ "devices.createPairingCode": async ({ team }) => {+ if (!ctx.signedIn()) throw new HostError("Sign in to Cua to add a machine", "signed_out");+ await wait(stepMs / 2);+ const t = Math.floor(now() / 1000);+ pairingSeq += 1;+ const code = `K7QM-4XPB-${["2RHD", "9TCW", "5JNF", "8LGV"][(pairingSeq - 1) % 4]}`;+ const made: PairingCode = {+ id: `pc_demo${pairingSeq}`,+ code,+ url: `https://spaces.cua.ai/add/${code}`,+ installSh: `curl -fsSL https://cua.ai/install.sh | sh -s -- --pair ${code}`,+ installPowershell: `& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair ${code}`,+ state: "active",+ team: team ?? null,+ createdAt: t,+ expiresAt: t + 30 * 60,+ usedAt: null,+ machine: null,+ };+ pairing = [{ code: made, polls: 0, joins: true }, ...pairing];+ return structuredClone(made);+ },+ "devices.pairingCodes": () => {+ const t = Math.floor(now() / 1000);+ pairing = pairing.map((p) => {+ const c = p.code;+ if (c.state === "active" && t >= c.expiresAt) return { ...p, code: { ...c, state: "expired" } };+ if (c.state !== "active" || !p.joins) return p;+ const polls = p.polls + 1;+ if (polls < DEMO_PAIRING_POLLS) return { ...p, polls };+ ctx.addMachine?.({ ...DEMO_PAIRED_MACHINE, lastSeen: t });+ return { ...p, polls, code: { ...c, state: "used", usedAt: t, machine: DEMO_PAIRED_MACHINE.id } };+ });+ // Listed without the codes, as the relay lists them.+ return pairing.map(({ code: c }) => ({ ...c, code: null, url: null, installSh: null, installPowershell: null }));+ },+ "devices.revokePairingCode": ({ id }) => {+ const p = pairing.find((x) => x.code.id === id);+ if (!p) throw new HostError(`no pairing code ${id}`, "not_found");+ if (p.code.state !== "active") throw new HostError(`This code was already ${p.code.state}.`, "conflict");+ pairing = pairing.map((x) => (x === p ? { ...x, code: { ...x.code, state: "revoked" } } : x));+ return null;+ },+"storage.get": () => structuredClone(storage),"storage.run": async ({ request }) => {await wait(stepMs);diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex 3695ceaa6d..92ffe9a1e5 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -1515,6 +1515,83 @@"body"]},+ "PairingCode": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "code": {+ "type": [+ "string",+ "null"+ ]+ },+ "url": {+ "type": [+ "string",+ "null"+ ]+ },+ "installSh": {+ "type": [+ "string",+ "null"+ ]+ },+ "installPowershell": {+ "type": [+ "string",+ "null"+ ]+ },+ "state": {+ "enum": [+ "active",+ "used",+ "revoked",+ "expired"+ ]+ },+ "team": {+ "type": [+ "string",+ "null"+ ]+ },+ "createdAt": {+ "type": "number"+ },+ "expiresAt": {+ "type": "number"+ },+ "usedAt": {+ "type": [+ "number",+ "null"+ ]+ },+ "machine": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "id",+ "code",+ "url",+ "installSh",+ "installPowershell",+ "state",+ "team",+ "createdAt",+ "expiresAt",+ "usedAt",+ "machine"+ ]+ },"RemoteWindow": {"type": "object","properties": {@@ -3736,6 +3813,9 @@"devices.confirmMachine": {"type": "null"},+ "devices.createPairingCode": {+ "$ref": "#/$defs/PairingCode"+ },"devices.enroll": {"type": "object","properties": {@@ -3757,12 +3837,21 @@"devices.get": {"$ref": "#/$defs/DevicesInput"},+ "devices.pairingCodes": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/PairingCode"+ }+ },"devices.rename": {"type": "null"},"devices.revoke": {"type": "null"},+ "devices.revokePairingCode": {+ "type": "null"+ },"experiments.get": {"$ref": "#/$defs/Experiments"},@@ -5086,6 +5175,9 @@"devices.confirmMachine": {"type": "null"},+ "devices.createPairingCode": {+ "$ref": "#/$defs/PairingCode"+ },"devices.enroll": {"type": "object","properties": {@@ -5107,12 +5199,21 @@"devices.get": {"$ref": "#/$defs/DevicesInput"},+ "devices.pairingCodes": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/PairingCode"+ }+ },"devices.rename": {"type": "null"},"devices.revoke": {"type": "null"},+ "devices.revokePairingCode": {+ "type": "null"+ },"host.action": {"anyOf": [{diff --git a/apps/cua-spaces-web/src/bridge/contracts/devices.ts b/apps/cua-spaces-web/src/bridge/contracts/devices.tsindex fa6a40e68e..5c3f21c87a 100644--- a/apps/cua-spaces-web/src/bridge/contracts/devices.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/devices.ts@@ -55,6 +55,35 @@ export interface DevicesInput {deviceName?: string | null;}+/** A one-time code that adds another computer to the account ("Add a+ * machine" by link or QR code; the cua SDK's `PairingCode`, camelCase).+ * `code`, `url` and the install commands are only there when just made. */+export interface PairingCode {+ /** `pc_…` (to revoke it). */+ id: string;+ /** `XXXX-XXXX-XXXX`. */+ code: string | null;+ /** `https://spaces.cua.ai/add/<code>`: the link and the QR code. */+ url: string | null;+ /** The macOS and Linux one-liner. */+ installSh: string | null;+ /** The Windows (PowerShell) one-liner. */+ installPowershell: string | null;+ state: PairingCodeState;+ /** Team the machine is added for; null for the personal account. */+ team: string | null;+ /** Unix seconds. */+ createdAt: number;+ /** Unix seconds. */+ expiresAt: number;+ /** Unix seconds, once a machine used it. */+ usedAt: number | null;+ /** The relay machine id it added. */+ machine: string | null;+}++export type PairingCodeState = "active" | "used" | "revoked" | "expired";+export type BannerTone = "info" | "warning" | "critical";export type DeviceAction = "enroll" | "approve" | "rename" | "revoke";export type EnrollmentKind = "enrolled" | "grace" | "needs-enrollment" | "waiting" | "due" | "revoked";diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 6b5f2d4fa0..5647e1cf0a 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -23,7 +23,7 @@*/import type { AgentEventsPage, AgentSetupRow, PersistentAgent, SpaceAgentRun } from "./agents";-import type { DeviceInput, DevicesInput, EnrollResult, MachineAccessNotice } from "./devices";+import type { DeviceInput, DevicesInput, EnrollResult, MachineAccessNotice, PairingCode } from "./devices";import type {CancelOutcome,DaemonStatus,@@ -275,6 +275,23 @@ const DevicesShape = ref(}),);+const PairingCodeShape = ref(+ "PairingCode",+ obj<PairingCode>()({+ id: str,+ code: nullable(str),+ url: nullable(str),+ installSh: nullable(str),+ installPowershell: nullable(str),+ state: oneOf("active", "used", "revoked", "expired"),+ team: nullable(str),+ createdAt: num,+ expiresAt: num,+ usedAt: nullable(num),+ machine: nullable(str),+ }),+);+const DriveMountShape = ref("DriveMountInput",obj<DriveMountInput>()({@@ -719,6 +736,9 @@ export const OP_SHAPES: Record<OpName, Schema> = {"devices.rename": nul,"devices.revoke": nul,"devices.confirmMachine": nul,+ "devices.createPairingCode": PairingCodeShape,+ "devices.pairingCodes": list(PairingCodeShape),+ "devices.revokePairingCode": nul,"storage.get": StorageShape,"storage.run": nullable(DriveCheckShape),"notifications.list": list(NotificationShape),@@ -1011,6 +1031,9 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"devices.rename": nul,"devices.revoke": nul,"devices.confirmMachine": nul,+ "devices.createPairingCode": PairingCodeShape,+ "devices.pairingCodes": list(PairingCodeShape),+ "devices.revokePairingCode": nul,"storage.get": StorageShape,"storage.run": nullable(DriveCheckShape),"notifications.list": list(NotificationShape),diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 2ad76ce533..74a2554e29 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -143,6 +143,9 @@ export const HOST_COVERAGE = {"devices.rename": { webkit: { methods: ["devices.rename"] }, tauri: ST["devices.rename"] },"devices.revoke": { webkit: { methods: ["devices.revoke"] }, tauri: ST["devices.revoke"] },"devices.confirmMachine": { webkit: { methods: ["devices.confirmMachine"] }, tauri: ST["devices.confirmMachine"] },+ "devices.createPairingCode": { webkit: { methods: ["devices.createPairingCode"] }, tauri: ST["devices.createPairingCode"] },+ "devices.pairingCodes": { webkit: { methods: ["devices.pairingCodes"] }, tauri: ST["devices.pairingCodes"] },+ "devices.revokePairingCode": { webkit: { methods: ["devices.revokePairingCode"] }, tauri: ST["devices.revokePairingCode"] },"storage.get": { webkit: { methods: ["storage.get"] }, tauri: ST["storage.get"] },"storage.run": { webkit: { methods: ["storage.run"] }, tauri: ST["storage.run"] },// Notifications (ops/notifications.ts).diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex 604fb5d1ce..974592823c 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -103,6 +103,7 @@ export { useThisMachine, type HostFailure, type HostFormView as HostSetupFormVieexport type { HostFormAction, HostSetupRequest } from "./ops/host-setup";export type { TelemetrySignal } from "./ops/telemetry";export { useStartup, type StartupHook } from "./startup";+export { expiresInText, PAIRING_POLL_MS, pairingUnsupported, usePairingCode, type PairingHook, type PairingPhase } from "./pairing";export { READY_STARTUP, type StartupAction, type StartupPhase, type StartupState } from "./ops/startup";export {CHECKLIST_STEPS,diff --git a/apps/cua-spaces-web/src/bridge/ops/settings.ts b/apps/cua-spaces-web/src/bridge/ops/settings.tsindex 5bbde906b5..d0ab683f81 100644--- a/apps/cua-spaces-web/src/bridge/ops/settings.ts+++ b/apps/cua-spaces-web/src/bridge/ops/settings.ts@@ -11,7 +11,7 @@import { UnsupportedOperationError } from "../adapter";import type { LoginItemStatus } from "../contracts/host";-import type { DevicesInput, EnrollResult } from "../contracts/devices";+import type { DevicesInput, EnrollResult, PairingCode } from "../contracts/devices";import type {AboutInput,DriveCacheInput,@@ -58,6 +58,13 @@ export interface SettingsOperations {"devices.revoke": { args: { id: string }; result: null };/** Vouches for a machine that registered without an enrolled device's proof. */"devices.confirmMachine": { args: { id: string }; result: null };+ /** A one-time link, QR code and install commands that add another+ * computer to the account (or to `team`), from this enrolled device. */+ "devices.createPairingCode": { args: { team?: string | null }; result: PairingCode };+ /** The account's pairing codes, newest first (without the codes). */+ "devices.pairingCodes": { args: Empty; result: PairingCode[] };+ /** Revokes an unused pairing code (`pc_…`). */+ "devices.revokePairingCode": { args: { id: string }; result: null };/** The Cua Volume's storage, mount and cache (`volume_storage`, `volume_mount_status`, `volume_cache_stats`). */"storage.get": { args: Empty; result: StorageInput };@@ -83,6 +90,9 @@ export const SETTINGS_OPERATIONS = ["devices.rename","devices.revoke","devices.confirmMachine",+ "devices.createPairingCode",+ "devices.pairingCodes",+ "devices.revokePairingCode","storage.get","storage.run",] as const satisfies readonly SettingsOpName[];@@ -179,6 +189,12 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): stringawait invoke("devices_confirm_machine", { id });return null;},+ "devices.createPairingCode": ({ team }) => invoke<PairingCode>("devices_create_pairing_code", { team: team ?? null }),+ "devices.pairingCodes": () => invoke<PairingCode[]>("devices_pairing_codes"),+ "devices.revokePairingCode": async ({ id }) => {+ await invoke("devices_revoke_pairing_code", { id });+ return null;+ },"storage.get": storage,"storage.run": async ({ request }) => {@@ -230,6 +246,9 @@ export const SETTINGS_TAURI_COMMANDS = {"devices.rename": ["devices_rename"],"devices.revoke": ["devices_revoke"],"devices.confirmMachine": ["devices_confirm_machine"],+ "devices.createPairingCode": ["devices_create_pairing_code"],+ "devices.pairingCodes": ["devices_pairing_codes"],+ "devices.revokePairingCode": ["devices_revoke_pairing_code"],"storage.get": ["get_environment", "agents_tool"],"storage.run": ["agents_tool", "drive_reveal", "host_open_settings"],} as const satisfies Record<SettingsOpName, readonly string[]>;diff --git a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.tsindex 7b0c6f9bc1..cfd06dce20 100644--- a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts+++ b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts@@ -77,6 +77,9 @@ export const WEBKIT_PAGE_OPS = ["devices.rename","devices.revoke","devices.confirmMachine",+ "devices.createPairingCode",+ "devices.pairingCodes",+ "devices.revokePairingCode","storage.get","storage.run","notifications.list",@@ -246,6 +249,9 @@ export function webkitPageOps(request: Request, toHostStatus: (h: WkHostState) ="devices.rename": none("devices.rename"),"devices.revoke": none("devices.revoke"),"devices.confirmMachine": none("devices.confirmMachine"),+ "devices.createPairingCode": ({ team }) => request("devices.createPairingCode", { team: team ?? null }),+ "devices.pairingCodes": list("devices.pairingCodes"),+ "devices.revokePairingCode": none("devices.revokePairingCode"),"storage.get": call("storage.get"),"storage.run": call("storage.run"),"notifications.list": list("notifications.list"),diff --git a/apps/cua-spaces-web/src/bridge/pairing.ts b/apps/cua-spaces-web/src/bridge/pairing.tsnew file mode 100644index 0000000000..ca295510a9--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/pairing.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * "Add a machine" by link or QR code: makes a one-time pairing code+ * (`devices.createPairingCode`), watches it (`devices.pairingCodes`) until+ * the other computer uses it, and revokes it on request+ * (`devices.revokePairingCode`). The relay holds the code's state; this+ * only asks.+ */++import { useEffect, useRef, useState } from "react";++import { HostError, isUnsupported } from "./adapter";+import type { PairingCode } from "./contracts/devices";+import { useBridge } from "./hooks";++/** How often an open "Add a machine" asks whether its code was used (ms). */+export const PAIRING_POLL_MS = 3000;++export type PairingPhase = "idle" | "minting" | "ready" | "used" | "revoked" | "expired" | "error";++export interface PairingState {+ phase: PairingPhase;+ /** The code as made (with its link and commands), then as last read. */+ code: PairingCode | null;+ /** Why no code could be made; `unsupported`: the host or relay can't make them. */+ error: { message: string; unsupported: boolean } | null;+}++export interface PairingHook extends PairingState {+ /** Unix ms, ticking each second while a code is active (for the countdown). */+ now: number;+ /** Makes a new code (after one expired or was revoked, or a failure). */+ renew(): void;+ /** Revokes the active code. */+ revoke(): Promise<void>;+}++const IDLE: PairingState = { phase: "idle", code: null, error: null };++/** Whether `e` says this host or its relay can't make pairing codes (an older relay answers 404). */+export function pairingUnsupported(e: unknown): boolean {+ if (isUnsupported(e)) return true;+ const text = e instanceof Error ? e.message : String(e);+ return (e instanceof HostError && e.code === "not_found") || /\b404\b/.test(text);+}++/** "Expires in 29 min" (rounded up), "Expires in 40 s" in the last minute. */+export function expiresInText(expiresAtSecs: number, nowMs: number): string {+ const left = Math.max(0, expiresAtSecs * 1000 - nowMs);+ if (left < 60_000) return `Expires in ${Math.ceil(left / 1000)} s`;+ return `Expires in ${Math.ceil(left / 60_000)} min`;+}++/**+ * The pairing code of an open "Add a machine". `enabled`: signed in, and this+ * device may make one (enrolled). A code that is still active stays across+ * closing and opening again; a used, revoked or expired one is replaced.+ */+export function usePairingCode({+ open,+ enabled,+ team = null,+ pollMs = PAIRING_POLL_MS,+ onUsed,+}: {+ open: boolean;+ enabled: boolean;+ team?: string | null;+ pollMs?: number;+ /** The code was used: the machine list can be read again. */+ onUsed?: (code: PairingCode) => void;+}): PairingHook {+ const { data: adapter } = useBridge();+ const [state, setState] = useState<PairingState>(IDLE);+ const [now, setNow] = useState(() => Date.now());+ const seq = useRef(0);+ const usedRef = useRef(onUsed);+ useEffect(() => {+ usedRef.current = onUsed;+ });++ const mint = () => {+ if (!adapter) return;+ const mine = ++seq.current;+ setState({ phase: "minting", code: null, error: null });+ adapter.call("devices.createPairingCode", { team }).then(+ (code) => {+ if (mine !== seq.current) return;+ setNow(Date.now());+ setState({ phase: code.state === "active" ? "ready" : code.state, code, error: null });+ },+ (e: unknown) => {+ if (mine !== seq.current) return;+ setState({ phase: "error", code: null, error: { message: e instanceof Error ? e.message : String(e), unsupported: pairingUnsupported(e) } });+ },+ );+ };++ // Opening makes a code, unless the last one is still good.+ useEffect(() => {+ if (!open || !enabled) return;+ if (state.phase !== "minting" && state.phase !== "ready") mint();+ // Only on opening (and on becoming able to): not on each change of phase.+ }, [open, enabled, adapter]);++ // The countdown, and expiry without waiting for the relay.+ const expiresAt = state.phase === "ready" ? state.code?.expiresAt : undefined;+ useEffect(() => {+ if (!open || expiresAt === undefined) return;+ const tick = () => {+ const t = Date.now();+ setNow(t);+ if (t >= expiresAt * 1000) setState((s) => (s.phase === "ready" ? { ...s, phase: "expired" } : s));+ };+ tick();+ const timer = setInterval(tick, 1000);+ return () => clearInterval(timer);+ }, [open, expiresAt]);++ // Waiting for the other computer: the relay says when the code was used.+ const watching = open && state.phase === "ready" ? state.code?.id : undefined;+ useEffect(() => {+ if (!adapter || !watching) return;+ let stopped = false;+ let busy = false;+ const poll = async () => {+ if (busy) return;+ busy = true;+ try {+ const listed = (await adapter.call("devices.pairingCodes", {})).find((c) => c.id === watching);+ if (stopped || !listed || listed.state === "active") return;+ const phase = listed.state;+ setState((s) => {+ if (s.phase !== "ready" || s.code?.id !== watching) return s;+ // Keep the link and commands the list leaves out.+ const code: PairingCode = { ...s.code, state: listed.state, usedAt: listed.usedAt, machine: listed.machine };+ return { ...s, phase, code };+ });+ if (listed.state === "used") usedRef.current?.(listed);+ } catch {+ // A missed read: the next one tries again.+ } finally {+ busy = false;+ }+ };+ const timer = setInterval(() => void poll(), pollMs);+ return () => {+ stopped = true;+ clearInterval(timer);+ };+ }, [adapter, watching, pollMs]);++ const revoke = async () => {+ const code = state.code;+ if (!adapter || !code || state.phase !== "ready") return;+ await adapter.call("devices.revokePairingCode", { id: code.id });+ setState((s) => (s.code?.id === code.id ? { ...s, phase: "revoked", code: { ...code, state: "revoked" } } : s));+ };++ return { ...state, now, renew: mint, revoke };+}diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 706454da56..994c714fad 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -110,6 +110,9 @@ export const WEBKIT_METHODS = ["devices.rename","devices.revoke","devices.confirmMachine",+ "devices.createPairingCode",+ "devices.pairingCodes",+ "devices.revokePairingCode","storage.get","storage.run","notifications.list",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.tsxnew file mode 100644index 0000000000..873769eb83--- /dev/null+++ b/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx@@ -0,0 +1,174 @@+// 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, expiresInText, useMachines } from "@/bridge";+import { HostError, type DataAdapter } from "@/bridge/adapter";+import { createDemoAdapter, type DemoOptions } from "@/bridge/adapters/demo";+import { unavailableCore } from "@/bridge/core";+import { AddMachineDialog } from "@/components/add-machine-dialog";++afterEach(cleanup);++/** The demo host, with some operations answered differently, recording the pairing calls. */+function host(options: DemoOptions = {}, override: Record<string, (args: Record<string, unknown>) => Promise<unknown>> = {}) {+ const base = createDemoAdapter({ latencyMs: 0, stepMs: 0, signedIn: true, onboarded: true, ...options });+ const calls: string[] = [];+ const adapter = Object.assign(Object.create(base) as DataAdapter, {+ call: ((op: string, args: Record<string, unknown>) => {+ if (op.startsWith("devices.") && op.includes("airing")) calls.push(op);+ const f = override[op];+ if (f) return f(args);+ return (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);+ }) as DataAdapter["call"],+ });+ return { adapter, calls };+}++function Harness() {+ const { data: machines = [], setupGuide } = useMachines();+ return (+ <>+ <ul aria-label="Machines">+ {machines.map((m) => (+ <li key={m.id}>{m.name}</li>+ ))}+ </ul>+ <AddMachineDialog open onOpenChange={() => {}} guide={setupGuide} pollMs={20} />+ </>+ );+}++async function mount(adapter: DataAdapter) {+ render(+ <BridgeProvider adapter={adapter} core={unavailableCore("test: no core")}>+ <Harness />+ </BridgeProvider>,+ );+ await act(() => new Promise((r) => setTimeout(r, 10)));+}++const dialog = () => document.querySelector<HTMLElement>("[data-add-machine]")!;+const phase = () => dialog()?.getAttribute("data-add-machine");++describe("Add a machine by link or QR code", () => {+ it("makes a link on opening: QR code, link, both commands and how long it lasts", async () => {+ const { adapter, calls } = host();+ await mount(adapter);+ await waitFor(() => expect(phase()).toBe("ready"));+ expect(calls[0]).toBe("devices.createPairingCode");+ expect(document.querySelector("[data-pairing-qr] path")?.getAttribute("d")).toMatch(/^M\d/);+ expect(screen.getByText(/^https:\/\/spaces\.cua\.ai\/add\/K7QM-4XPB-/)).toBeTruthy();+ expect(screen.getByText(/sh -s -- --pair K7QM-4XPB-/)).toBeTruthy();+ expect(screen.getByText("Waiting for the computer…")).toBeTruthy();+ expect(document.querySelector("[data-pairing-expires]")?.textContent).toBe("Works once. Expires in 30 min");++ fireEvent.click(screen.getByText("Windows (preview)"));+ await waitFor(() => expect(screen.getByText(/install\.ps1\)\)\) -Pair K7QM-4XPB-/)).toBeTruthy());+ // The by-hand steps stay one click away.+ expect(document.querySelector("details[data-manual-steps] summary")?.textContent?.trim()).toBe("Set it up by hand instead");+ });++ it("waits for the other computer and says which one was added", async () => {+ const { adapter, calls } = host();+ await mount(adapter);+ await waitFor(() => expect(phase()).toBe("used"), { timeout: 3000 });+ expect(calls.filter((c) => c === "devices.pairingCodes").length).toBeGreaterThanOrEqual(3);+ expect(document.querySelector("[data-pairing-added]")?.textContent).toMatch(/^Added Office PC\./);+ // The machine list reads it again: the new computer is there.+ // (The page behind the dialog is inert, so not by role.)+ await waitFor(() => expect(document.querySelector('ul[aria-label="Machines"]')?.textContent).toContain("Office PC"));+ expect(screen.queryByText("Revoke link")).toBeNull();+ });++ it("revokes the link, then makes a new one", async () => {+ const { adapter, calls } = host();+ await mount(adapter);+ await waitFor(() => expect(phase()).toBe("ready"));+ fireEvent.click(screen.getByText("Revoke link"));+ await waitFor(() => expect(phase()).toBe("revoked"));+ expect(calls).toContain("devices.revokePairingCode");+ expect(screen.getByText(/This link was revoked/)).toBeTruthy();+ fireEvent.click(screen.getByText("Make a new link"));+ await waitFor(() => expect(phase()).toBe("ready"));+ expect(calls.filter((c) => c === "devices.createPairingCode")).toHaveLength(2);+ });++ it("says when the link expired and offers a new one", async () => {+ // A code the relay made 31 minutes ago (30 minutes is its life).+ const { adapter } = host({ now: () => Date.now() - 31 * 60_000 });+ await mount(adapter);+ await waitFor(() => expect(phase()).toBe("expired"));+ expect(screen.getByText("This link expired.")).toBeTruthy();+ expect(screen.getByText("Make a new link")).toBeTruthy();+ });++ it("shows that it is making the link", async () => {+ const { adapter } = host({}, { "devices.createPairingCode": () => new Promise(() => {}) });+ await mount(adapter);+ await waitFor(() => expect(phase()).toBe("minting"));+ expect(screen.getByText("Making a link…")).toBeTruthy();+ });++ it("falls back to the steps by hand when the relay can't make links", async () => {+ const { adapter } = host({}, { "devices.createPairingCode": () => Promise.reject(new HostError("relay: 404 Not Found", "failed")) });+ await mount(adapter);+ await waitFor(() => expect(phase()).toBe("error"));+ expect(screen.getByText(/Your Cua relay can't make links yet/)).toBeTruthy();+ expect(document.querySelector("[data-manual-steps]")?.tagName).toBe("DIV");+ expect(screen.getByText("Install Cua Spaces on the other computer")).toBeTruthy();+ });++ it("says what failed otherwise, and tries again", async () => {+ let fail = true;+ const { adapter, calls } = host({}, {});+ const base = adapter.call.bind(adapter);+ const flaky = Object.assign(Object.create(adapter) as DataAdapter, {+ call: ((op: string, args: never) =>+ op === "devices.createPairingCode" && fail ? Promise.reject(new Error("relay unreachable")) : base(op as never, args)) as DataAdapter["call"],+ });+ await mount(flaky);+ await waitFor(() => expect(phase()).toBe("error"));+ expect(screen.getByText(/Couldn't make a link: relay unreachable/)).toBeTruthy();+ fail = false;+ fireEvent.click(screen.getByText("Try again"));+ await waitFor(() => expect(phase()).toBe("ready"));+ expect(calls).toContain("devices.createPairingCode");+ });++ it("asks to sign in when signed out, and makes no link", async () => {+ const { adapter, calls } = host({ signedIn: false });+ await mount(adapter);+ expect(screen.getByText(/Sign in to add a machine with a link/)).toBeTruthy();+ expect(screen.getByText("Sign in")).toBeTruthy();+ expect(document.querySelector("[data-manual-steps]")?.tagName).toBe("DIV");+ expect(calls).toEqual([]);+ });++ it("makes no link on a device that is not enrolled", async () => {+ const notice = { kind: "needs-enrollment", status: "Needs enrollment", text: "Enroll this Mac to open your machines.", actionLabel: "Enroll This Mac…" };+ const { adapter, calls } = host(+ {},+ {+ "machines.list": async () => {+ const rows = (await createDemoAdapter({ latencyMs: 0 }).call("machines.list", {})) as { current?: boolean }[];+ return rows.map((r) => (r.current ? { ...r, accessNotice: notice } : r));+ },+ },+ );+ await mount(adapter);+ await waitFor(() => expect(screen.getByText(/Enroll this Mac to open your machines\. Set the computer up by hand instead\./)).toBeTruthy());+ expect(calls).toEqual([]);+ });+});++describe("expiresInText", () => {+ it("rounds minutes up, and counts seconds in the last minute", () => {+ expect(expiresInText(1800, 0)).toBe("Expires in 30 min");+ expect(expiresInText(1800, 1_000)).toBe("Expires in 30 min");+ expect(expiresInText(100, 50_000)).toBe("Expires in 50 s");+ expect(expiresInText(100, 200_000)).toBe("Expires in 0 s");+ });+});diff --git a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx b/apps/cua-spaces-web/src/components/add-machine-dialog.tsxindex a651ded2b7..d85abb0e93 100644--- a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx+++ b/apps/cua-spaces-web/src/components/add-machine-dialog.tsx@@ -1,13 +1,16 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { ExternalLinkIcon } from "lucide-react";-import type { ReactNode } from "react";+import { CheckIcon, ChevronRightIcon, CopyIcon, ExternalLinkIcon, LoaderCircleIcon } from "lucide-react";+import { useState, type ReactNode } from "react";+import { encode } from "uqr";-import { useSession, type HostFormField, type HostSetupGuide } from "@/bridge";+import { expiresInText, useMachines, usePairingCode, useSession, type HostFormField, type HostSetupGuide, type Machine, type PairingHook } from "@/bridge";import { Button } from "@/components/ui/button";import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";+import { Segmented } from "@/components/ui/segmented";import { toast } from "@/components/ui/toast";+import { cn } from "@/lib/utils";/** Where Cua Spaces is downloaded (`teleport::flow::CUA_INSTALL_URL`). */export const INSTALL_URL = "https://cua.ai/install";@@ -18,89 +21,86 @@ const CHOICE_HELP: Record<string, string> = {spare: "Its screen stays private. Your devices create Spaces on it.",};+type Shell = "sh" | "powershell";+const SHELLS = [+ { value: "sh", label: "macOS / Linux" },+ { value: "powershell", label: "Windows (preview)" },+] as const satisfies readonly { value: Shell; label: string }[];+/**- * "Add a machine": how host setup goes on the other computer, in the words- * that computer will show (the core's `host.panel` and `host.formView`).- * Setup runs there, so this only explains it. Its buttons call existing- * bridge actions: `session.openExternal` and `session.signIn`.+ * "Add a machine". Signed in on an enrolled device, opening it makes a+ * one-time link (and QR code, and install commands) that adds the other+ * computer to the account, and waits until that computer uses it. Without+ * one (signed out, not enrolled, a relay that can't make links), it explains+ * setting the other computer up by hand, in the words that computer shows+ * (the core's `host.panel` and `host.formView`).*/-export function AddMachineDialog({ open, onOpenChange, guide }: { open: boolean; onOpenChange: (open: boolean) => void; guide: HostSetupGuide }) {- const { data: session, openExternal, signIn } = useSession();+export function AddMachineDialog({+ open,+ onOpenChange,+ guide,+ pollMs,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ guide: HostSetupGuide;+ /** How often to ask whether the link was used (tests). */+ pollMs?: number;+}) {+ const { data: session, signIn } = useSession();+ const { data: listed, refresh } = useMachines();+ const machines = listed ?? [];const signedIn = session?.signedIn ?? false;- const identity = session?.identity;+ // Signed in but not enrolled: this device can't vouch for a new machine+ // (known once the machines are read).+ const notice = machines.find((m) => m.current)?.accessNotice ?? null;+ const pairing = usePairingCode({ open, enabled: signedIn && listed !== undefined && !notice, pollMs, onUsed: () => void refresh().catch(() => {}) });const fail = (title: string) => (e: unknown) => toast(title, { description: e instanceof Error ? e.message : String(e) });- const fields = guide.form?.fields ?? [];- const basic = fields.filter((f) => !f.advanced);- const advanced = fields.filter((f) => f.advanced);++ // Any reason there is no link: the manual steps are the way, so show them.+ const manualOnly = !signedIn || Boolean(notice) || pairing.phase === "error";return (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogPopup className="top-[8vh] w-[min(600px,calc(100vw-2rem))]">+ <DialogPopup className="top-[8vh] w-[min(600px,calc(100vw-2rem))]" data-add-machine={pairing.phase}><div className="max-h-[84vh] overflow-y-auto px-6 pt-5 pb-4"><DialogTitle className="text-[15px] font-semibold">Add a machine</DialogTitle><DialogDescription className="mt-1 text-[13px] text-muted-foreground">- Any Mac, Linux or Windows computer you own can run Spaces for you. You set it up on that computer, and it- shows up here once it is online.+ {manualOnly+ ? "Any Mac, Linux or Windows computer you own can run Spaces for you. You set it up on that computer, and it shows up here once it is online."+ : "Open this link on the other computer, scan the code with its camera, or run the command in its terminal. It installs Cua and adds the computer to your account."}</DialogDescription>- <ol className="mt-5 space-y-5">- <Step n={1} title="Install Cua Spaces on the other computer">- <Button variant="outline" size="sm" className="mt-2" onClick={() => void openExternal(INSTALL_URL).catch(fail("Couldn't open the page"))}>- Open download page <ExternalLinkIcon />+ {!signedIn ? (+ <Notice>+ <p>Sign in to add a machine with a link. You can also set it up by hand.</p>+ <Button size="sm" className="mt-2" onClick={() => void signIn().catch(fail("Couldn't start sign-in"))}>+ Sign in+ </Button>+ </Notice>+ ) : notice ? (+ <Notice>{notice.text || "This device isn't enrolled yet, so it can't make a link."} Set the computer up by hand instead.</Notice>+ ) : pairing.phase === "error" ? (+ <Notice>+ {pairing.error?.unsupported+ ? "Your Cua relay can't make links yet. Set the computer up by hand instead."+ : `Couldn't make a link: ${pairing.error?.message ?? "unknown error"}. Set the computer up by hand instead.`}+ <Button variant="outline" size="sm" className="mt-2 flex" onClick={pairing.renew}>+ Try again</Button>- </Step>-- <Step n={2} title="Sign in with the same account">- {signedIn ? (- <p>- Use {identity ? <span className="font-medium text-foreground">{identity}</span> : "the account you use here"}. Machines- join the account they are set up with.- </p>- ) : (- <>- <p>You are not signed in here. Sign in so this app can list the machines on your account.</p>- <Button size="sm" className="mt-2" onClick={() => void signIn().catch(fail("Couldn't start sign-in"))}>- Sign in- </Button>- </>- )}- </Step>-- <Step n={3} title="Open This machine and choose how to use it">- <p>On the other computer, open This machine. It offers two ways to set it up:</p>- <ul className="mt-2 divide-y overflow-hidden rounded-lg border bg-card">- {guide.choices.map((c) => (- <li key={c.id} className="px-3 py-2">- <div className="text-[13px] text-foreground">{c.label}</div>- {CHOICE_HELP[c.id] ? <div className="text-xs">{CHOICE_HELP[c.id]}</div> : null}- </li>- ))}- </ul>- </Step>-- <Step n={4} title={guide.form ? `Fill in the form and press ${quote(submitLabel(guide.form.submitLabel))}` : "Set it up for access"}>- <p>It connects through the Cua relay, so you don't need to forward ports. Under Advanced you can choose a direct connection instead.</p>- {basic.length ? (- <dl className="mt-2 divide-y overflow-hidden rounded-lg border bg-card">- {basic.map((f) => (- <FieldRow key={f.id} field={f} />- ))}- {advanced.length ? (- <div className="bg-muted/40 px-3 py-1.5 text-xs font-medium">{guide.form?.advancedLabel ?? "Advanced"}</div>- ) : null}- {advanced.map((f) => (- <FieldRow key={f.id} field={f} />- ))}- </dl>- ) : null}- </Step>-- <Step n={5} title="Grant permissions if it shares its desktop">- <p>On a Mac, This machine lists the System Settings panes to turn on, such as Screen Recording and Accessibility.</p>- </Step>- </ol>+ </Notice>+ ) : (+ <PairingPanel pairing={pairing} machines={machines} />+ )}++ {pairing.phase === "used" ? null : <ManualSteps guide={guide} open={manualOnly} />}</div><div className="flex justify-end gap-2 border-t px-6 py-3">+ {pairing.phase === "ready" ? (+ <Button variant="outline" onClick={() => void pairing.revoke().catch(fail("Couldn't revoke the link"))}>+ Revoke link+ </Button>+ ) : null}<Button onClick={() => onOpenChange(false)}>Done</Button></div></DialogPopup>@@ -108,6 +108,188 @@ export function AddMachineDialog({ open, onOpenChange, guide }: { open: boolean;);}+function Notice({ children }: { children: ReactNode }) {+ return <div className="mt-4 rounded-lg border bg-card px-3 py-2.5 text-[13px] text-muted-foreground">{children}</div>;+}++/** The link, its QR code, the commands, and how long it lasts. */+function PairingPanel({ pairing, machines }: { pairing: PairingHook; machines: Machine[] }) {+ const [shell, setShell] = useState<Shell>("sh");+ const { phase, code } = pairing;++ if (phase === "idle" || phase === "minting" || !code) {+ return (+ <div className="mt-5 flex items-center gap-2 text-[13px] text-muted-foreground" data-pairing-minting>+ <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> Making a link…+ </div>+ );+ }++ if (phase === "used") {+ const name = machines.find((m) => m.id === code.machine)?.name;+ return (+ <div className="mt-5 flex items-center gap-2.5 rounded-lg border bg-card px-3 py-3 text-[13px]" data-pairing-added>+ <CheckIcon className="size-4 shrink-0 text-success" aria-hidden />+ <span>{name ? `Added ${name}.` : "Added the computer."} It shows in your machines.</span>+ </div>+ );+ }++ if (phase === "expired" || phase === "revoked") {+ return (+ <div className="mt-5 rounded-lg border bg-card px-3 py-3 text-[13px] text-muted-foreground" data-pairing-ended={phase}>+ {phase === "expired" ? "This link expired." : "This link was revoked. It can't add a computer now."}+ <Button size="sm" className="mt-2 flex" onClick={pairing.renew}>+ Make a new link+ </Button>+ </div>+ );+ }++ const command = shell === "sh" ? code.installSh : code.installPowershell;+ return (+ <div className="mt-5" data-pairing-ready>+ <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-5">+ {code.url ? <QrCode text={code.url} /> : null}+ <div className="min-w-0 space-y-3">+ <div>+ <div className="mb-1 text-xs font-medium text-muted-foreground">Link</div>+ {code.url ? <CopyField text={code.url} label="Copy link" /> : null}+ </div>+ <div>+ <Segmented aria-label="The other computer's system" value={shell} options={SHELLS} onValueChange={setShell} />+ {command ? <CopyField text={command} label="Copy command" mono /> : null}+ </div>+ </div>+ </div>+ <div className="mt-4 flex items-center justify-between gap-3 text-xs text-muted-foreground">+ <span className="flex items-center gap-2" data-pairing-waiting>+ <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> Waiting for the computer…+ </span>+ <span className="tabular-nums" data-pairing-expires>+ Works once. {expiresInText(code.expiresAt, pairing.now)}+ </span>+ </div>+ </div>+ );+}++/** One line to copy: the link, or a command. */+function CopyField({ text, label, mono }: { text: string; label: string; mono?: boolean }) {+ const [copied, setCopied] = useState(false);+ const copy = () => {+ void navigator.clipboard?.writeText(text).then(+ () => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1200);+ },+ () => {},+ );+ };+ return (+ <div className="mt-1.5 flex items-center gap-1 rounded-lg border bg-muted/40 pl-3">+ <code className={cn("min-w-0 flex-1 py-1.5 text-xs", mono ? "font-mono break-all" : "truncate font-sans")} title={text}>+ {text}+ </code>+ <Button size="icon-sm" variant="ghost" aria-label={label} onClick={copy}>+ {copied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}+ </Button>+ </div>+ );+}++/** The link as a QR code, drawn here (nothing leaves the page). */+export function QrCode({ text, size = 148 }: { text: string; size?: number }) {+ const qr = encode(text, { ecc: "M", border: 2 });+ let d = "";+ qr.data.forEach((row, y) =>+ row.forEach((dark, x) => {+ if (dark) d += `M${x} ${y}h1v1h-1z`;+ }),+ );+ return (+ <svg+ role="img"+ aria-label="QR code of the link"+ data-pairing-qr+ width={size}+ height={size}+ viewBox={`0 0 ${qr.size} ${qr.size}`}+ shapeRendering="crispEdges"+ className="rounded-lg border bg-white"+ >+ <path d={d} fill="#000" />+ </svg>+ );+}++/** The by-hand setup: install, sign in, set up for access. */+function ManualSteps({ guide, open }: { guide: HostSetupGuide; open: boolean }) {+ const { data: session, openExternal } = useSession();+ const identity = session?.identity;+ const fail = (title: string) => (e: unknown) => toast(title, { description: e instanceof Error ? e.message : String(e) });+ const fields = guide.form?.fields ?? [];+ const basic = fields.filter((f) => !f.advanced);+ const advanced = fields.filter((f) => f.advanced);++ const steps = (+ <ol className="mt-4 space-y-5">+ <Step n={1} title="Install Cua Spaces on the other computer">+ <Button variant="outline" size="sm" className="mt-2" onClick={() => void openExternal(INSTALL_URL).catch(fail("Couldn't open the page"))}>+ Open download page <ExternalLinkIcon />+ </Button>+ </Step>++ <Step n={2} title="Sign in with the same account">+ <p>+ Use {identity ? <span className="font-medium text-foreground">{identity}</span> : "the account you use here"}. Machines join the+ account they are set up with.+ </p>+ </Step>++ <Step n={3} title="Open This machine and choose how to use it">+ <ul className="mt-1 divide-y overflow-hidden rounded-lg border bg-card">+ {guide.choices.map((c) => (+ <li key={c.id} className="px-3 py-2">+ <div className="text-[13px] text-foreground">{c.label}</div>+ {CHOICE_HELP[c.id] ? <div className="text-xs">{CHOICE_HELP[c.id]}</div> : null}+ </li>+ ))}+ </ul>+ </Step>++ <Step n={4} title={guide.form ? `Fill in the form and press ${quote(submitLabel(guide.form.submitLabel))}` : "Set it up for access"}>+ <p>It connects through the Cua relay, so you don't need to forward ports. Under Advanced you can choose a direct connection instead.</p>+ {basic.length ? (+ <dl className="mt-2 divide-y overflow-hidden rounded-lg border bg-card">+ {basic.map((f) => (+ <FieldRow key={f.id} field={f} />+ ))}+ {advanced.length ? <div className="bg-muted/40 px-3 py-1.5 text-xs font-medium">{guide.form?.advancedLabel ?? "Advanced"}</div> : null}+ {advanced.map((f) => (+ <FieldRow key={f.id} field={f} />+ ))}+ </dl>+ ) : null}+ </Step>++ <Step n={5} title="Grant permissions if it shares its desktop">+ <p>On a Mac, This machine lists the System Settings panes to turn on, such as Screen Recording and Accessibility.</p>+ </Step>+ </ol>+ );++ if (open) return <div data-manual-steps>{steps}</div>;+ return (+ <details className="group mt-5 border-t pt-3" data-manual-steps>+ <summary className="flex cursor-default list-none items-center gap-1 text-[13px] text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden">+ <ChevronRightIcon className="size-3.5 transition-transform group-open:rotate-90" aria-hidden /> Set it up by hand instead+ </summary>+ {steps}+ </details>+ );+}+function Step({ n, title, children }: { n: number; title: string; children: ReactNode }) {return (<li className="grid grid-cols-[24px_minmax(0,1fr)] gap-3">diff --git a/apps/cua-spaces/src-tauri/src/commands.rs b/apps/cua-spaces/src-tauri/src/commands.rsindex 114f514cd5..d889c82f30 100644--- a/apps/cua-spaces/src-tauri/src/commands.rs+++ b/apps/cua-spaces/src-tauri/src/commands.rs@@ -988,6 +988,30 @@ pub async fn devices_confirm_machine(state: State<'_, AppState>, id: String) ->state.0.devices()?.confirm_machine(&id).await}+/// Makes a one-time link, QR code and install commands that add another+/// computer to the account (or to `team`): "Add a machine".+#[tauri::command]+pub async fn devices_create_pairing_code(+ state: State<'_, AppState>,+ team: Option<String>,+) -> CmdResult<crate::devices::PairingCodeView> {+ state.0.devices()?.create_pairing_code(team).await+}++/// The account's pairing codes, newest first (without the codes).+#[tauri::command]+pub async fn devices_pairing_codes(+ state: State<'_, AppState>,+) -> CmdResult<Vec<crate::devices::PairingCodeView>> {+ state.0.devices()?.pairing_codes().await+}++/// Revokes an unused pairing code.+#[tauri::command]+pub async fn devices_revoke_pairing_code(state: State<'_, AppState>, id: String) -> CmdResult<()> {+ state.0.devices()?.revoke_pairing_code(&id).await+}+/// Posts a system notification (a device asks for approval).#[tauri::command]pub fn devices_notify(app: AppHandle, title: String, body: String) -> CmdResult<()> {diff --git a/apps/cua-spaces/src-tauri/src/devices.rs b/apps/cua-spaces/src-tauri/src/devices.rsindex 840d9fbc14..2a3fed34c3 100644--- a/apps/cua-spaces/src-tauri/src/devices.rs+++ b/apps/cua-spaces/src-tauri/src/devices.rs@@ -16,7 +16,7 @@ use std::collections::HashMap;use std::sync::Arc;use async_trait::async_trait;-use cua_host::{AccountTokens, DeviceAuth, DeviceState, RelayClient};+use cua_host::{AccountTokens, DeviceAuth, DeviceState, PairingCodeRequest, RelayClient};use cua_spaces_app_core::devices::{AuditInput, DeviceInput, DevicesInput, MachineInput};use serde::Serialize;@@ -35,6 +35,53 @@ pub trait PresenceGate: Send + Sync {async fn confirm(&self, reason: &str, passphrase: Option<String>) -> Result<(), String>;}+/// A one-time code that adds a machine to the account ("Add a machine" by+/// link or QR code), as the page reads it (the cua SDK's `PairingCode`).+/// `code`, `url` and the install commands are only there when just made.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PairingCodeView {+ pub id: String,+ pub code: Option<String>,+ pub url: Option<String>,+ pub install_sh: Option<String>,+ pub install_powershell: Option<String>,+ /// `active`, `used`, `revoked` or `expired`.+ pub state: String,+ pub team: Option<String>,+ /// Unix seconds.+ pub created_at: u64,+ pub expires_at: u64,+ pub used_at: Option<u64>,+ /// The relay machine id it added.+ pub machine: Option<String>,+}++impl PairingCodeView {+ /// The relay's code, with the link and commands for `relay`.+ pub fn new(p: cua_host::PairingCode, relay: &str) -> Self {+ let made = |os: Option<&str>| {+ p.code.as_deref().map(|c| match os {+ None => cua_host::add_machine_url(c, relay),+ Some(os) => cua_host::install_command(c, relay, os),+ })+ };+ Self {+ url: made(None),+ install_sh: made(Some("linux")),+ install_powershell: made(Some("windows")),+ id: p.id,+ code: p.code,+ state: p.state,+ team: p.team,+ created_at: p.created_at,+ expires_at: p.expires_at,+ used_at: p.used_at,+ machine: p.machine,+ }+ }+}+/// `devices_enroll`'s result.#[derive(Clone, Debug, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]@@ -198,6 +245,50 @@ impl DevicesService {.map(|_| ()).map_err(err)}++ /// The relay, as this device and the account (the pairing-code calls).+ async fn account_relay(&self) -> Result<(RelayClient, String), String> {+ let session = self.auth.session().await.map_err(err)?;+ let token = self.tokens.access_token().await.map_err(err)?;+ let relay = RelayClient::new(self.auth.relay_url())+ .map_err(err)?+ .with_device_session(Some(session));+ Ok((relay, token))+ }++ /// Makes a one-time code (link, QR code, install commands) that adds+ /// another computer to the account, or to `team`, from this enrolled+ /// device. It expires after 30 minutes.+ pub async fn create_pairing_code(+ &self,+ team: Option<String>,+ ) -> Result<PairingCodeView, String> {+ let (relay, token) = self.account_relay().await?;+ let req = PairingCodeRequest {+ name: None,+ team,+ ttl_secs: None,+ };+ let code = relay.create_pairing_code(&token, &req).await.map_err(err)?;+ Ok(PairingCodeView::new(code, self.auth.relay_url()))+ }++ /// The account's pairing codes, newest first (without the codes).+ pub async fn pairing_codes(&self) -> Result<Vec<PairingCodeView>, String> {+ let (relay, token) = self.account_relay().await?;+ let codes = relay.pairing_codes(&token).await.map_err(err)?;+ let url = self.auth.relay_url();+ Ok(codes+ .into_iter()+ .map(|c| PairingCodeView::new(c, url))+ .collect())+ }++ /// Revokes an unused pairing code (`pc_…`).+ pub async fn revoke_pairing_code(&self, id: &str) -> Result<(), String> {+ let (relay, token) = self.account_relay().await?;+ relay.revoke_pairing_code(&token, id).await.map_err(err)+ }}/// The app's presence gate: the biometric prompt on macOS, else thediff --git a/apps/cua-spaces/src-tauri/src/lib.rs b/apps/cua-spaces/src-tauri/src/lib.rsindex 8f59d7a249..9beb71206e 100644--- a/apps/cua-spaces/src-tauri/src/lib.rs+++ b/apps/cua-spaces/src-tauri/src/lib.rs@@ -512,6 +512,9 @@ pub fn run() {commands::devices_rename,commands::devices_revoke,commands::devices_confirm_machine,+ commands::devices_create_pairing_code,+ commands::devices_pairing_codes,+ commands::devices_revoke_pairing_code,commands::devices_notify,commands::space_shares,commands::share_space,diff --git a/apps/cua-spaces/src/model/devices.ts b/apps/cua-spaces/src/model/devices.tsindex 61c8da51be..ddc8409cfd 100644--- a/apps/cua-spaces/src/model/devices.ts+++ b/apps/cua-spaces/src/model/devices.ts@@ -36,6 +36,26 @@ export interface MachineInput {confirmed: boolean;}+/** A one-time code that adds a machine to the account (the shell's+ * `devices_create_pairing_code` and `devices_pairing_codes`). `code`, `url`+ * and the install commands are only there when just made. */+export interface PairingCode {+ id: string;+ code: string | null;+ url: string | null;+ installSh: string | null;+ installPowershell: string | null;+ /** `active`, `used`, `revoked` or `expired`. */+ state: string;+ team: string | null;+ /** Unix seconds. */+ createdAt: number;+ expiresAt: number;+ usedAt: number | null;+ /** The relay machine id it added. */+ machine: string | null;+}+/** What the Devices page reads (the shell's `devices_snapshot`). */export interface DevicesInput {devices: DeviceInput[];diff --git a/apps/cua-spaces/src/native/devices.ts b/apps/cua-spaces/src/native/devices.tsindex e3121b514f..d384ef7d54 100644--- a/apps/cua-spaces/src/native/devices.ts+++ b/apps/cua-spaces/src/native/devices.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import type { DevicesInput } from "../model/devices";+import type { DevicesInput, PairingCode } from "../model/devices";import { hasTauri } from "./bridge";/**@@ -25,6 +25,13 @@ export interface DevicesBridge {/** Vouches for a machine that registered without an enrolled device's* proof (S5), after the row's confirmation. */confirmMachine(id: string): Promise<void>;+ /** A one-time link, QR code and install commands that add another+ * computer to the account (or to `team`): "Add a machine". */+ createPairingCode(team?: string | null): Promise<PairingCode>;+ /** The account's pairing codes, newest first (without the codes). */+ pairingCodes(): Promise<PairingCode[]>;+ /** Revokes an unused pairing code. */+ revokePairingCode(id: string): Promise<void>;/** A system notification (a device asks for approval). */notify(title: string, body: string): Promise<void>;}@@ -44,6 +51,9 @@ export function createTauriDevicesBridge(): DevicesBridge {rename: (id, name) => invoke<void>("devices_rename", { id, name }),revoke: (id) => invoke<void>("devices_revoke", { id }),confirmMachine: (id) => invoke<void>("devices_confirm_machine", { id }),+ createPairingCode: (team) => invoke<PairingCode>("devices_create_pairing_code", { team: team ?? null }),+ pairingCodes: () => invoke<PairingCode[]>("devices_pairing_codes"),+ revokePairingCode: (id) => invoke<void>("devices_revoke_pairing_code", { id }),notify: (title, body) => invoke<void>("devices_notify", { title, body }),};}@@ -61,6 +71,9 @@ export function createFallbackDevicesBridge(): DevicesBridge {rename: unavailable,revoke: unavailable,confirmMachine: unavailable,+ createPairingCode: unavailable,+ pairingCodes: unavailable,+ revokePairingCode: unavailable,notify: async () => {},};}@@ -85,6 +98,7 @@ export function createFakeDevicesBridge(): DevicesBridge & { calls: string[]; state: { snapshot: DevicesInput } } {const state = { snapshot: options.snapshot ?? { devices: [], audit: [] } };const calls: string[] = [];+ const pairing: PairingCode[] = [];let checks = 0;return {isNative: true,@@ -135,6 +149,34 @@ export function createFakeDevicesBridge(machines: (state.snapshot.machines ?? []).map((m) => (m.id === id ? { ...m, confirmed: true } : m)),};},+ createPairingCode: async (team) => {+ calls.push(`create-pairing-code:${team ?? ""}`);+ const now = Math.floor(Date.now() / 1000);+ const code = `K7QM-4XPB-${String(pairing.length + 1).padStart(4, "0")}`;+ const made: PairingCode = {+ id: `pc_fake${pairing.length + 1}`,+ code,+ url: `https://spaces.cua.ai/add/${code}`,+ installSh: `curl -fsSL https://cua.ai/install.sh | sh -s -- --pair ${code}`,+ installPowershell: `& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair ${code}`,+ state: "active",+ team: team ?? null,+ createdAt: now,+ expiresAt: now + 1800,+ usedAt: null,+ machine: null,+ };+ pairing.unshift(made);+ return made;+ },+ pairingCodes: async () => {+ calls.push("pairing-codes");+ return pairing.map((p) => ({ ...p, code: null, url: null, installSh: null, installPowershell: null }));+ },+ revokePairingCode: async (id) => {+ calls.push(`revoke-pairing-code:${id}`);+ for (const p of pairing) if (p.id === id) p.state = "revoked";+ },notify: async (title, body) => {calls.push(`notify:${title}:${body}`);},