Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(spaces): Spaces as a tree and a default Space, behind Labs, with the SDK bindings and CLI (CUA-3413) (#6508)

cua-agents[bot]b6090f6fb2f5
diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.ts
index 3785e3b007..f59f55b574 100644
--- a/apps/cua-spaces-desktop/src/bridge/index.ts
+++ b/apps/cua-spaces-desktop/src/bridge/index.ts
@@ -36,6 +36,7 @@ import { ciMethods } from "./ci";
import { threadMethods } from "./thread";
import { agentThreadsMethods } from "./agent-threads";
import { relayUsageMethods } from "./relay-usage";
+import { spacesSettingsMethods } from "./spaces-settings";
import { resourcesMethods } from "./resources";
import { sessionMethods, sessionState } from "./session";
import { settingsMethods } from "./settings";
@@ -79,6 +80,7 @@ export const AREAS = [
streamMethods,
onboardingMethods,
relayUsageMethods,
+ spacesSettingsMethods,
nudgesMethods,
resourcesMethods,
checklistMethods,
diff --git a/apps/cua-spaces-desktop/src/bridge/machines.ts b/apps/cua-spaces-desktop/src/bridge/machines.ts
index 47aa7fd0bd..a76142064e 100644
--- a/apps/cua-spaces-desktop/src/bridge/machines.ts
+++ b/apps/cua-spaces-desktop/src/bridge/machines.ts
@@ -135,11 +135,14 @@ export function machinesMethods({ model }: BridgeContext): Handlers {
},
// Remove from account: the machine leaves the relay directory, then
// the device on it is revoked; the Spaces and machines are read again.
+ // The Spaces made on it are detached (they come back when it is added
+ // again), or with `deleteSpaces` deleted with it.
"machines.remove": async (args) => {
const machine = optionalString(args, "machine");
const device = optionalString(args, "device");
+ const deleteSpaces = args.deleteSpaces === true;
if (!machine && !device) throw Failure.badArgs("machine or device");
- if (machine) await relayCall(model, () => model.backend.relayUnregister(machine));
+ if (machine) await relayCall(model, () => model.backend.relayUnregister(machine, deleteSpaces));
if (device) await relayCall(model, () => model.devices.revoke(device));
else await model.devices.refresh();
await model.refresh();
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.ts
index bf59a22a3f..c86e60fecc 100644
--- a/apps/cua-spaces-desktop/src/bridge/methods.ts
+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts
@@ -53,6 +53,7 @@ export const METHODS = [
"nudges.pending", "nudges.answer",
"resources.get",
"machines.rename", "machines.remove", "machines.checkHealth",
+ "spaces.settings", "spaces.setSettings", "spaces.resolveDefault",
"checklist.get", "checklist.send",
"links.list", "links.create", "links.stop", "links.approve", "links.deny",
"shares.settings.get", "shares.settings.set", "shares.edge.remove",
diff --git a/apps/cua-spaces-desktop/src/bridge/spaces-settings.ts b/apps/cua-spaces-desktop/src/bridge/spaces-settings.ts
new file mode 100644
index 0000000000..1f2fe387b5
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/bridge/spaces-settings.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The account's default Space (`spaces.settings`, `spaces.setSettings`,
+// `spaces.resolveDefault`; the web bridge's ops/spaces-settings.ts): the
+// SDK's `Devices.spaces_settings`, `set_spaces_settings` and
+// `resolve_default_space` from this enrolled device, the same calls as the
+// SwiftUI host's. Null before the session is up or signed out. Nothing here
+// creates a Space.
+import { optionalString, bool, strings } from "./args";
+import type { BridgeContext } from "./context";
+import { Failure, type Handlers } from "./host";
+import { encode } from "./value";
+
+/** Space ids the relay keeps: `relay:<machine>` or `relay:<machine>/<name>`. */
+const SPACE_ID = /^relay:[^/\s]+(\/[a-z0-9-]{1,63})?$/;
+
+export function spacesSettingsMethods({ model }: BridgeContext): Handlers {
+ /** The session's `Devices`, or null (signed out, not set up yet): the page then shows nothing. */
+ const devices = () => (model.servicesIn && model.devices.signedIn ? model.devices.devices() : null);
+ return {
+ "spaces.settings": async () => {
+ const d = devices();
+ return d ? encode(await d.spacesSettings()) : null;
+ },
+ "spaces.setSettings": async (args) => {
+ const defaultSpace = optionalString(args, "defaultSpace");
+ const fallback = strings(args, "fallback");
+ const fallbackOn = bool(args, "fallbackOn");
+ for (const id of [defaultSpace, ...fallback]) if (id !== null && !SPACE_ID.test(id)) throw Failure.badArgs(`not a Space id: ${id}`);
+ const d = devices();
+ if (!d) return null;
+ return encode(await d.setSpacesSettings({ defaultSpace: defaultSpace ?? undefined, fallback, fallbackOn, updatedAt: 0n }));
+ },
+ "spaces.resolveDefault": async () => {
+ const d = devices();
+ return d ? encode(await d.resolveDefaultSpace()) : null;
+ },
+ };
+}
diff --git a/apps/cua-spaces-desktop/src/model/backend.ts b/apps/cua-spaces-desktop/src/model/backend.ts
index 23d8d23b84..154cd870d6 100644
--- a/apps/cua-spaces-desktop/src/model/backend.ts
+++ b/apps/cua-spaces-desktop/src/model/backend.ts
@@ -247,8 +247,9 @@ export interface SpacesBackend {
/** `services.list` / `services.control`: the commands a Space keeps running. */
services?(id: string): Promise<ServiceJson[]>;
controlService?(id: string, name: string, action: string): Promise<void>;
- /** Takes one of your machines off the relay directory (`relay:<machine>`), refused while it is online. */
- relayUnregister(machineId: string): Promise<void>;
+ /** Takes one of your machines off the relay directory (`relay:<machine>`), refused while it is online. The Spaces made on
+ * it are detached, or with `deleteSpaces` deleted too (the SDK's `relay_unregister_computer`). */
+ relayUnregister(machineId: string, deleteSpaces?: boolean): Promise<void>;
/** A machine's health as its own cua daemon checks it (the SDK's `Spaces.machine_health`): null for this one, else another of yours by id. */
machineHealth(machine: string | null): Promise<MachineHealthReport>;
setPower(id: string, on: boolean): Promise<void>;
@@ -765,8 +766,9 @@ export class LiveSpacesBackend implements SpacesBackend {
}
}
- async relayUnregister(machineId: string): Promise<void> {
- await this.cua.spaces().relayUnregister(`relay:${machineId}`);
+ async relayUnregister(machineId: string, deleteSpaces = false): Promise<void> {
+ if (deleteSpaces) await this.cua.spaces().relayUnregisterComputer(`relay:${machineId}`, true);
+ else await this.cua.spaces().relayUnregister(`relay:${machineId}`);
}
async machineHealth(machine: string | null): Promise<MachineHealthReport> {
diff --git a/apps/cua-spaces-desktop/src/model/pending.ts b/apps/cua-spaces-desktop/src/model/pending.ts
index 38d9627609..19eac7bb5e 100644
--- a/apps/cua-spaces-desktop/src/model/pending.ts
+++ b/apps/cua-spaces-desktop/src/model/pending.ts
@@ -106,7 +106,7 @@ export class PendingSpacesBackend implements SpacesBackend {
deleteMany = async (ids: string[]) => (await this.b()).deleteMany(ids);
leave = async (ids: string[]) => (await this.b()).leave(ids);
rename = async (id: string, name: string) => (await this.b()).rename(id, name);
- relayUnregister = async (machineId: string) => (await this.b()).relayUnregister(machineId);
+ relayUnregister = async (machineId: string, deleteSpaces?: boolean) => (await this.b()).relayUnregister(machineId, deleteSpaces);
network = async (id: string) => {
const b = await this.b();
if (!b.network) throw new Error("network settings are not available in this build");
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts
index ae16e36ab5..9ac9706f97 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
@@ -1359,6 +1359,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_devices_resolve_default_space": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_devices_revoke": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -1369,11 +1374,21 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_devices_set_spaces_settings": {
+ 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,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_devices_spaces_settings": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_forkbatch_collect": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -2719,6 +2734,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_remove": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -3984,6 +4004,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_devices_resolve_default_space": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_devices_revoke": {
args: [],
ret: FfiType.UInt16,
@@ -3994,11 +4019,21 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_devices_set_spaces_settings": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_devices_snapshot": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_devices_spaces_settings": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_forkbatch_collect": {
args: [],
ret: FfiType.UInt16,
@@ -5344,6 +5379,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_remove": {
args: [],
ret: FfiType.UInt16,
@@ -6361,9 +6401,12 @@ interface NativeModuleInterface {
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_rename_machine(uniffiSelf: bigint, machineId: Uint8Array, name: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_devices_resolve_default_space(uniffiSelf: bigint): 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_set_spaces_settings(uniffiSelf: bigint, settings: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_devices_snapshot(uniffiSelf: bigint, auditLimit: number): bigint;
+ uniffi_cua_sdk_fn_method_devices_spaces_settings(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_forkbatch_collect(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_forkbatch_next(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_framesink_on_frame(uniffiSelf: bigint, frame: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;
@@ -6633,6 +6676,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_prewarms(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_relay_register(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_relay_unregister(uniffiSelf: bigint, space: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(uniffiSelf: bigint, space: Uint8Array, deleteSpaces: number): bigint;
uniffi_cua_sdk_fn_method_spaces_remove(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_remove_prewarm(uniffiSelf: bigint, id: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_rename(uniffiSelf: bigint, space: Uint8Array, name: Uint8Array): bigint;
@@ -6886,9 +6930,12 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_devices_relay_url(): number;
uniffi_cua_sdk_checksum_method_devices_rename(): number;
uniffi_cua_sdk_checksum_method_devices_rename_machine(): number;
+ uniffi_cua_sdk_checksum_method_devices_resolve_default_space(): 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_set_spaces_settings(): number;
uniffi_cua_sdk_checksum_method_devices_snapshot(): number;
+ uniffi_cua_sdk_checksum_method_devices_spaces_settings(): number;
uniffi_cua_sdk_checksum_method_forkbatch_collect(): number;
uniffi_cua_sdk_checksum_method_forkbatch_next(): number;
uniffi_cua_sdk_checksum_method_framesink_on_frame(): number;
@@ -7158,6 +7205,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_prewarms(): number;
uniffi_cua_sdk_checksum_method_spaces_relay_register(): number;
uniffi_cua_sdk_checksum_method_spaces_relay_unregister(): number;
+ uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer(): number;
uniffi_cua_sdk_checksum_method_spaces_remove(): number;
uniffi_cua_sdk_checksum_method_spaces_remove_prewarm(): number;
uniffi_cua_sdk_checksum_method_spaces_rename(): number;
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
index e39efacae6..da9160ccf0 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
@@ -7287,6 +7287,146 @@ const FfiConverterTypeCursorArt = (() => {
return new FFIConverter();
})();
+/**
+ * One entry of the order [`Devices::resolve_default_space`] tried.
+ */
+export type DefaultSpaceStep = {
+ /**
+ * The Space id.
+ */
+ space: string,
+ /**
+ * Its display name.
+ */
+ name: string,
+ /**
+ * Connected and sharing now.
+ */
+ online: boolean,
+ /**
+ * `default`, `fallback` or `here`.
+ */
+ role: string
+}
+
+/**
+ * Generated factory for {@link DefaultSpaceStep} record objects.
+ */
+export const DefaultSpaceStep = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DefaultSpaceStep, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DefaultSpaceStep>,
+ });
+})();
+
+const FfiConverterTypeDefaultSpaceStep = (() => {
+ type TypeName = DefaultSpaceStep;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ space: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ online: FfiConverterBool.read(from),
+ role: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.space, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterBool.write(value.online, into);
+ FfiConverterString.write(value.role, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.space) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterBool.allocationSize(value.online) +
+ FfiConverterString.allocationSize(value.role);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * Where the default Space resolves now.
+ */
+export type DefaultSpace = {
+ /**
+ * The first online entry; none when this device is the answer
+ * (`reason` `here`).
+ */
+ space?: string,
+ /**
+ * `default`, `fallback`, `here` or `unset`.
+ */
+ reason: string,
+ /**
+ * The chosen default, online or not.
+ */
+ defaultSpace?: string,
+ /**
+ * Whether the default is online; none when unset.
+ */
+ defaultOnline?: boolean,
+ /**
+ * The order the relay tried.
+ */
+ order: Array<DefaultSpaceStep>
+}
+
+/**
+ * Generated factory for {@link DefaultSpace} record objects.
+ */
+export const DefaultSpace = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DefaultSpace, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DefaultSpace>,
+ });
+})();
+
+const FfiConverterTypeDefaultSpace = (() => {
+ type TypeName = DefaultSpace;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ space: FfiConverterOptionalString.read(from),
+ reason: FfiConverterString.read(from),
+ defaultSpace: FfiConverterOptionalString.read(from),
+ defaultOnline: FfiConverterOptionalBoolean.read(from),
+ order: FfiConverterSequenceTypeDefaultSpaceStep.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.space, into);
+ FfiConverterString.write(value.reason, into);
+ FfiConverterOptionalString.write(value.defaultSpace, into);
+ FfiConverterOptionalBoolean.write(value.defaultOnline, into);
+ FfiConverterSequenceTypeDefaultSpaceStep.write(value.order, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.space) +
+ FfiConverterString.allocationSize(value.reason) +
+ FfiConverterOptionalString.allocationSize(value.defaultSpace) +
+ FfiConverterOptionalBoolean.allocationSize(value.defaultOnline) +
+ FfiConverterSequenceTypeDefaultSpaceStep.allocationSize(value.order);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* A client device of the account, as the relay lists it.
*/
@@ -23190,6 +23330,73 @@ const FfiConverterTypeSpacesHost = (() => {
return new FFIConverter();
})();
+/**
+ * The account's default Space and the order to try when it is offline.
+ */
+export type SpacesSettings = {
+ /**
+ * `relay:<machine>` or `relay:<machine>/<name>`; none when unset.
+ */
+ defaultSpace?: string,
+ /**
+ * The order to try when the default is offline; empty means every
+ * online computer you can use, oldest first.
+ */
+ fallback: Array<string>,
+ /**
+ * false: only the default, then this device.
+ */
+ fallbackOn: boolean,
+ /**
+ * Unix seconds the relay saved it (ignored when writing).
+ */
+ updatedAt: bigint
+}
+
+/**
+ * Generated factory for {@link SpacesSettings} record objects.
+ */
+export const SpacesSettings = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpacesSettings, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpacesSettings>,
+ });
+})();
+
+const FfiConverterTypeSpacesSettings = (() => {
+ type TypeName = SpacesSettings;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ defaultSpace: FfiConverterOptionalString.read(from),
+ fallback: FfiConverterSequenceString.read(from),
+ fallbackOn: FfiConverterBool.read(from),
+ updatedAt: FfiConverterUInt64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.defaultSpace, into);
+ FfiConverterSequenceString.write(value.fallback, into);
+ FfiConverterBool.write(value.fallbackOn, into);
+ FfiConverterUInt64.write(value.updatedAt, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.defaultSpace) +
+ FfiConverterSequenceString.allocationSize(value.fallback) +
+ FfiConverterBool.allocationSize(value.fallbackOn) +
+ FfiConverterUInt64.allocationSize(value.updatedAt);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One row of [`SPACES_TOOL_METHODS`].
*/
@@ -28974,6 +29181,12 @@ export interface DevicesLike {
* its host setup takes the new name too.
*/
renameMachine(machineId: string, name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RelayMachine>;
+/**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+ resolveDefaultSpace(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DefaultSpace>;
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -28983,12 +29196,22 @@ export interface DevicesLike {
* Revokes an unused pairing code (`pc_…`).
*/
revokePairingCode(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+/**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+ setSpacesSettings(settings: SpacesSettings, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacesSettings>;
/**
* The account's devices, the grace period, the newest `audit_limit`
* audit events and the machines' names. Only the device list must
* succeed; the rest is empty when the relay refuses it.
*/
snapshot(auditLimit: number, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DevicesSnapshot>;
+/**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+ spacesSettings(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacesSettings>;
}
/**
* @deprecated Use `DevicesLike` instead.
@@ -29350,6 +29573,43 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+ async resolveDefaultSpace(asyncOpts_?: { signal: AbortSignal }): Promise<DefaultSpace> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_devices_resolve_default_space(
+ 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:*/ FfiConverterTypeDefaultSpace.lift.bind(FfiConverterTypeDefaultSpace),
+ /*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;
+ }
+ }
+
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -29416,6 +29676,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+ async setSpacesSettings(settings: SpacesSettings, asyncOpts_?: { signal: AbortSignal }): Promise<SpacesSettings> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_devices_set_spaces_settings(
+ uniffiTypeDevicesObjectFactory.clonePointer(this),FfiConverterTypeSpacesSettings.lower(settings, 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:*/ FfiConverterTypeSpacesSettings.lift.bind(FfiConverterTypeSpacesSettings),
+ /*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
@@ -29453,6 +29749,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+ async spacesSettings(asyncOpts_?: { signal: AbortSignal }): Promise<SpacesSettings> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_devices_spaces_settings(
+ 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:*/ FfiConverterTypeSpacesSettings.lift.bind(FfiConverterTypeSpacesSettings),
+ /*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;
+ }
+ }
+
uniffiDestroy(): void {
const ptr = (this as any)[destructorGuardSymbol];
@@ -42386,6 +42718,16 @@ export interface SpacesLike {
* Returns false when it was not on the relay.
*/
relayUnregister(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<boolean>;
+/**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+ relayUnregisterComputer(space: string, deleteSpaces: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<boolean>;
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -44851,6 +45193,47 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+ async relayUnregisterComputer(space: string, deleteSpaces: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<boolean> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(deleteSpaces, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_i8,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_i8,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_i8,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_i8,
+ // 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:*/ FfiConverterBool.lift.bind(FfiConverterBool),
+ /*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;
+ }
+ }
+
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -48468,6 +48851,9 @@ const FfiConverterSequenceTypeCloudSweepItem = new FfiConverterArray(FfiConverte
// FfiConverter for Array<number>
const FfiConverterSequenceUInt16 = new FfiConverterArray(FfiConverterUInt16);
+// FfiConverter for Array<DefaultSpaceStep>
+const FfiConverterSequenceTypeDefaultSpaceStep = new FfiConverterArray(FfiConverterTypeDefaultSpaceStep);
+
// FfiConverter for Array<RelayDevice>
const FfiConverterSequenceTypeRelayDevice = new FfiConverterArray(FfiConverterTypeRelayDevice);
@@ -49339,15 +49725,24 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_devices_rename_machine() !== 63088) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_rename_machine");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_resolve_default_space() !== 5493) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_resolve_default_space");
+ }
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_set_spaces_settings() !== 38780) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_set_spaces_settings");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_devices_snapshot() !== 26132) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_snapshot");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_spaces_settings() !== 1866) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_spaces_settings");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_forkbatch_collect() !== 56883) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_forkbatch_collect");
}
@@ -50155,6 +50550,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_relay_unregister() !== 53366) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_relay_unregister");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer() !== 32336) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_remove() !== 23086) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_remove");
}
@@ -50584,6 +50982,8 @@ export default Object.freeze({
FfiConverterTypeCuaInfo,
FfiConverterTypeCuaMode,
FfiConverterTypeCursorArt,
+ FfiConverterTypeDefaultSpace,
+ FfiConverterTypeDefaultSpaceStep,
FfiConverterTypeDeviceEnrollment,
FfiConverterTypeDevices,
FfiConverterTypeDevicesSnapshot,
@@ -50797,6 +51197,7 @@ export default Object.freeze({
FfiConverterTypeSpacesHostLoad,
FfiConverterTypeSpacesListListener,
FfiConverterTypeSpacesListWatch,
+ FfiConverterTypeSpacesSettings,
FfiConverterTypeSpacesToolMethod,
FfiConverterTypeSpacesdCapabilities,
FfiConverterTypeSpacesdClient,
diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.ts
index 6838f51035..b762822325 100644
--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts
+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts
@@ -212,9 +212,9 @@ describe.skipIf(!built)("the bridge on the app core", () => {
for (const [method, args] of cases) problems.push(...shapeProblems(method, await call(method, args)));
expect(problems).toEqual([]);
// Every ported method has its case (or is checked below).
- // (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts; resource numbers: resources.test.ts; presence: presence-bridge.test.ts; the Machines page's rename, remove and health checks: machines-view.test.ts; the Windows runtime fix: below.)
+ // (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts; resource numbers: resources.test.ts; presence: presence-bridge.test.ts; the Machines page's rename, remove and health checks, and the default Space: machines-view.test.ts; the Windows runtime fix: below.)
// (The CI Runners methods, ci.*: ci.test.ts. They run the bundled `cua`, which this core-only test does not have.)
- const elsewhere = new Set(["ci.overview", "ci.connect", "ci.connectToken", "ci.connectCancel", "ci.repositories", "ci.goal", "ci.log", "session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear", ...THREAD_OPERATIONS, ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);
+ const elsewhere = new Set(["ci.overview", "ci.connect", "ci.connectToken", "ci.connectCancel", "ci.repositories", "ci.goal", "ci.log", "session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "spaces.settings", "spaces.setSettings", "spaces.resolveDefault", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear", ...THREAD_OPERATIONS, ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);
const ported = bridge.registry.methods.filter((m) => !NOT_YET.includes(m) && !elsewhere.has(m));
expect(ported.filter((m) => !cases.some(([c]) => c === m))).toEqual([]);
});
@@ -660,7 +660,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {
};
// This machine, Devices, Settings and the rest: host-bridge.test.ts reads them with their arguments (the Machines page's rename and remove: machines-view.test.ts).
// (The CI Runners methods, ci.*: ci.test.ts. They run the bundled `cua`, which this core-only test does not have.)
- const skip = new Set<OpName>(["ci.overview", "ci.connect", "ci.connectToken", "ci.connectCancel", "ci.repositories", "ci.goal", "ci.log", "spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear", ...(THREAD_OPERATIONS as readonly string[] as OpName[]), ...VAULT_OPS, ...(HOST_OPS as OpName[])]);
+ const skip = new Set<OpName>(["ci.overview", "ci.connect", "ci.connectToken", "ci.connectCancel", "ci.repositories", "ci.goal", "ci.log", "spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "spaces.settings", "spaces.setSettings", "spaces.resolveDefault", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear", ...(THREAD_OPERATIONS as readonly string[] as OpName[]), ...VAULT_OPS, ...(HOST_OPS as OpName[])]);
// (The thread: thread.test.ts.)
const problems: string[] = [];
const checked: string[] = [];
diff --git a/apps/cua-spaces-desktop/test/fixtures.ts b/apps/cua-spaces-desktop/test/fixtures.ts
index e092118181..8c4a19e0c4 100644
--- a/apps/cua-spaces-desktop/test/fixtures.ts
+++ b/apps/cua-spaces-desktop/test/fixtures.ts
@@ -191,8 +191,11 @@ export class FixtureSpacesBackend implements SpacesBackend {
return h ?? { cuaVersion: "0.4.1", checks: [] };
}
readonly unregistered: string[] = [];
- async relayUnregister(machineId: string) {
+ /** The machines taken off the relay with the Spaces made on them deleted too. */
+ readonly unregisteredWithSpaces: string[] = [];
+ async relayUnregister(machineId: string, deleteSpaces = false) {
this.unregistered.push(machineId);
+ if (deleteSpaces) this.unregisteredWithSpaces.push(machineId);
this.rowsNow = this.rowsNow.filter((r) => r.id !== `relay:${machineId}`);
}
async setPower(id: string, on: boolean) {
diff --git a/apps/cua-spaces-desktop/test/host-fixtures.ts b/apps/cua-spaces-desktop/test/host-fixtures.ts
index acf81cd5d4..f320820d46 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, PairingCode, RelayDevice } from "../src/native/generated/index";
+import type { DefaultSpace, DeviceEnrollment, DevicesLike, DevicesSnapshot, HostLike, HostSettingsChange, HostSetupOptions, HostStatus, PairingCode, RelayDevice, SpacesSettings } 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";
@@ -289,6 +289,40 @@ export class FixtureDevices {
this.calls.push(`revoke-pairing-code:${id}`);
this.pairing = this.pairing.map((p) => (p.id === id ? { ...p, state: "revoked" } : p));
}
+
+ /** The account's default Space as the relay keeps it (unset unless set). */
+ spaces: SpacesSettings = { defaultSpace: undefined, fallback: [], fallbackOn: true, updatedAt: 0n };
+
+ async spacesSettings(): Promise<SpacesSettings> {
+ this.calls.push("spaces-settings");
+ return this.spaces;
+ }
+
+ async setSpacesSettings(settings: SpacesSettings): Promise<SpacesSettings> {
+ this.calls.push(`set-spaces-settings:${settings.defaultSpace ?? ""}`);
+ this.spaces = { ...settings, updatedAt: BigInt(Math.floor(Date.now() / 1000)) };
+ return this.spaces;
+ }
+
+ /** The relay's answer over the fixture account's machines: the default, every other machine, then this one. */
+ async resolveDefaultSpace(): Promise<DefaultSpace> {
+ this.calls.push("resolve-default-space");
+ const machines = this.current.machines.map((m) => ({ space: `relay:${m.id}`, name: m.name, online: m.online }));
+ const def = machines.find((m) => m.space === this.spaces.defaultSpace);
+ const order = [
+ ...(def ? [{ ...def, role: "default" }] : []),
+ ...(this.spaces.fallbackOn ? machines.filter((m) => m !== def).map((m) => ({ ...m, role: "fallback" })) : []),
+ { space: "relay:self-id", name: "This Mac", online: true, role: "here" },
+ ];
+ const first = order.find((o) => o.online && o.role !== "here");
+ return {
+ space: first?.space,
+ reason: first ? (first.role === "default" ? "default" : this.spaces.defaultSpace ? "fallback" : "unset") : "here",
+ defaultSpace: this.spaces.defaultSpace,
+ defaultOnline: def ? def.online : undefined,
+ order,
+ };
+ }
}
/** The system in memory: what was opened, shown, posted and asked. */
diff --git a/apps/cua-spaces-desktop/test/machines-view.test.ts b/apps/cua-spaces-desktop/test/machines-view.test.ts
index 463e8274e1..fc9708dc5a 100644
--- a/apps/cua-spaces-desktop/test/machines-view.test.ts
+++ b/apps/cua-spaces-desktop/test/machines-view.test.ts
@@ -181,6 +181,8 @@ describe.skipIf(!built)("the Machines page on the app core", () => {
await model.refresh();
await expect(call("machines.remove", { machine: "m2", device: "dev_old" })).resolves.toBeNull();
expect(backend.unregistered).toEqual(["m2"]);
+ // Detached, not deleted, unless the page asks.
+ expect(backend.unregisteredWithSpaces).toEqual([]);
expect(devices.calls).toContain("revoke:dev_old");
await expect(call("machines.remove", {})).rejects.toMatchObject({ code: "bad_args" });
// Signed out: no relay to ask.
@@ -189,4 +191,37 @@ describe.skipIf(!built)("the Machines page on the app core", () => {
Object.assign(model, { devices: signedOut });
await expect(call("machines.remove", { machine: "m2" })).rejects.toMatchObject({ code: "unsupported" });
});
+
+ it("removes a computer with the Spaces made on it when the page asks (CUA-3413)", async () => {
+ await model.refresh();
+ await expect(call("machines.remove", { machine: "m2", deleteSpaces: true })).resolves.toBeNull();
+ expect(backend.unregisteredWithSpaces).toEqual(["m2"]);
+ });
+
+ it("reads, replaces and resolves the default Space from this enrolled device (CUA-3413)", async () => {
+ await model.refresh();
+ const unset = await call("spaces.settings");
+ expect(unset).toEqual({ defaultSpace: null, fallback: [], fallbackOn: true, updatedAt: 0 });
+ expect(validate(WEBKIT_SHAPES["spaces.settings"]!, unset, SHAPE_DEFS)).toEqual([]);
+
+ const saved = (await call("spaces.setSettings", { defaultSpace: "relay:m2", fallback: [], fallbackOn: true })) as { defaultSpace: string };
+ expect(saved.defaultSpace).toBe("relay:m2");
+ expect(devices.calls).toContain("set-spaces-settings:relay:m2");
+ expect(validate(WEBKIT_SHAPES["spaces.setSettings"]!, saved, SHAPE_DEFS)).toEqual([]);
+
+ // m2 is offline in the fixture account: the next online computer, else this one; nothing is made.
+ const resolved = (await call("spaces.resolveDefault")) as { reason: string; defaultOnline: boolean; order: { role: string }[] };
+ expect(validate(WEBKIT_SHAPES["spaces.resolveDefault"]!, resolved, SHAPE_DEFS)).toEqual([]);
+ expect(resolved).toMatchObject({ reason: "here", defaultOnline: false });
+ expect(resolved.order.map((o) => o.role)).toEqual(["default", "here"]);
+
+ // A bad id is refused before the relay is asked.
+ await expect(call("spaces.setSettings", { defaultSpace: "local:aurora", fallback: [], fallbackOn: true })).rejects.toMatchObject({ code: "bad_args" });
+ await expect(call("spaces.setSettings", { defaultSpace: null, fallback: "relay:m2", fallbackOn: true })).rejects.toMatchObject({ code: "bad_args" });
+
+ // Signed out: nothing to read.
+ model.devices.signedIn = false;
+ await expect(call("spaces.settings")).resolves.toBeNull();
+ await expect(call("spaces.resolveDefault")).resolves.toBeNull();
+ });
});
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index 57039a438c..a1e056ede7 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -521,9 +521,16 @@ public final class AppModel {
/// Remove from account: `machine` leaves the relay directory, then
/// `device` is revoked. This Mac's own host setup is the host's
- /// `remove` instead.
- public func removeMachine(machine: String?, device: String?) async throws {
- if let machine { try await backend.relayUnregister(id: "relay:\(machine)") }
+ /// `remove` instead. The Spaces made on the machine are detached (they
+ /// come back when it is added again), or with `deleteSpaces` deleted too.
+ public func removeMachine(machine: String?, device: String?, deleteSpaces: Bool = false) async throws {
+ if let machine {
+ if deleteSpaces {
+ try await backend.relayUnregisterComputer(id: "relay:\(machine)", deleteSpaces: true)
+ } else {
+ try await backend.relayUnregister(id: "relay:\(machine)")
+ }
+ }
if let device {
guard let relay = devices.devices else {
throw CuaError.InvalidArgument(message: "Revoking a machine needs a signed-in Cua account")
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
index 98a591508d..7023bd836d 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
@@ -674,6 +674,9 @@ public final class PendingSpacesBackend: SpacesBackend, AgentsToolRunning, Cloud
// The Machines page: Remove from account and each computer's health
// checks (the protocol's defaults would refuse them).
public func relayUnregister(id: String) async throws { try await b().relayUnregister(id: id) }
+ public func relayUnregisterComputer(id: String, deleteSpaces: Bool) async throws {
+ try await b().relayUnregisterComputer(id: id, deleteSpaces: deleteSpaces)
+ }
public func machineHealth(machine: String?) async throws -> AppMachinesViewHealth {
try await b().machineHealth(machine: machine)
}
@@ -820,6 +823,11 @@ public final class PendingDevices: DevicesRunning, @unchecked Sendable {
public func pairingCodes() async throws -> [PairingCode] { try await d().pairingCodes() }
public func revokePairingCode(id: String) async throws { try await d().revokePairingCode(id: id) }
public func relayUsage() async throws -> AppRelayUsage? { try await d().relayUsage() }
+ public func spacesSettings() async throws -> SpacesSettings { try await d().spacesSettings() }
+ public func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings {
+ try await d().setSpacesSettings(settings)
+ }
+ public func resolveDefaultSpace() async throws -> DefaultSpace { try await d().resolveDefaultSpace() }
}
/// 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.swift
index 461c751a58..18c07ac4dc 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
@@ -34,6 +34,14 @@ public protocol DevicesRunning: AnyObject, Sendable {
/// The account's relay allowance this month; nil from a relay that
/// meters nothing.
func relayUsage() async throws -> AppRelayUsage?
+ /// The account's default Space and the order to try when it is offline
+ /// (`Devices.spaces_settings`).
+ func spacesSettings() async throws -> SpacesSettings
+ /// Replaces them (the whole setting); what the relay saved.
+ func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings
+ /// Where the default Space resolves now, with this Mac as the last
+ /// resort (`Devices.resolve_default_space`). Creates nothing.
+ func resolveDefaultSpace() async throws -> DefaultSpace
}
/// The SDK's `Devices` for the signed-in session (key in the session's vault,
@@ -88,6 +96,11 @@ public final class LiveDevices: DevicesRunning, @unchecked Sendable {
guard let auth else { return nil }
return try await appRelayUsage(devices: inner, accountToken: try await auth.accessToken(force: false))
}
+ public func spacesSettings() async throws -> SpacesSettings { try await inner.spacesSettings() }
+ public func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings {
+ try await inner.setSpacesSettings(settings: settings)
+ }
+ public func resolveDefaultSpace() async throws -> DefaultSpace { try await inner.resolveDefaultSpace() }
}
/// An in-memory account on a relay (fixtures, tests): this Mac enrolled,
@@ -235,6 +248,46 @@ public final class FixtureDevices: DevicesRunning, @unchecked Sendable {
return usage
}
+ /// The account's default Space as the relay keeps it (unset unless set).
+ public var spaces = SpacesSettings(defaultSpace: nil, fallback: [], fallbackOn: true, updatedAt: 0)
+
+ public func spacesSettings() async throws -> SpacesSettings {
+ calls.append("spaces-settings")
+ return spaces
+ }
+
+ public func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings {
+ calls.append("set-spaces-settings:\(settings.defaultSpace ?? "")")
+ spaces = SpacesSettings(defaultSpace: settings.defaultSpace, fallback: settings.fallback,
+ fallbackOn: settings.fallbackOn, updatedAt: UInt64(Date().timeIntervalSince1970))
+ return spaces
+ }
+
+ /// The relay's resolution over the fixture account's machines: the
+ /// default, the order to try (or every other machine), then this Mac.
+ public func resolveDefaultSpace() async throws -> DefaultSpace {
+ calls.append("resolve-default-space")
+ let machines = current.machines.map { ("relay:\($0.id)", $0.name, $0.online) }
+ var order: [DefaultSpaceStep] = []
+ if let d = spaces.defaultSpace, let m = machines.first(where: { $0.0 == d }) {
+ order.append(DefaultSpaceStep(space: m.0, name: m.1, online: m.2, role: "default"))
+ }
+ if spaces.fallbackOn {
+ let listed = spaces.fallback.isEmpty ? machines.map(\.0) : spaces.fallback
+ for id in listed where id != spaces.defaultSpace {
+ if let m = machines.first(where: { $0.0 == id }) {
+ order.append(DefaultSpaceStep(space: m.0, name: m.1, online: m.2, role: "fallback"))
+ }
+ }
+ }
+ order.append(DefaultSpaceStep(space: "relay:this-mac", name: "This Mac", online: true, role: "here"))
+ let first = order.first(where: { $0.online && $0.role != "here" })
+ let online = spaces.defaultSpace.map { d in machines.first(where: { $0.0 == d })?.2 ?? false }
+ let reason = first.map { $0.role == "default" ? "default" : (spaces.defaultSpace == nil ? "unset" : "fallback") } ?? "here"
+ return DefaultSpace(space: first?.space, reason: reason, defaultSpace: spaces.defaultSpace,
+ defaultOnline: online, order: order)
+ }
+
/// A relay allowance by name: `reached` (past it: the notice shows),
/// `team` (a pooled team allowance, within it), `none` (a relay that
/// meters nothing), else the free plan partway through the month.
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift
index b3600fd3ce..ffce55b9b6 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift
@@ -109,6 +109,11 @@ public protocol SpacesBackend: AnyObject, Sendable {
/// directory (`Spaces.relay_unregister`): Remove from account on the
/// Machines page. The relay refuses one that is online.
func relayUnregister(id: String) async throws
+ /// The same for one of your computers, choosing what happens to the
+ /// Spaces made on it (`Spaces.relay_unregister_computer`): detached
+ /// (they come back when it is added again), or with `deleteSpaces`
+ /// deleted too.
+ func relayUnregisterComputer(id: String, deleteSpaces: Bool) async throws
/// A machine's health as its own cua daemon checks it
/// (`Spaces.machine_health`): `nil` for this Mac, else another of your
/// machines by id, asked over the relay or mesh. The Machines page
@@ -476,6 +481,9 @@ public extension SpacesBackend {
func relayUnregister(id: String) async throws {
throw FixtureError(message: "Machines can't be removed here")
}
+ func relayUnregisterComputer(id: String, deleteSpaces: Bool) async throws {
+ try await relayUnregister(id: id)
+ }
func machineHealth(machine: String?) async throws -> AppMachinesViewHealth {
throw FixtureError(message: "Machines can't be checked here")
}
@@ -711,6 +719,10 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {
_ = try await cua.spaces().relayUnregister(space: id)
}
+ public func relayUnregisterComputer(id: String, deleteSpaces: Bool) async throws {
+ _ = try await cua.spaces().relayUnregisterComputer(space: id, deleteSpaces: deleteSpaces)
+ }
+
public func machineHealth(machine: String?) async throws -> AppMachinesViewHealth {
let h = try await cua.spaces().machineHealth(machine: machine)
return AppMachinesViewHealth(
@@ -1478,6 +1490,14 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {
}
}
+ /// The machines taken off the relay with their Spaces deleted too.
+ public private(set) var unregisteredWithSpaces: [String] = []
+
+ public func relayUnregisterComputer(id: String, deleteSpaces: Bool) async throws {
+ try await relayUnregister(id: id)
+ if deleteSpaces { await MainActor.run { unregisteredWithSpaces.append(id) } }
+ }
+
/// What `machineHealth` answers, by machine (`""` for this Mac); a
/// machine without an entry has no issues.
public var fixtureHealth: [String: AppMachinesViewHealth] = [:]
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
index 1388cda91b..adafdc34af 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
@@ -267,8 +267,30 @@ extension WebUIBridge {
let machine = (args["machine"] as? String).flatMap { $0.isEmpty ? nil : $0 }
let device = (args["device"] as? String).flatMap { $0.isEmpty ? nil : $0 }
guard machine != nil || device != nil else { throw Failure.badArgs("machine or device") }
- try await model.removeMachine(machine: machine, device: device)
+ // The Spaces made on it are detached unless the page asked to delete them too.
+ try await model.removeMachine(machine: machine, device: device, deleteSpaces: args["deleteSpaces"] as? Bool == true)
return NSNull()
+
+ // The account's default Space (the relay keeps it, so the apps, the
+ // CLI and agents agree) and where a new task goes now. Signed out or
+ // not enrolled: null. Nothing here creates a Space.
+ case "spaces.settings":
+ guard let relay = signedInDevices() else { return NSNull() }
+ return BridgeValue.encode(try await relay.spacesSettings())
+ case "spaces.setSettings":
+ let defaultSpace = (args["defaultSpace"] as? String).flatMap { $0.isEmpty ? nil : $0 }
+ let fallback = try strings(args, "fallback")
+ guard let fallbackOn = args["fallbackOn"] as? Bool else { throw Failure.badArgs("fallbackOn: boolean") }
+ for id in [defaultSpace].compactMap({ $0 }) + fallback where !Self.isRelaySpaceId(id) {
+ throw Failure.badArgs("not a Space id: \(id)")
+ }
+ guard let relay = signedInDevices() else { return NSNull() }
+ let saved = try await relay.setSpacesSettings(
+ SpacesSettings(defaultSpace: defaultSpace, fallback: fallback, fallbackOn: fallbackOn, updatedAt: 0))
+ return BridgeValue.encode(saved)
+ case "spaces.resolveDefault":
+ guard let relay = signedInDevices() else { return NSNull() }
+ return BridgeValue.encode(try await relay.resolveDefaultSpace())
// Each machine's own daemon checks its health; the next
// `machines.list` view carries the issues.
case "machines.checkHealth":
@@ -1131,3 +1153,17 @@ extension WebUIBridge {
return "data:\(type);base64,\(data.base64EncodedString())"
}
}
+
+extension WebUIBridge {
+ /// The session's relay devices, or nil (signed out, or before the SDK is in).
+ func signedInDevices() -> DevicesRunning? {
+ let devices = model.devices
+ guard devices.signedIn else { return nil }
+ return devices.devices
+ }
+
+ /// A Space id the relay keeps: `relay:<machine>` or `relay:<machine>/<name>`.
+ static func isRelaySpaceId(_ id: String) -> Bool {
+ id.range(of: #"^relay:[^/\s]+(/[a-z0-9-]{1,63})?$"#, options: .regularExpression) != nil
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 26fc5890e7..1216ee269a 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -132,6 +132,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
// The Machines page's rename, Remove from account and each machine's
// health checks (WebUIBridge+Pages.swift).
"machines.rename", "machines.remove", "machines.checkHealth",
+ // The account's default Space and where a new task goes now
+ // (WebUIBridge+Pages.swift; the Labs switch for Spaces as a tree).
+ "spaces.settings", "spaces.setSettings", "spaces.resolveDefault",
// The getting-started checklist: the app's one copy (`ChecklistModel`).
"checklist.get", "checklist.send",
// Links to things you run (WebUIBridge+Pages.swift).
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
index 02b99c69e4..88503022d5 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
@@ -258,7 +258,10 @@ struct BridgeContractTests {
// The relay allowance before the sign-out below (signed out, it is null).
// No request is waiting on the fixtures: an answer to none is left alone.
("nudges.pending", [:]), ("nudges.answer", ["id": "risky-1-1", "choice": "here"]),
- ("app.info", [:]), ("session.get", [:]), ("relay.usage", [:]), ("resources.get", ["visible": true]), ("session.signOut", [:]),
+ ("app.info", [:]), ("session.get", [:]), ("relay.usage", [:]), ("resources.get", ["visible": true]),
+ // The default Space reads from the fixture account (before the sign-out: signed out, each is null).
+ ("spaces.settings", [:]), ("spaces.setSettings", ["defaultSpace": NSNull(), "fallback": [String](), "fallbackOn": true]),
+ ("spaces.resolveDefault", [:]), ("session.signOut", [:]),
("links.list", [:]), ("links.create", ["target": "space:dev:3000"]), ("links.stop", ["id": "all"]),
("links.approve", ["id": "share-pending"]), ("links.deny", ["id": "share-pending"]),
("shares.settings.get", [:]), ("shares.edge.remove", [:]),
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
index 67b74f1914..47a2f0ebed 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
@@ -233,6 +233,9 @@ final class RelayAnswering: DevicesRunning, @unchecked Sendable {
func pairingCodes() async throws -> [PairingCode] { try await fixture.pairingCodes() }
func revokePairingCode(id: String) async throws { try await fixture.revokePairingCode(id: id) }
func relayUsage() async throws -> AppRelayUsage? { try await fixture.relayUsage() }
+ func spacesSettings() async throws -> SpacesSettings { try await fixture.spacesSettings() }
+ func setSpacesSettings(_ settings: SpacesSettings) async throws -> SpacesSettings { try await fixture.setSpacesSettings(settings) }
+ func resolveDefaultSpace() async throws -> DefaultSpace { try await fixture.resolveDefaultSpace() }
}
/// Settings' Relay usage row and the notice above the main window: the
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swift
index 2a2ffa86d8..e8e76629b3 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachinesViewTests.swift
@@ -218,6 +218,52 @@ struct MachinesViewTests {
await #expect(throws: (any Error).self) { _ = try await bridge.handle("machines.remove", [:]) }
}
+ /// `machines.remove` with `deleteSpaces` deletes the Spaces made on the
+ /// computer too (`relay_unregister_computer`); without it they are only
+ /// detached, as before (CUA-3413).
+ @Test func removeAComputerWithItsSpaces() async throws {
+ let backend = FixtureSpacesBackend()
+ let m = await signedInModel(backend: backend, devices: FixtureDevices())
+ let bridge = WebUIBridge(model: m, allowedOrigins: [])
+ _ = try await bridge.handle("machines.remove", ["machine": "m2"])
+ #expect(backend.unregistered == ["relay:m2"])
+ #expect(backend.unregisteredWithSpaces.isEmpty)
+ _ = try await bridge.handle("machines.remove", ["machine": "m3", "deleteSpaces": true])
+ #expect(backend.unregistered == ["relay:m2", "relay:m3"])
+ #expect(backend.unregisteredWithSpaces == ["relay:m3"])
+ }
+
+ /// The default Space: read, replaced and resolved from this enrolled
+ /// device; a bad id is refused before the relay is asked; signed out,
+ /// each answers null (CUA-3413).
+ @Test func defaultSpaceSettings() async throws {
+ let devices = FixtureDevices()
+ let m = await signedInModel(backend: FixtureSpacesBackend(), devices: devices)
+ let bridge = WebUIBridge(model: m, allowedOrigins: [])
+ for method in ["spaces.settings", "spaces.setSettings", "spaces.resolveDefault"] {
+ #expect(WebUIBridge.methods.contains(method))
+ }
+ let unset = try #require(try await bridge.handle("spaces.settings", [:]) as? [String: Any])
+ #expect(unset["defaultSpace"] is NSNull)
+ #expect(unset["fallbackOn"] as? Bool == true)
+
+ let machine = try #require(devices.current.machines.first).id
+ let saved = try #require(try await bridge.handle(
+ "spaces.setSettings", ["defaultSpace": "relay:\(machine)", "fallback": [String](), "fallbackOn": true]) as? [String: Any])
+ #expect(saved["defaultSpace"] as? String == "relay:\(machine)")
+ #expect(devices.calls.contains("set-spaces-settings:relay:\(machine)"))
+
+ let resolved = try #require(try await bridge.handle("spaces.resolveDefault", [:]) as? [String: Any])
+ let order = try #require(resolved["order"] as? [[String: Any]])
+ #expect(order.first?["role"] as? String == "default")
+ #expect(order.last?["role"] as? String == "here")
+
+ await #expect(throws: (any Error).self) {
+ _ = try await bridge.handle("spaces.setSettings", ["defaultSpace": "local:x", "fallback": [String](), "fallbackOn": true])
+ }
+ await #expect(throws: (any Error).self) { _ = try await bridge.handle("spaces.setSettings", ["fallback": [String]()]) }
+ }
+
/// `checkMachineHealth` asks only the machines the view says can be
/// checked: This Mac (through its daemon) and your machines that are
/// online; never an offline or a team machine.
diff --git a/apps/cua-spaces-web/src/__tests__/spaces-tree.test.tsx b/apps/cua-spaces-web/src/__tests__/spaces-tree.test.tsx
new file mode 100644
index 0000000000..aebd8d6d16
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/spaces-tree.test.tsx
@@ -0,0 +1,289 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Spaces as a tree and a default Space (CUA-3413, Labs `spaces_tree`) on the
+// real routes and the wasm core: off, the app is as it was; on, Machines
+// leaves the nav and the sidebar and the Spaces page list each computer with
+// the Spaces made on it; rename by double-click; Remove names each Space and
+// deletes them only with the box ticked; Home starts on the default Space,
+// says why when it falls back, and never makes a computer by itself.
+
+import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { setFlagOverride } from "@/bridge";
+import { wasmBuilt } from "@/bridge/__tests__/testCore";
+import type { MachineRow } from "@/bridge/contracts/host";
+import type { DefaultSpace } from "@/bridge/ops/spaces-settings";
+import { DOUBLE_CLICK_MS } from "@/components/spaces/spaces-tree-page";
+import { resetCollapsed } from "@/components/spaces/tree-parts";
+import { resetAskTasks } from "@/lib/ask-first";
+import { resetPrepare } from "@/lib/prepare/store";
+import { mountApp, stubBrowserApis, type TestHost } from "./app-harness";
+
+stubBrowserApis();
+beforeEach(() => {
+ localStorage.clear();
+ resetAskTasks();
+ resetPrepare();
+ resetCollapsed();
+});
+afterEach(() => {
+ cleanup();
+ resetPrepare();
+});
+
+const q = (s: string) => document.querySelector<HTMLElement>(s);
+const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];
+/** Waits until `s` is in the page: waitFor retries only while its callback throws. */
+const found = (s: string) =>
+ waitFor(() => {
+ const el = q(s);
+ if (!el) throw new Error(`not yet in the page: ${s}`);
+ return el;
+ });
+type Call = [string, Record<string, unknown>];
+
+/** The demo host with the Linux box sharing its desktop; `offline` machines are offline; every change recorded. */
+function host(calls: Call[], opts: { offline?: string[]; resolved?: DefaultSpace } = {}): TestHost {
+ return {
+ failsCreates: false,
+ listsGhost: false,
+ demo: { onboarded: true, desktops: true },
+ answer: (op, out) => (op === "machines.list" ? (out as MachineRow[]).map((m) => (opts.offline?.includes(m.id) ? { ...m, online: false } : m)) : out),
+ intercept: (op, args) => {
+ if (op === "spaces.rename" || op === "machines.rename" || op === "machines.remove" || op === "spaces.delete" || op === "spaces.setSettings" || op === "spaces.create") {
+ calls.push([op, args as Record<string, unknown>]);
+ if (op === "spaces.setSettings") return { ...(args as object), updatedAt: 1 };
+ return op === "spaces.delete" ? "" : null;
+ }
+ if (op === "spaces.resolveDefault" && opts.resolved) return opts.resolved;
+ return undefined;
+ },
+ };
+}
+
+/** The switch on, with the "Ask first" Home it changes (Labs turns both on). */
+/** A double-click as a person makes it: two clicks (detail 1, then 2), then the dblclick. */
+const doubleClick = (el: HTMLElement) => {
+ fireEvent.click(el, { detail: 1 });
+ fireEvent.click(el, { detail: 2 });
+ fireEvent.doubleClick(el, { detail: 2 });
+};
+
+const on = () => {
+ setFlagOverride("spaces_tree", true);
+ setFlagOverride("spaces_ask_first_home", true);
+};
+
+describe.skipIf(!wasmBuilt)("Spaces as a tree (Labs)", () => {
+ it("off: the nav keeps Machines and the Spaces page is the grid", { timeout: 30000 }, async () => {
+ setFlagOverride("spaces_ask_first_home", true);
+ const { router } = await mountApp("/spaces", host([]));
+ await router.load();
+ await waitFor(() => expect(screen.getByRole("link", { name: /Machines/ })).toBeTruthy());
+ expect(q("[data-sidebar-tree]")).toBeNull();
+ expect(q("[data-spaces-tree]")).toBeNull();
+ });
+
+ it("on: Machines leaves the nav, and each computer lists the Spaces made on it, This Mac first", { timeout: 30000 }, async () => {
+ on();
+ const { router } = await mountApp("/spaces", host([]));
+ await router.load();
+ await waitFor(() => expect(q("[data-spaces-tree]")).not.toBeNull());
+ expect(screen.queryByRole("link", { name: /^Machines/ })).toBeNull();
+ await waitFor(() => expect(qa("[data-tree-kind=computer]").length).toBeGreaterThan(1));
+ const names = qa("[data-tree-kind=computer] [data-tree-name]").map((e) => e.textContent);
+ expect(names[0]).toBe("This Mac");
+ expect(names).toContain("Linux box");
+ // The Linux box's Spaces sit under it, in the sidebar too.
+ const rows = qa("[data-tree-row]").map((r) => r.getAttribute("data-tree-row"));
+ expect(rows.indexOf("relay:linux-box/ubuntu-build")).toBeGreaterThan(rows.indexOf("relay:linux-box"));
+ expect(q('[data-sidebar-tree-row="relay:linux-box/ubuntu-build"]')).not.toBeNull();
+ // The first computer that isn't this Mac is the default until one is set.
+ expect(q('[data-tree-status="relay:mac-mini"]')?.textContent).toMatch(/, Default$/);
+ expect(q("[data-sidebar-tree] [data-tree-default]")).not.toBeNull();
+ // Folding a computer hides its Spaces in both lists.
+ fireEvent.click(q('[data-tree-fold="relay:linux-box"]')!);
+ expect(q('[data-tree-row="relay:linux-box/ubuntu-build"]')).toBeNull();
+ expect(q('[data-sidebar-tree-row="relay:linux-box/ubuntu-build"]')).toBeNull();
+ // Machines' page still opens.
+ await act(() => router.navigate({ to: "/machines" }));
+ await waitFor(() => expect(router.state.location.pathname).toBe("/machines"));
+ });
+
+ it("greys out the Spaces of an offline computer: they wait for it", { timeout: 30000 }, async () => {
+ on();
+ await mountApp("/spaces", host([], { offline: ["linux-box"] }));
+ await waitFor(() => expect(q('[data-tree-status="relay:linux-box/ubuntu-build"]')?.textContent).toBe("Waits for Linux box"));
+ expect(q('[data-tree-row="relay:linux-box/ubuntu-build"]')?.hasAttribute("data-dim")).toBe(true);
+ expect(document.body.textContent).toContain("Linux box is offline, so the 2 Spaces on it are too. They come back when it does.");
+ });
+
+ it("renames a Space by double-clicking its name: Enter saves, Esc cancels", { timeout: 30000 }, async () => {
+ on();
+ const calls: Call[] = [];
+ const { router } = await mountApp("/spaces", host(calls));
+ const name = await found('[data-tree-name="relay:linux-box/ubuntu-build"]');
+ doubleClick(name);
+ const input = (await found("[data-tree-rename-input]")) as HTMLInputElement;
+ expect(document.body.textContent).toContain("Renaming changes the name only.");
+ fireEvent.change(input, { target: { value: "nightly-builds" } });
+ fireEvent.keyDown(input, { key: "Escape" });
+ expect(q("[data-tree-rename-input]")).toBeNull();
+ expect(calls).toEqual([]);
+ doubleClick(q('[data-tree-name="relay:linux-box/ubuntu-build"]')!);
+ const again = (await found("[data-tree-rename-input]")) as HTMLInputElement;
+ fireEvent.change(again, { target: { value: "nightly-builds" } });
+ fireEvent.keyDown(again, { key: "Enter" });
+ await waitFor(() => expect(calls).toEqual([["spaces.rename", { spaceId: "relay:linux-box/ubuntu-build", name: "nightly-builds" }]]));
+ // The clicks that started each double-click never opened the Space.
+ await new Promise((r) => setTimeout(r, DOUBLE_CLICK_MS + 100));
+ expect(router.state.location.pathname).toBe("/spaces");
+ });
+
+ it("a single click on a name opens it once the double-click time has passed", { timeout: 30000 }, async () => {
+ on();
+ const { router } = await mountApp("/spaces", host([]));
+ fireEvent.click(await found('[data-tree-name="relay:linux-box/ubuntu-build"]'), { detail: 1 });
+ expect(router.state.location.pathname).toBe("/spaces");
+ await waitFor(() => expect(decodeURIComponent(router.state.location.pathname)).toBe("/spaces/relay:linux-box/ubuntu-build"));
+ });
+
+ it("a computer the relay calls offline is offline in the tree, and can be removed, while the machines list lags", { timeout: 30000 }, async () => {
+ on();
+ const resolved = {
+ space: "relay:this-mac",
+ reason: "fallback",
+ defaultSpace: "relay:linux-box",
+ defaultOnline: false,
+ order: [
+ { space: "relay:linux-box", name: "Linux box", online: false, role: "default" },
+ { space: "relay:this-mac", name: "This Mac", online: true, role: "here" },
+ ],
+ };
+ await mountApp("/spaces", host([], { resolved }));
+ await waitFor(() => expect(q('[data-tree-status="relay:linux-box/ubuntu-build"]')?.textContent).toBe("Waits for Linux box"));
+ fireEvent.click(await found('[data-tree-menu="relay:linux-box"]'));
+ const remove = await screen.findByRole("menuitem", { name: "Remove Linux box" });
+ expect(remove.getAttribute("aria-disabled")).not.toBe("true");
+ expect(remove.hasAttribute("data-disabled")).toBe(false);
+ });
+
+ it("removes a computer: names each Space, deletes nothing unless the box is ticked", { timeout: 40000 }, async () => {
+ on();
+ const calls: Call[] = [];
+ await mountApp("/spaces", host(calls, { offline: ["linux-box"] }));
+ const open = async () => {
+ fireEvent.click(await found('[data-tree-menu="relay:linux-box"]'));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Remove Linux box" }));
+ return found('[data-tree-remove="relay:linux-box"]');
+ };
+ let dialog = await open();
+ expect(within(dialog).getByText("Remove Linux box?")).toBeTruthy();
+ expect(q("[data-tree-remove-children]")?.textContent).toContain("ubuntu-build");
+ expect(q("[data-tree-remove-children]")?.textContent).toContain("windows-legacy");
+ expect(dialog.textContent).toContain("Nothing is deleted from Linux box. Add it again and all 2 come back.");
+ const box = q("[data-tree-also-delete]")!;
+ expect(box.getAttribute("aria-checked")).toBe("false");
+ fireEvent.click(q("[data-tree-remove-confirm]")!);
+ await waitFor(() => expect(calls.filter(([op]) => op === "machines.remove")).toHaveLength(1));
+ expect(calls.some(([op]) => op === "spaces.delete")).toBe(false);
+ expect(calls.find(([op]) => op === "machines.remove")![1]).not.toHaveProperty("deleteSpaces", true);
+
+ // Ticked: each Space is deleted through the computer first, then the computer goes with them.
+ calls.length = 0;
+ dialog = await open();
+ fireEvent.click(q("[data-tree-also-delete]")!);
+ // Ticked, it says what really happens: the Spaces leave the account, their files stay on the offline computer.
+ expect(dialog.textContent).toContain("The 2 Spaces are deleted from your account and won't come back. Their files stay on Linux box, which is offline, until you delete them there.");
+ expect(q("[data-tree-remove-confirm]")?.textContent).toBe("Remove and delete");
+ fireEvent.click(q("[data-tree-remove-confirm]")!);
+ await waitFor(() => expect(calls.map(([op]) => op)).toEqual(["spaces.delete", "spaces.delete", "machines.remove"]));
+ expect(calls.slice(0, 2).map(([, a]) => a.spaceId).sort()).toEqual(["relay:linux-box/ubuntu-build", "relay:linux-box/windows-legacy"]);
+ expect(calls[2]![1]).toMatchObject({ machine: "linux-box", deleteSpaces: true });
+ });
+});
+
+describe.skipIf(!wasmBuilt)("Home with Spaces as a tree (Labs)", () => {
+ const step = (space: string, name: string, online: boolean, role: string) => ({ space, name, online, role });
+
+ it("starts on the default Space, marked Default, with no line under the box", { timeout: 30000 }, async () => {
+ on();
+ const resolved = { space: "relay:linux-box", reason: "default", defaultSpace: "relay:linux-box", defaultOnline: true, order: [step("relay:linux-box", "Linux box", true, "default"), step("relay:this-mac", "This Mac", true, "here")] };
+ await mountApp("/home", host([], { resolved }));
+ await waitFor(() => expect(q("[data-ask-where]")?.textContent).toBe("Linux boxDefault"));
+ expect(q("[data-tree-fallback]")).toBeNull();
+ });
+
+ it("falls back to the next online computer when the default is offline, and says why", { timeout: 30000 }, async () => {
+ on();
+ const resolved = {
+ space: "relay:linux-box",
+ reason: "fallback",
+ defaultSpace: "relay:mac-mini",
+ defaultOnline: false,
+ order: [step("relay:mac-mini", "Mac mini", false, "default"), step("relay:linux-box", "Linux box", true, "fallback"), step("relay:this-mac", "This Mac", true, "here")],
+ };
+ await mountApp("/home", host([], { offline: ["mac-mini"], resolved }));
+ await waitFor(() => expect(q("[data-ask-where]")?.textContent).toBe("Linux box"));
+ const line = await found("[data-tree-fallback]");
+ expect(line.textContent).toContain("Mac mini, your default, is offline. This runs on Linux box, your next online computer. If none is online, it runs on This Mac.");
+ expect(qa("[data-tree-fallback-step]").map((s) => s.textContent)).toEqual(["1Mac miniYour default. Offline now", "2Linux boxNext online computer. Used now", "3This MacLast resort"]);
+ expect(line.textContent).toContain("A new computer is never made unless you pick one.");
+ });
+
+ it("with nothing else online runs on This Mac, and never makes a computer by itself", { timeout: 30000 }, async () => {
+ on();
+ const calls: Call[] = [];
+ const resolved = { space: null, reason: "here", defaultSpace: "relay:mac-mini", defaultOnline: false, order: [step("relay:mac-mini", "Mac mini", false, "default"), step("relay:this-mac", "This Mac", true, "here")] };
+ await mountApp("/home", host(calls, { offline: ["mac-mini", "linux-box"], resolved }));
+ await waitFor(() => expect(q("[data-ask-where]")?.textContent).toBe("This Mac"));
+ expect(q("[data-tree-fallback]")?.textContent).toContain("Mac mini, your default, is offline, and no other computer is online. This runs on This Mac.");
+ expect(q("[data-ask-where]")?.textContent).not.toMatch(/New Space/);
+ expect(calls.some(([op]) => op === "spaces.create")).toBe(false);
+ });
+
+ it("the picker lists the default first, then the tree, then New Space on each computer; Make this my default saves it", { timeout: 30000 }, async () => {
+ on();
+ const calls: Call[] = [];
+ await mountApp("/home", host(calls));
+ fireEvent.click(await found('[data-picker="where"]'));
+ await waitFor(() => expect(q("[data-tree-where]")).not.toBeNull());
+ expect(q("[data-tree-where-current]")).not.toBeNull();
+ expect(q('[data-tree-where-row="relay:linux-box/ubuntu-build"]')).not.toBeNull();
+ expect(q("[data-tree-new-here]")?.textContent).toContain("New Space on This Mac");
+ expect(q('[data-tree-new-on="linux-box"]')?.textContent).toContain("New Space on Linux box");
+ fireEvent.click(q('[data-tree-make-default="relay:linux-box"]')!);
+ await waitFor(() => expect(calls).toContainEqual(["spaces.setSettings", { defaultSpace: "relay:linux-box", fallback: [], fallbackOn: true }]));
+ });
+});
+
+describe.skipIf(!wasmBuilt)("Labs and Settings with Spaces as a tree", () => {
+ it("the Labs switch is off by default and turns on the new Home with it", { timeout: 30000 }, async () => {
+ await mountApp("/settings/advanced", host([]));
+ const sw = () => q('[data-setting-row="flag:spaces_tree"] [role=switch]')!;
+ await waitFor(() => expect(sw()).toBeTruthy());
+ expect(sw().getAttribute("aria-checked")).toBe("false");
+ expect(q('[data-setting-row="flag:spaces_tree"]')?.textContent).toContain("Spaces as a tree");
+ fireEvent.click(sw());
+ await waitFor(() => expect(sw().getAttribute("aria-checked")).toBe("true"));
+ expect(localStorage.getItem("cua.flag.spaces_tree")).toBe("1");
+ expect(localStorage.getItem("cua.flag.spaces_ask_first_home")).toBe("1");
+ });
+
+ it("General has the default Space, If it's offline and the order to try, only while the switch is on", { timeout: 30000 }, async () => {
+ const off = await mountApp("/settings/general", host([]));
+ await off.router.load();
+ await new Promise((r) => setTimeout(r, 300));
+ expect(q("[data-default-space-group]")).toBeNull();
+ cleanup();
+ on();
+ await mountApp("/settings/general", host([]));
+ const group = await found("[data-default-space-group]");
+ expect(group.textContent).toContain("Default Space");
+ expect(group.textContent).toContain("If it's offline");
+ expect(group.textContent).toContain("Order to try");
+ expect(q('[data-order-item="here"]')?.textContent).toContain("Last resort");
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
index adf0510bce..34cf856857 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
@@ -140,6 +140,9 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"machines.rename": { id: "m-studio", name: "Studio" },
"machines.remove": { machine: "m-old", device: "dev_old" },
"machines.checkHealth": {},
+ "spaces.settings": {},
+ "spaces.setSettings": { defaultSpace: "relay:mac-mini", fallback: ["relay:linux-box"], fallbackOn: true },
+ "spaces.resolveDefault": {},
"checklist.get": {},
"checklist.send": { action: { type: "done", step: "teleport" } },
"links.list": {},
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
index 8492e11241..89c8f32c31 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
@@ -16,6 +16,7 @@ import { KEYVAULT_MANAGE_ARGS } from "../ops/keyvault-manage";
import { KEYVAULT_SETUP_ARGS } from "../ops/keyvault-setup";
import { STREAM_ARGS } from "../ops/stream";
import { RELAY_USAGE_ARGS } from "../ops/relay-usage";
+import { SPACES_SETTINGS_ARGS } from "../ops/spaces-settings";
import { NUDGES_ARGS } from "../ops/nudges";
import { RESOURCES_ARGS } from "../ops/resources";
import { MACHINES_ARGS } from "../ops/machines";
@@ -174,6 +175,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {
"startup.act": { action: "allowAccess" },
...STREAM_ARGS,
...RELAY_USAGE_ARGS,
+ ...SPACES_SETTINGS_ARGS,
...NUDGES_ARGS,
...RESOURCES_ARGS,
...MACHINES_ARGS,
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index 7e41409798..5af6a1f099 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -63,6 +63,7 @@ import { demoLinksHandlers, demoLinksState, type DemoLinksState, type DemoShares
import { demoResourcesHandlers, demoResourcesState, type DemoResourcesState } from "./demo/resources";
import { demoDriverHandlers, demoDriverState, type DemoDriverState } from "./demo/driver";
import { demoRelayUsageHandlers, demoRelayUsageNamed, demoRelayUsageState, type DemoRelayUsageState } from "./demo/relay-usage";
+import { demoSpacesSettingsHandlers, demoSpacesSettingsState, type DemoSpacesSettingsState } from "./demo/spaces-settings";
import { demoStartupHandlers, demoStartupState, type DemoStartupState } from "./demo/startup";
import { createChildrenStore } from "../children";
import { createDemoChildren } from "./demo/children";
@@ -429,6 +430,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
})(),
...demoTelemetryState(),
...demoRelayUsageState(),
+ ...demoSpacesSettingsState(),
links: demoLinksState(now(), options.shares),
...demoResourcesState(options.disk ?? "healthy"),
...(options.usage ? { relayUsage: demoRelayUsageNamed(options.usage) } : {}),
@@ -757,6 +759,12 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
"machines.remove": async ({ machine, device }) => {
await wait(step / 2);
state.removed = [...state.removed, ...[machine, device].filter((x): x is string => Boolean(x))];
+ // The Spaces made on it leave the list with it: detached, or with `deleteSpaces` forgotten (the same to the list).
+ if (machine) {
+ const before = state.rows.length;
+ state.rows = state.rows.filter((r) => r.host !== machine);
+ if (state.rows.length !== before) emit({ type: "spaces.changed" });
+ }
emit({ type: "machines.changed" });
return null;
},
@@ -1056,6 +1064,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
...demoTelemetryHandlers(ctx),
...(options.noTeam ? { "teams.list": () => ({ teams: [], currentTeamId: null }) } : {}),
...demoRelayUsageHandlers(ctx),
+ ...demoSpacesSettingsHandlers(ctx, () => handlers["machines.list"]({}) as MachineRow[]),
...demoLinksHandlers(ctx),
...((): ReturnType<typeof demoThreadHandlers> => {
const h = demoThreadHandlers({ now, wait, stepMs: step, enabled: !options.noThread, role: options.threadRole ?? "owner", lookalike: options.threadLookalike ?? false, authFailed: options.threadAuthFailed ?? false, stranger: options.threadStranger ?? false, paused: options.threadPaused ?? false,
@@ -1119,7 +1128,7 @@ interface DemoLinksStateField {
links: DemoLinksState;
}
-export interface DemoState extends DemoDriverState, DemoLinksStateField, DemoTelemetryState, DemoRelayUsageState, DemoResourcesState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {
+export interface DemoState extends DemoDriverState, DemoLinksStateField, DemoTelemetryState, DemoRelayUsageState, DemoSpacesSettingsState, DemoResourcesState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {
rows: SpaceRow[];
items: KvItem[];
keyvaultLocked: boolean;
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/spaces-settings.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/spaces-settings.ts
new file mode 100644
index 0000000000..d361c12ec0
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/spaces-settings.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/** The demo host's default Space (ops/spaces-settings.ts): kept in memory,
+ * resolved over the demo's machines the way the relay resolves it. Signed
+ * out: null, as the native hosts answer. */
+
+import type { MachineRow } from "../../contracts/host";
+import { resolveDefaultSpace, type SpacesSettings } from "../../ops/spaces-settings";
+import { HostError } from "../../adapter";
+import type { DemoContext, DemoHandlers } from "./context";
+
+export interface DemoSpacesSettingsState {
+ spacesSettings: SpacesSettings;
+}
+
+export const demoSpacesSettingsState = (): DemoSpacesSettingsState => ({ spacesSettings: { defaultSpace: null, fallback: [], fallbackOn: true, updatedAt: 0 } });
+
+/** A demo machine's Space id: this Mac's own is `relay:this-mac`. */
+const spaceOf = (m: Pick<MachineRow, "id">) => `relay:${m.id}`;
+
+export function demoSpacesSettingsHandlers(
+ { state, now }: DemoContext,
+ machines: () => MachineRow[],
+): DemoHandlers<"spaces.settings" | "spaces.setSettings" | "spaces.resolveDefault"> {
+ const copy = (): SpacesSettings => ({ ...state.spacesSettings, fallback: [...state.spacesSettings.fallback] });
+ return {
+ "spaces.settings": () => (state.identity ? copy() : null),
+ "spaces.setSettings": ({ defaultSpace, fallback, fallbackOn }) => {
+ if (!state.identity) return null;
+ const ids = [defaultSpace, ...fallback].filter((x): x is string => x !== null);
+ if (ids.some((id) => !/^relay:[^/]+(\/[a-z0-9-]{1,63})?$/.test(id))) throw new HostError("That isn't a Space id.", "bad_args");
+ if (new Set(fallback).size !== fallback.length || fallback.length > 16) throw new HostError("The order to try lists a computer twice, or more than 16.", "bad_args");
+ state.spacesSettings = { defaultSpace, fallback: [...fallback], fallbackOn, updatedAt: Math.floor(now() / 1000) };
+ return copy();
+ },
+ "spaces.resolveDefault": () => {
+ if (!state.identity) return null;
+ const rows = machines().filter((m) => !m.device && m.via !== "direct");
+ return resolveDefaultSpace(
+ state.spacesSettings,
+ rows.map((m) => ({ space: spaceOf(m), name: m.name, online: m.online, here: m.current === true })),
+ );
+ },
+ };
+}
diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
index 6d894de114..23304b3163 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
@@ -62,6 +62,7 @@ import { NUDGES_OPERATIONS } from "../ops/nudges";
import { AGENT_THREADS_OPERATIONS } from "../ops/agent-threads";
import { RESOURCES_OPERATIONS } from "../ops/resources";
import { MACHINES_OPERATIONS } from "../ops/machines";
+import { SPACES_SETTINGS_OPERATIONS } from "../ops/spaces-settings";
import { CHECKLIST_OPERATIONS } from "../ops/checklist";
import { LINKS_OPERATIONS } from "../ops/links";
import { CLI_OPERATIONS } from "../ops/cli";
@@ -130,6 +131,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [
...AGENT_THREADS_OPERATIONS,
...RESOURCES_OPERATIONS,
...MACHINES_OPERATIONS,
+ ...SPACES_SETTINGS_OPERATIONS,
...CHECKLIST_OPERATIONS,
...LINKS_OPERATIONS,
...CLI_OPERATIONS,
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index ebd3337eaa..6198d92b76 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -67,6 +67,7 @@ import { startupFromHost, webkitStartupOps } from "../ops/startup";
import { webkitTelemetryNoticeOps } from "../ops/telemetry";
import { unsupportedStreamOps, type StreamTicket } from "../ops/stream";
import type { RelayUsage } from "../ops/relay-usage";
+import type { DefaultSpace, SpacesSettings } from "../ops/spaces-settings";
import type { RiskyRequest } from "../ops/nudges";
import type { ResourcesSnapshot } from "../ops/resources";
import type { HostChecklistState } from "../ops/checklist";
@@ -795,10 +796,15 @@ export function createWebkitAdapter(
await request("machines.checkHealth");
return null;
},
- "machines.remove": async ({ machine, device }) => {
- await request("machines.remove", { machine: machine ?? null, device: device ?? null });
+ "machines.remove": async ({ machine, device, deleteSpaces }) => {
+ // `deleteSpaces` only when asked: an older host never sees it.
+ await request("machines.remove", { machine: machine ?? null, device: device ?? null, ...(deleteSpaces ? { deleteSpaces: true } : {}) });
return null;
},
+ // The default Space (ops/spaces-settings.ts): the relay's own words.
+ "spaces.settings": () => request<SpacesSettings | null>("spaces.settings"),
+ "spaces.setSettings": ({ defaultSpace, fallback, fallbackOn }) => request<SpacesSettings | null>("spaces.setSettings", { defaultSpace, fallback: [...(fallback ?? [])], fallbackOn: fallbackOn ?? true }),
+ "spaces.resolveDefault": () => request<DefaultSpace | null>("spaces.resolveDefault"),
"checklist.get": () => request<{ state: HostChecklistState }>("checklist.get"),
"checklist.send": ({ action }) => request<{ state: HostChecklistState }>("checklist.send", { action }),
"links.list": () => request<{ links: ShareLink[] }>("links.list"),
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index bd26662488..099c43ba0c 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -1764,6 +1764,65 @@
"percent"
]
},
+ "DefaultSpace": {
+ "type": "object",
+ "properties": {
+ "space": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "reason": {
+ "type": "string"
+ },
+ "defaultSpace": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "defaultOnline": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "order": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "space": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "online": {
+ "type": "boolean"
+ },
+ "role": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "space",
+ "name",
+ "online",
+ "role"
+ ]
+ }
+ }
+ },
+ "required": [
+ "space",
+ "reason",
+ "defaultSpace",
+ "defaultOnline",
+ "order"
+ ]
+ },
"DevicesInput": {
"type": "object",
"properties": {
@@ -6043,6 +6102,35 @@
"role"
]
},
+ "SpacesSettings": {
+ "type": "object",
+ "properties": {
+ "defaultSpace": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "fallback": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "fallbackOn": {
+ "type": "boolean"
+ },
+ "updatedAt": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "defaultSpace",
+ "fallback",
+ "fallbackOn",
+ "updatedAt"
+ ]
+ },
"StartupState": {
"type": "object",
"properties": {
@@ -10315,6 +10403,16 @@
"spaces.rename": {
"type": "null"
},
+ "spaces.resolveDefault": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DefaultSpace"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"spaces.sendFiles": {
"type": "array",
"items": {
@@ -10363,6 +10461,26 @@
"message"
]
},
+ "spaces.setSettings": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SpacesSettings"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "spaces.settings": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SpacesSettings"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"spaces.thumbnail": {
"type": [
"object",
@@ -14389,6 +14507,16 @@
"type": "object",
"properties": {}
},
+ "spaces.resolveDefault": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DefaultSpace"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"spaces.sendFiles": {
"type": "array",
"items": {
@@ -14418,6 +14546,26 @@
"spaces.setPower": {
"$ref": "#/$defs/WkSpaces"
},
+ "spaces.setSettings": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SpacesSettings"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "spaces.settings": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SpacesSettings"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"spaces.thumbnail": {
"type": [
"object",
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index 5108848488..86f1a11b0b 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -69,6 +69,7 @@ import type { TelemetryLinkNotice } from "../ops/telemetry";
import type { SentFileInfo, SpaceThumbnail, SpaceUsage, SpaceWindows } from "../ops/space-detail";
import type { RelayUsage } from "../ops/relay-usage";
import type { DriverActivity, DriverApp, DriverLiveTest, DriverMachine, DriverPermission, DriverStatus, DriverUpdate } from "../ops/driver";
+import type { DefaultSpace, DefaultSpaceStep, SpacesSettings } from "../ops/spaces-settings";
import type { RiskyRequest } from "../ops/nudges";
import type { PastMessage, PastThread, RecentThread } from "../ops/agent-threads";
import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SharedBase, SpaceResources } from "../ops/resources";
@@ -90,6 +91,17 @@ const ref = (name: string, s: Schema) => defs.ref(name, s);
const strings = list(str);
const limits = list(object({ resource: str, used: num, limit: num, reason: str }));
const os = oneOf("macos", "windows", "linux", "unknown");
+const SpacesSettingsShape = ref("SpacesSettings", obj<SpacesSettings>()({ defaultSpace: nullable(str), fallback: strings, fallbackOn: bool, updatedAt: num }));
+const DefaultSpaceShape = ref(
+ "DefaultSpace",
+ obj<DefaultSpace>()({
+ space: nullable(str),
+ reason: str,
+ defaultSpace: nullable(str),
+ defaultOnline: nullable(bool),
+ order: list(obj<DefaultSpaceStep>()({ space: str, name: str, online: bool, role: str })),
+ }),
+);
const RecentThreadShape = ref(
"RecentThread",
obj<RecentThread>()({ agent: oneOf("claude-code", "openai-codex", "hermes"), id: str, title: str, cwd: nullable(str), lastActiveMs: num, resume: strings }),
@@ -1592,6 +1604,9 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"machines.rename": nul,
"machines.remove": nul,
"machines.checkHealth": nul,
+ "spaces.settings": nullable(SpacesSettingsShape),
+ "spaces.setSettings": nullable(SpacesSettingsShape),
+ "spaces.resolveDefault": nullable(DefaultSpaceShape),
"spaces.openStream": obj<StreamTicket>()({ wsUrl: str, expiresAt: nullable(str) }),
"nudges.pending": list(obj<RiskyRequest>()({ id: str, agent: str, action: str, atMs: num, expiresMs: num })),
"agents.recentThreads": list(RecentThreadShape),
@@ -2213,6 +2228,9 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"machines.rename": nul,
"machines.remove": nul,
"machines.checkHealth": nul,
+ "spaces.settings": OP_SHAPES["spaces.settings"],
+ "spaces.setSettings": OP_SHAPES["spaces.setSettings"],
+ "spaces.resolveDefault": OP_SHAPES["spaces.resolveDefault"],
"checklist.get": OP_SHAPES["checklist.get"],
"checklist.send": OP_SHAPES["checklist.send"],
"links.list": OP_SHAPES["links.list"],
diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.ts
index 906d421b44..1759c7be26 100644
--- a/apps/cua-spaces-web/src/bridge/coverage.ts
+++ b/apps/cua-spaces-web/src/bridge/coverage.ts
@@ -44,6 +44,7 @@ import { RELAY_USAGE_COVERAGE } from "./ops/relay-usage";
import { NUDGES_COVERAGE } from "./ops/nudges";
import { RESOURCES_COVERAGE } from "./ops/resources";
import { MACHINES_COVERAGE } from "./ops/machines";
+import { SPACES_SETTINGS_COVERAGE } from "./ops/spaces-settings";
import { CHECKLIST_COVERAGE } from "./ops/checklist";
import { CI_COVERAGE } from "./ops/ci";
import { LINKS_COVERAGE } from "./ops/links";
@@ -230,6 +231,7 @@ export const HOST_COVERAGE = {
...NUDGES_COVERAGE,
...RESOURCES_COVERAGE,
...MACHINES_COVERAGE,
+ ...SPACES_SETTINGS_COVERAGE,
...CHECKLIST_COVERAGE,
...CI_COVERAGE,
...LINKS_COVERAGE,
diff --git a/apps/cua-spaces-web/src/bridge/flags.ts b/apps/cua-spaces-web/src/bridge/flags.ts
index 6b9d84254c..03a868c0ec 100644
--- a/apps/cua-spaces-web/src/bridge/flags.ts
+++ b/apps/cua-spaces-web/src/bridge/flags.ts
@@ -31,10 +31,15 @@ import { useSyncExternalStore } from "react";
* once the first run is over. It needs that Home, so it counts only while
* `spaces_ask_first_home` is on too (Labs turns both on). Off by default:
* the first run stays as it is.
+ * - `spaces_tree`: Spaces as a tree and a default Space (CUA-3413): your
+ * computers and the Spaces made on them in one list (the sidebar and the
+ * Spaces page; Machines leaves the sidebar, its page still opens), and Home's
+ * "in" picker starts on your default Space instead of a new Linux computer.
+ * Labs turns the new Home on with it.
*/
-export type FlagName = "upsell_cards" | "spaces_ask_first_home" | "spaces_new_onboarding";
+export type FlagName = "upsell_cards" | "spaces_ask_first_home" | "spaces_new_onboarding" | "spaces_tree";
-const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false, spaces_new_onboarding: false };
+const DEFAULTS: Record<FlagName, boolean> = { upsell_cards: false, spaces_ask_first_home: false, spaces_new_onboarding: false, spaces_tree: false };
const key = (name: string) => `cua.flag.${name}`;
@@ -118,3 +123,10 @@ export function useNewOnboarding(): boolean {
const home = useFlag("spaces_ask_first_home");
return own && home;
}
+
+/** Spaces as a tree is on: its own switch and the "Ask first" Home whose picker it changes. */
+export function useSpacesTree(): boolean {
+ const own = useFlag("spaces_tree");
+ const home = useFlag("spaces_ask_first_home");
+ return own && home;
+}
diff --git a/apps/cua-spaces-web/src/bridge/hooks.ts b/apps/cua-spaces-web/src/bridge/hooks.ts
index c94adee725..ed9418a8c7 100644
--- a/apps/cua-spaces-web/src/bridge/hooks.ts
+++ b/apps/cua-spaces-web/src/bridge/hooks.ts
@@ -207,8 +207,8 @@ export interface MachinesHook extends Resource<Machine[]> {
view: MachinesView | null;
/** Renames a machine (`machines.rename`). */
rename(id: string, name: string): Promise<void>;
- /** Removes a machine from the account (`machines.remove`). */
- remove(machine: string | null, device: string | null): Promise<void>;
+ /** Removes a machine from the account (`machines.remove`); `deleteSpaces`: the relay forgets the Spaces made on it too. */
+ remove(machine: string | null, device: string | null, deleteSpaces?: boolean): Promise<void>;
/** Asks the machines for their health (`machines.checkHealth`); their
* issues show in the next view. Never throws: a check that fails shows
* on that machine. */
@@ -229,7 +229,7 @@ export function useMachines(): MachinesHook {
setupGuide,
view: ctx.store?.machinesView ?? null,
rename: (id, name) => run((s) => s.renameMachine(id, name)),
- remove: (machine, device) => run((s) => s.removeMachine(machine, device)),
+ remove: (machine, device, deleteSpaces) => run((s) => s.removeMachine(machine, device, deleteSpaces)),
// The page asks once on opening, which can be before the store is up
// (the core still loading): wait for it rather than skip the check
// until the next minute's.
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index 041504757e..5a8155d12c 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -181,6 +181,17 @@ export {
type RelayUsage,
type RelayUsageView,
} from "./relay-usage";
+export {
+ resolveDefaultSpace,
+ useSpacesDefault,
+ type DefaultCandidate,
+ type DefaultSpace,
+ type DefaultSpaceReason,
+ type DefaultSpaceStep,
+ type SpacesDefaultHook,
+ type SpacesSettings,
+ type SpacesSettingsInput,
+} from "./spaces-settings";
export { dataWords, linkEnds, needsRelaySetup, useLinks, useShareSettings, type LinksHook, type ShareSettingsHook } from "./links";
export {
@@ -268,7 +279,7 @@ export {
type UpsellPrompt,
type UpsellSurface,
} from "./upsell";
-export { flagOn, newOnboardingOn, setFlagOverride, setRemoteFlags, useFlag, useNewOnboarding, type FlagName } from "./flags";
+export { flagOn, newOnboardingOn, setFlagOverride, setRemoteFlags, useFlag, useNewOnboarding, useSpacesTree, type FlagName } from "./flags";
export type { CreateReport, ReportPart, ReportSend } from "./diagnostic-report";
export {
FIRST_RUN_POLL_MS,
diff --git a/apps/cua-spaces-web/src/bridge/ops/machines.ts b/apps/cua-spaces-web/src/bridge/ops/machines.ts
index b70bec4d0a..6b8045bb03 100644
--- a/apps/cua-spaces-web/src/bridge/ops/machines.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/machines.ts
@@ -22,7 +22,9 @@
* `machines.remove {machine, device}`: `machine` leaves the relay directory
* (`Spaces.relay_unregister("relay:<machine>")`, refused while it is
* online), then `device` is revoked. This machine's own host setup is
- * removed with `host.action {action: "remove"}`.
+ * removed with `host.action {action: "remove"}`. With `deleteSpaces: true`
+ * the relay also forgets the Spaces made on it (`?spaces=delete`); without
+ * it they are detached and come back when the computer is added again.
*
* `machines.checkHealth {}`: the host asks each machine the view names a
* `healthTarget` for (This Mac through its own daemon, another of yours
@@ -36,7 +38,9 @@ import type { OpCoverage } from "../coverage";
export interface MachinesOps {
"machines.rename": { args: { id: string; name: string }; result: null };
- "machines.remove": { args: { machine?: string | null; device?: string | null }; result: null };
+ /** `deleteSpaces`: the relay also forgets the Spaces made on it (the page deleted each one through the computer first);
+ * without it they are only detached, and come back when the computer is added again. */
+ "machines.remove": { args: { machine?: string | null; device?: string | null; deleteSpaces?: boolean }; result: null };
"machines.checkHealth": { args: Record<string, never>; result: null };
}
diff --git a/apps/cua-spaces-web/src/bridge/ops/spaces-settings.ts b/apps/cua-spaces-web/src/bridge/ops/spaces-settings.ts
new file mode 100644
index 0000000000..518d2f39a9
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/ops/spaces-settings.ts
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The account's default Space (CUA-3413): where new tasks from Home run
+ * unless you pick another, and the order to try when it's offline. The
+ * relay keeps it per account (`GET`/`PUT /v1/spaces/settings`), so the
+ * apps, the CLI, the phone and agents agree; the relay also resolves it
+ * (`GET /v1/spaces/default?here=<this machine>`), and every client uses
+ * that answer.
+ *
+ * | Operation | Electron | SwiftUI | Tauri |
+ * |---|---|---|---|
+ * | `spaces.settings` | the host method `spaces.settings` | the host method `spaces.settings` | unsupported |
+ * | `spaces.setSettings` | the host method `spaces.setSettings` | the host method `spaces.setSettings` | unsupported |
+ * | `spaces.resolveDefault` | the host method `spaces.resolveDefault` | the host method `spaces.resolveDefault` | unsupported |
+ *
+ * Both native hosts call the SDK's `Devices.spaces_settings`,
+ * `set_spaces_settings` and `resolve_default_space` from this enrolled
+ * device (the resolution fills `here` with this computer's own machine id).
+ * Null: signed out, or not enrolled. Nothing here ever creates a Space: a
+ * new computer is made only when the person picks "New Space on ...".
+ */
+
+import type { OpCoverage } from "../coverage";
+
+/** The stored setting (`cua_sdk::SpacesSettings`, camelCase). */
+export interface SpacesSettings {
+ /** A Space id (`relay:<machine>` or `relay:<machine>/<name>`), or null when unset. */
+ defaultSpace: string | null;
+ /** The order to try when the default is offline. Empty: every online computer, oldest first. */
+ fallback: string[];
+ /** False: only the default, then this computer. */
+ fallbackOn: boolean;
+ /** Unix seconds, set by the relay. */
+ updatedAt: number;
+}
+
+/** What `spaces.setSettings` takes: the whole setting (it replaces the stored one). */
+export type SpacesSettingsInput = Pick<SpacesSettings, "defaultSpace" | "fallback" | "fallbackOn">;
+
+/** One computer in the order the relay tried (`cua_sdk::DefaultSpaceStep`). */
+export interface DefaultSpaceStep {
+ space: string;
+ name: string;
+ online: boolean;
+ /** `default`, `fallback` or `here`. */
+ role: "default" | "fallback" | "here" | string;
+}
+
+/** Why `space` was chosen. */
+export type DefaultSpaceReason = "default" | "fallback" | "here" | "unset";
+
+/** The relay's resolution (`cua_sdk::DefaultSpace`, camelCase). */
+export interface DefaultSpace {
+ /** Where a new task runs; null with `here`: on this computer. */
+ space: string | null;
+ reason: DefaultSpaceReason | string;
+ defaultSpace: string | null;
+ /** Null when no default is set. */
+ defaultOnline: boolean | null;
+ order: DefaultSpaceStep[];
+}
+
+export interface SpacesSettingsOps {
+ "spaces.settings": { args: Record<string, never>; result: SpacesSettings | null };
+ "spaces.setSettings": { args: SpacesSettingsInput; result: SpacesSettings | null };
+ "spaces.resolveDefault": { args: Record<string, never>; result: DefaultSpace | null };
+}
+
+export const SPACES_SETTINGS_OPERATIONS = ["spaces.settings", "spaces.setSettings", "spaces.resolveDefault"] as const satisfies readonly (keyof SpacesSettingsOps)[];
+
+/** The native hosts' methods: the operations' own names and arguments. */
+export const SPACES_SETTINGS_WEBKIT_METHODS = SPACES_SETTINGS_OPERATIONS;
+
+const tauri = { tauri: "the Tauri app has no default Space" };
+
+export const SPACES_SETTINGS_COVERAGE = {
+ "spaces.settings": { webkit: { methods: ["spaces.settings"] }, tauri: [], unsupported: tauri },
+ "spaces.setSettings": { webkit: { methods: ["spaces.setSettings"] }, tauri: [], unsupported: tauri },
+ "spaces.resolveDefault": { webkit: { methods: ["spaces.resolveDefault"] }, tauri: [], unsupported: tauri },
+} as const satisfies Record<keyof SpacesSettingsOps, OpCoverage>;
+
+/** Arguments that take each down its usual path (coverage tests). */
+export const SPACES_SETTINGS_ARGS = {
+ "spaces.settings": {},
+ "spaces.setSettings": { defaultSpace: "relay:m-studio", fallback: [], fallbackOn: true },
+ "spaces.resolveDefault": {},
+};
+
+/** A computer the resolution may pick, in the account's order (oldest first). */
+export interface DefaultCandidate {
+ /** Its Space id (`relay:<machine>`, or a Space on one: `relay:<machine>/<name>`). */
+ space: string;
+ name: string;
+ online: boolean;
+ /** This computer (the caller's own): always last, the last resort. */
+ here?: boolean;
+}
+
+/**
+ * The relay's resolution rule (`GET /v1/spaces/default`), for a host or a
+ * demo that has no relay to ask: the default, then the fallback list
+ * (explicit, or every other computer when empty; never `here` or the
+ * default again), then this computer. The first online one wins. It never
+ * makes anything: with nothing online, the answer is this computer.
+ */
+export function resolveDefaultSpace(settings: SpacesSettingsInput | null, candidates: readonly DefaultCandidate[]): DefaultSpace {
+ const here = candidates.find((c) => c.here) ?? null;
+ const known = new Map(candidates.map((c) => [c.space, c]));
+ const def = settings?.defaultSpace ? (known.get(settings.defaultSpace) ?? null) : null;
+ const order: DefaultSpaceStep[] = [];
+ if (def && !def.here) order.push({ space: def.space, name: def.name, online: def.online, role: "default" });
+ if (!settings || settings.fallbackOn) {
+ const explicit = settings?.fallback.length ? settings.fallback.map((id) => known.get(id)).filter((c): c is DefaultCandidate => Boolean(c)) : candidates;
+ for (const c of explicit) {
+ if (c.here || c.space === def?.space || order.some((o) => o.space === c.space)) continue;
+ order.push({ space: c.space, name: c.name, online: c.online, role: "fallback" });
+ }
+ }
+ if (here) order.push({ space: here.space, name: here.name, online: true, role: "here" });
+ const first = order.find((o) => o.online && o.role !== "here");
+ const defaultSpace = settings?.defaultSpace ?? null;
+ const defaultOnline = defaultSpace === null ? null : def?.here ? true : (def?.online ?? false);
+ if (def?.here) return { space: here!.space, reason: "default", defaultSpace, defaultOnline, order };
+ if (!first) return { space: here?.space ?? null, reason: defaultSpace === null && order.length <= (here ? 1 : 0) ? "unset" : "here", defaultSpace, defaultOnline, order };
+ return { space: first.space, reason: first.role === "default" ? "default" : defaultSpace === null ? "unset" : "fallback", defaultSpace, defaultOnline, order };
+}
diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.ts
index fd391fa0f7..87f47c1d45 100644
--- a/apps/cua-spaces-web/src/bridge/protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/protocol.ts
@@ -51,6 +51,7 @@ import { RELAY_USAGE_OPERATIONS, type RelayUsageOps } from "./ops/relay-usage";
import { NUDGES_OPERATIONS, type NudgesOps } from "./ops/nudges";
import { RESOURCES_OPERATIONS, type ResourcesOps } from "./ops/resources";
import { MACHINES_OPERATIONS, type MachinesOps } from "./ops/machines";
+import { SPACES_SETTINGS_OPERATIONS, type SpacesSettingsOps } from "./ops/spaces-settings";
import { CHECKLIST_OPERATIONS, type ChecklistOps } from "./ops/checklist";
import { LINKS_OPERATIONS, type LinksOps } from "./ops/links";
import { CLI_OPERATIONS, type CliOps } from "./ops/cli";
@@ -247,6 +248,7 @@ export interface HostOperations
NudgesOps,
ResourcesOps,
MachinesOps,
+ SpacesSettingsOps,
ChecklistOps,
LinksOps,
CliOps,
@@ -552,6 +554,7 @@ export const OPERATIONS = [
...NUDGES_OPERATIONS,
...RESOURCES_OPERATIONS,
...MACHINES_OPERATIONS,
+ ...SPACES_SETTINGS_OPERATIONS,
...CHECKLIST_OPERATIONS,
...LINKS_OPERATIONS,
...CLI_OPERATIONS,
diff --git a/apps/cua-spaces-web/src/bridge/spaces-settings.ts b/apps/cua-spaces-web/src/bridge/spaces-settings.ts
new file mode 100644
index 0000000000..40115ceb46
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/spaces-settings.ts
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The account's default Space (`spaces.settings`, `spaces.resolveDefault`,
+ * ops/spaces-settings.ts), read while a screen shows it: at once, when a
+ * computer or a Space changes (one may have gone offline), when the account
+ * changes, and after a change made here. A host without the operations, or
+ * signed out, reads as null: the screens fall back to the tree's own order
+ * (`lib/spaces-tree.ts`).
+ */
+
+import { useContext, useSyncExternalStore } from "react";
+
+import { isUnsupported, type DataAdapter } from "./adapter";
+import { BridgeContext } from "./BridgeProvider";
+import type { DefaultSpace, SpacesSettings, SpacesSettingsInput } from "./ops/spaces-settings";
+
+export type { DefaultCandidate, DefaultSpace, DefaultSpaceReason, DefaultSpaceStep, SpacesSettings, SpacesSettingsInput } from "./ops/spaces-settings";
+export { resolveDefaultSpace } from "./ops/spaces-settings";
+
+export interface SpacesDefaultSnapshot {
+ settings: SpacesSettings | null;
+ resolved: DefaultSpace | null;
+ /** The first read answered (or failed). */
+ loaded: boolean;
+ /** This host has no default Space. */
+ unsupported: boolean;
+}
+
+const EMPTY: SpacesDefaultSnapshot = { settings: null, resolved: null, loaded: false, unsupported: false };
+
+class SpacesDefaultStore {
+ snap: SpacesDefaultSnapshot = EMPTY;
+ private listeners = new Set<() => void>();
+ private stop: (() => void) | null = null;
+ private generation = 0;
+
+ constructor(private readonly adapter: DataAdapter) {}
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.listeners.add(listener);
+ if (this.listeners.size === 1) this.start();
+ return () => {
+ this.listeners.delete(listener);
+ if (this.listeners.size === 0) {
+ this.stop?.();
+ this.stop = null;
+ }
+ };
+ };
+
+ snapshot = (): SpacesDefaultSnapshot => this.snap;
+
+ async read(): Promise<void> {
+ if (this.snap.unsupported) return;
+ const generation = ++this.generation;
+ try {
+ const [settings, resolved] = await Promise.all([this.adapter.call("spaces.settings", {}), this.adapter.call("spaces.resolveDefault", {})]);
+ if (generation === this.generation) this.set({ settings, resolved, loaded: true, unsupported: false });
+ } catch (e) {
+ if (generation !== this.generation) return;
+ // Unsupported: never again. Anything else keeps the last answer.
+ this.set(isUnsupported(e) ? { ...EMPTY, loaded: true, unsupported: true } : { ...this.snap, loaded: true });
+ }
+ }
+
+ /** Replaces the setting, then reads the resolution again. */
+ async save(next: SpacesSettingsInput): Promise<void> {
+ const saved = await this.adapter.call("spaces.setSettings", { defaultSpace: next.defaultSpace, fallback: [...next.fallback], fallbackOn: next.fallbackOn });
+ this.set({ ...this.snap, settings: saved });
+ await this.read();
+ }
+
+ private set(snap: SpacesDefaultSnapshot) {
+ this.snap = snap;
+ for (const l of [...this.listeners]) l();
+ }
+
+ private start() {
+ void this.read();
+ const unsubscribe = this.adapter.subscribe((e) => {
+ if (e.type === "machines.changed" || e.type === "spaces.changed" || e.type === "session.signedIn" || e.type === "session.signedOut" || e.type === "session.changed") {
+ void this.read();
+ }
+ });
+ this.stop = unsubscribe;
+ }
+}
+
+const stores = new WeakMap<DataAdapter, SpacesDefaultStore>();
+
+function storeFor(adapter: DataAdapter): SpacesDefaultStore {
+ let s = stores.get(adapter);
+ if (!s) stores.set(adapter, (s = new SpacesDefaultStore(adapter)));
+ return s;
+}
+
+const none = () => () => {};
+const empty = () => EMPTY;
+
+export interface SpacesDefaultHook extends SpacesDefaultSnapshot {
+ /** Replaces the whole setting (the relay keeps it for the account). */
+ save(next: SpacesSettingsInput): Promise<void>;
+ /** "Make this my default": only the default changes. */
+ makeDefault(space: string): Promise<void>;
+ refresh(): Promise<void>;
+}
+
+/** The default Space and where a new task goes now. `enabled` false reads nothing (the Labs switch is off). */
+export function useSpacesDefault(enabled = true): SpacesDefaultHook {
+ const adapter = useContext(BridgeContext)?.adapter ?? null;
+ const store = enabled && adapter ? storeFor(adapter) : null;
+ const snap = useSyncExternalStore(store?.subscribe ?? none, store?.snapshot ?? empty, empty);
+ const settings = snap.settings;
+ return {
+ ...snap,
+ save: async (next) => {
+ if (!store) throw new Error("Not connected.");
+ await store.save(next);
+ },
+ makeDefault: async (space) => {
+ if (!store) throw new Error("Not connected.");
+ // The fallback order stays; the new default leaves it (it is tried first anyway).
+ const fallback = (settings?.fallback ?? []).filter((id) => id !== space);
+ await store.save({ defaultSpace: space, fallback, fallbackOn: settings?.fallbackOn ?? true });
+ },
+ refresh: async () => {
+ await store?.read();
+ },
+ };
+}
diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.ts
index 2088892313..439331f4f0 100644
--- a/apps/cua-spaces-web/src/bridge/store.ts
+++ b/apps/cua-spaces-web/src/bridge/store.ts
@@ -413,9 +413,10 @@ export class BridgeStore {
}
/** Removes a machine from the account (`machines.remove`), then lists
- * the Spaces and machines again. */
- async removeMachine(machine: string | null, device: string | null): Promise<void> {
- await this.adapter.call("machines.remove", { machine, device });
+ * the Spaces and machines again. `deleteSpaces`: the relay forgets the
+ * Spaces made on it too (else they are detached). */
+ async removeMachine(machine: string | null, device: string | null, deleteSpaces = false): Promise<void> {
+ await this.adapter.call("machines.remove", deleteSpaces ? { machine, device, deleteSpaces } : { machine, device });
await this.refresh("spaces");
await this.refresh("machines");
}
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index 1203eda126..1a5c0e59fc 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -39,6 +39,7 @@ import { KEYVAULT_MANAGE_WEBKIT_METHODS } from "./ops/keyvault-manage";
import { KEYVAULT_SETUP_WEBKIT_METHODS } from "./ops/keyvault-setup";
import { THREAD_WEBKIT_METHODS } from "./ops/thread";
import { AGENT_THREADS_WEBKIT_METHODS } from "./ops/agent-threads";
+import { SPACES_SETTINGS_WEBKIT_METHODS } from "./ops/spaces-settings";
export const WEBKIT_HANDLER_NAME = "cua";
/** The window event the host dispatches. */
@@ -211,6 +212,7 @@ export const WEBKIT_METHODS = [
"machines.rename",
"machines.remove",
"machines.checkHealth",
+ ...SPACES_SETTINGS_WEBKIT_METHODS,
"checklist.get",
"checklist.send",
"links.list",
diff --git a/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx b/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx
index b43c958c48..56b0aecd7a 100644
--- a/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx
+++ b/apps/cua-spaces-web/src/components/ask-first/ask-box.tsx
@@ -15,6 +15,8 @@ import { cn } from "@/lib/utils";
import { AgentPicker, type AccountActions } from "./agent-picker";
import { RepoChip } from "./repo-chip";
+import { TreeWherePicker, whereNode, type TreeWhere } from "./tree-where";
+import { TreeIcon } from "@/components/spaces/tree-parts";
export type { TaskWhere } from "@/lib/ask-first";
@@ -26,7 +28,7 @@ const OS_WORD: Record<SpaceOs, string> = { linux: "Linux", macos: "Mac", windows
export function whereSpaceLabel(where: TaskWhere): { title: string; detail: string | null } {
if (where.kind === "agent") return { title: where.fresh ? "Agent decides, new Home" : "Agent decides", detail: null };
if (where.kind === "machine") return { title: where.machine.name, detail: null };
- if (where.kind === "new") return { title: "New Space", detail: `${OS_WORD[where.os]} on This Mac` };
+ if (where.kind === "new") return { title: "New Space", detail: `${OS_WORD[where.os]} on ${where.on?.name ?? "This Mac"}` };
return { title: where.kind === "this-mac" ? "This Mac" : where.space.name, detail: null };
}
@@ -131,6 +133,7 @@ export function AskBox({
onSubmit,
compact,
autoFocus,
+ tree = null,
}: {
text: string;
onText: (t: string) => void;
@@ -167,8 +170,11 @@ export function AskBox({
onSubmit: () => void;
compact?: boolean;
autoFocus?: boolean;
+ /** Spaces as a tree (Labs): the tree picker, starting on your default Space. */
+ tree?: TreeWhere | null;
}) {
const ref = useRef<HTMLTextAreaElement>(null);
+ const treeNode = tree ? whereNode(tree.tree, where) : undefined;
useEffect(() => {
if (autoFocus) ref.current?.focus();
}, [autoFocus]);
@@ -211,9 +217,12 @@ export function AskBox({
onOpenChange={onWhereOpen}
kinds={kinds}
spaces={spaces}
+ tree={tree}
trigger={
<button type="button" className={whereButton} data-picker="where">
- {where.kind === "new" ? (
+ {treeNode ? (
+ <TreeIcon node={treeNode} />
+ ) : where.kind === "new" ? (
<OsIcon os={where.os} className="size-3.5" />
) : where.kind === "this-mac" ? (
<LaptopIcon className="size-3.5" />
@@ -221,8 +230,13 @@ export function AskBox({
<MonitorIcon className="size-3.5" />
)}
<span className="max-w-64 truncate" data-ask-where="">
- {label.title}
- {label.detail ? <span className="ml-1.5 text-muted-foreground">{label.detail}</span> : null}
+ {treeNode?.name ?? label.title}
+ {treeNode ? null : label.detail ? <span className="ml-1.5 text-muted-foreground">{label.detail}</span> : null}
+ {treeNode?.isDefault ? (
+ <span className="ml-2 text-[13px] text-muted-foreground" data-ask-where-default="">
+ Default
+ </span>
+ ) : null}
</span>
<ChevronDownIcon className="size-3.5 text-muted-foreground" />
</button>
@@ -283,6 +297,7 @@ export function WherePicker({
trigger,
open,
onOpenChange,
+ tree = null,
}: {
where: TaskWhere | null;
onWhere: (w: TaskWhere) => void;
@@ -297,7 +312,10 @@ export function WherePicker({
trigger: ReactElement;
open?: boolean;
onOpenChange?: (open: boolean) => void;
+ /** Spaces as a tree (Labs): the tree in place of this list. */
+ tree?: TreeWhere | null;
}) {
+ if (tree) return <TreeWherePicker tw={tree} where={where} onWhere={onWhere} kinds={kinds} trigger={trigger} open={open} onOpenChange={onOpenChange} />;
return (
<Picker title="Where it runs" trigger={trigger} footer={agentHome ? `${WHERE_FOOTER} ${WHERE_FOOTER_HOME}` : WHERE_FOOTER} open={open} onOpenChange={onOpenChange}>
{agentHome ? (
diff --git a/apps/cua-spaces-web/src/components/ask-first/home.tsx b/apps/cua-spaces-web/src/components/ask-first/home.tsx
index 676518e832..7cd48222cc 100644
--- a/apps/cua-spaces-web/src/components/ask-first/home.tsx
+++ b/apps/cua-spaces-web/src/components/ask-first/home.tsx
@@ -11,7 +11,7 @@ import { useAgentAttempts } from "@/hooks/use-agent-attempts";
import { useAgentMenu } from "@/hooks/use-agent-menu";
import { useConnectors } from "@/hooks/use-connectors";
import { OsIcon } from "@/components/os-icon";
-import { currentWhere, SUGGESTIONS, useAskTasks, type AskTask, type TaskState } from "@/lib/ask-first";
+import { currentWhere, SUGGESTIONS, thisMacConfirmed, useAskTasks, type AskTask, type TaskState } from "@/lib/ask-first";
import { pickAccount, pickOf, rememberAgent, resolveAgent, usePickedAgent } from "@/lib/ask-first-model";
import { reusableHome } from "@/lib/agent-home/home-space";
import { useRepos } from "@/lib/ask-first-repo";
@@ -28,6 +28,8 @@ import { YourAgents, YourSpaces as YourSpacesRow } from "./home-sections";
import { useWherePick } from "./this-mac-confirm";
import { useStartTask } from "./use-start-task";
import { useWhereOptions } from "./where-options";
+import { FallbackLine, useTreeWhere } from "./tree-where";
+import { currentTreeWhere } from "@/lib/default-where";
import { PrepareLine } from "@/components/prepare/prepare-line";
import { usePrepareAction } from "@/components/prepare/use-prepare-action";
import { usePrepare } from "@/lib/prepare/store";
@@ -87,9 +89,18 @@ export function AskFirstHome() {
const onPrepareAction = usePrepareAction();
const [whereOpen, setWhereOpen] = useState(false);
const pick = useWherePick(agentName(chosenAgent));
- const where = currentWhere(pickedWhere ?? (agentHome ? { kind: "agent" } : null), kinds, pickable);
+ // Spaces as a tree (Labs): your default Space unless you pick, or the next online computer; never a new one.
+ // With agent homes the agent decides where, so the tree's default doesn't apply.
+ const treeWhere = useTreeWhere();
+ const tw = agentHome ? null : treeWhere;
+ const where = tw ? currentTreeWhere(pickedWhere, tw.def.where, kinds, tw.tree) : currentWhere(pickedWhere ?? (agentHome ? { kind: "agent" } : null), kinds, pickable);
const submit = (prompt = text, w = where) => {
if (!prompt.trim() || !selected) return;
+ // The default can be This Mac itself: it asks once, as picking it does.
+ if (tw && w.kind === "this-mac" && !thisMacConfirmed()) {
+ pick.choose(w, (ok) => submit(prompt, ok), () => setWhereOpen(true));
+ return;
+ }
// The run uses the app's own choice of account: make it the one shown.
if (!selected.account.selected) void connectors.useCredential(selected.group.app, { env: selected.account.env, slot: selected.account.slot });
start({ prompt, agent: chosenAgent, where: w, model: selected.model.id, repo });
@@ -106,6 +117,7 @@ export function AskFirstHome() {
// Another sign-in or key beside the others: Claude Code's takes a token, the others the key of their provider.
onAdd: (g, name, value) => keys.save(g.accounts[0]?.provider ?? (g.app === "claude-code" ? "anthropic" : g.app === "codex" ? "openai" : "anthropic"), value, null, {}, { add: true, ...(name ? { label: name } : {}) }),
};
+ const fallback = tw && pickedWhere === null ? tw.def.fallback : null;
// Home lists agents and Spaces, not tasks: with neither (a first run,
// or tasks whose Spaces are gone), Home is the welcome again.
@@ -144,8 +156,10 @@ export function AskFirstHome() {
onSubmit={() => submit()}
compact={!first}
autoFocus
+ tree={tw}
/>
<AgentStatus state={agentHome ? readiness : "none"} onReconnect={() => selected && void connectors.connectApp(selected.group.app)} />
+ {fallback ? <FallbackLine fallback={fallback} /> : null}
{/* Preparing is silent: only a failed prepare says so, with Try again. */}
<PrepareLine view={prep.view} onRetry={onPrepareAction} />
{first ? (
diff --git a/apps/cua-spaces-web/src/components/ask-first/task-view.tsx b/apps/cua-spaces-web/src/components/ask-first/task-view.tsx
index 016f0f528d..03b0d4e3cc 100644
--- a/apps/cua-spaces-web/src/components/ask-first/task-view.tsx
+++ b/apps/cua-spaces-web/src/components/ask-first/task-view.tsx
@@ -24,6 +24,7 @@ import { StateDot, taskRun } from "./home";
import { useWherePick } from "./this-mac-confirm";
import { useStartTask } from "./use-start-task";
import { useWhereOptions } from "./where-options";
+import { useTreeWhere } from "./tree-where";
/** What the agent is told when the person hands the computer back. */
/** How long a sent reply may take to show in the run before the thread trusts the run's status again (ms). */
@@ -302,6 +303,7 @@ export function StartFailed({ error, name, agent, host, onRetry }: { error: stri
if (outcome === "connected") onRetry();
};
const { kinds, spaces } = useWhereOptions();
+ const tree = useTreeWhere();
const [open, setOpen] = useState(false);
const pick = useWherePick(name);
return (
@@ -335,6 +337,7 @@ export function StartFailed({ error, name, agent, host, onRetry }: { error: stri
onOpenChange={setOpen}
kinds={kinds}
spaces={spaces}
+ tree={tree}
trigger={
<Button variant={view.action === "change-computer" ? "default" : "outline"} className="h-10 px-4" data-ask-change-computer="">
Change computer <ChevronDownIcon />
diff --git a/apps/cua-spaces-web/src/components/ask-first/tree-where.tsx b/apps/cua-spaces-web/src/components/ask-first/tree-where.tsx
new file mode 100644
index 0000000000..fb70d293ff
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/ask-first/tree-where.tsx
@@ -0,0 +1,258 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { Menu as MenuPrimitive } from "@base-ui/react/menu";
+import { CheckIcon, PlusIcon } from "lucide-react";
+import { useMemo, type ReactElement, type ReactNode } from "react";
+
+import type { SpaceOs } from "@/bridge";
+import { TreeDot, TreeIcon } from "@/components/spaces/tree-parts";
+import { useRunningBySpace, useSpacesTreeData } from "@/components/spaces/use-spaces-tree";
+import { toastError } from "@/components/ui/toast";
+import type { NewKind, TaskWhere } from "@/lib/ask-first";
+import { newSpaceTargets, nodeWhere, treeDefault, type TreeDefault } from "@/lib/default-where";
+import { findNode, treeRows, type SpacesTree, type TreeNode } from "@/lib/spaces-tree";
+import { cn } from "@/lib/utils";
+
+const OS_WORD: Record<SpaceOs, string> = { linux: "Linux", macos: "Mac", windows: "Windows", unknown: "" };
+
+/** The picker's closing line: nothing is made without being picked. */
+export const NEVER_MADE = "A new computer is never made unless you pick one.";
+
+export interface TreeWhere {
+ tree: SpacesTree;
+ /** Where a task goes unless you pick (the default, or the next online computer). */
+ def: TreeDefault;
+ makeDefault: ((settingsId: string) => void) | null;
+}
+
+/** Home's "in" with Spaces as a tree (Labs): the tree and its default; null while the switch is off or the lists load. */
+export function useTreeWhere(): TreeWhere | null {
+ const running = useRunningBySpace();
+ const { on, tree, defaults } = useSpacesTreeData(running);
+ const { settings, resolved, unsupported } = defaults;
+ const def = useMemo(() => (tree ? treeDefault(tree, settings, resolved) : null), [tree, settings, resolved]);
+ if (!on || !tree || !def) return null;
+ return {
+ tree,
+ def,
+ makeDefault: unsupported ? null : (id) => void defaults.makeDefault(id).catch(toastError("Couldn't change your default Space")),
+ };
+}
+
+/** The row a choice is, when it is one of the tree's. */
+export function whereNode(tree: SpacesTree, where: TaskWhere | null): TreeNode | undefined {
+ if (!where) return undefined;
+ if (where.kind === "this-mac") return tree.roots.find((r) => r.current);
+ if (where.kind === "space") return findNode(tree, where.space.id);
+ return undefined;
+}
+
+function agentsLine(n: Pick<TreeNode, "running">): string | null {
+ return n.running === 0 ? null : n.running === 1 ? "1 agent working" : `${n.running} agents working`;
+}
+
+/** A row's second line in the picker. */
+export function pickerNote(n: TreeNode): string {
+ if (!n.online) return n.status.replace(/, Default$/, "");
+ const agents = agentsLine(n);
+ if (n.current) return agents ?? "Works on your own files and apps";
+ if (n.kind === "computer" && n.people.length > 1) return agents ? `Shared with your team. ${agents}` : "Shared with your team";
+ return agents ?? "On now";
+}
+
+function Row({
+ icon,
+ title,
+ note,
+ dot,
+ selected,
+ disabled,
+ trailing,
+ indent,
+ onSelect,
+ attrs,
+}: {
+ icon: ReactNode;
+ title: string;
+ note?: string | null;
+ dot?: ReactNode;
+ selected?: boolean;
+ disabled?: boolean;
+ trailing?: ReactNode;
+ indent?: boolean;
+ onSelect: () => void;
+ attrs?: Record<`data-${string}`, string>;
+}) {
+ return (
+ <MenuPrimitive.Item
+ onClick={onSelect}
+ disabled={disabled}
+ {...attrs}
+ className={cn(
+ "group/row flex min-h-11 cursor-default items-center gap-3 rounded-lg px-3 py-1.5 outline-none data-disabled:opacity-50 data-highlighted:bg-foreground/[0.06]",
+ selected && "bg-foreground/[0.06]",
+ indent && "pl-9",
+ )}
+ >
+ {icon}
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2 text-[14px] font-medium">
+ <span className="truncate">{title}</span>
+ {dot}
+ </div>
+ {note ? <div className="truncate text-[12px] text-muted-foreground">{note}</div> : null}
+ </div>
+ {trailing}
+ {selected ? <CheckIcon className="size-4 shrink-0" /> : null}
+ </MenuPrimitive.Item>
+ );
+}
+
+/**
+ * "Where it runs" as a tree (f1): what's picked first, then your Spaces under
+ * the computers they're on, each with "Default" or "Make this my default",
+ * then "New Space on ..." (the only rows that make a computer).
+ */
+export function TreeWherePicker({
+ tw,
+ where,
+ onWhere,
+ kinds,
+ trigger,
+ open,
+ onOpenChange,
+}: {
+ tw: TreeWhere;
+ where: TaskWhere | null;
+ onWhere: (w: TaskWhere) => void;
+ kinds: NewKind[];
+ trigger: ReactElement;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+}) {
+ const { tree, def, makeDefault } = tw;
+ const chosen = whereNode(tree, where);
+ const rows = treeRows(tree);
+ const okKinds = kinds.filter((k) => !k.blocked);
+ const head = chosen ?? (where?.kind === "new" ? null : def.node);
+ return (
+ <MenuPrimitive.Root {...(open === undefined ? {} : { open })} onOpenChange={(o) => onOpenChange?.(o)}>
+ <MenuPrimitive.Trigger render={trigger} />
+ <MenuPrimitive.Portal>
+ <MenuPrimitive.Positioner sideOffset={6} align="start" className="z-50 outline-none">
+ {/* design-ok: a pop-up menu's edge, as the other pickers' */}
+ <MenuPrimitive.Popup data-tree-where="" className="glass max-h-[min(640px,80vh)] w-[480px] origin-(--transform-origin) overflow-y-auto rounded-lg border p-2 text-popover-foreground shadow-float outline-none transition-[opacity,scale] data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0"
+ >
+ <p className="px-3 pt-2 pb-1 text-[12px] font-medium text-muted-foreground">Where it runs</p>
+ {head ? (
+ <Row
+ icon={<TreeIcon node={head} />}
+ title={head.name}
+ dot={<TreeDot tone={head.tone} />}
+ note={head.isDefault ? `Default. ${head.online ? "Online" : "Offline"}${agentsLine(head) ? `, ${agentsLine(head)}` : ""}` : pickerNote(head)}
+ selected
+ onSelect={() => {
+ const w = nodeWhere(head);
+ if (w) onWhere(w);
+ }}
+ attrs={{ "data-tree-where-current": head.key }}
+ />
+ ) : null}
+ <p className="px-3 pt-4 pb-1 text-[12px] font-medium text-muted-foreground">Your Spaces</p>
+ {rows.map((n) => {
+ const w = nodeWhere(n);
+ return (
+ <Row
+ key={n.key}
+ icon={<TreeIcon node={n} className={cn(n.dim && "opacity-50")} />}
+ title={n.name}
+ dot={<TreeDot tone={n.tone} />}
+ note={n.kind === "space" && n.online ? agentsLine(n) : pickerNote(n)}
+ indent={n.parentKey !== null}
+ disabled={!w || !n.online}
+ onSelect={() => w && onWhere(w)}
+ attrs={{ "data-tree-where-row": n.key }}
+ trailing={
+ n.isDefault ? (
+ <span data-tree-default="" className="shrink-0 text-[12px] text-muted-foreground">
+ Default
+ </span>
+ ) : n.settingsId && makeDefault ? (
+ <button
+ type="button"
+ data-tree-make-default={n.settingsId}
+ className="shrink-0 text-[12px] text-brand-strong opacity-0 group-data-highlighted/row:opacity-100 hover:underline focus-visible:opacity-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ makeDefault(n.settingsId!);
+ }}
+ >
+ Make this my default
+ </button>
+ ) : null
+ }
+ />
+ );
+ })}
+ <div className="h-3" aria-hidden />
+ {newSpaceTargets(tree).flatMap((t) =>
+ t.on
+ ? [
+ <Row
+ key={t.key}
+ icon={<PlusIcon className="size-4 text-muted-foreground" />}
+ title={`New Space on ${t.name}`}
+ note="A Linux computer, made fresh"
+ selected={where?.kind === "new" && where.on?.machine === t.on.machine}
+ onSelect={() => onWhere({ kind: "new", os: "linux", on: t.on! })}
+ attrs={{ "data-tree-new-on": t.on.machine }}
+ />,
+ ]
+ : okKinds.map((k) => (
+ <Row
+ key={`${t.key}:${k.os}`}
+ icon={<PlusIcon className="size-4 text-muted-foreground" />}
+ title={`New Space on ${t.name}`}
+ note={`A ${OS_WORD[k.os]} computer, made fresh. ${k.note}`}
+ selected={where?.kind === "new" && !where.on && where.os === k.os}
+ onSelect={() => onWhere({ kind: "new", os: k.os })}
+ attrs={{ "data-tree-new-here": k.os }}
+ />
+ )),
+ )}
+ {/* design-ok: the menu's footer rule, as the other pickers' */}
+ <div className="mt-1 border-t px-3 pt-2 pb-1 text-[12px] text-muted-foreground">{NEVER_MADE}</div>
+ </MenuPrimitive.Popup>
+ </MenuPrimitive.Positioner>
+ </MenuPrimitive.Portal>
+ </MenuPrimitive.Root>
+ );
+}
+
+/** f2: the default is offline. One line says why, then the order tried. */
+export function FallbackLine({ fallback }: { fallback: NonNullable<TreeDefault["fallback"]> }) {
+ return (
+ <div data-tree-fallback="" className="flex flex-col gap-3 text-[14px]">
+ <p className="flex items-start gap-2 text-muted-foreground">
+ <span className="mt-2 size-1.5 shrink-0 rounded-full bg-muted-foreground/50" aria-hidden />
+ {fallback.line}
+ </p>
+ <div>
+ <p className="mb-2 text-[13px] text-muted-foreground">Where a task goes</p>
+ <ol className="flex flex-col gap-2">
+ {fallback.steps.map((s, i) => (
+ <li key={`${s.name}:${i}`} className="flex items-center gap-3" data-tree-fallback-step={s.used ? "used" : s.online ? "online" : "offline"}>
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-foreground/[0.06] text-[12px] text-muted-foreground">{i + 1}</span>
+ {s.node ? <TreeIcon node={s.node} /> : null}
+ <span className={cn(!s.online && "text-muted-foreground")}>{s.name}</span>
+ <span className="text-[13px] text-muted-foreground">{s.note}</span>
+ </li>
+ ))}
+ </ol>
+ </div>
+ <p className="text-[13px] text-muted-foreground">{NEVER_MADE}</p>
+ </div>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts b/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts
index 2048d9e731..a4ff25da0b 100644
--- a/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts
+++ b/apps/cua-spaces-web/src/components/ask-first/use-start-task.ts
@@ -132,7 +132,9 @@ export function useStartTask(): {
rememberHome(agent, space.id);
} else {
const offer = offers.find((o) => o.os === os);
- space = await createSpace(offer ? { ...offer.args, os } : { os }, pendingId);
+ // "New Space on <computer>": made on that computer (`host:<machine>`), never silently.
+ const on = target.kind === "create" && target.on ? { on: target.on } : {};
+ space = await createSpace(offer ? { ...offer.args, os, ...on } : { os, ...on }, pendingId);
}
spaceId = space.id;
updateAskTask(id, { spaceId, pendingId: null });
diff --git a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
index ad60396016..0875a58bbb 100644
--- a/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
+++ b/apps/cua-spaces-web/src/components/settings/advanced-tab.tsx
@@ -149,6 +149,7 @@ function Labs() {
const { data, chooseExperiment } = useExperiments();
const askFirst = useFlag("spaces_ask_first_home");
const newSetup = useFlag("spaces_new_onboarding");
+ const tree = useFlag("spaces_tree");
const thisMacOk = useThisMacConfirmed();
const rows = (data?.page?.sections.flatMap((s) => s.rows) ?? []).filter((r) => LABS.has(r.id));
const note: Record<string, string> = {
@@ -176,6 +177,14 @@ function Labs() {
if (option === "on") setFlagOverride("spaces_ask_first_home", true);
}}
/>
+ <CoreSettingsRow
+ row={flagRow("spaces_tree", "Spaces as a tree", tree && askFirst)}
+ description="Your computers and the Spaces made on them in one list. New tasks run on your default Space. Turns on the new Home too. On this device only."
+ onChoose={(_, option) => {
+ setFlagOverride("spaces_tree", option === "on");
+ if (option === "on") setFlagOverride("spaces_ask_first_home", true);
+ }}
+ />
{askFirst ? (
<CoreSettingsRow
row={thisMacAskRow(!thisMacOk)}
diff --git a/apps/cua-spaces-web/src/components/settings/default-space-group.tsx b/apps/cua-spaces-web/src/components/settings/default-space-group.tsx
new file mode 100644
index 0000000000..646ba23cc7
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/settings/default-space-group.tsx
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { GripVerticalIcon } from "lucide-react";
+import { useState, type DragEvent, type KeyboardEvent } from "react";
+
+import type { SpacesSettings } from "@/bridge";
+import { SettingsGroup, SettingsRow } from "@/components/settings-group";
+import { TreeIcon } from "@/components/spaces/tree-parts";
+import { useSpacesTreeData } from "@/components/spaces/use-spaces-tree";
+import { NEVER_MADE } from "@/components/ask-first/tree-where";
+import { Select } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { toastError } from "@/components/ui/toast";
+import { findNode, treeRows, type SpacesTree, type TreeNode } from "@/lib/spaces-tree";
+import { cn } from "@/lib/utils";
+
+/**
+ * The order to try when the default is offline: the saved one (computers
+ * still listed), else every other computer in the account's order. This
+ * Mac is never in it: it's always the last resort.
+ */
+export function orderToTry(tree: SpacesTree, settings: Pick<SpacesSettings, "fallback"> | null, defaultKey: string | null): TreeNode[] {
+ const def = findNode(tree, defaultKey);
+ const usable = (n: TreeNode | undefined): n is TreeNode => Boolean(n?.settingsId) && !n!.current && n!.key !== def?.key;
+ if (settings?.fallback.length) return settings.fallback.map((id) => findNode(tree, id)).filter(usable);
+ return tree.roots.filter((r) => r.kind === "computer").filter(usable);
+}
+
+/** Moves the item at `from` to `to`. */
+export function moved<T>(list: readonly T[], from: number, to: number): T[] {
+ const next = [...list];
+ const [item] = next.splice(from, 1);
+ next.splice(Math.max(0, Math.min(to, next.length)), 0, item!);
+ return next;
+}
+
+/**
+ * Settings, General (Labs "Spaces as a tree", f3): where new agent tasks run.
+ * The same setting as "Make this my default" in Home's picker; the relay
+ * keeps it for the account, so every computer and the CLI agree.
+ */
+export function DefaultSpaceGroup() {
+ const { on, tree, defaults } = useSpacesTreeData();
+ const [dragging, setDragging] = useState<number | null>(null);
+ if (!on || !tree || defaults.unsupported || tree.roots.length === 0) return null;
+ const settings = defaults.settings;
+ const defaultKey = settings?.defaultSpace ?? tree.defaultKey;
+ const choices = treeRows(tree).filter((n) => n.settingsId);
+ const parentName = (n: TreeNode) => (n.parentKey ? findNode(tree, n.parentKey)?.name : null);
+ const value = findNode(tree, defaultKey)?.settingsId ?? choices[0]?.settingsId ?? "";
+ const fallbackOn = settings?.fallbackOn ?? true;
+ const order = orderToTry(tree, settings, defaultKey);
+ const here = tree.roots.find((r) => r.current);
+ const fail = toastError("Couldn't change where tasks run");
+ const save = (patch: Partial<Pick<SpacesSettings, "defaultSpace" | "fallback" | "fallbackOn">>) =>
+ void defaults
+ .save({ defaultSpace: patch.defaultSpace !== undefined ? patch.defaultSpace : (settings?.defaultSpace ?? null), fallback: patch.fallback ?? settings?.fallback ?? [], fallbackOn: patch.fallbackOn ?? fallbackOn })
+ .catch(fail);
+ const reorder = (from: number, to: number) => {
+ if (from === to) return;
+ save({ fallback: moved(order, from, to).map((n) => n.settingsId!) });
+ };
+ const onKey = (i: number) => (e: KeyboardEvent<HTMLLIElement>) => {
+ if (e.key === "ArrowUp" && i > 0) reorder(i, i - 1);
+ else if (e.key === "ArrowDown" && i < order.length - 1) reorder(i, i + 1);
+ else return;
+ e.preventDefault();
+ };
+ return (
+ <SettingsGroup title="Where new agent tasks run" footer={NEVER_MADE} data-default-space-group="">
+ <SettingsRow
+ label="Default Space"
+ description="New tasks from Home run here unless you pick another."
+ control={
+ <Select
+ aria-label="Default Space"
+ className="min-w-56"
+ value={value}
+ options={choices.map((n) => ({ value: n.settingsId!, label: parentName(n) ? `${n.name}, on ${parentName(n)}` : n.name }))}
+ onValueChange={(v) => save({ defaultSpace: v, fallback: (settings?.fallback ?? []).filter((id) => id !== v) })}
+ />
+ }
+ />
+ <SettingsRow
+ label="If it's offline"
+ description="Use your next online computer, then This Mac."
+ control={<Switch aria-label="If it's offline, use your next online computer" checked={fallbackOn} onCheckedChange={(v) => save({ fallbackOn: v })} />}
+ />
+ {fallbackOn && (order.length > 0 || here) ? (
+ <SettingsRow
+ label="Order to try"
+ description="Drag to change."
+ control={
+ <ol className="flex min-w-56 flex-col gap-1.5" data-order-to-try="">
+ {order.map((n, i) => (
+ <li
+ key={n.key}
+ draggable
+ tabIndex={0}
+ aria-label={`${i + 1}. ${n.name}. Use the arrow keys to move it.`}
+ onKeyDown={onKey(i)}
+ onDragStart={(e: DragEvent) => {
+ setDragging(i);
+ e.dataTransfer.effectAllowed = "move";
+ }}
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ if (dragging !== null) reorder(dragging, i);
+ setDragging(null);
+ }}
+ onDragEnd={() => setDragging(null)}
+ data-order-item={n.settingsId!}
+ className={cn("flex h-8 cursor-grab items-center gap-2 rounded-lg bg-foreground/[0.05] px-2.5 text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring/60", dragging === i && "opacity-50")}
+ >
+ <GripVerticalIcon className="size-3.5 text-muted-foreground" aria-hidden />
+ <TreeIcon node={n} />
+ <span className="truncate">{n.name}</span>
+ </li>
+ ))}
+ {here ? (
+ <li className="flex h-8 items-center gap-2 px-2.5 text-[13px] text-muted-foreground" data-order-item="here">
+ <TreeIcon node={here} />
+ <span className="truncate">This Mac</span>
+ <span className="ml-auto">Last resort</span>
+ </li>
+ ) : null}
+ </ol>
+ }
+ />
+ ) : null}
+ </SettingsGroup>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/settings/general-tab.tsx b/apps/cua-spaces-web/src/components/settings/general-tab.tsx
index 2c2d4ef157..8173d322d5 100644
--- a/apps/cua-spaces-web/src/components/settings/general-tab.tsx
+++ b/apps/cua-spaces-web/src/components/settings/general-tab.tsx
@@ -10,6 +10,7 @@ import { chooseSettings, useBridge, useLoginItem, useMachines, useSession, useSe
import { SettingsGroup, SettingsRow } from "@/components/settings-group";
import { CliSettingsSection } from "@/components/settings/cli-section";
import { CoreSettingsRow } from "@/components/settings/core-section";
+import { DefaultSpaceGroup } from "@/components/settings/default-space-group";
import { RepoCacheGroup } from "@/components/settings/repo-cache-group";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -64,6 +65,8 @@ export function GeneralTab() {
return (
<div data-settings-tab="general">
+ {/* Labs "Spaces as a tree": the default Space and the order to try (nothing while it's off). */}
+ <DefaultSpaceGroup />
<SettingsGroup
title="Everyday"
footer={
diff --git a/apps/cua-spaces-web/src/components/shell/nav.ts b/apps/cua-spaces-web/src/components/shell/nav.ts
index 1b2ce29389..940adcce68 100644
--- a/apps/cua-spaces-web/src/components/shell/nav.ts
+++ b/apps/cua-spaces-web/src/components/shell/nav.ts
@@ -3,7 +3,7 @@
import { BellIcon, BotIcon, HardDriveIcon, HouseIcon, KeyRoundIcon, LayoutGridIcon, MousePointer2Icon, ServerIcon, SettingsIcon, WorkflowIcon, type LucideIcon } from "lucide-react";
-import { useDriver, useExperimentFlags, useFlag } from "@/bridge";
+import { useDriver, useExperimentFlags, useFlag, useSpacesTree } from "@/bridge";
import type { KeybindingCommand } from "@/lib/keybindings";
export interface NavItem {
@@ -35,22 +35,28 @@ const HOME_ITEM: NavItem = { to: "/home", label: "Home", icon: HouseIcon };
/** Cua Driver, under Machines, while this Mac's Cua Spaces carries the driver (CUA-2706). */
const DRIVER_ITEM: NavItem = { to: "/driver", label: "Cua Driver", icon: MousePointer2Icon };
-/** The nav, with Cua Driver while this Mac has it, Volume while the Cua Volume experiment is on, CI Runners while its experiment is, and Home while the Ask-first flag is. */
+/**
+ * The nav, with Cua Driver while this Mac has it, Volume while the Cua Volume experiment is on, CI Runners while its
+ * experiment is, and Home while the Ask-first flag is. With Spaces as a tree (Labs) your computers are in the Spaces
+ * list, so Machines leaves the nav (its page still opens); Cua Driver keeps its place.
+ */
export function useNavItems(): NavItem[] {
const experiments = useExperimentFlags();
const home = useFlag("spaces_ask_first_home");
const driver = useDriver().available;
+ const tree = useSpacesTree();
let items = NAV_ITEMS;
if (driver) {
const i = items.findIndex((n) => n.to === "/machines") + 1;
items = [...items.slice(0, i), DRIVER_ITEM, ...items.slice(i)];
}
+ if (tree) items = items.filter((n) => n.to !== "/machines");
if (experiments?.cuaVolume) {
const i = items.findIndex((n) => n.to === "/agents") + 1;
items = [...items.slice(0, i), VOLUME_ITEM, ...items.slice(i)];
}
if (experiments?.ciRunners) {
- const i = items.findIndex((n) => n.to === "/machines") + 1;
+ const i = items.findIndex((n) => n.to === (tree ? "/spaces" : "/machines")) + 1;
items = [...items.slice(0, i), CI_ITEM, ...items.slice(i)];
}
return home ? [HOME_ITEM, ...items] : items;
diff --git a/apps/cua-spaces-web/src/components/shell/sidebar-tree.tsx b/apps/cua-spaces-web/src/components/shell/sidebar-tree.tsx
new file mode 100644
index 0000000000..16c0c5ed31
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/shell/sidebar-tree.tsx
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { Link } from "@tanstack/react-router";
+import { ChevronRightIcon } from "lucide-react";
+
+import { TreeDot, TreeIcon, toggleCollapsed, useCollapsed } from "@/components/spaces/tree-parts";
+import type { SpacesTree, TreeNode } from "@/lib/spaces-tree";
+import { cn } from "@/lib/utils";
+
+const row =
+ "group flex h-7 min-w-0 flex-1 items-center gap-2 rounded-lg px-2 text-[13px] outline-none hover:bg-foreground/5 focus-visible:ring-2 focus-visible:ring-ring/60 data-[status=active]:bg-foreground/[0.07] data-[status=active]:font-medium dark:data-[status=active]:bg-white/[0.08]";
+
+function NodeLink({ node, depth }: { node: TreeNode; depth: 0 | 1 }) {
+ const body = (
+ <>
+ <TreeIcon node={node} className={cn(node.dim && "opacity-50")} />
+ <span className={cn("min-w-0 flex-1 truncate", node.dim && "text-muted-foreground")}>{node.name}</span>
+ {node.isDefault ? (
+ <span data-tree-default="" className="shrink-0 text-2xs text-muted-foreground">
+ Default
+ </span>
+ ) : null}
+ <TreeDot tone={node.tone} />
+ </>
+ );
+ const cls = cn(row, depth === 1 && "pl-7");
+ // A computer that shares no desktop has no page of its own: its Machines page.
+ return node.space ? (
+ <Link to="/spaces/$spaceId" params={{ spaceId: node.space.id }} className={cls} data-sidebar-tree-row={node.key}>
+ {body}
+ </Link>
+ ) : (
+ <Link to="/machines" className={cls} data-sidebar-tree-row={node.key}>
+ {body}
+ </Link>
+ );
+}
+
+/**
+ * The sidebar's Spaces as a tree (Labs, CUA-3413): each computer, with the
+ * Spaces made on it under it. A computer with Spaces folds and unfolds.
+ */
+export function SidebarTree({ tree }: { tree: SpacesTree }) {
+ const collapsed = useCollapsed();
+ if (tree.roots.length === 0) return null;
+ return (
+ <ul className="flex flex-col gap-px pb-1" data-sidebar-tree="" aria-label="Your Spaces">
+ {tree.roots.map((node) => {
+ const folded = collapsed.has(node.key);
+ return (
+ <li key={node.key}>
+ <div className="relative flex items-center">
+ <NodeLink node={node} depth={0} />
+ {node.children.length > 0 ? (
+ <button
+ type="button"
+ aria-label={folded ? `Show the Spaces on ${node.name}` : `Hide the Spaces on ${node.name}`}
+ aria-expanded={!folded}
+ data-sidebar-tree-fold={node.key}
+ onClick={() => toggleCollapsed(node.key)}
+ className="absolute -left-2 flex size-4 items-center justify-center rounded-lg text-muted-foreground opacity-0 outline-none hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 [li:hover_&]:opacity-100"
+ >
+ <ChevronRightIcon className={cn("size-3 transition-transform", !folded && "rotate-90")} />
+ </button>
+ ) : null}
+ </div>
+ {node.children.length > 0 && !folded ? (
+ <ul className="flex flex-col gap-px">
+ {node.children.map((c) => (
+ <li key={c.key} className="flex">
+ <NodeLink node={c} depth={1} />
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
index 2dde85fe0c..51a61eea4b 100644
--- a/apps/cua-spaces-web/src/components/shell/sidebar.tsx
+++ b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
@@ -26,6 +26,8 @@ import { SidebarUpdateButton } from "./update-indicator";
import { SidebarTip } from "@/components/tips";
import { useMachinesAccount } from "@/components/machines/account-parts";
import { AccountLine, ProBanner } from "./account-area";
+import { SidebarTree } from "./sidebar-tree";
+import { useSpacesTreeData } from "@/components/spaces/use-spaces-tree";
export function Sidebar() {
const width = useUiStore((s) => s.sidebarWidth);
@@ -41,7 +43,10 @@ export function Sidebar() {
const spacesCount = spaces && listStatus.loaded ? counted.length : undefined;
// Machines waiting to be added show beside the item, so they are seen from every page.
const { pending } = useMachinesAccount();
- const counts: Partial<Record<string, number>> = { "/spaces": spacesCount, "/machines": machines?.length };
+ // Spaces as a tree (Labs): your computers and the Spaces on them, counted together, under Spaces.
+ const { tree } = useSpacesTreeData();
+ const treeCount = tree && listStatus.loaded ? tree.computers + tree.spaces : undefined;
+ const counts: Partial<Record<string, number>> = { "/spaces": tree ? treeCount : spacesCount, "/machines": machines?.length };
const navItems = useNavItems();
const unread = notifications.data?.unread ?? 0;
@@ -58,7 +63,7 @@ export function Sidebar() {
// A host without the feed has no Notifications page.
if (item.to === "/notifications" && notifications.unsupported) return null;
const shortcut = item.command ? bindingFor(item.command) : undefined;
- return (
+ const link = (
<Link
key={item.to}
to={item.to}
@@ -88,6 +93,14 @@ export function Sidebar() {
)}
</Link>
);
+ return item.to === "/spaces" && tree ? (
+ <div key={item.to} className="flex flex-col gap-px">
+ {link}
+ <SidebarTree tree={tree} />
+ </div>
+ ) : (
+ link
+ );
})}
</nav>
{/* A spacer, not a wrapper pushed down: what appears at the foot (a tip, the account) grows
diff --git a/apps/cua-spaces-web/src/components/spaces/spaces-tree-page.tsx b/apps/cua-spaces-web/src/components/spaces/spaces-tree-page.tsx
new file mode 100644
index 0000000000..bb4dbaf09a
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/spaces/spaces-tree-page.tsx
@@ -0,0 +1,366 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { Link, useNavigate } from "@tanstack/react-router";
+import { ChevronRightIcon, HardDriveIcon, MoreHorizontalIcon, PlusIcon } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+
+import { useMachines, useSpaces } from "@/bridge";
+import { AddComputerSheet } from "@/components/add-computer-sheet";
+import { Page, PageHeader } from "@/components/page";
+import { Button } from "@/components/ui/button";
+import { ConfirmDialog } from "@/components/ui/alert-dialog";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";
+import { GroupedSection } from "@/components/ui/grouped";
+import { Input } from "@/components/ui/input";
+import { Menu, type MenuItem } from "@/components/ui/menu";
+import { toast, toastError } from "@/components/ui/toast";
+import { useNewSpace } from "@/hooks/use-new-space";
+import { plural } from "@/lib/plural";
+import { treeSummary, type TreeNode } from "@/lib/spaces-tree";
+import { cn } from "@/lib/utils";
+
+import { PeopleFaces, TreeDot, TreeIcon, toggleCollapsed, useCollapsed } from "./tree-parts";
+import { useRunningBySpace, useSpacesTreeData } from "./use-spaces-tree";
+
+// Name gets the most room; Status shares what is left, so neither is cut to a few letters in a narrow window.
+/** How long a click on a name waits for a second one (a double-click renames) before it opens the row. */
+export const DOUBLE_CLICK_MS = 300;
+
+const COLS = "grid grid-cols-[minmax(0,3fr)_minmax(0,2fr)_96px_96px_32px] items-center gap-3";
+
+export const RENAME_NOTE = "Renaming changes the name only. Your team sees the new name, and agent tasks and links keep working.";
+
+/** "Safari check, 1 agent task stops". */
+export function stopsLine(node: Pick<TreeNode, "name" | "running">): string {
+ if (node.running === 0) return node.name;
+ return `${node.name}, ${plural(node.running, "agent task")} ${node.running === 1 ? "stops" : "stop"}`;
+}
+
+/** The remove dialog's words (f9): what leaves the list, what stops, and that nothing is deleted unless asked. */
+export function removeText(
+ node: Pick<TreeNode, "name" | "children">,
+ alsoDelete = false,
+): { title: string; lead: string; keep: string; box: string | null; confirm: string } {
+ const n = node.children.length;
+ const lead =
+ n === 0
+ ? "It leaves your Spaces list, and your team can't use it any more."
+ : `It leaves your Spaces list, and your team can't use it any more. The ${plural(n, "Space")} made on it leave${n === 1 ? "s" : ""} the list with it:`;
+ const back = n === 0 ? "" : n === 1 ? " Add it again and it comes back." : ` Add it again and all ${n} come back.`;
+ // Stopgap (CUA-3413): a computer can only be removed while it is offline, so its Spaces can't be deleted on it. Ticked,
+ // they leave your account and their files stay on the computer until it deletes them. Say exactly that.
+ const them = n === 1 ? "Its files stay" : "Their files stay";
+ return {
+ title: `Remove ${node.name}?`,
+ lead,
+ keep: alsoDelete ? `${n === 1 ? "The Space is" : `The ${n} Spaces are`} deleted from your account and won't come back. ${them} on ${node.name}, which is offline, until you delete them there.` : `Nothing is deleted from ${node.name}.${back}`,
+ box: n === 0 ? null : `Also delete the ${n === 1 ? "Space" : `${n} Spaces`}`,
+ confirm: alsoDelete ? `Remove and delete` : `Remove ${node.name}`,
+ };
+}
+
+/**
+ * The Spaces page as one list (Labs "Spaces as a tree", CUA-3413): each
+ * computer you added, the Spaces made on it under it, and for every row its
+ * status, who's on it and its running agent tasks.
+ */
+export function SpacesTreePage() {
+ const running = useRunningBySpace();
+ const { tree, loaded, defaults } = useSpacesTreeData(running);
+ const { renameSpace, deleteSpace } = useSpaces();
+ const machines = useMachines();
+ const navigate = useNavigate();
+ const newSpace = useNewSpace();
+ const collapsed = useCollapsed();
+ const [adding, setAdding] = useState(false);
+ const [editing, setEditing] = useState<{ key: string; name: string } | null>(null);
+ const [removing, setRemoving] = useState<TreeNode | null>(null);
+ const [deleting, setDeleting] = useState<TreeNode | null>(null);
+ // A click on a name waits out the double-click time before opening (see clickName below).
+ const clickTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const cancelClick = () => {
+ if (clickTimer.current) clearTimeout(clickTimer.current);
+ clickTimer.current = null;
+ };
+ useEffect(() => cancelClick, []);
+
+ if (!tree || !loaded) return <Page><div aria-busy="true" aria-label="Loading Spaces" /></Page>;
+
+ const addButton = (
+ <Button onClick={() => setAdding(true)} data-tree-add-computer="">
+ <PlusIcon /> Add a computer
+ </Button>
+ );
+ const sheet = <AddComputerSheet open={adding} onOpenChange={setAdding} />;
+
+ // f6: nothing yet. A Space is a computer you own; a new one on this Mac is the second choice.
+ if (tree.roots.length === 0) {
+ return (
+ <Page>
+ <div className="mx-auto max-w-xl pt-24" data-tree-empty="">
+ <h1 className="font-heading text-[32px] font-semibold tracking-tight">No Spaces yet</h1>
+ <p className="mt-3 text-[15px] text-muted-foreground">A Space is a computer your agents can work on. Add this Mac, or another computer you own, and agents run there while you keep working.</p>
+ <div className="mt-6 flex flex-wrap gap-2">
+ <Button size="lg" render={<Link to="/machines" />} data-tree-add-this-mac="">
+ Add this Mac
+ </Button>
+ <Button size="lg" variant="outline" onClick={() => setAdding(true)}>
+ Add another computer
+ </Button>
+ </div>
+ <p className="mt-5 text-[13px] text-muted-foreground">
+ Or{" "}
+ <button type="button" className="underline underline-offset-2 hover:text-foreground" onClick={newSpace} data-tree-new-local="">
+ make a new Linux or Mac computer on this Mac
+ </button>
+ .
+ </p>
+ </div>
+ {sheet}
+ </Page>
+ );
+ }
+
+ const open = (n: TreeNode) => (n.space ? void navigate({ to: "/spaces/$spaceId", params: { spaceId: n.space.id } }) : void navigate({ to: "/machines" }));
+ // A click on a name opens it, a double-click renames it. A real double-click starts with a click, so a click waits out
+ // the double-click time before opening, and a double-click cancels it. A keyboard press (detail 0) opens at once.
+ const clickName = (n: TreeNode, detail: number) => {
+ cancelClick();
+ if (detail === 0 || !canRename(n)) return open(n);
+ if (detail > 1) return;
+ clickTimer.current = setTimeout(() => {
+ clickTimer.current = null;
+ open(n);
+ }, DOUBLE_CLICK_MS);
+ };
+ const canRename = (n: TreeNode) => (n.kind === "computer" ? Boolean(n.machine) : n.space?.access?.canRename !== false);
+ const saveRename = (n: TreeNode, raw: string) => {
+ setEditing(null);
+ const name = raw.trim();
+ if (!name || name === n.name) return;
+ const done = n.kind === "computer" ? machines.rename(n.current ? "this-mac" : n.machine!.id, name) : renameSpace(n.space!.id, name);
+ void done.then(() => toast(`Renamed to ${name}`, { type: "success" }), toastError(`Couldn't rename ${n.name}`));
+ };
+ const viewRemove = (n: TreeNode) => machines.view?.machines.find((m) => m.id === n.machine?.id)?.remove ?? null;
+ const menu = (n: TreeNode): MenuItem[] => {
+ const items: MenuItem[] = [{ label: "Open", onSelect: () => open(n) }];
+ if (canRename(n)) items.push({ label: "Rename", onSelect: () => setEditing({ key: n.key, name: n.name }) });
+ if (n.settingsId && !n.isDefault && !defaults.unsupported)
+ items.push({ label: "Make this my default", onSelect: () => void defaults.makeDefault(n.settingsId!).catch(toastError("Couldn't change your default Space")) });
+ if (n.kind === "computer" && !n.current && n.machine) {
+ const r = viewRemove(n);
+ // The core keeps Remove off while a computer is online. The tree's offline (the relay's own answer) wins over a
+ // machines list that lags; the relay still refuses a computer that is connected.
+ items.push({ label: `Remove ${n.name}`, destructive: true, disabled: r ? !r.enabled && n.online : false, onSelect: () => setRemoving(n) });
+ }
+ if (n.kind === "space" && n.space?.access?.canDelete !== false) items.push({ label: "Delete", destructive: true, onSelect: () => setDeleting(n) });
+ return items;
+ };
+
+ const rowFor = (n: TreeNode, depth: 0 | 1) => {
+ const folded = collapsed.has(n.key);
+ const isEditing = editing?.key === n.key;
+ return (
+ <div key={n.key} role="row" data-tree-row={n.key} data-tree-kind={n.kind} data-dim={n.dim ? "" : undefined} className={cn(COLS, "min-h-12 px-4 py-1.5 text-[14px]", n.dim && "text-muted-foreground")}>
+ <div role="cell" className={cn("flex min-w-0 items-center gap-2.5", depth === 1 && "pl-8", isEditing && "col-span-2")}>
+ {depth === 0 && n.children.length > 0 ? (
+ <button
+ type="button"
+ aria-label={folded ? `Show the Spaces on ${n.name}` : `Hide the Spaces on ${n.name}`}
+ aria-expanded={!folded}
+ onClick={() => toggleCollapsed(n.key)}
+ className="-ml-5 flex size-4 items-center justify-center text-muted-foreground hover:text-foreground"
+ data-tree-fold={n.key}
+ >
+ <ChevronRightIcon className={cn("size-3.5 transition-transform", !folded && "rotate-90")} />
+ </button>
+ ) : null}
+ <TreeIcon node={n} className={cn(n.dim && "opacity-50")} />
+ {isEditing ? (
+ <Input
+ autoFocus
+ aria-label={`New name for ${n.name}`}
+ value={editing.name}
+ maxLength={64}
+ onChange={(e) => setEditing({ key: n.key, name: e.currentTarget.value })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") saveRename(n, editing.name);
+ if (e.key === "Escape") setEditing(null);
+ }}
+ onBlur={() => setEditing(null)}
+ data-tree-rename-input=""
+ className="h-8 w-full min-w-0 text-[14px]"
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={(e) => clickName(n, e.detail)}
+ onDoubleClick={(e) => {
+ e.preventDefault();
+ cancelClick();
+ if (canRename(n)) setEditing({ key: n.key, name: n.name });
+ }}
+ className={cn("min-w-0 truncate text-left outline-none hover:underline focus-visible:underline", n.kind === "computer" && "font-semibold")}
+ data-tree-name={n.key}
+ >
+ {n.name}
+ </button>
+ )}
+ </div>
+ {isEditing ? (
+ <div role="cell" className="col-span-3 text-right text-[13px] text-muted-foreground">
+ Enter to save, Esc to cancel
+ </div>
+ ) : (
+ <>
+ <div role="cell" className="flex min-w-0 items-center gap-2 text-[13px] text-muted-foreground" data-tree-status={n.key}>
+ <TreeDot tone={n.tone} />
+ <span className="truncate">{n.status}</span>
+ </div>
+ <div role="cell">
+ <PeopleFaces people={n.people} />
+ </div>
+ <div role="cell" className="text-[13px] text-muted-foreground" data-tree-tasks={n.key}>
+ {n.tasks}
+ </div>
+ <div role="cell" className="flex justify-end">
+ <Menu
+ items={menu(n)}
+ trigger={
+ <button type="button" aria-label={`More for ${n.name}`} className="flex size-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-foreground/5 hover:text-foreground" data-tree-menu={n.key}>
+ <MoreHorizontalIcon className="size-4" />
+ </button>
+ }
+ />
+ </div>
+ </>
+ )}
+ </div>
+ );
+ };
+
+ const single = tree.computers === 1 && tree.spaces === 0;
+ return (
+ <Page>
+ <PageHeader title="Spaces" description={editing ? "Double-click a name, or pick Rename from its menu." : treeSummary(tree)} actions={addButton} />
+ <div role="table" aria-label="Your Spaces" data-spaces-tree="">
+ <div role="row" className={cn(COLS, "px-4 pb-2 text-[13px] text-muted-foreground")}>
+ <div role="columnheader">Name</div>
+ <div role="columnheader">Status</div>
+ <div role="columnheader">Who's on it</div>
+ <div role="columnheader">Agent tasks</div>
+ <div role="columnheader" aria-label="Actions" />
+ </div>
+ <GroupedSection role="rowgroup">{tree.roots.flatMap((r) => [rowFor(r, 0), ...(collapsed.has(r.key) ? [] : r.children.map((c) => rowFor(c, 1)))])}</GroupedSection>
+ </div>
+ {editing ? <p className="mt-4 text-[13px] text-muted-foreground">{RENAME_NOTE}</p> : null}
+ {single ? (
+ // f7: only This Mac. Agents are better off on a computer you're not using.
+ <GroupedSection className="mt-8" data-tree-single="">
+ <div className="flex items-center gap-4 px-5 py-4">
+ <HardDriveIcon className="size-6 shrink-0 text-muted-foreground" strokeWidth={1.5} />
+ <div className="min-w-0 flex-1">
+ <div className="text-[15px] font-medium">Add a computer you're not using</div>
+ <div className="text-[13px] text-muted-foreground">A Mac mini or PC you own. Agents work there and This Mac stays yours.</div>
+ </div>
+ <Button variant="outline" onClick={() => setAdding(true)}>
+ Add a computer
+ </Button>
+ </div>
+ </GroupedSection>
+ ) : null}
+ {sheet}
+ {removing ? <RemoveComputerDialog node={removing} onClose={() => setRemoving(null)} /> : null}
+ <ConfirmDialog
+ open={deleting !== null}
+ onOpenChange={(o) => !o && setDeleting(null)}
+ title={deleting ? `Delete ${deleting.name}?` : ""}
+ description="It's deleted with its files. This can't be undone."
+ confirmLabel="Delete"
+ destructive
+ cancelFirst
+ onConfirm={() => {
+ const n = deleting!;
+ setDeleting(null);
+ void deleteSpace(n.space!.id).then(() => toast(`Deleted ${n.name}`, { type: "success" }), toastError(`Couldn't delete ${n.name}`));
+ }}
+ />
+ </Page>
+ );
+}
+
+/**
+ * f9: removing a computer names each Space made on it and any task that
+ * stops. They are only detached unless "Also delete" is ticked: then each is
+ * deleted through the computer first, and the relay forgets them with it.
+ */
+export function RemoveComputerDialog({ node, onClose }: { node: TreeNode; onClose: () => void }) {
+ const { deleteSpace } = useSpaces();
+ const machines = useMachines();
+ const [alsoDelete, setAlsoDelete] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const text = removeText(node, alsoDelete);
+ const r = machines.view?.machines.find((m) => m.id === node.machine?.id)?.remove ?? null;
+ const run = async () => {
+ setBusy(true);
+ try {
+ if (alsoDelete) {
+ for (const c of node.children) {
+ if (!c.space) continue;
+ try {
+ await deleteSpace(c.space.id);
+ } catch (e) {
+ // A Space that couldn't be deleted stops here: the computer stays, so nothing is half-removed.
+ toastError(`Couldn't delete ${c.name}, so ${node.name} wasn't removed`)(e);
+ return;
+ }
+ }
+ }
+ await machines.remove(r?.machine ?? node.machine!.id, r?.device ?? null, alsoDelete);
+ toast(`Removed ${node.name}`, { type: "success" });
+ onClose();
+ } catch (e) {
+ toastError(`Couldn't remove ${node.name}`)(e);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <Dialog open onOpenChange={(o) => !o && !busy && onClose()}>
+ <DialogPopup className="w-[min(480px,calc(100vw-2rem))]" data-tree-remove={node.key}>
+ <div className="px-6 pt-6 pb-5">
+ <DialogTitle className="text-[17px] font-semibold">{text.title}</DialogTitle>
+ <p className="mt-3 text-[14px] text-muted-foreground">{text.lead}</p>
+ {node.children.length > 0 ? (
+ <ul className="mt-3 flex flex-col gap-1.5 text-[14px]" data-tree-remove-children="">
+ {node.children.map((c) => (
+ <li key={c.key} className="flex items-center gap-2.5">
+ <TreeIcon node={c} />
+ {stopsLine(c)}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ <p className="mt-3 text-[14px] text-muted-foreground">{text.keep}</p>
+ {text.box ? (
+ <label className="mt-4 flex items-start gap-2.5 text-[14px]">
+ <Checkbox checked={alsoDelete} onCheckedChange={(v) => setAlsoDelete(v === true)} data-tree-also-delete="" />
+ <span>{text.box}</span>
+ </label>
+ ) : null}
+ </div>
+ {/* design-ok: a dialog's footer bar, as ConfirmDialog's */}
+ <div className="flex justify-end gap-2 border-t bg-muted/60 px-6 py-3">
+ <Button variant="outline" disabled={busy} onClick={onClose}>
+ Cancel
+ </Button>
+ <Button variant="destructive" disabled={busy} onClick={() => void run()} data-tree-remove-confirm="">
+ {text.confirm}
+ </Button>
+ </div>
+ </DialogPopup>
+ </Dialog>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/spaces/tree-parts.tsx b/apps/cua-spaces-web/src/components/spaces/tree-parts.tsx
new file mode 100644
index 0000000000..93876176aa
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/spaces/tree-parts.tsx
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { HardDriveIcon, LaptopIcon, MonitorIcon } from "lucide-react";
+import { useSyncExternalStore } from "react";
+
+import { OsIcon } from "@/components/os-icon";
+import { avatarColor, initial } from "@/lib/spaces-page";
+import type { TreeNode, TreeTone } from "@/lib/spaces-tree";
+import { cn } from "@/lib/utils";
+
+/** A row's mark: This Mac's laptop, a Mac mini's box, a PC's screen; a Space's OS. */
+export function TreeIcon({ node, className }: { node: Pick<TreeNode, "kind" | "current" | "os">; className?: string }) {
+ const cls = cn("size-4 shrink-0 text-muted-foreground", className);
+ if (node.kind === "space") return node.os ? <OsIcon os={node.os} className={cls} /> : <MonitorIcon className={cls} strokeWidth={1.75} aria-hidden />;
+ if (node.current) return <LaptopIcon className={cls} strokeWidth={1.75} aria-hidden />;
+ if (node.os === "macos") return <HardDriveIcon className={cls} strokeWidth={1.75} aria-hidden />;
+ return <MonitorIcon className={cls} strokeWidth={1.75} aria-hidden />;
+}
+
+const TONE: Record<TreeTone, string> = {
+ online: "bg-success",
+ busy: "bg-brand animate-pulse",
+ offline: "bg-muted-foreground/50",
+ stopped: "bg-muted-foreground/50",
+ waits: "bg-muted-foreground/50",
+};
+
+export function TreeDot({ tone, className }: { tone: TreeTone; className?: string }) {
+ return <span data-tree-dot={tone} aria-hidden className={cn("size-1.5 shrink-0 rounded-full", TONE[tone], className)} />;
+}
+
+/** Who's on it: up to three initials, then "+2". */
+export function PeopleFaces({ people, className }: { people: readonly string[]; className?: string }) {
+ if (people.length === 0) return null;
+ const more = people.length - 3;
+ return (
+ <span data-people={people.length} title={people.join(", ")} className={cn("inline-flex items-center", className)}>
+ {people.slice(0, 3).map((name, i) => (
+ <span key={`${name}:${i}`} aria-hidden className={cn("flex size-5 items-center justify-center rounded-full text-[10px] font-semibold text-white ring-2 ring-background", avatarColor(name), i > 0 && "-ml-1")}>
+ {initial(name)}
+ </span>
+ ))}
+ {more > 0 ? <span className="ml-1 text-[11px] text-muted-foreground tabular-nums">+{more}</span> : null}
+ <span className="sr-only">{people.join(", ")}</span>
+ </span>
+ );
+}
+
+/* ---- Which computers are folded (this device only) ------------------------ */
+
+const KEY = "cua.spacesTree.collapsed";
+const listeners = new Set<() => void>();
+let cache: ReadonlySet<string> | null = null;
+
+function load(): ReadonlySet<string> {
+ if (cache) return cache;
+ try {
+ const raw = JSON.parse(globalThis.localStorage?.getItem(KEY) ?? "[]") as unknown;
+ cache = new Set(Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : []);
+ } catch {
+ cache = new Set();
+ }
+ return cache;
+}
+
+/** Folds or unfolds a computer in every tree (the sidebar and the Spaces page). */
+export function toggleCollapsed(key: string): void {
+ const next = new Set(load());
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ cache = next;
+ try {
+ globalThis.localStorage?.setItem(KEY, JSON.stringify([...next]));
+ } catch {
+ // Kept for this session only.
+ }
+ for (const l of [...listeners]) l();
+}
+
+export function useCollapsed(): ReadonlySet<string> {
+ return useSyncExternalStore(
+ (l) => {
+ listeners.add(l);
+ return () => listeners.delete(l);
+ },
+ load,
+ load,
+ );
+}
+
+/** For tests: forget the cached folds. */
+export function resetCollapsed(): void {
+ cache = null;
+}
diff --git a/apps/cua-spaces-web/src/components/spaces/use-spaces-tree.ts b/apps/cua-spaces-web/src/components/spaces/use-spaces-tree.ts
new file mode 100644
index 0000000000..b03d403b50
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/spaces/use-spaces-tree.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { useEffect, useMemo } from "react";
+
+import { useAgents, useBridge, useMachines, useSession, useSpaces, useSpacesDefault, useSpacesTree, type SpacesDefaultHook } from "@/bridge";
+import { useHiddenSpaceIds } from "@/lib/prepare/store";
+import { buildSpacesTree, type SpacesTree } from "@/lib/spaces-tree";
+
+const NO_RUNS: ReadonlyMap<string, number> = new Map();
+
+/** How often the tree reads the computers again while it is on (the host answers from memory and asks the relay only when its copy is stale). */
+export const MACHINES_REFRESH_MS = 30_000;
+
+/** Running agent tasks by Space id, from the runs in your running Spaces. */
+export function useRunningBySpace(): ReadonlyMap<string, number> {
+ const { data } = useAgents();
+ return useMemo(() => {
+ const out = new Map<string, number>();
+ for (const r of data?.runs ?? []) if (r.status === "running") out.set(r.spaceId, (out.get(r.spaceId) ?? 0) + 1);
+ return out;
+ }, [data?.runs]);
+}
+
+/**
+ * The Spaces tree (lib/spaces-tree.ts) with the account's default Space, while
+ * Labs' "Spaces as a tree" is on (`on`); nothing is read while it's off.
+ * `running`: the task counts, where the screen shows them.
+ */
+export function useSpacesTreeData(running: ReadonlyMap<string, number> = NO_RUNS): { on: boolean; tree: SpacesTree | null; loaded: boolean; defaults: SpacesDefaultHook } {
+ const on = useSpacesTree();
+ const { data: spaces, listStatus } = useSpaces();
+ const { data: machines, refresh: refreshMachines } = useMachines();
+ // The tree is always on screen, so nothing else asks for the computers again: without this a computer that went
+ // offline keeps its green dot (and "Online, Default") while Home already says it is offline.
+ useEffect(() => {
+ if (!on) return;
+ const t = setInterval(() => void refreshMachines().catch(() => {}), MACHINES_REFRESH_MS);
+ return () => clearInterval(t);
+ }, [on]);
+ const { data: session } = useSession();
+ const { core } = useBridge();
+ // The Space being prepared for Home's box is no Space of yours yet.
+ const warming = useHiddenSpaceIds(core);
+ const defaults = useSpacesDefault(on);
+ // The setting names the default; until it's read (or when it names none) the relay's own answer does.
+ const defaultSpace = defaults.settings?.defaultSpace ?? defaults.resolved?.defaultSpace ?? null;
+ const order = defaults.resolved?.order;
+ const relayOnline = useMemo(() => new Map((order ?? []).filter((o) => o.role !== "here").map((o) => [o.space, o.online] as const)), [order]);
+ const tree = useMemo(
+ () =>
+ on && spaces && machines
+ ? buildSpacesTree({ spaces: spaces.filter((s) => !warming.has(s.id)), machines, defaultSpace, running, me: session?.identity ?? null, relayOnline })
+ : null,
+ [on, spaces, machines, warming, defaultSpace, running, session?.identity, relayOnline],
+ );
+ return { on, tree, loaded: Boolean(spaces && machines && listStatus.loaded), defaults };
+}
diff --git a/apps/cua-spaces-web/src/lib/ask-first.ts b/apps/cua-spaces-web/src/lib/ask-first.ts
index 8a47d24072..5426c3cb9e 100644
--- a/apps/cua-spaces-web/src/lib/ask-first.ts
+++ b/apps/cua-spaces-web/src/lib/ask-first.ts
@@ -223,18 +223,25 @@ export function taskTitle(prompt: string, max = 80): string {
/**
* Where the job runs, as picked: a new computer of a kind on this Mac, a Space
- * you already have, or this Mac itself. With the Child Spaces experiment on
+ * you already have (or one on another of your computers, `on`), or this Mac itself. With the Child Spaces experiment on
* (agent homes, CUA-2630) the agent may also decide (`agent`: it starts in its
* own home Space and makes what the job needs) or be told one of your machines
* (`machine`).
*/
export type TaskWhere =
- | { kind: "new"; os: SpaceOs }
+ | { kind: "new"; os: SpaceOs; on?: NewSpaceOn }
| { kind: "space"; space: Space }
| { kind: "this-mac" }
| { kind: "agent"; fresh?: boolean }
| { kind: "machine"; machine: { id: string; name: string } };
+/** Another of your computers a new Space is made on ("New Space on Studio Mac mini"); absent: this Mac. */
+export interface NewSpaceOn {
+ /** Its relay machine id (`host:<machine>` in the create's `on`). */
+ machine: string;
+ name: string;
+}
+
/**
* What `agents.start` is pointed at. The core's `agent_start` only takes a
* Space id (`local:`, `cloud:`, `direct:`, `relay:`), so this Mac (the
@@ -243,7 +250,7 @@ export type TaskWhere =
* This Mac. The person confirms once that the agent works on their own
* files and apps.
*/
-export type TaskTarget = { kind: "create"; os: SpaceOs } | { kind: "space"; spaceId: string } | { kind: "host" };
+export type TaskTarget = { kind: "create"; os: SpaceOs; on?: string } | { kind: "space"; spaceId: string } | { kind: "host" };
/** The id of this Mac's own row in the Spaces list. */
export const THIS_MAC_ID = "this-mac";
@@ -273,7 +280,7 @@ export function hostSpaceId(status: Pick<HostStatus, "configured" | "mode" | "ma
export function taskTarget(where: TaskWhere): TaskTarget {
// An agent home is a Linux Space made for the task (`useStartTask` decides whether it is a home).
if (where.kind === "agent" || where.kind === "machine") return { kind: "create", os: "linux" };
- if (where.kind === "new") return { kind: "create", os: where.os };
+ if (where.kind === "new") return where.on ? { kind: "create", os: where.os, on: `host:${where.on.machine}` } : { kind: "create", os: where.os };
if (where.kind === "this-mac" || where.space.id === THIS_MAC_ID) return { kind: "host" };
return { kind: "space", spaceId: where.space.id };
}
@@ -310,7 +317,7 @@ export function defaultWhere(kinds: readonly NewKind[]): TaskWhere {
/** The pick if it's still offered, else the default (a picked Space that went away falls back). */
export function currentWhere(picked: TaskWhere | null, kinds: readonly NewKind[], spaces: readonly Space[]): TaskWhere {
if (picked?.kind === "this-mac" || picked?.kind === "agent" || picked?.kind === "machine") return picked;
- if (picked?.kind === "new" && kinds.some((k) => k.os === picked.os && !k.blocked)) return picked;
+ if (picked?.kind === "new" && (picked.on || kinds.some((k) => k.os === picked.os && !k.blocked))) return picked;
if (picked?.kind === "space") {
const row = spaces.find((s) => s.id === picked.space.id);
if (row) return { kind: "space", space: row };
diff --git a/apps/cua-spaces-web/src/lib/default-where.ts b/apps/cua-spaces-web/src/lib/default-where.ts
new file mode 100644
index 0000000000..8877e6d264
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/default-where.ts
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Where a new task from Home goes with Spaces as a tree on (CUA-3413): your
+ * default Space, or when it's offline your next online computer, then This
+ * Mac. It replaces `defaultWhere()` (a new Linux computer) while the Labs
+ * switch is on. A new computer is never made unless you pick
+ * "New Space on ..." yourself.
+ *
+ * The relay resolves the order (`spaces.resolveDefault`); a host that can't
+ * ask it resolves the same way over the tree (`resolveDefaultSpace`).
+ */
+
+import { resolveDefaultSpace, type DefaultSpace, type SpacesSettings } from "@/bridge";
+
+import type { NewKind, TaskWhere } from "./ask-first";
+import { defaultCandidates, findNode, type SpacesTree, type TreeNode } from "./spaces-tree";
+
+/** One line of "Where a task goes" (f2). */
+export interface WhereStep {
+ name: string;
+ /** "Your default. Offline now", "Next online computer. Used now", "Last resort". */
+ note: string;
+ online: boolean;
+ used: boolean;
+ node: TreeNode | null;
+}
+
+export interface TreeDefault {
+ where: TaskWhere;
+ /** The row it runs on; null: This Mac before it's in the tree. */
+ node: TreeNode | null;
+ /** The default is offline: the line under Home's box and the order tried. Null otherwise. */
+ fallback: { line: string; steps: WhereStep[] } | null;
+}
+
+/** A row as a place to run: This Mac itself, or the Space row (a computer's own desktop, or a Space on it). Null: nothing to run in. */
+export function nodeWhere(node: TreeNode): TaskWhere | null {
+ if (node.current) return { kind: "this-mac" };
+ return node.space ? { kind: "space", space: node.space } : null;
+}
+
+/** The relay's answer when it gave one, else the same rule over the tree. */
+export function resolvedDefault(tree: SpacesTree, settings: SpacesSettings | null, resolved: DefaultSpace | null): DefaultSpace {
+ if (resolved) return resolved;
+ // The tree's own default stands in for an unset one ("Default" is shown on it).
+ const def = settings?.defaultSpace ?? (tree.defaultKey && findNode(tree, tree.defaultKey)?.settingsId) ?? null;
+ return resolveDefaultSpace({ defaultSpace: def, fallback: settings?.fallback ?? [], fallbackOn: settings?.fallbackOn ?? true }, defaultCandidates(tree));
+}
+
+/**
+ * Where a task goes unless you pick: the resolution's Space, as a place
+ * to run. Anything that can't be run in (gone from the list, no desktop
+ * to start in) goes to This Mac. Never a new computer.
+ */
+export function treeDefault(tree: SpacesTree, settings: SpacesSettings | null, resolved: DefaultSpace | null): TreeDefault {
+ const r = resolvedDefault(tree, settings, resolved);
+ const picked = findNode(tree, r.space);
+ const where = picked ? (nodeWhere(picked) ?? ({ kind: "this-mac" } as const)) : ({ kind: "this-mac" } as const);
+ const node = where.kind === "this-mac" ? (tree.roots.find((n) => n.current) ?? null) : (picked ?? null);
+ const usedKey = node?.key ?? null;
+ const defOffline = r.defaultSpace !== null && r.defaultOnline === false;
+ if (!defOffline) return { where, node, fallback: null };
+
+ const steps: WhereStep[] = r.order.map((o) => {
+ const n = findNode(tree, o.space) ?? null;
+ const used = o.role === "here" ? where.kind === "this-mac" : where.kind !== "this-mac" && n !== null && n.key === usedKey;
+ const name = o.role === "here" ? "This Mac" : (n?.name ?? o.name);
+ const note =
+ o.role === "default" ? (o.online ? "Your default" : "Your default. Offline now") : o.role === "here" ? (used ? "Last resort. Used now" : "Last resort") : used ? "Next online computer. Used now" : o.online ? "Next to try" : "Offline now";
+ return { name, note, online: o.online, used, node: n };
+ });
+ const defName = steps.find((s) => s.note.startsWith("Your default"))?.name ?? findNode(tree, r.defaultSpace)?.name ?? "Your default";
+ const usedStep = steps.find((s) => s.used);
+ const line =
+ where.kind === "this-mac" || !usedStep
+ ? `${defName}, your default, is offline, and no other computer is online. This runs on This Mac.`
+ : `${defName}, your default, is offline. This runs on ${usedStep.name}, your next online computer. If none is online, it runs on This Mac.`;
+ return { where, node, fallback: { line, steps } };
+}
+
+/** The pick if it's still there and usable, else the default. A pick that went away never becomes a new computer. */
+export function currentTreeWhere(picked: TaskWhere | null, fallback: TaskWhere, kinds: readonly NewKind[], tree: SpacesTree): TaskWhere {
+ if (picked?.kind === "this-mac") return picked;
+ if (picked?.kind === "new") {
+ if (picked.on) return tree.roots.some((r) => r.machine?.id === picked.on!.machine && r.online) ? picked : fallback;
+ return kinds.some((k) => k.os === picked.os && !k.blocked) ? picked : fallback;
+ }
+ if (picked?.kind === "space") {
+ const n = findNode(tree, picked.space.id);
+ if (n?.online && n.space) return { kind: "space", space: n.space };
+ }
+ return fallback;
+}
+
+/** "New Space on <computer>": This Mac first, then each online computer of yours that makes Spaces. */
+export function newSpaceTargets(tree: SpacesTree): { key: string; name: string; on: { machine: string; name: string } | null }[] {
+ return tree.roots
+ .filter((r) => r.kind === "computer" && (r.current || (r.online && r.machine && r.machine.connection !== "direct")))
+ .map((r) => ({ key: r.key, name: r.name, on: r.current || !r.machine ? null : { machine: r.machine.id, name: r.name } }));
+}
diff --git a/apps/cua-spaces-web/src/lib/spaces-tree.test.ts b/apps/cua-spaces-web/src/lib/spaces-tree.test.ts
new file mode 100644
index 0000000000..2258ae1018
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/spaces-tree.test.ts
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+
+import type { Machine, Space } from "@/bridge";
+
+import { currentTreeWhere, newSpaceTargets, treeDefault } from "./default-where";
+import { buildSpacesTree, defaultCandidates, findNode, treeRows, treeSummary } from "./spaces-tree";
+
+const NOW = Date.parse("2026-11-04T12:00:00Z");
+
+const machine = (over: Partial<Machine>): Machine => ({ id: "m", name: "M", os: "macos", via: "relay", connection: "relay", online: true, current: false, spaceIds: [], limits: [], ...over });
+const space = (over: Partial<Space>): Space => ({ id: "s", name: "s", os: "linux", status: "running", detail: "", lastUsedAt: 0, scene: "blank", provider: "relay", ...over });
+
+const THIS_MAC = machine({ id: "this-mac", name: "Francesco's MacBook", current: true, via: "local", relayId: "mac-here" });
+const STUDIO = machine({ id: "studio", name: "Studio Mac mini", lastSeen: Math.floor((NOW - 20 * 60_000) / 1000) });
+const DILLON = machine({ id: "dillon", name: "Dillon's PC", os: "windows" });
+
+/** f4: 3 computers and 4 Spaces made on them. */
+const SPACES: Space[] = [
+ space({ id: "this-mac", name: "This Mac", status: "local", provider: "local", os: "macos" }),
+ space({ id: "local:linux-test-box", name: "Linux test box", provider: "local" }),
+ space({ id: "relay:studio", name: "Studio Mac mini", os: "macos" }),
+ space({ id: "relay:studio/safari-check", name: "Safari check", os: "macos", host: "studio", hostName: "Studio Mac mini" }),
+ space({ id: "relay:studio/build-box", name: "Build box", host: "studio", hostName: "Studio Mac mini" }),
+ space({ id: "relay:studio/release-runner", name: "Release runner", host: "studio", hostName: "Studio Mac mini", power: { control: "stop", off: true } }),
+ space({ id: "relay:dillon", name: "Dillon's PC", os: "windows" }),
+];
+const RUNNING = new Map([
+ ["local:linux-test-box", 1],
+ ["relay:studio/safari-check", 1],
+ ["relay:studio/build-box", 1],
+ ["relay:dillon", 1],
+]);
+
+const tree = (over: Partial<Parameters<typeof buildSpacesTree>[0]> = {}) =>
+ buildSpacesTree({ spaces: SPACES, machines: [THIS_MAC, STUDIO, DILLON], defaultSpace: null, running: RUNNING, me: "[email protected]", now: NOW, ...over });
+
+describe("buildSpacesTree", () => {
+ it("puts each computer first, This Mac at the top, and its Spaces under it", () => {
+ const t = tree();
+ expect(t.roots.map((r) => r.name)).toEqual(["This Mac", "Studio Mac mini", "Dillon's PC"]);
+ expect(t.roots[0]!.children.map((c) => c.name)).toEqual(["Linux test box"]);
+ expect(t.roots[1]!.children.map((c) => c.name)).toEqual(["Safari check", "Build box", "Release runner"]);
+ expect(t.roots[2]!.children).toEqual([]);
+ expect(t.roots[0]!.settingsId).toBe("relay:mac-here");
+ expect(t.roots[1]!.children[0]!.parentKey).toBe("relay:studio");
+ });
+
+ it("counts computers, Spaces, online rows and running tasks (a computer adds up its Spaces')", () => {
+ const t = tree();
+ expect([t.computers, t.spaces, t.online]).toEqual([3, 4, 6]);
+ expect(treeSummary(t)).toBe("3 computers and 4 Spaces made on them. 7 in all, 6 online.");
+ expect(t.roots.map((r) => r.tasks)).toEqual(["1 running", "2 running", "1 running"]);
+ expect(t.roots[1]!.children.map((c) => [c.status, c.tasks])).toEqual([
+ ["Online", "1 running"],
+ ["Online", "1 running"],
+ ["Stopped", "None"],
+ ]);
+ });
+
+ it("while none is set, an offline computer is never marked Default: the first online one is, else This Mac", () => {
+ expect(tree({ machines: [THIS_MAC, { ...STUDIO, online: false }, DILLON] }).defaultKey).toBe("relay:dillon");
+ const allOff = tree({ machines: [THIS_MAC, { ...STUDIO, online: false }, { ...DILLON, online: false }] });
+ expect(allOff.defaultKey).toBe("relay:mac-here");
+ expect(treeRows(allOff).filter((n) => n.isDefault).map((n) => n.name)).toEqual(["This Mac"]);
+ });
+
+ it("marks the first online computer that isn't this Mac Default while none is set, and the setting once it is", () => {
+ expect(tree().defaultKey).toBe("relay:studio");
+ expect(tree().roots[1]!.status).toBe("Online, Default");
+ const set = tree({ defaultSpace: "relay:dillon" });
+ expect(set.defaultKey).toBe("relay:dillon");
+ expect(treeRows(set).filter((n) => n.isDefault).map((n) => n.name)).toEqual(["Dillon's PC"]);
+ // A default that's no longer listed: the first other computer again.
+ expect(tree({ defaultSpace: "relay:gone" }).defaultKey).toBe("relay:studio");
+ });
+
+ it("a computer the relay calls offline is offline, even while the machines list still says connected", () => {
+ const t = tree({ defaultSpace: "relay:studio", relayOnline: new Map([["relay:studio", false]]) });
+ expect(t.roots[1]!.online).toBe(false);
+ expect(t.roots[1]!.status).toBe("Offline, seen 20 minutes ago, Default");
+ expect(t.roots[1]!.children.every((c) => c.status === "Waits for Studio Mac mini")).toBe(true);
+ // Unset: the relay's offline computer isn't the default either.
+ expect(tree({ relayOnline: new Map([["relay:studio", false]]) }).defaultKey).toBe("relay:dillon");
+ // The relay only ever turns a computer offline here, never online.
+ expect(tree({ machines: [THIS_MAC, { ...STUDIO, online: false }, DILLON], relayOnline: new Map([["relay:studio", true]]) }).roots[1]!.online).toBe(false);
+ });
+
+ it("greys out the Spaces of an offline computer: they wait for it and their tasks are paused", () => {
+ // Set as the default, it stays marked Default while offline (the fallback line says where tasks go instead).
+ const t = tree({ machines: [THIS_MAC, { ...STUDIO, online: false }, DILLON], defaultSpace: "relay:studio" });
+ const studio = t.roots[1]!;
+ expect(studio.status).toBe("Offline, seen 20 minutes ago, Default");
+ expect(studio.tasks).toBe("Paused");
+ expect(studio.children.map((c) => [c.status, c.tasks, c.dim, c.online])).toEqual([
+ ["Waits for Studio Mac mini", "Paused", true, false],
+ ["Waits for Studio Mac mini", "Paused", true, false],
+ ["Waits for Studio Mac mini", "None", true, false],
+ ]);
+ expect(t.offlineParent?.key).toBe("relay:studio");
+ expect(treeSummary(t)).toBe("Studio Mac mini is offline, so the 3 Spaces on it are too. They come back when it does.");
+ });
+
+ it("lists a Space whose computer isn't one of yours as a top row of its own", () => {
+ const shared = space({ id: "relay:space-sam-qa", name: "Sam's QA", hostName: "Sam's Mac", access: { kind: "withMe", role: "editor", ownerName: "Sam", place: "Sam's Mac", people: [], canPower: false, canTeleport: false, canShare: false, canRename: false, canDelete: false, canLeave: true } });
+ const t = tree({ spaces: [...SPACES, shared] });
+ expect(t.roots.map((r) => r.name)).toEqual(["This Mac", "Studio Mac mini", "Dillon's PC", "Sam's QA"]);
+ const orphan = t.roots[3]!;
+ expect([orphan.kind, orphan.parentKey, orphan.people]).toEqual(["space", null, ["Sam"]]);
+ expect(t.spaces).toBe(5);
+ });
+
+ it("is empty before this Mac is added, and has one computer (the default) when it's the only one", () => {
+ const unshared = { ...THIS_MAC, relayId: undefined, connection: null };
+ const empty = buildSpacesTree({ spaces: [], machines: [unshared], defaultSpace: null, now: NOW });
+ expect(empty.roots).toEqual([]);
+ expect([empty.computers, empty.spaces]).toEqual([0, 0]);
+
+ const single = buildSpacesTree({ spaces: [SPACES[0]!], machines: [THIS_MAC], defaultSpace: null, me: "[email protected]", now: NOW });
+ expect(single.roots.map((r) => [r.name, r.status, r.tasks, r.people])).toEqual([["This Mac", "Online, Default", "None", ["[email protected]"]]]);
+ expect(treeSummary(single)).toBe("1 computer. New tasks run on This Mac until you add another.");
+ });
+
+ it("leaves devices that are only signed in out of the tree", () => {
+ const t = tree({ machines: [THIS_MAC, STUDIO, DILLON, machine({ id: "phone", name: "iPhone", device: true })] });
+ expect(t.roots.map((r) => r.name)).not.toContain("iPhone");
+ });
+});
+
+describe("treeDefault", () => {
+ const settings = (defaultSpace: string | null, fallback: string[] = [], fallbackOn = true) => ({ defaultSpace, fallback, fallbackOn, updatedAt: 0 });
+
+ it("runs on the default while it's online, with no line under the box", () => {
+ const t = tree({ defaultSpace: "relay:studio" });
+ const d = treeDefault(t, settings("relay:studio"), null);
+ expect(d.where).toEqual({ kind: "space", space: SPACES[2] });
+ expect(d.fallback).toBeNull();
+ });
+
+ it("goes to the next online computer when the default is offline, and says why", () => {
+ const t = tree({ defaultSpace: "relay:studio", machines: [THIS_MAC, { ...STUDIO, online: false }, DILLON] });
+ const d = treeDefault(t, settings("relay:studio"), null);
+ expect(d.where).toEqual({ kind: "space", space: SPACES[6] });
+ expect(d.fallback?.line).toBe("Studio Mac mini, your default, is offline. This runs on Dillon's PC, your next online computer. If none is online, it runs on This Mac.");
+ expect(d.fallback?.steps.map((s) => [s.name, s.note])).toEqual([
+ ["Studio Mac mini", "Your default. Offline now"],
+ ["Dillon's PC", "Next online computer. Used now"],
+ ["This Mac", "Last resort"],
+ ]);
+ });
+
+ it("runs on This Mac when nothing else is online, and never makes a new computer", () => {
+ const t = tree({ defaultSpace: "relay:studio", machines: [THIS_MAC, { ...STUDIO, online: false }, { ...DILLON, online: false }] });
+ const d = treeDefault(t, settings("relay:studio"), null);
+ expect(d.where).toEqual({ kind: "this-mac" });
+ expect(d.fallback?.line).toBe("Studio Mac mini, your default, is offline, and no other computer is online. This runs on This Mac.");
+ expect(d.fallback?.steps.at(-1)).toMatchObject({ name: "This Mac", note: "Last resort. Used now", used: true });
+ // Fallback off: only the default, then This Mac.
+ const off = treeDefault(tree({ defaultSpace: "relay:studio", machines: [THIS_MAC, { ...STUDIO, online: false }, DILLON] }), settings("relay:studio", [], false), null);
+ expect(off.where).toEqual({ kind: "this-mac" });
+ });
+
+ it("follows the order to try, and the relay's own answer when it gave one", () => {
+ const machines = [THIS_MAC, { ...STUDIO, online: false }, DILLON, machine({ id: "linux", name: "Linux box", os: "linux" })];
+ const spaces = [...SPACES, space({ id: "relay:linux", name: "Linux box" })];
+ const t = tree({ defaultSpace: "relay:studio", machines, spaces });
+ expect(treeDefault(t, settings("relay:studio", ["relay:linux", "relay:dillon"]), null).where).toMatchObject({ kind: "space", space: { id: "relay:linux" } });
+ const relay = { space: "relay:dillon", reason: "fallback", defaultSpace: "relay:studio", defaultOnline: false, order: [{ space: "relay:studio", name: "Studio Mac mini", online: false, role: "default" }, { space: "relay:dillon", name: "Dillon's PC", online: true, role: "fallback" }, { space: "relay:mac-here", name: "This Mac", online: true, role: "here" }] };
+ expect(treeDefault(t, settings("relay:studio"), relay).where).toMatchObject({ kind: "space", space: { id: "relay:dillon" } });
+ // The relay says "here" with no Space: This Mac.
+ expect(treeDefault(t, settings("relay:studio"), { ...relay, space: null, reason: "here" }).where).toEqual({ kind: "this-mac" });
+ });
+
+ it("with no default set, uses the first other computer, else This Mac", () => {
+ expect(treeDefault(tree(), null, null).where).toMatchObject({ kind: "space", space: { id: "relay:studio" } });
+ const single = buildSpacesTree({ spaces: [SPACES[0]!], machines: [THIS_MAC], defaultSpace: null, now: NOW });
+ expect(treeDefault(single, null, null).where).toEqual({ kind: "this-mac" });
+ });
+
+ it("lists This Mac last among the candidates", () => {
+ const c = defaultCandidates(tree());
+ expect(c.map((x) => x.space)).toEqual(["relay:mac-here", "relay:studio", "relay:dillon"]);
+ expect(c[0]!.here).toBe(true);
+ });
+});
+
+describe("currentTreeWhere", () => {
+ const t = tree({ defaultSpace: "relay:studio" });
+ const fallback = { kind: "space", space: SPACES[2]! } as const;
+ const kinds = [{ os: "linux" as const, note: "", blocked: null }];
+
+ it("keeps a pick that's still usable", () => {
+ expect(currentTreeWhere({ kind: "space", space: SPACES[6]! }, fallback, kinds, t)).toEqual({ kind: "space", space: SPACES[6] });
+ expect(currentTreeWhere({ kind: "this-mac" }, fallback, kinds, t)).toEqual({ kind: "this-mac" });
+ expect(currentTreeWhere({ kind: "new", os: "linux", on: { machine: "dillon", name: "Dillon's PC" } }, fallback, kinds, t)).toMatchObject({ kind: "new", on: { machine: "dillon" } });
+ });
+
+ it("falls back to the default, never to a new computer, when the pick went away or went offline", () => {
+ expect(currentTreeWhere({ kind: "space", space: space({ id: "relay:gone" }) }, fallback, kinds, t)).toBe(fallback);
+ const off = tree({ machines: [THIS_MAC, STUDIO, { ...DILLON, online: false }] });
+ expect(currentTreeWhere({ kind: "space", space: SPACES[6]! }, fallback, kinds, off)).toBe(fallback);
+ expect(currentTreeWhere({ kind: "new", os: "linux", on: { machine: "dillon", name: "Dillon's PC" } }, fallback, kinds, off)).toBe(fallback);
+ expect(currentTreeWhere(null, fallback, kinds, t)).toBe(fallback);
+ });
+
+ it("offers New Space on This Mac and on each online computer", () => {
+ expect(newSpaceTargets(t).map((n) => [n.name, n.on?.machine ?? null])).toEqual([
+ ["This Mac", null],
+ ["Studio Mac mini", "studio"],
+ ["Dillon's PC", "dillon"],
+ ]);
+ });
+
+ it("finds a row by its key or the relay's id", () => {
+ expect(findNode(t, "relay:studio/build-box")?.name).toBe("Build box");
+ expect(findNode(t, "relay:mac-here")?.name).toBe("This Mac");
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/spaces-tree.ts b/apps/cua-spaces-web/src/lib/spaces-tree.ts
new file mode 100644
index 0000000000..cd706ff8b3
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/spaces-tree.ts
@@ -0,0 +1,271 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Spaces as a tree (CUA-3413, Labs `spaces_tree`): every computer you added
+ * is a top row, and the Spaces made on it sit under it. One pure function
+ * builds it for the sidebar, the Spaces page, Home's "in" picker and
+ * Settings, from what the app already has: the Spaces list (`Space.host`,
+ * `provider`), the machines (`Machine.current`, `relayId`) and the agent
+ * runs. Nothing new is stored; the default Space is the relay's
+ * (`spaces.settings`).
+ */
+
+import type { DefaultCandidate, Machine, Space, SpaceOs } from "@/bridge";
+import { ownerLabel, peopleNames } from "@/lib/space-access";
+import { machineOs, reachable } from "@/lib/machines";
+import { plural } from "@/lib/plural";
+import { isMachineDesktop, spaceState, type SpaceState } from "@/lib/spaces";
+import { relativeTime } from "@/lib/utils";
+
+/** How a row reads in the Status column (and its dot). */
+export type TreeTone = "online" | "offline" | "stopped" | "waits" | "busy";
+
+export interface TreeNode {
+ /** A stable key: the computer's Space id, or the Space's. */
+ key: string;
+ kind: "computer" | "space";
+ name: string;
+ os: SpaceOs | null;
+ /** The id the relay knows it by (`relay:<machine>`, `relay:<machine>/<name>`): it can be the default. Null: it can't (a Space on This Mac only, or a computer added by address). */
+ settingsId: string | null;
+ /** The Spaces list's row: what opens it and what a task runs in. Null: nothing to open (a computer that shares no desktop). */
+ space: Space | null;
+ /** The machine, for a computer. */
+ machine: Machine | null;
+ /** This Mac. */
+ current: boolean;
+ /** Usable now: online, and (for a Space) its computer is too. */
+ online: boolean;
+ tone: TreeTone;
+ /** "Online", "Online, Default", "Offline, seen 20 minutes ago", "Waits for Studio Mac mini", "Stopped". */
+ status: string;
+ isDefault: boolean;
+ /** Its computer is offline: the row is greyed out until it's back. */
+ dim: boolean;
+ /** Running agent tasks: its own, and for a computer its Spaces' too. */
+ running: number;
+ /** "1 running", "None", or "Paused" while its computer is offline. */
+ tasks: string;
+ /** Who's on it: the owner (or you) first, then who it's shared with. */
+ people: string[];
+ /** The computer it was made on; null for a computer, or a Space whose computer isn't listed. */
+ parentKey: string | null;
+ children: TreeNode[];
+}
+
+export interface SpacesTree {
+ /** Computers (This Mac first), then any Space whose computer isn't listed. */
+ roots: TreeNode[];
+ computers: number;
+ /** Spaces made on the computers (and any whose computer isn't listed). */
+ spaces: number;
+ online: number;
+ /** The default, marked "Default" (the setting, else the first computer that isn't this Mac, else This Mac). */
+ defaultKey: string | null;
+ /** The first offline computer that has Spaces on it (the page's line says so). */
+ offlineParent: TreeNode | null;
+}
+
+export interface TreeInput {
+ spaces: readonly Space[];
+ machines: readonly Machine[];
+ /** The stored default (`spaces.settings`); null: unset. */
+ defaultSpace: string | null;
+ /** Running agent tasks by Space id. */
+ running?: ReadonlyMap<string, number>;
+ /** Your own name or email, for "Who's on it". */
+ me?: string | null;
+ now?: number;
+ /** What the relay said about each computer when it last resolved the default (`spaces.resolveDefault`'s order, by
+ * Space id). A computer it calls offline is offline here too, so the tree never shows green where Home says offline
+ * (the machines list can lag, as it also counts a connection the relay has not dropped yet). */
+ relayOnline?: ReadonlyMap<string, boolean>;
+}
+
+/** A computer's own Space id: `relay:<machine>` (This Mac's once it is on the relay), else its list row's. */
+export function computerSpaceId(m: Pick<Machine, "id" | "current" | "relayId" | "connection">): string | null {
+ if (m.current) return m.relayId ? `relay:${m.relayId}` : null;
+ return m.connection === "direct" ? null : `relay:${m.id}`;
+}
+
+/** A Space id the relay knows (`relay:<machine>` or `relay:<machine>/<name>`): one that can be the default. */
+const relayId = (id: string): string | null => (id.startsWith("relay:") ? id : null);
+
+const SPACE_WORD: Record<SpaceState, string> = { running: "Online", stopped: "Stopped", creating: "Getting ready", deleting: "Deleting", failed: "Didn't start" };
+
+function offlineWord(m: Pick<Machine, "lastSeen">, now: number): string {
+ return m.lastSeen ? `Offline, seen ${relativeTime(m.lastSeen * 1000, now)}` : "Offline";
+}
+
+function tasksText(running: number, waits: boolean): string {
+ if (running === 0) return "None";
+ return waits ? "Paused" : `${running} running`;
+}
+
+function peopleOf(space: Space | null, me: string | null): string[] {
+ const access = space?.access;
+ const first = access ? (ownerLabel(access) ?? me) : me;
+ const rest = access && access.kind === "mine" ? peopleNames(access) : [];
+ return [...new Set([first, ...rest].filter((n): n is string => Boolean(n)))];
+}
+
+/** Whether a machine row is one of your computers (not only a signed-in device). This Mac counts once it is shared or has Spaces. */
+const isComputer = (m: Machine) => !m.device;
+
+/**
+ * Builds the tree. Computers come in the machines' order with This Mac
+ * first; a Space sits under the computer it was made on (`host`, or
+ * `provider: local` for This Mac). A Space whose computer isn't listed (a
+ * teammate's, one in your cloud) is a top row of its own after them. While
+ * a computer is offline its Spaces wait for it, and their running tasks
+ * read "Paused".
+ */
+export function buildSpacesTree({ spaces, machines, defaultSpace, running = new Map(), me = null, now = Date.now(), relayOnline }: TreeInput): SpacesTree {
+ const listed = spaces.filter((s) => !isMachineDesktop(s));
+ const placed = new Set<string>();
+ const here = machines.find((m) => m.current && isComputer(m)) ?? null;
+ const others = machines.filter((m) => !m.current && isComputer(m));
+ const ordered = [...(here ? [here] : []), ...others];
+
+ // The default: the setting when it's listed, else where a task goes while none is set (the relay's rule): the first
+ // online computer that isn't this Mac, else This Mac. An offline computer is never shown as a default nobody chose.
+ const ids = new Set<string>();
+ for (const m of ordered) {
+ const id = computerSpaceId(m);
+ if (id) ids.add(id);
+ }
+ for (const s of listed) if (relayId(s.id)) ids.add(s.id);
+ const isOnline = (m: Machine) => {
+ const id = computerSpaceId(m);
+ return m.online && !(id !== null && relayOnline?.get(id) === false);
+ };
+ const fallbackDefault = others.filter(isOnline).map(computerSpaceId).find((id): id is string => id !== null) ?? (here ? (computerSpaceId(here) ?? "this-mac") : null);
+ const defaultKey = defaultSpace && ids.has(defaultSpace) ? defaultSpace : fallbackDefault;
+
+ const runningOf = (id: string | null | undefined) => (id ? (running.get(id) ?? 0) : 0);
+
+ const spaceNode = (s: Space, parent: TreeNode | null): TreeNode => {
+ const waits = parent !== null && !parent.online;
+ const state = spaceState(s);
+ const settingsId = relayId(s.id);
+ const isDefault = settingsId !== null && settingsId === defaultKey;
+ const word = waits ? `Waits for ${parent.name}` : SPACE_WORD[state];
+ const n = runningOf(s.id);
+ return {
+ key: s.id,
+ kind: "space",
+ name: s.name,
+ os: s.os === "unknown" ? null : s.os,
+ settingsId,
+ space: s,
+ machine: null,
+ current: false,
+ online: !waits && state === "running",
+ tone: waits ? "waits" : state === "running" ? "online" : state === "creating" || state === "deleting" ? "busy" : state === "failed" ? "offline" : "stopped",
+ status: isDefault && !waits ? `${word}, Default` : word,
+ isDefault,
+ dim: waits,
+ running: n,
+ tasks: tasksText(n, waits),
+ people: peopleOf(s, me),
+ parentKey: parent?.key ?? null,
+ children: [],
+ };
+ };
+
+ const roots: TreeNode[] = [];
+ for (const m of ordered) {
+ const own = m.current ? (spaces.find((s) => s.id === "this-mac") ?? null) : (spaces.find((s) => s.id === `relay:${m.id}`) ?? null);
+ const id = computerSpaceId(m);
+ const key = id ?? (m.current ? "this-mac" : `machine:${m.id}`);
+ const kids = listed.filter((s) => !placed.has(s.id) && (m.current ? s.provider === "local" || (m.relayId !== undefined && s.host === m.relayId) : s.host === m.id));
+ // This Mac before it is shared, with no Space on it: not a Space yet (the empty state offers "Add this Mac").
+ if (m.current && !id && !m.connection && kids.length === 0) continue;
+ const online = reachable(m) && !(id !== null && !m.current && relayOnline?.get(id) === false);
+ const isDefault = key === defaultKey;
+ const word = online ? "Online" : m.online && m.notSharing ? "Not sharing" : offlineWord(m, now);
+ const node: TreeNode = {
+ key,
+ kind: "computer",
+ name: m.current ? "This Mac" : m.name,
+ os: machineOs(m),
+ settingsId: id,
+ space: own,
+ machine: m,
+ current: m.current,
+ online,
+ tone: online ? "online" : "offline",
+ status: isDefault ? `${word}, Default` : word,
+ isDefault,
+ dim: false,
+ running: 0,
+ tasks: "",
+ people: peopleOf(own, me),
+ parentKey: null,
+ children: [],
+ };
+ for (const s of kids) placed.add(s.id);
+ node.children = kids.map((s) => spaceNode(s, node));
+ node.running = runningOf(id) + (m.current ? runningOf("this-mac") : 0) + node.children.reduce((sum, c) => sum + c.running, 0);
+ node.tasks = tasksText(node.running, false);
+ if (!online && node.running > 0) node.tasks = "Paused";
+ // A computer shared with you: whoever is on its Spaces is on it too.
+ if (node.people.length <= 1) node.people = [...new Set([...node.people, ...node.children.flatMap((c) => c.people)])];
+ roots.push(node);
+ }
+ const orphans = listed.filter((s) => !placed.has(s.id)).map((s) => spaceNode(s, null));
+
+ const all = [...roots, ...roots.flatMap((r) => r.children), ...orphans];
+ return {
+ roots: [...roots, ...orphans],
+ computers: roots.length,
+ spaces: all.length - roots.length,
+ online: all.filter((n) => n.online).length,
+ defaultKey: all.some((n) => n.key === defaultKey) ? defaultKey : null,
+ offlineParent: roots.find((r) => !r.online && r.children.length > 0) ?? null,
+ };
+}
+
+/** Every row, depth first. */
+export function treeRows(tree: Pick<SpacesTree, "roots">): TreeNode[] {
+ return tree.roots.flatMap((r) => [r, ...r.children]);
+}
+
+/** The Spaces page's line under its title. */
+export function treeSummary(tree: SpacesTree): string {
+ if (tree.offlineParent) {
+ const p = tree.offlineParent;
+ return `${p.name} is offline, so the ${plural(p.children.length, "Space")} on it ${p.children.length === 1 ? "is" : "are"} too. ${p.children.length === 1 ? "It comes" : "They come"} back when it does.`;
+ }
+ if (tree.computers === 1 && tree.spaces === 0) {
+ const only = tree.roots[0]!;
+ return `1 computer. New tasks run on ${only.name} until you add another.`;
+ }
+ const total = tree.computers + tree.spaces;
+ const made = tree.spaces === 0 ? "" : ` and ${plural(tree.spaces, "Space")} made on ${tree.computers === 1 ? "it" : "them"}`;
+ return `${plural(tree.computers, "computer")}${made}. ${total} in all, ${tree.online} online.`;
+}
+
+/**
+ * The computers a task may go to, in the account's order, for the
+ * resolution when the host can't ask the relay (`resolveDefaultSpace`):
+ * the default first if it's a Space, then each computer, This Mac last.
+ */
+export function defaultCandidates(tree: SpacesTree): DefaultCandidate[] {
+ const out: DefaultCandidate[] = [];
+ for (const n of treeRows(tree)) {
+ if (!n.settingsId) continue;
+ if (n.kind === "space" && !n.isDefault) continue;
+ out.push({ space: n.settingsId, name: n.name, online: n.online, here: n.current });
+ }
+ // This Mac before it is on the relay is still the last resort.
+ const here = tree.roots.find((r) => r.current);
+ if (here && !here.settingsId) out.push({ space: here.key, name: here.name, online: true, here: true });
+ return out;
+}
+
+/** A node by key. */
+export function findNode(tree: Pick<SpacesTree, "roots">, key: string | null | undefined): TreeNode | undefined {
+ return key ? treeRows(tree).find((n) => n.key === key || n.settingsId === key) : undefined;
+}
diff --git a/apps/cua-spaces-web/src/routes/spaces/index.tsx b/apps/cua-spaces-web/src/routes/spaces/index.tsx
index e651b6b1c0..0ac6420f0b 100644
--- a/apps/cua-spaces-web/src/routes/spaces/index.tsx
+++ b/apps/cua-spaces-web/src/routes/spaces/index.tsx
@@ -5,7 +5,7 @@ import { createFileRoute } from "@tanstack/react-router";
import { MonitorIcon, PlusIcon, SearchIcon } from "lucide-react";
import { memo, useEffect, useMemo, useRef, useState, type RefObject } from "react";
-import { emptyHome, listView, spaceDiskBytes, useBridge, useResources, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaces, type Space } from "@/bridge";
+import { emptyHome, listView, useSpacesTree, spaceDiskBytes, useBridge, useResources, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaces, type Space } from "@/bridge";
import { EmptyHome } from "@/components/empty-home";
import { useFirstSpaceMilestones } from "@/components/first-run-guide";
import { EmptyState, Page, PageHeader } from "@/components/page";
@@ -20,6 +20,7 @@ import { SpaceTile, TILE_CELL } from "@/components/spaces/space-tile";
import { CreatingElsewhereTile } from "@/components/spaces/creating-elsewhere-tile";
import { WindowedGrid, type WindowedGridHandle } from "@/components/spaces/windowed-grid";
import { SpacesToolbar } from "@/components/spaces/spaces-toolbar";
+import { SpacesTreePage } from "@/components/spaces/spaces-tree-page";
import { PageTip, useTipsLoaded } from "@/components/tips";
import { useNewSpace } from "@/hooks/use-new-space";
import { useQuiet } from "@/hooks/use-quiet";
@@ -41,7 +42,12 @@ export const Route = createFileRoute("/spaces/")({
validateSearch: (s: Record<string, unknown>): SpacesSearch => validateSpacesSearch(s),
});
+/** Spaces as a tree (Labs) draws its own page; off, the grid as it is. */
function SpacesPage() {
+ return useSpacesTree() ? <SpacesTreePage /> : <SpacesGridPage />;
+}
+
+function SpacesGridPage() {
const search = Route.useSearch();
const navigate = Route.useNavigate();
const setSearch = (next: Partial<Record<keyof SpacesSearch, string | undefined>>) =>
diff --git a/docs/content/docs/cua-cli/reference/cli/computers-and-teams.mdx b/docs/content/docs/cua-cli/reference/cli/computers-and-teams.mdx
index 0ae091154e..719fdaacc3 100644
--- a/docs/content/docs/cua-cli/reference/cli/computers-and-teams.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/computers-and-teams.mdx
@@ -12,8 +12,6 @@ description: "Your computers, unattended access on this computer, teams and your
| Command | Description |
| --- | --- |
-| [`cua machines`](#cua-machines) | Your computers on the relay: remove one that is gone. |
-| [`cua machines rm`](#cua-machines-rm) | Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). |
| [`cua host`](#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). |
| [`cua host setup`](#cua-host-setup) | Set this computer up for unattended access: install cua-spacesd as a service that joins the cua.ai relay as your account (default) or serves on a direct ip:port. |
| [`cua host pair`](#cua-host-pair) | Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. |
@@ -58,37 +56,6 @@ description: "Your computers, unattended access on this computer, teams and your
Every command also accepts the [global options](/cua-cli/reference/cli#global-options).
-## `cua machines`
-
-Your computers on the relay: remove one that is gone.
-
-```text output
-cua machines [OPTIONS] <COMMAND>
-```
-
-### `cua machines rm`
-
-Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). A computer that is connected now is refused: run `cua host remove` on it.
-
-```text output
-cua machines rm [OPTIONS] <NAME>
-```
-
-| Argument | Type | Default | Description |
-| --- | --- | --- | --- |
-| `<NAME>` | string | required | The computer's name, machine id or `relay:<id>` (`cua spaces ls`). |
-
-| Flag | Short | Type | Default | Description |
-| --- | --- | --- | --- | --- |
-| <span id="cua-machines-rm--yes"></span>`--yes` | `-y` | boolean | `false` | Remove without asking. |
-
-**Examples**
-
-```bash test="cli-shape" id="ref-cua-machines-rm"
-cua machines rm old-laptop
-cua machines rm relay:0123abcd4567ef89 --yes --json
-```
-
## `cua host`
Unattended access to this computer (setup, status, stop, start, remove).
diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdx
index 8cd289c911..bff8b7d54d 100644
--- a/docs/content/docs/cua-cli/reference/cli/index.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx
@@ -24,7 +24,7 @@ Your Spaces, and a cua-spacesd by URL. [Reference](/cua-cli/reference/cli/spaces
| Command | Description | Subcommands |
| --- | --- | --- |
-| <span id="cua-spaces"></span><span id="cua-spaces-ls"></span><span id="cua-spaces-add"></span><span id="cua-spaces-create"></span><span id="cua-spaces-prewarm"></span><span id="cua-spaces-egress"></span><span id="cua-spaces-children"></span><span id="cua-spaces-budget"></span><span id="cua-spaces-orphans"></span><span id="cua-spaces-service"></span><span id="cua-spaces-service-add"></span><span id="cua-spaces-service-ls"></span><span id="cua-spaces-service-logs"></span><span id="cua-spaces-service-start"></span><span id="cua-spaces-service-stop"></span><span id="cua-spaces-service-restart"></span><span id="cua-spaces-service-rm"></span><span id="cua-spaces-cancel"></span><span id="cua-spaces-gpus"></span><span id="cua-spaces-delete"></span><span id="cua-spaces-stop"></span><span id="cua-spaces-suspend"></span><span id="cua-spaces-resize"></span><span id="cua-spaces-start"></span><span id="cua-spaces-rm"></span><span id="cua-spaces-rename"></span><span id="cua-spaces-set"></span><span id="cua-spaces-share"></span><span id="cua-spaces-unshare"></span><span id="cua-spaces-shares"></span><span id="cua-spaces-relay-register"></span><span id="cua-spaces-relay-unregister"></span>[`cua spaces`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces) | Spaces: registered ones and your computers on the relay. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-ls), [`add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-add), [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-create), [`prewarm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-prewarm), [`egress`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-egress), [`children`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-children), [`budget`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-budget), [`orphans`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-orphans), [`service`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service), [`service add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-add), [`service ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-ls), [`service logs`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-logs), [`service start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-start), [`service stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-stop), [`service restart`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-restart), [`service rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-rm), [`cancel`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-cancel), [`gpus`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-gpus), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-delete), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-stop), [`suspend`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-suspend), [`resize`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-resize), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-start), [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rm), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rename), [`set`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-set), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-unshare), [`shares`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-shares), [`relay-register`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-register), [`relay-unregister`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-unregister) |
+| <span id="cua-spaces"></span><span id="cua-spaces-ls"></span><span id="cua-spaces-add"></span><span id="cua-spaces-create"></span><span id="cua-spaces-prewarm"></span><span id="cua-spaces-egress"></span><span id="cua-spaces-children"></span><span id="cua-spaces-budget"></span><span id="cua-spaces-orphans"></span><span id="cua-spaces-service"></span><span id="cua-spaces-service-add"></span><span id="cua-spaces-service-ls"></span><span id="cua-spaces-service-logs"></span><span id="cua-spaces-service-start"></span><span id="cua-spaces-service-stop"></span><span id="cua-spaces-service-restart"></span><span id="cua-spaces-service-rm"></span><span id="cua-spaces-cancel"></span><span id="cua-spaces-gpus"></span><span id="cua-spaces-delete"></span><span id="cua-spaces-stop"></span><span id="cua-spaces-suspend"></span><span id="cua-spaces-resize"></span><span id="cua-spaces-start"></span><span id="cua-spaces-rm"></span><span id="cua-spaces-default"></span><span id="cua-spaces-rename"></span><span id="cua-spaces-set"></span><span id="cua-spaces-share"></span><span id="cua-spaces-unshare"></span><span id="cua-spaces-shares"></span><span id="cua-spaces-relay-register"></span><span id="cua-spaces-relay-unregister"></span>[`cua spaces`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces) | Spaces: registered ones and your computers on the relay. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-ls), [`add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-add), [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-create), [`prewarm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-prewarm), [`egress`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-egress), [`children`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-children), [`budget`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-budget), [`orphans`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-orphans), [`service`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service), [`service add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-add), [`service ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-ls), [`service logs`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-logs), [`service start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-start), [`service stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-stop), [`service restart`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-restart), [`service rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-service-rm), [`cancel`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-cancel), [`gpus`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-gpus), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-delete), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-stop), [`suspend`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-suspend), [`resize`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-resize), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-start), [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rm), [`default`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-default), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rename), [`set`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-set), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-unshare), [`shares`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-shares), [`relay-register`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-register), [`relay-unregister`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-unregister) |
| <span id="cua-spacesd"></span><span id="cua-spacesd-caps"></span><span id="cua-spacesd-exec"></span><span id="cua-spacesd-cp"></span><span id="cua-spacesd-shell"></span><span id="cua-spacesd-targets"></span><span id="cua-spacesd-call"></span>[`cua spacesd`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd) | Talk to a cua-spacesd directly by URL. | [`caps`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-caps), [`exec`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-exec), [`cp`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-cp), [`shell`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-shell), [`targets`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-targets), [`call`](/cua-cli/reference/cli/spaces-and-computers#cua-spacesd-call) |
### Computers and teams
@@ -33,7 +33,6 @@ Your computers, unattended access on this computer, teams and your remote use th
| Command | Description | Subcommands |
| --- | --- | --- |
-| <span id="cua-machines"></span><span id="cua-machines-rm"></span>[`cua machines`](/cua-cli/reference/cli/computers-and-teams#cua-machines) | Your computers on the relay: remove one that is gone. | [`rm`](/cua-cli/reference/cli/computers-and-teams#cua-machines-rm) |
| <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-cache"></span><span id="cua-host-cache-status"></span><span id="cua-host-cache-fill"></span><span id="cua-host-cache-clear"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-migrate"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/computers-and-teams#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/computers-and-teams#cua-host-setup), [`pair`](/cua-cli/reference/cli/computers-and-teams#cua-host-pair), [`config`](/cua-cli/reference/cli/computers-and-teams#cua-host-config), [`cache`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache), [`cache status`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache-status), [`cache fill`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache-fill), [`cache clear`](/cua-cli/reference/cli/computers-and-teams#cua-host-cache-clear), [`status`](/cua-cli/reference/cli/computers-and-teams#cua-host-status), [`stop`](/cua-cli/reference/cli/computers-and-teams#cua-host-stop), [`start`](/cua-cli/reference/cli/computers-and-teams#cua-host-start), [`share`](/cua-cli/reference/cli/computers-and-teams#cua-host-share), [`unshare`](/cua-cli/reference/cli/computers-and-teams#cua-host-unshare), [`migrate`](/cua-cli/reference/cli/computers-and-teams#cua-host-migrate), [`remove`](/cua-cli/reference/cli/computers-and-teams#cua-host-remove) |
| <span id="cua-devices"></span><span id="cua-devices-status"></span><span id="cua-devices-enroll"></span><span id="cua-devices-approve"></span><span id="cua-devices-ls"></span><span id="cua-devices-rename"></span><span id="cua-devices-revoke"></span><span id="cua-devices-audit"></span>[`cua devices`](/cua-cli/reference/cli/computers-and-teams#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. | [`status`](/cua-cli/reference/cli/computers-and-teams#cua-devices-status), [`enroll`](/cua-cli/reference/cli/computers-and-teams#cua-devices-enroll), [`approve`](/cua-cli/reference/cli/computers-and-teams#cua-devices-approve), [`ls`](/cua-cli/reference/cli/computers-and-teams#cua-devices-ls), [`rename`](/cua-cli/reference/cli/computers-and-teams#cua-devices-rename), [`revoke`](/cua-cli/reference/cli/computers-and-teams#cua-devices-revoke), [`audit`](/cua-cli/reference/cli/computers-and-teams#cua-devices-audit) |
| <span id="cua-team"></span><span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/computers-and-teams#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. | [`create`](/cua-cli/reference/cli/computers-and-teams#cua-team-create), [`ls`](/cua-cli/reference/cli/computers-and-teams#cua-team-ls), [`show`](/cua-cli/reference/cli/computers-and-teams#cua-team-show), [`invite`](/cua-cli/reference/cli/computers-and-teams#cua-team-invite), [`join`](/cua-cli/reference/cli/computers-and-teams#cua-team-join), [`leave`](/cua-cli/reference/cli/computers-and-teams#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/computers-and-teams#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/computers-and-teams#cua-team-set-role), [`devices`](/cua-cli/reference/cli/computers-and-teams#cua-team-devices), [`approve`](/cua-cli/reference/cli/computers-and-teams#cua-team-approve), [`deny`](/cua-cli/reference/cli/computers-and-teams#cua-team-deny), [`request`](/cua-cli/reference/cli/computers-and-teams#cua-team-request), [`add-machine`](/cua-cli/reference/cli/computers-and-teams#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/computers-and-teams#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/computers-and-teams#cua-team-audit), [`delete`](/cua-cli/reference/cli/computers-and-teams#cua-team-delete) |
diff --git a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx
index 8348626104..260cebf754 100644
--- a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx
@@ -37,6 +37,7 @@ description: "Your Spaces, and a cua-spacesd by URL."
| [`cua spaces resize`](#cua-spaces-resize) | Give a local VM Space more or fewer vCPUs, more or less memory, or a bigger disk. |
| [`cua spaces start`](#cua-spaces-start) | Turn a Space back on: resume a suspended one or boot a stopped one. |
| [`cua spaces rm`](#cua-spaces-rm) | Forget a registered Space and its stored token. |
+| [`cua spaces default`](#cua-spaces-default) | Your default Space: where "my Space" goes when you do not say. |
| [`cua spaces rename`](#cua-spaces-rename) | Give a Space a new name; its id stays the same. |
| [`cua spaces set`](#cua-spaces-set) | Change a setting of a Space. |
| [`cua spaces share`](#cua-spaces-share) | Let someone in your team watch (viewer) or use (editor) a Space, through the relay. |
@@ -629,6 +630,11 @@ Alias: `cua spaces remove`.
| --- | --- | --- | --- |
| `<SPACE>` | string | required | Space id, address or display name (as `cua spaces ls` shows). |
+| Flag | Short | Type | Default | Description |
+| --- | --- | --- | --- | --- |
+| <span id="cua-spaces-rm--delete-spaces"></span>`--delete-spaces` | | boolean | `false` | For one of your computers: also delete the Spaces it provides and their files (through the computer while it is reachable). Without it they stay on your account, detached, and come back if the computer is added again. |
+| <span id="cua-spaces-rm--yes"></span>`--yes` | `-y` | boolean | `false` | Remove a computer without asking. |
+
**Examples**
```bash test="cli-shape" id="ref-cua-spaces-rm"
@@ -636,6 +642,40 @@ cua spaces rm direct:10.0.0.5:3211
cua spaces rm studio
```
+### `cua spaces default`
+
+Your default Space: where "my Space" goes when you do not say. With no argument it prints the Space it resolves to now and the order it tries (online or not); with a Space it sets the default.
+
+```text output
+cua spaces default [OPTIONS] [SPACE]
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<SPACE>` | string | optional | The Space to make your default: a name or id (as `cua spaces ls` shows). |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-spaces-default--fallback"></span>`--fallback` | string | | Spaces to try, in this order, when the default is offline (names or ids, comma separated). Repeatable. |
+| <span id="cua-spaces-default--clear"></span>`--clear` | boolean | `false` | Have no default. |
+| <span id="cua-spaces-default--no-fallback"></span>`--no-fallback` | boolean | `false` | When the default is offline, use this computer instead of trying the others. |
+| <span id="cua-spaces-default--fallback-on"></span>`--fallback-on` | boolean | `false` | Try the others again when the default is offline (every online computer, oldest first, unless `--fallback` names an order). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-spaces-default"
+cua spaces default
+cua spaces default studio
+cua spaces default studio --fallback office-pc,relay:0123abcd4567ef89
+
+# Only the default, then this computer
+cua spaces default --no-fallback
+
+# Back to trying every online computer, oldest first
+cua spaces default --fallback-on
+cua spaces default --clear
+```
+
### `cua spaces rename`
Give a Space a new name; its id stays the same. Lowercase letters, digits and dashes, as at create. A Space you shared, or one of your computers provides, is renamed on the relay too, so your other devices and the people it is shared with see the new name. Only its owner can rename a Space.
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index 9d2deb9286..8c25b1dff1 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -74,6 +74,7 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| [The list and its changes](/cua-sdk/reference/spaces/list-watch) | The Space list `Spaces.list` reads, and hearing when it changed so it is read again then instead of on a timer. |
| [Agents in a Space](/cua-sdk/reference/spaces/agents) | Start, follow, message and stop coding-agent runs inside a Space. |
| [Persistent agents and your cloud](/cua-sdk/reference/spaces/persistent-agents) | Named agents whose memory outlives their Space: homes in the Cua Volume, routines, notifications, pause and resume, access to your computers, and Spaces in your own AWS, Google Cloud or Modal account. |
+| [Default Space](/cua-sdk/reference/spaces/default-space) | The account's default Space, the order to try when it is offline, and where a new task runs now. |
| [Host, relay and devices](/cua-sdk/reference/spaces/host) | Unattended host setup, the cua-relay directory client, and this device's enrollment on the relay. |
## Account
@@ -103,4 +104,4 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| --- | --- |
| [Protocol](/cua-sdk/reference/protocol) | The gRPC contracts of cua-spacesd (`cua.env.v1`) and the cua daemon (`cua.daemon.v1`). |
-368 items, 461 methods. The [Types](/cua-sdk/reference/types) page lists them.
+371 items, 465 methods. The [Types](/cua-sdk/reference/types) page lists them.
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
index b15060d25a..0fbe988a8a 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
@@ -18,7 +18,7 @@ The cua SDK: the only `#[uniffi::export]` crate of `libs/cua`.
These are the objects, records, enums and functions the language bindings export, documented once in the [Cua SDK reference](/cua-sdk/reference), whose Rust tabs show each signature. Objects are `Arc<T>` handles whose methods are `async fn` returning `Result<_, CuaError>`, records are structs with public fields, and names are snake_case.
-[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`NetworkEvent`](/cua-sdk/reference/spaces/space#networkevent-record), [`NetworkSettings`](/cua-sdk/reference/spaces/network#networksettings-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`repo_cache_clear`](/cua-sdk/reference/repo-cache#repo_cache_clear), [`repo_cache_status`](/cua-sdk/reference/repo-cache#repo_cache_status), [`RepoCacheStatus`](/cua-sdk/reference/repo-cache#repocachestatus-record), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record), [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record), [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetNetworkResult`](/cua-sdk/reference/spaces/network#setnetworkresult-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`ShareLanding`](/cua-sdk/reference/share#sharelanding-enum), [`ShareSettings`](/cua-sdk/reference/share#sharesettings-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpaceNetworkInfo`](/cua-sdk/reference/spaces/network#spacenetworkinfo-record), [`SpaceOrphan`](/cua-sdk/reference/spaces/children#spaceorphan-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces/info#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceServiceDef`](/cua-sdk/reference/spaces/services#spaceservicedef-record), [`SpaceServiceInfo`](/cua-sdk/reference/spaces/services#spaceserviceinfo-record), [`SpaceServiceProbe`](/cua-sdk/reference/spaces/services#spaceserviceprobe-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces/info#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`TreeBudget`](/cua-sdk/reference/spaces/children#treebudget-record), [`TreeBudgetLimits`](/cua-sdk/reference/spaces/children#treebudgetlimits-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
+[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DefaultSpace`](/cua-sdk/reference/spaces/default-space#defaultspace-record), [`DefaultSpaceStep`](/cua-sdk/reference/spaces/default-space#defaultspacestep-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`NetworkEvent`](/cua-sdk/reference/spaces/space#networkevent-record), [`NetworkSettings`](/cua-sdk/reference/spaces/network#networksettings-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`repo_cache_clear`](/cua-sdk/reference/repo-cache#repo_cache_clear), [`repo_cache_status`](/cua-sdk/reference/repo-cache#repo_cache_status), [`RepoCacheStatus`](/cua-sdk/reference/repo-cache#repocachestatus-record), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record), [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record), [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetNetworkResult`](/cua-sdk/reference/spaces/network#setnetworkresult-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`ShareLanding`](/cua-sdk/reference/share#sharelanding-enum), [`ShareSettings`](/cua-sdk/reference/share#sharesettings-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces/info#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpaceNetworkInfo`](/cua-sdk/reference/spaces/network#spacenetworkinfo-record), [`SpaceOrphan`](/cua-sdk/reference/spaces/children#spaceorphan-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces/info#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceServiceDef`](/cua-sdk/reference/spaces/services#spaceservicedef-record), [`SpaceServiceInfo`](/cua-sdk/reference/spaces/services#spaceserviceinfo-record), [`SpaceServiceProbe`](/cua-sdk/reference/spaces/services#spaceserviceprobe-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesSettings`](/cua-sdk/reference/spaces/default-space#spacessettings-record), [`SpacesToolMethod`](/cua-sdk/reference/spaces/info#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`TreeBudget`](/cua-sdk/reference/spaces/children#treebudget-record), [`TreeBudgetLimits`](/cua-sdk/reference/spaces/children#treebudgetlimits-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
## Types
diff --git a/docs/content/docs/cua-sdk/reference/spaces/default-space.mdx b/docs/content/docs/cua-sdk/reference/spaces/default-space.mdx
new file mode 100644
index 0000000000..5df116b0eb
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/default-space.mdx
@@ -0,0 +1,200 @@
+---
+title: "Default Space"
+description: "The account's default Space, the order to try when it is offline, and where a new task runs now."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs (UniFFI metadata of libcua_sdk)
+ Version: 0.10.1
+*/}
+
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+The relay keeps one default Space per account: where a new task runs unless you pick another. `Devices.spaces_settings` reads it, `set_spaces_settings` replaces it, and `resolve_default_space` says where a task goes now: the default when it is online, else the next online computer in `fallback` (while `fallback_on`), else this computer. A new computer is never made. `cua spaces default` is the same from the CLI.
+
+## Default Space
+
+Methods of [`Devices`](/cua-sdk/reference/spaces/host#devices).
+
+### `Devices.spaces_settings`
+
+The account's default Space and fallback order. A relay that
+predates them answers "the Cua relay needs an update".
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def spaces_settings(self) -> SpacesSettings
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+spacesSettings(asyncOpts_?: { signal: AbortSignal }): Promise<SpacesSettings>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func spacesSettings() async throws -> SpacesSettings
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun spacesSettings(): SpacesSettings
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn spaces_settings(&self) -> Result<SpacesSettings, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+**Returns** [`SpacesSettings`](#spacessettings-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Devices.set_spaces_settings`
+
+Replaces the account's default Space settings (the whole object;
+`updated_at` is set by the relay). Returns what the relay saved.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def set_spaces_settings(self, settings: SpacesSettings) -> SpacesSettings
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+setSpacesSettings(settings: SpacesSettings, asyncOpts_?: { signal: AbortSignal }): Promise<SpacesSettings>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func setSpacesSettings(settings: SpacesSettings) async throws -> SpacesSettings
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun setSpacesSettings(settings: SpacesSettings): SpacesSettings
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn set_spaces_settings(&self, settings: SpacesSettings) -> Result<SpacesSettings, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `settings` | [`SpacesSettings`](#spacessettings-record) | required |
+
+**Returns** [`SpacesSettings`](#spacessettings-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+### `Devices.resolve_default_space`
+
+Where the default Space resolves now: the first online entry of the
+default, the fallback order, then this computer (its own relay
+machine id, when it has one). Creates nothing.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def resolve_default_space(self) -> DefaultSpace
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+resolveDefaultSpace(asyncOpts_?: { signal: AbortSignal }): Promise<DefaultSpace>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func resolveDefaultSpace() async throws -> DefaultSpace
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun resolveDefaultSpace(): DefaultSpace
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn resolve_default_space(&self) -> Result<DefaultSpace, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+**Returns** [`DefaultSpace`](#defaultspace-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## `SpacesSettings` record
+
+The account's default Space and the order to try when it is offline.
+
+Returned by [`Devices.set_spaces_settings`](#devicesset_spaces_settings), [`Devices.spaces_settings`](#devicesspaces_settings).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `default_space` / `defaultSpace` | `Option<String>` | | `relay:<machine>` or `relay:<machine>/<name>`; none when unset. |
+| `fallback` | `Vec<String>` | | The order to try when the default is offline; empty means every online computer you can use, oldest first. |
+| `fallback_on` / `fallbackOn` | `bool` | | false: only the default, then this device. |
+| `updated_at` / `updatedAt` | `u64` | | Unix seconds the relay saved it (ignored when writing). |
+
+## `DefaultSpace` record
+
+Where the default Space resolves now.
+
+Returned by [`Devices.resolve_default_space`](#devicesresolve_default_space).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `space` | `Option<String>` | | The first online entry; none when this device is the answer (`reason` `here`). |
+| `reason` | `String` | | `default`, `fallback`, `here` or `unset`. |
+| `default_space` / `defaultSpace` | `Option<String>` | | The chosen default, online or not. |
+| `default_online` / `defaultOnline` | `Option<bool>` | | Whether the default is online; none when unset. |
+| `order` | [`Vec<DefaultSpaceStep>`](#defaultspacestep-record) | | The order the relay tried. |
+
+## `DefaultSpaceStep` record
+
+One entry of the order `Devices.resolve_default_space` tried.
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `space` | `String` | | The Space id. |
+| `name` | `String` | | Its display name. |
+| `online` | `bool` | | Connected and sharing now. |
+| `role` | `String` | | `default`, `fallback` or `here`. |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/host.mdx b/docs/content/docs/cua-sdk/reference/spaces/host.mdx
index d4765f8486..ba79e36a24 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/host.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/host.mdx
@@ -1089,6 +1089,9 @@ Returned by [`Auth.devices`](/cua-sdk/reference/auth#authdevices).
| [`revoke`](#devicesrevoke) | Revokes a device (from this enrolled device). |
| [`revoke_pairing_code`](#devicesrevoke_pairing_code) | Revokes an unused pairing code (`pc_…`). |
| [`snapshot`](#devicessnapshot) | The account's devices, the grace period, the newest `audit_limit` audit events and the machines' names. |
+| [`resolve_default_space`](/cua-sdk/reference/spaces/default-space#devicesresolve_default_space) | Where the default Space resolves now: the first online entry of the default, the fallback order, then this computer (its own relay machine id, when it has one). |
+| [`set_spaces_settings`](/cua-sdk/reference/spaces/default-space#devicesset_spaces_settings) | Replaces the account's default Space settings (the whole object; `updated_at` is set by the relay). |
+| [`spaces_settings`](/cua-sdk/reference/spaces/default-space#devicesspaces_settings) | The account's default Space and fallback order. |
| Accessor | Returns | Description |
| --- | --- | --- |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/index.mdx b/docs/content/docs/cua-sdk/reference/spaces/index.mdx
index f5c17f5da7..b40d9ae697 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/index.mdx
@@ -92,6 +92,7 @@ Returned by [`Cua.spaces`](/cua-sdk/reference/cua#cua).
| [`prewarms`](/cua-sdk/reference/spaces/elastic#spacesprewarms) | The prewarms, with how many each keeps ready now. |
| [`relay_register`](/cua-sdk/reference/spaces/relay-registration#spacesrelay_register) | Publishes `space` on the cua.ai relay as a machine of the signed-in account, the way `cua host setup` publishes this computer: the Space's own driver dials out, so the account's other devices (a phone off this network) reach it as `relay:<machine>`, and nobody else until it is shared. |
| [`relay_unregister`](/cua-sdk/reference/spaces/relay-registration#spacesrelay_unregister) | Takes `space` off the relay (its driver leaves; every share goes). |
+| [`relay_unregister_computer`](/cua-sdk/reference/spaces/relay-registration#spacesrelay_unregister_computer) | `Spaces.relay_unregister` for one of your computers (`relay:<machine>`), choosing what happens to the Spaces it provides: with `delete_spaces` false they stay on the account, detached (they come back when the computer registers again); with true they are deleted too, files first (through the computer while it answers), then their records. |
| [`remove_prewarm`](/cua-sdk/reference/spaces/elastic#spacesremove_prewarm) | Ends prewarm `id` (its ready Spaces go). |
| [`resize`](/cua-sdk/reference/spaces/resize#spacesresize) | Gives a local VM Space another shape: `cpus` vCPUs, `memory_mb` MiB of memory, a disk grown to `disk_gb` GiB (each `None` keeps it). |
| [`resources`](/cua-sdk/reference/spaces/resources#spacesresources) | What this Mac, its extra Spaces and your other computers use now: processor, memory and disk, as one snapshot (a few seconds old at most). |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/meta.json b/docs/content/docs/cua-sdk/reference/spaces/meta.json
index 7365dba826..95bba515c1 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/meta.json
+++ b/docs/content/docs/cua-sdk/reference/spaces/meta.json
@@ -19,6 +19,7 @@
"list-watch",
"agents",
"persistent-agents",
+ "default-space",
"host"
]
}
diff --git a/docs/content/docs/cua-sdk/reference/spaces/relay-registration.mdx b/docs/content/docs/cua-sdk/reference/spaces/relay-registration.mdx
index f7a90a2c1f..4a8a0a632f 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/relay-registration.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/relay-registration.mdx
@@ -12,7 +12,7 @@ description: "Register a Space with the relay so other devices reach it, and unr
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
-`Spaces.relay_register` makes a Space reachable from your other devices through the relay; `Spaces.relay_unregister` stops that.
+`Spaces.relay_register` makes a Space reachable from your other devices through the relay; `Spaces.relay_unregister` stops that. `Spaces.relay_unregister_computer` takes one of your computers off the relay: its Spaces stay on it, detached, unless `delete_spaces` deletes them first.
## Relay registration
@@ -121,6 +121,62 @@ pub async fn relay_unregister(&self, space: String) -> Result<bool, CuaError>
**Returns** `bool` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+### `Spaces.relay_unregister_computer`
+
+`Spaces.relay_unregister` for one of your computers
+(`relay:<machine>`), choosing what happens to the Spaces it
+provides: with `delete_spaces` false they stay on the account,
+detached (they come back when the computer registers again); with
+true they are deleted too, files first (through the computer while
+it answers), then their records. Returns false when it was not on
+the relay.
+
+<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Python">
+
+```python
+async def relay_unregister_computer(self, space: str, delete_spaces: bool) -> bool
+```
+
+</Tab>
+<Tab value="TypeScript">
+
+```ts
+relayUnregisterComputer(space: string, deleteSpaces: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<boolean>
+```
+
+</Tab>
+<Tab value="Swift">
+
+```swift
+func relayUnregisterComputer(space: String, deleteSpaces: Bool) async throws -> Bool
+```
+
+</Tab>
+<Tab value="Kotlin">
+
+```kotlin
+@Throws(CuaException::class)
+suspend fun relayUnregisterComputer(space: String, deleteSpaces: Boolean): Boolean
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn relay_unregister_computer(&self, space: String, delete_spaces: bool) -> Result<bool, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `space` | `String` | required |
+| `delete_spaces` | `bool` | required |
+
+**Returns** `bool` · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
## `SpaceRelayRegistration` record
A Space published on the relay (`Spaces.relay_register`).
diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdx
index 9a03b989c5..262e28c20d 100644
--- a/docs/content/docs/cua-sdk/reference/types.mdx
+++ b/docs/content/docs/cua-sdk/reference/types.mdx
@@ -48,7 +48,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f
## All items
-340 items. Methods are listed on their object.
+343 items. Methods are listed on their object.
The 10 items of Batched forks are listed on [its page](/cua-sdk/reference/sandbox/fork-batch#all-items).
@@ -133,6 +133,8 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record) | record | Identity of the SDK (and daemon, when connected). |
| [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum) | enum | Where the SDK runtime lives. |
| [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record) | record | One cursor shape's shared art: an SVG path on a square canvas, filled with the participant's color over an outline. |
+| [`DefaultSpace`](/cua-sdk/reference/spaces/default-space#defaultspace-record) | record | Where the default Space resolves now. |
+| [`DefaultSpaceStep`](/cua-sdk/reference/spaces/default-space#defaultspacestep-record) | record | One entry of the order `Devices.resolve_default_space` tried. |
| [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record) | record | `Devices.enroll`'s result. |
| [`Devices`](/cua-sdk/reference/spaces/host#devices) | object | This device as a client of the signed-in account on a relay: its enrollment, the account's other devices and its audit log. |
| [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record) | record | Everything the Devices page reads, in one call. |
@@ -346,6 +348,7 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record) | record | How busy one of your machines is (its job runner's view). |
| [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener) | object | Hears that the Space list changed (`Spaces.watch_list`). |
| [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch) | object | A running `Spaces.watch_list`. |
+| [`SpacesSettings`](/cua-sdk/reference/spaces/default-space#spacessettings-record) | record | The account's default Space and the order to try when it is offline. |
| [`SpacesToolMethod`](/cua-sdk/reference/spaces/info#spacestoolmethod-record) | record | One row of `SPACES_TOOL_METHODS`. |
| [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record) | record | What to stream and how. |
| [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession) | object | A live Space media session (see `Space.stream_session`). |
diff --git a/docs/content/docs/spaces/concepts/machines-and-spaces.mdx b/docs/content/docs/spaces/concepts/machines-and-spaces.mdx
index 15a00120e4..df7af0ef13 100644
--- a/docs/content/docs/spaces/concepts/machines-and-spaces.mdx
+++ b/docs/content/docs/spaces/concepts/machines-and-spaces.mdx
@@ -57,7 +57,7 @@ or the app). They describe one computer, and the **Computers** tab joins them in
one row when it can match them safely, for example by the same id or matching
names. If the match is unclear, such as two Macs with the same name, they stay as
separate rows. The `cua devices` commands manage the sign-in record, and
-`cua machines rm` removes a computer that is gone.
+`cua spaces rm` removes a computer that is gone, and keeps its Spaces on your account (detached) unless you pass `--delete-spaces`.
A computer that only hosts, set up with `--direct` or with its own token, can't
reach your other computers: signing in is what lets a computer see them.
@@ -65,3 +65,13 @@ reach your other computers: signing in is what lets a computer see them.
See [Add a computer](/spaces/guides/add-a-computer) for the two switches and how
to add one, and [How Spaces works](/spaces/concepts/how-spaces-works#space-ids)
for Space ids.
+
+## Your default Space
+
+Your account can name one Space as its default: where "my Space" goes when you do not say. The
+relay keeps it, so the app, `cua`, your phone and your agents all agree. If the default is
+offline, they try the order you set (or, by default, every online computer, oldest first), and
+then this computer. `cua spaces default` shows which one it picks and why, `cua spaces default
+<space>` sets it, and `--clear`, `--fallback a,b` and `--no-fallback` change the rest.
+`cua spaces ls --json` and the `list_spaces` tool mark it with `"default": true`, and give each
+Space a `parent`: the computer that provides it, or null for a computer.
diff --git a/docs/content/docs/spaces/guides/add-a-computer.mdx b/docs/content/docs/spaces/guides/add-a-computer.mdx
index 04fd87a600..738b577095 100644
--- a/docs/content/docs/spaces/guides/add-a-computer.mdx
+++ b/docs/content/docs/spaces/guides/add-a-computer.mdx
@@ -166,7 +166,10 @@ cua devices audit # who opened which machine, from which machine, and when
cua devices revoke dev_0123456789abcdef01234567
```
-A computer that is gone: `cua machines rm <name>` removes it from your relay directory and revokes its sign-in.
+A computer that is gone: `cua spaces rm <name>` removes it from your relay directory and revokes its sign-in.
+The Spaces it provided stay on your account, hidden, and come back unchanged if the computer is added
+again under the same id. `cua spaces rm <name> --delete-spaces` deletes them too, and their files on
+that computer when it can be reached. (`cua machines rm` still works for one more release and says so.)
In the app, the **Computers** tab holds all of it. A computer that asks to join waits under
**Waiting for you** with **Add computer** and **Not me** (Add computer asks for Touch ID or your login
diff --git a/docs/content/docs/spaces/reference/sharing-and-clouds.mdx b/docs/content/docs/spaces/reference/sharing-and-clouds.mdx
index 6550a8ec94..b6535b285c 100644
--- a/docs/content/docs/spaces/reference/sharing-and-clouds.mdx
+++ b/docs/content/docs/spaces/reference/sharing-and-clouds.mdx
@@ -257,7 +257,7 @@ JSON: `space`, `relay_space` (`relay:<computer>`: how the account's other device
Take a Space off the relay.
-Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead.
+Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead. Removing one of your computers keeps the Spaces it provides on your account, detached (hidden, and refused until the computer registers again with the same id, which brings them back unchanged); `delete_spaces: true` deletes them too, files first (through the computer while it answers), then their records.
| | |
| --- | --- |
@@ -273,6 +273,7 @@ Takes the Space off the relay: its driver leaves and its computer is removed, wi
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
+| `delete_spaces` | `boolean` | `false` | For one of your computers: also delete the Spaces it provides, their files first (through the computer while it answers), then their records. Default false: they stay on your account, detached, and come back when the computer registers again. |
| `space` | `string` | required | Space id or name. |
#### Result
diff --git a/docs/content/docs/spaces/reference/spaces.mdx b/docs/content/docs/spaces/reference/spaces.mdx
index 6835d23fac..5425a636da 100644
--- a/docs/content/docs/spaces/reference/spaces.mdx
+++ b/docs/content/docs/spaces/reference/spaces.mdx
@@ -112,7 +112,7 @@ Every registered Space (cloud, local, direct and relay) with its id (local:&lt;n
#### Result
-JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your computers provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay computer the relay cannot reach now `status` (`offline` or `not sharing`)), each with `phase`: `ready`, or `offline` for a relay computer the relay cannot reach now (a computer that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).
+JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your computers provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay computer the relay cannot reach now `status` (`offline` or `not sharing`)), `parent` (a Space one of your computers provides: that computer's Space id, `relay:<computer>`; null for a computer or any other Space) and `default` (true for the Space the account chose as its default, false for every other; false for all when signed out or the relay does not answer), each with `phase`: `ready`, or `offline` for a relay computer the relay cannot reach now (a computer that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).
#### Errors
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index d1369e713e..ab37e3555f 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -323,7 +323,7 @@ pub enum HostCmd {
},
}
-/// `cua machines`: your computers on the relay.
+/// `cua machines`: now `cua spaces` (kept one release).
#[derive(Subcommand, Debug)]
pub enum MachinesCmd {
/// Remove a computer that is gone: its row leaves your relay directory,
@@ -331,8 +331,8 @@ pub enum MachinesCmd {
/// device; nothing when several match). A computer that is connected now
/// is refused: run `cua host remove` on it.
#[command(after_help = "Examples:
- cua machines rm old-laptop
- cua machines rm relay:0123abcd4567ef89 --yes --json")]
+ cua spaces rm old-laptop
+ cua spaces rm relay:0123abcd4567ef89 --yes --json")]
Rm {
/// The computer's name, machine id or `relay:<id>` (`cua spaces ls`).
#[arg(value_name = "NAME")]
@@ -781,6 +781,52 @@ Examples:
Rm {
/// Space id, address or display name (as `cua spaces ls` shows).
space: String,
+ /// For one of your computers: also delete the Spaces it provides
+ /// and their files (through the computer while it is reachable).
+ /// Without it they stay on your account, detached, and come back
+ /// if the computer is added again.
+ #[arg(long)]
+ delete_spaces: bool,
+ /// Remove a computer without asking.
+ #[arg(long, short = 'y')]
+ yes: bool,
+ },
+ /// Your default Space: where "my Space" goes when you do not say. With
+ /// no argument it prints the Space it resolves to now and the order it
+ /// tries (online or not); with a Space it sets the default.
+ #[command(after_help = "Examples:
+ cua spaces default
+ cua spaces default studio
+ cua spaces default studio --fallback office-pc,relay:0123abcd4567ef89
+ # Only the default, then this computer
+ cua spaces default --no-fallback
+ # Back to trying every online computer, oldest first
+ cua spaces default --fallback-on
+ cua spaces default --clear")]
+ Default {
+ /// The Space to make your default: a name or id (as `cua spaces ls`
+ /// shows).
+ space: Option<String>,
+ /// Have no default.
+ #[arg(long, conflicts_with_all = ["space", "fallback", "no_fallback", "fallback_on"])]
+ clear: bool,
+ /// Spaces to try, in this order, when the default is offline
+ /// (names or ids, comma separated).
+ #[arg(
+ long,
+ value_delimiter = ',',
+ value_name = "SPACES",
+ conflicts_with = "no_fallback"
+ )]
+ fallback: Option<Vec<String>>,
+ /// When the default is offline, use this computer instead of trying
+ /// the others.
+ #[arg(long)]
+ no_fallback: bool,
+ /// Try the others again when the default is offline (every online
+ /// computer, oldest first, unless `--fallback` names an order).
+ #[arg(long)]
+ fallback_on: bool,
},
/// Give a Space a new name; its id stays the same. Lowercase letters,
/// digits and dashes, as at create. A Space you shared, or one of your
@@ -1199,7 +1245,7 @@ pub async fn run_spaces_sdk(
);
}
}
- SpacesCmd::Rm { space } => {
+ SpacesCmd::Rm { space, .. } => {
let info = spaces.resolve(space.clone()).await?;
// A Space cua created owns a sandbox (billed, for a cloud one):
// forgetting it would leave that sandbox running with nothing
@@ -1921,6 +1967,11 @@ pub async fn run_spaces_sdk(
"`cua spaces ls` runs over the registry directly".into(),
));
}
+ SpacesCmd::Default { .. } => {
+ return Err(CuaError::Internal(
+ "`cua spaces default` runs against the relay directly".into(),
+ ));
+ }
}
Ok(0)
}
@@ -2026,14 +2077,17 @@ impl AccountTokens for SessionTokens {
}
}
-/// `cua machines rm`: removes a computer that is gone (its relay row, then
-/// the one signed-in device named like it). The caller folds `--yes` into
-/// `confirm`.
+/// `cua spaces rm <computer>`: removes a computer that is gone (its relay
+/// row, then the one signed-in device named like it). Its Spaces stay on the
+/// account, detached, or with `delete_spaces` are deleted too. The caller
+/// folds `--yes` into `confirm`.
+#[allow(clippy::too_many_arguments)]
pub async fn remove_machine(
cua: &cua_sdk::Cua,
auth: &DeviceAuth,
tokens: &dyn AccountTokens,
name: &str,
+ delete_spaces: bool,
confirm: &dyn Fn(&str) -> bool,
json: bool,
out: &mut dyn Write,
@@ -2082,15 +2136,7 @@ pub async fn remove_machine(
"{rid} is shared with you; only its owner can remove it"
)));
}
- let hosted = m.host.as_deref().is_some_and(|h| !h.is_empty());
- let cloud = m
- .meta
- .get(cua_sandbox_core::byoc::meta::PROVIDER)
- .is_some_and(|p| !p.is_empty());
- let registered = !hosted
- && !m.meta.contains_key(cua_host::META_PROVIDES_SPACES)
- && m.id.starts_with("space-");
- if hosted || cloud || registered {
+ if !is_computer_row(m) {
return Err(CuaError::InvalidArgument(format!(
"{rid} is a Space, not a computer; manage it with `cua spaces`"
)));
@@ -2101,8 +2147,28 @@ pub async fn remove_machine(
m.name
)));
}
+ let children: Vec<String> = machines
+ .iter()
+ .filter(|c| c.host.as_deref() == Some(m.id.as_str()))
+ .map(|c| format!("relay:{}", c.id))
+ .collect();
+ let kept = if children.is_empty() {
+ String::new()
+ } else if delete_spaces {
+ format!(
+ " Its {} Space{} and their files will be deleted (the files only if the computer answers).",
+ children.len(),
+ if children.len() == 1 { "" } else { "s" }
+ )
+ } else {
+ format!(
+ " Its {} Space{} stay on your account, detached, and come back if the computer is added again.",
+ children.len(),
+ if children.len() == 1 { "" } else { "s" }
+ )
+ };
if !confirm(&format!(
- "Remove {} ({rid}) from your relay directory and revoke the signed-in device named {}?",
+ "Remove {} ({rid}) from your relay directory and revoke the signed-in device named {}?{kept}",
m.name, m.name
)) {
return Err(CuaError::PermissionDenied(
@@ -2110,12 +2176,16 @@ pub async fn remove_machine(
));
}
// Refuses again if the computer connected meanwhile.
- let removed = cua.spaces().relay_unregister(rid.clone()).await?;
+ let removed = cua
+ .spaces()
+ .relay_unregister_computer(rid.clone(), delete_spaces)
+ .await?;
let report = |out: &mut dyn Write, status: &str, ids: &[String], text: String| {
if json {
let v = serde_json::json!({
"machine": { "id": rid, "name": m.name },
"removed": removed,
+ "spaces": { "action": if delete_spaces { "deleted" } else { "detached" }, "ids": children },
"device": { "status": status, "ids": ids, "message": text },
});
line(out, v.to_string());
@@ -2125,6 +2195,21 @@ pub async fn remove_machine(
out,
format!("Removed {} ({rid}) from your relay directory.", m.name),
);
+ if !children.is_empty() {
+ line(
+ out,
+ format!(
+ "{} Space{} {}.",
+ children.len(),
+ if children.len() == 1 { "" } else { "s" },
+ if delete_spaces {
+ "deleted"
+ } else {
+ "detached: they come back if the computer is added again"
+ }
+ ),
+ );
+ }
} else {
line(
out,
@@ -2208,6 +2293,221 @@ pub async fn remove_machine(
Ok(0)
}
+/// Whether `m` is one of the account's computers (not a Space a computer
+/// provides, one in a cloud, or one that registered itself).
+fn is_computer_row(m: &cua_host::Machine) -> bool {
+ let hosted = m.host.as_deref().is_some_and(|h| !h.is_empty());
+ let cloud = m
+ .meta
+ .get(cua_sandbox_core::byoc::meta::PROVIDER)
+ .is_some_and(|p| !p.is_empty());
+ let registered = !hosted
+ && !m.meta.contains_key(cua_host::META_PROVIDES_SPACES)
+ && m.id.starts_with("space-");
+ !(hosted || cloud || registered)
+}
+
+/// Whether `name` (a name, machine id or `relay:<id>`) is exactly one of
+/// YOUR computers on the relay, so `cua spaces rm` takes it off the relay
+/// (detaching its Spaces) instead of forgetting a registered Space. Signed
+/// out, a relay that does not answer, no match or several: no.
+pub async fn owned_computer(auth: &DeviceAuth, tokens: &dyn AccountTokens, name: &str) -> bool {
+ let Ok(relay) = RelayClient::new(auth.relay_url()) else {
+ return false;
+ };
+ let Ok(token) = tokens.access_token().await else {
+ return false;
+ };
+ let Ok(machines) = auth.machines_for(&relay, &token).await else {
+ return false;
+ };
+ let mut hits = machines
+ .iter()
+ .filter(|m| m.id == name || format!("relay:{}", m.id) == name || m.name == name);
+ matches!((hits.next(), hits.next()), (Some(m), None) if m.role == "owner" && is_computer_row(m))
+}
+
+fn parse_fallback_id(raw: &str, machines: &[cua_host::Machine]) -> Result<String, CuaError> {
+ let raw = raw.trim();
+ let id = raw.strip_prefix("relay:").unwrap_or(raw);
+ // `relay:<computer>/<name>`: a Space inside a computer.
+ let (machine, rest) = match id.split_once('/') {
+ Some((m, n)) => (m, Some(n)),
+ None => (id, None),
+ };
+ let hits: Vec<&cua_host::Machine> = machines
+ .iter()
+ .filter(|m| m.id == machine || m.name.eq_ignore_ascii_case(machine))
+ .collect();
+ match hits.as_slice() {
+ [m] => Ok(match rest {
+ Some(n) => format!("relay:{}/{n}", m.id),
+ None => format!("relay:{}", m.id),
+ }),
+ [] => Err(CuaError::NotFound(format!(
+ "no Space named {raw:?} on your account (`cua spaces ls` lists them)"
+ ))),
+ many => Err(CuaError::InvalidArgument(format!(
+ "several Spaces are named {raw:?}: pass one of {}",
+ many.iter()
+ .map(|m| format!("relay:{}", m.id))
+ .collect::<Vec<_>>()
+ .join(", ")
+ ))),
+ }
+}
+
+/// `cua spaces default`: show, or change, the account's default Space.
+pub async fn run_spaces_default(
+ cmd: SpacesCmd,
+ home: &Path,
+ tokens: Option<Arc<dyn AccountTokens>>,
+ device: Option<Arc<DeviceAuth>>,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<i32, CuaError> {
+ let SpacesCmd::Default {
+ space,
+ clear,
+ fallback,
+ no_fallback,
+ fallback_on,
+ } = cmd
+ else {
+ return Err(CuaError::Internal("not `cua spaces default`".into()));
+ };
+ let (Some(tokens), Some(auth)) = (tokens, device) else {
+ return Err(CuaError::Unauthenticated(
+ "sign in to cua.ai first (`cua auth login`): the default Space is kept on your account"
+ .into(),
+ ));
+ };
+ let token = tokens.access_token().await.map_err(host_err)?;
+ let session = auth.session().await.map_err(host_err)?;
+ let relay = RelayClient::new(auth.relay_url())
+ .map_err(host_err)?
+ .with_device_session(Some(session));
+ let changes = space.is_some() || clear || fallback.is_some() || no_fallback || fallback_on;
+ let mut saved = None;
+ if changes {
+ let machines = auth.machines_for(&relay, &token).await.map_err(host_err)?;
+ let mut s = relay.spaces_settings(&token).await.map_err(host_err)?;
+ if clear {
+ s.default_space = None;
+ }
+ if let Some(sp) = &space {
+ s.default_space = Some(parse_fallback_id(sp, &machines)?);
+ }
+ if let Some(list) = &fallback {
+ s.fallback = list
+ .iter()
+ .filter(|v| !v.trim().is_empty())
+ .map(|v| parse_fallback_id(v, &machines))
+ .collect::<Result<_, _>>()?;
+ s.fallback_on = true;
+ }
+ if no_fallback {
+ s.fallback_on = false;
+ }
+ if fallback_on {
+ s.fallback_on = true;
+ }
+ // The default is not also one of its own fallbacks.
+ if let Some(d) = s.default_space.clone() {
+ s.fallback.retain(|f| *f != d);
+ }
+ saved = Some(
+ relay
+ .set_spaces_settings(&token, &s)
+ .await
+ .map_err(host_err)?,
+ );
+ }
+ let here = cua_host::Host::new(home)
+ .config()
+ .ok()
+ .flatten()
+ .and_then(|c| c.machine_id)
+ .filter(|id| !id.is_empty());
+ let resolved = relay
+ .resolve_default_space(&token, here.as_deref())
+ .await
+ .map_err(host_err)?;
+ let settings = match saved {
+ Some(s) => s,
+ None => relay.spaces_settings(&token).await.map_err(host_err)?,
+ };
+ if json {
+ line(
+ out,
+ serde_json::json!({
+ "space": resolved.space,
+ "reason": resolved.reason,
+ "default_space": resolved.default_space,
+ "default_online": resolved.default_online,
+ "order": resolved.order,
+ "settings": settings,
+ })
+ .to_string(),
+ );
+ return Ok(0);
+ }
+ let state = |online: bool| if online { "online" } else { "offline" };
+ let name_of = |id: &str| {
+ resolved
+ .order
+ .iter()
+ .find(|s| s.space == id)
+ .map(|s| s.name.clone())
+ .filter(|n| !n.is_empty())
+ .unwrap_or_else(|| id.to_string())
+ };
+ match &resolved.default_space {
+ None => line(out, "No default Space is set."),
+ Some(d) => line(
+ out,
+ format!(
+ "Default: {} ({d}), {}",
+ name_of(d),
+ state(resolved.default_online.unwrap_or(false))
+ ),
+ ),
+ }
+ match (&resolved.space, resolved.reason.as_str()) {
+ (Some(s), "default") => line(out, format!("Using: {} (the default)", name_of(s))),
+ (Some(s), _) => line(
+ out,
+ format!(
+ "Using: {} ({}, because the default is not available)",
+ name_of(s),
+ resolved.reason
+ ),
+ ),
+ (None, _) => line(out, "Using: this computer."),
+ }
+ line(
+ out,
+ if settings.fallback_on {
+ "If the default is offline: try the others"
+ } else {
+ "If the default is offline: use this computer"
+ },
+ );
+ for (i, st) in resolved.order.iter().enumerate() {
+ line(
+ out,
+ format!(
+ " {}. {:<28} {:<9} {}",
+ i + 1,
+ st.name,
+ st.role,
+ state(st.online)
+ ),
+ );
+ }
+ Ok(0)
+}
+
pub fn host_err(e: cua_host::Error) -> CuaError {
let message = e.to_string();
host_error(e, message)
@@ -3614,6 +3914,8 @@ fn ls_json(list: &[cua_spaces::SpaceInfo]) -> Vec<serde_json::Value> {
let mut v = serde_json::to_value(s).unwrap_or_default();
if let Some(o) = v.as_object_mut() {
o.insert("display_name".into(), display_name(s).into());
+ o.insert("parent".into(), s.parent_space_id().into());
+ o.insert("default".into(), false.into());
}
v
})
@@ -3976,8 +4278,17 @@ pub async fn run_spaces(
let on_account = spaces.relay_states(&list);
if json {
let mut rows = ls_json(&list);
+ // Never holds the list up: signed out or a relay that does not
+ // answer is "no default".
+ let default = spaces.default_space_id().await;
for (row, info) in rows.iter_mut().zip(&list) {
columns.annotate(info, row);
+ if let Some(o) = row.as_object_mut() {
+ o.insert(
+ "default".into(),
+ (default.as_deref() == Some(info.id.as_str())).into(),
+ );
+ }
if let (Some(o), Some(state)) = (row.as_object_mut(), on_account.get(&info.id)) {
o.insert("relay".into(), (*state).into());
}
@@ -5853,6 +6164,16 @@ mod tests {
arg: &str,
json: bool,
answer: impl Fn() -> bool,
+ ) -> (Result<i32, CuaError>, String, u32) {
+ rm_with(f, arg, false, json, answer).await
+ }
+
+ async fn rm_with(
+ f: &Fx,
+ arg: &str,
+ delete_spaces: bool,
+ json: bool,
+ answer: impl Fn() -> bool,
) -> (Result<i32, CuaError>, String, u32) {
let asked = Cell::new(0);
let mut out = Vec::new();
@@ -5861,6 +6182,7 @@ mod tests {
&f.auth,
&StaticToken("acct".into()),
arg,
+ delete_spaces,
&|_| {
asked.set(asked.get() + 1);
answer()
@@ -5902,6 +6224,151 @@ mod tests {
assert_eq!(v["device"]["ids"], serde_json::json!([f.remote[0]]));
}
+ const CHILD: &str = "bbbb111122223333";
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn spaces_rm_of_a_computer_detaches_its_spaces_unless_told_to_delete_them() {
+ for delete_spaces in [false, true] {
+ let f = fx(&["old-laptop"]).await;
+ register(&f.relay, CHILD, "research", Some(ID), Default::default()).await;
+ let (r, text, asked) =
+ rm_with(&f, "old-laptop", delete_spaces, true, || true).await;
+ assert_eq!(r.unwrap(), 0, "{text}");
+ assert_eq!(asked, 1);
+ let v: serde_json::Value = serde_json::from_str(&text).unwrap();
+ assert_eq!(
+ v["spaces"]["action"],
+ if delete_spaces { "deleted" } else { "detached" }
+ );
+ assert_eq!(
+ v["spaces"]["ids"],
+ serde_json::json!([format!("relay:{CHILD}")])
+ );
+ assert!(f.relay.machine(ID).is_none());
+ assert_eq!(f.relay.machine(CHILD).is_some(), !delete_spaces, "{text}");
+ }
+ // The prompt and the one-line summary say what happens to them.
+ let f = fx(&["old-laptop"]).await;
+ register(&f.relay, CHILD, "research", Some(ID), Default::default()).await;
+ let prompt = Cell::new(String::new());
+ let mut out = Vec::new();
+ remove_machine(
+ &f.cua,
+ &f.auth,
+ &StaticToken("acct".into()),
+ "old-laptop",
+ false,
+ &|q| {
+ prompt.set(q.to_string());
+ true
+ },
+ false,
+ &mut out,
+ )
+ .await
+ .unwrap();
+ let text = String::from_utf8(out).unwrap();
+ assert!(
+ prompt
+ .take()
+ .contains("Its 1 Space stay on your account, detached"),
+ "prompt"
+ );
+ assert!(
+ text.contains("1 Space detached: they come back if the computer is added again."),
+ "{text}"
+ );
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn owned_computer_is_only_one_of_your_computers() {
+ let f = fx(&["old-laptop"]).await;
+ register(&f.relay, CHILD, "research", Some(ID), Default::default()).await;
+ let tokens = StaticToken("acct".into());
+ assert!(owned_computer(&f.auth, &tokens, "old-laptop").await);
+ assert!(owned_computer(&f.auth, &tokens, &format!("relay:{ID}")).await);
+ // A Space a computer provides, and a name that matches nothing,
+ // keep `cua spaces rm`'s old meaning.
+ assert!(!owned_computer(&f.auth, &tokens, "research").await);
+ assert!(!owned_computer(&f.auth, &tokens, "nothing-here").await);
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn spaces_default_shows_sets_and_clears_the_default() {
+ let f = fx(&["old-laptop"]).await;
+ f.relay.set_online(ID, true, "1.0");
+ let run = |cmd: SpacesCmd, json: bool| {
+ let auth = f.auth.clone();
+ let home = f._dir.path().join("cua");
+ async move {
+ let mut out = Vec::new();
+ let r = run_spaces_default(
+ cmd,
+ &home,
+ Some(Arc::new(StaticToken("acct".into()))),
+ Some(auth),
+ json,
+ &mut out,
+ )
+ .await;
+ (r, String::from_utf8(out).unwrap())
+ }
+ };
+ let cmd = |space: Option<&str>, clear: bool| SpacesCmd::Default {
+ space: space.map(Into::into),
+ clear,
+ fallback: None,
+ no_fallback: false,
+ fallback_on: false,
+ };
+ // Unset.
+ let (r, text) = run(cmd(None, false), true).await;
+ assert_eq!(r.unwrap(), 0, "{text}");
+ let v: serde_json::Value = serde_json::from_str(&text).unwrap();
+ assert!(v["default_space"].is_null(), "{text}");
+ // Set by name, and read back with the order.
+ let (r, text) = run(cmd(Some("old-laptop"), false), true).await;
+ assert_eq!(r.unwrap(), 0, "{text}");
+ let v: serde_json::Value = serde_json::from_str(&text).unwrap();
+ assert_eq!(v["default_space"], format!("relay:{ID}"), "{text}");
+ assert_eq!(v["reason"], "default");
+ assert_eq!(v["default_online"], true);
+ assert_eq!(v["order"][0]["role"], "default");
+ assert_eq!(v["settings"]["fallback_on"], true);
+ let (r, text) = run(cmd(None, false), false).await;
+ assert_eq!(r.unwrap(), 0);
+ assert!(
+ text.contains("Default: old-laptop (relay:0123abcd4567ef89), online"),
+ "{text}"
+ );
+ assert!(text.contains("Using: old-laptop (the default)"), "{text}");
+ // No fallback, then clear.
+ let no_fallback = SpacesCmd::Default {
+ space: None,
+ clear: false,
+ fallback: None,
+ no_fallback: true,
+ fallback_on: false,
+ };
+ let (_, text) = run(no_fallback, true).await;
+ let v: serde_json::Value = serde_json::from_str(&text).unwrap();
+ assert_eq!(v["settings"]["fallback_on"], false, "{text}");
+ let (_, text) = run(cmd(None, true), true).await;
+ let v: serde_json::Value = serde_json::from_str(&text).unwrap();
+ assert!(v["default_space"].is_null(), "{text}");
+ // An unknown name is refused with its name; signed out says so.
+ let (r, _) = run(cmd(Some("no-such-box"), false), true).await;
+ let Err(CuaError::NotFound(m)) = r else {
+ panic!("{r:?}")
+ };
+ assert!(m.contains("no-such-box"), "{m}");
+ let mut out = Vec::new();
+ let r =
+ run_spaces_default(cmd(None, false), f._dir.path(), None, None, false, &mut out)
+ .await;
+ assert!(matches!(r, Err(CuaError::Unauthenticated(_))), "{r:?}");
+ }
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn machines_rm_refuses_a_connected_computer() {
let f = fx(&["old-laptop"]).await;
@@ -6049,6 +6516,7 @@ mod tests {
&g.auth,
&StaticToken("acct".into()),
"old-laptop",
+ false,
&|_| {
g.relay.require_devices(false);
std::thread::scope(|s| {
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index d57819316e..503b830b87 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -338,8 +338,8 @@ enum Command {
cua computers
cua computers --json")]
Computers,
- /// Your computers on the relay: remove one that is gone.
- #[command(subcommand)]
+ /// Now `cua spaces` (kept for one release).
+ #[command(subcommand, hide = true)]
Machines(host::MachinesCmd),
/// Unattended access to this computer (setup, status, stop, start, remove).
#[command(subcommand)]
@@ -1767,6 +1767,27 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
}
_ => {}
}
+ // `cua spaces rm <computer>`: one of your computers on the relay is
+ // taken off it (its Spaces detached); anything else is a registered
+ // Space, forgotten as before.
+ if let Command::Machines(host::MachinesCmd::Rm { name, yes }) = &cli.command {
+ let (name, yes) = (name.clone(), *yes);
+ eprintln!("`cua machines` is now `cua spaces`.");
+ return remove_computer(cli, &name, false, yes, json, out).await;
+ }
+ let rm = match &cli.command {
+ Command::Spaces(host::SpacesCmd::Rm {
+ space,
+ delete_spaces,
+ yes,
+ }) => Some((space.clone(), *delete_spaces, *yes)),
+ _ => None,
+ };
+ if let Some((space, delete_spaces, yes)) = rm
+ && owns_computer(&space).await
+ {
+ return remove_computer(cli, &space, delete_spaces, yes, json, out).await;
+ }
match cli.command {
Command::Run(a) => return jobs_cmd::run(a, json, out).await,
Command::Jobs(a) => return jobs_cmd::jobs(a, json, out).await,
@@ -2007,33 +2028,17 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
host::attach_relay_account(&cua, || host::daemon_relay_account(&util::cua_home()));
return cloud_cmd::run(&cua, cmd, json, out).await;
}
- Command::Machines(host::MachinesCmd::Rm { name, yes }) => {
- // Embedded: the row, the lookup and the device all use this
- // process's relay, never a daemon's.
- let rest = Cli {
- command: Command::Spaces(host::SpacesCmd::Ls {
- relay: None,
- label: vec![],
- no_size: false,
- tree: false,
- }),
- embedded: true,
- ..cli
- };
- let cua = open(&rest, false).await?;
+ Command::Spaces(cmd @ host::SpacesCmd::Default { .. }) => {
+ let tokens: Option<Arc<dyn cua_host::AccountTokens>> =
+ match auth::session_token(&auth::Store::from_env()).await {
+ Ok(Some(_)) => Some(Arc::new(host::SessionTokens)),
+ _ => None,
+ };
let home = util::cua_home();
- host::attach_relay_account(&cua, || host::daemon_relay_account(&home));
- let auth = devices_cmd::device_auth(&host::relay_url(None, &home))?;
- return host::remove_machine(
- &cua,
- &auth,
- &host::SessionTokens,
- &name,
- &|q| yes || (util::interactive() && util::confirm(q, false)),
- json,
- out,
- )
- .await;
+ let device = tokens
+ .as_ref()
+ .and_then(|_| devices_cmd::device_auth(&host::relay_url(None, &home)).ok());
+ return host::run_spaces_default(cmd, &home, tokens, device, json, out).await;
}
Command::Spaces(host::SpacesCmd::Ls { .. })
if cli.daemon.is_none() && cua_daemon::client::spawn_channel().is_some() =>
@@ -2429,6 +2434,63 @@ async fn run_sdk(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
Ok(0)
}
+/// Whether `target` is one of your computers on the relay (signed in, one
+/// match, you own it): see [`host::owned_computer`].
+async fn owns_computer(target: &str) -> bool {
+ if auth::session_token(&auth::Store::from_env())
+ .await
+ .ok()
+ .flatten()
+ .is_none()
+ {
+ return false;
+ }
+ let home = util::cua_home();
+ match devices_cmd::device_auth(&host::relay_url(None, &home)) {
+ Ok(a) => host::owned_computer(&a, &host::SessionTokens, target).await,
+ Err(_) => false,
+ }
+}
+
+/// Takes one of your computers off the relay (`cua spaces rm <computer>`):
+/// its Spaces are detached, or with `delete_spaces` deleted too.
+async fn remove_computer(
+ cli: Cli,
+ name: &str,
+ delete_spaces: bool,
+ yes: bool,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<i32, CuaError> {
+ // Embedded: the row, the lookup and the device all use this process's
+ // relay, never a daemon's.
+ let rest = Cli {
+ command: Command::Spaces(host::SpacesCmd::Ls {
+ relay: None,
+ label: vec![],
+ no_size: false,
+ tree: false,
+ }),
+ embedded: true,
+ ..cli
+ };
+ let cua = open(&rest, false).await?;
+ let home = util::cua_home();
+ host::attach_relay_account(&cua, || host::daemon_relay_account(&home));
+ let auth = devices_cmd::device_auth(&host::relay_url(None, &home))?;
+ host::remove_machine(
+ &cua,
+ &auth,
+ &host::SessionTokens,
+ name,
+ delete_spaces,
+ &|q| yes || (util::interactive() && util::confirm(q, false)),
+ json,
+ out,
+ )
+ .await
+}
+
/// `cua cloud add aws` (builds with AWS: the `byoc` feature).
#[cfg(feature = "byoc")]
async fn add_aws(a: onboard::AwsArgs, json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {
@@ -3801,6 +3863,37 @@ mod tests {
};
assert!(name == "old-laptop" && yes);
assert!(parse(&["machines", "ls"]).is_err());
+ // `cua spaces rm <computer>` and `cua spaces default` take the new flags.
+ let Command::Spaces(host::SpacesCmd::Rm {
+ space,
+ delete_spaces,
+ yes,
+ }) = parse(&["spaces", "rm", "old-laptop", "--delete-spaces", "-y"])
+ .unwrap()
+ .command
+ else {
+ panic!()
+ };
+ assert!(space == "old-laptop" && delete_spaces && yes);
+ let Command::Spaces(host::SpacesCmd::Default {
+ space,
+ fallback,
+ no_fallback,
+ ..
+ }) = parse(&["spaces", "default", "studio", "--fallback", "a,relay:b"])
+ .unwrap()
+ .command
+ else {
+ panic!()
+ };
+ assert_eq!(space.as_deref(), Some("studio"));
+ assert_eq!(fallback, Some(vec!["a".to_string(), "relay:b".to_string()]));
+ assert!(!no_fallback);
+ assert!(parse(&["spaces", "default", "--clear", "studio"]).is_err());
+ assert!(parse(&["spaces", "default", "--no-fallback", "--fallback", "a"]).is_err());
+ // The old name is hidden from help.
+ let help = Cli::command().render_help().to_string();
+ assert!(!help.contains(" machines "), "{help}");
for sb in ["sb", "sandbox"] {
let e = parse(&[sb, "runs", "--machines"]).unwrap_err();
assert_eq!(
diff --git a/libs/cua/crates/cua-cli/src/onboard.rs b/libs/cua/crates/cua-cli/src/onboard.rs
index 135a3c2e33..d1b82e05ae 100644
--- a/libs/cua/crates/cua-cli/src/onboard.rs
+++ b/libs/cua/crates/cua-cli/src/onboard.rs
@@ -238,10 +238,13 @@ impl HostState {
HostState { status, dedicated }
}
- /// Whether this machine already is the host `w` asks for.
+ /// Whether this machine already is the host `w` asks for. A computer
+ /// the relay no longer knows (removed from the account on another
+ /// device) is not: setup registers it again, so "add it again" works.
pub fn is_up(&self, w: &Want) -> bool {
let s = &self.status;
s["configured"].as_bool() == Some(true)
+ && s["revoked"].as_bool() != Some(true)
&& s["mode"].as_str() == Some("relay")
&& s["service"]["running"].as_bool() == Some(true)
&& w.provide_spaces
@@ -576,6 +579,30 @@ mod tests {
}
}
+ #[test]
+ fn a_computer_removed_from_the_account_is_set_up_again() {
+ let status = json!({
+ "configured": true, "mode": "relay", "relayUrl": "https://relay.example/",
+ "machineId": "abc", "name": "studio",
+ "service": {"running": true, "kind": "systemd"}, "provideSpaces": true,
+ "shareDesktop": false, "revoked": true, "error": "relay: invalid computer token",
+ });
+ let up = HostState {
+ status: status.clone(),
+ dedicated: false,
+ };
+ assert!(!up.is_up(&want()));
+ let mut down = status;
+ down["service"]["running"] = json!(false);
+ assert!(
+ !HostState {
+ status: down,
+ dedicated: false
+ }
+ .is_down(&want())
+ );
+ }
+
#[test]
fn setup_is_a_no_op_only_when_everything_matches() {
let status = json!({
diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rs
index 2c714d459a..ca77b9fef0 100644
--- a/libs/cua/crates/cua-host/src/host.rs
+++ b/libs/cua/crates/cua-host/src/host.rs
@@ -835,6 +835,11 @@ pub struct HostStatus {
pub permissions: Vec<PermissionHint>,
/// Last error talking to the relay, if any.
pub error: Option<String>,
+ /// The relay refused this computer's token: it was removed from the
+ /// account (from another device, which detaches or deletes its Spaces).
+ /// `host setup` then registers it again instead of calling it set up.
+ #[serde(default)]
+ pub revoked: bool,
/// Who reached this machine recently, newest first (the driver's
/// hash-chained access log).
#[serde(default)]
@@ -2229,7 +2234,10 @@ impl Host {
status.allow = m.allow;
}
}
- Err(e) => status.error = Some(e.to_string()),
+ Err(e) => {
+ status.revoked = matches!(e, Error::Unauthenticated(_));
+ status.error = Some(e.to_string());
+ }
}
}
self.add_access(&mut status, now_ms());
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index 9ec6eeb63d..803954b5c2 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -79,9 +79,10 @@ pub use provided::{
HostProfile, HostSpacesSettings, MachineMatch, ProvidedSpace, SpacesAuditRecord, match_machine,
};
pub use relay::{
- AccountTokens, AuditEvent, ConnectedClient, DEFAULT_RELAY_URL, DeviceListing, DeviceState,
- DeviceView, Enrollment, Identity, LinkProbe, Machine, MachinePatch, NoAccount, RelayClient,
- RelayUsage, RelayUsageTeam, StaticToken, TcpShareRequest, TcpShareView, relay_url_from_env,
+ AccountTokens, AuditEvent, ConnectedClient, DEFAULT_RELAY_URL, DefaultSpace, DefaultSpaceStep,
+ DeviceListing, DeviceState, DeviceView, Enrollment, Identity, LinkProbe, Machine, MachinePatch,
+ NoAccount, RelayClient, RelayUsage, RelayUsageTeam, SpacesSettings, StaticToken,
+ TcpShareRequest, TcpShareView, relay_url_from_env,
};
pub use service::{RunnerKind, ServiceManager, ServiceSpec, ServiceState};
diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rs
index 6581adfe44..043c739ede 100644
--- a/libs/cua/crates/cua-host/src/relay.rs
+++ b/libs/cua/crates/cua-host/src/relay.rs
@@ -247,6 +247,66 @@ pub struct Registration {
pub jwks: serde_json::Value,
}
+/// The account's default Space and the order to try when it is offline
+/// (`GET`/`PUT /v1/spaces/settings`).
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub struct SpacesSettings {
+ /// `relay:<machine>` or `relay:<machine>/<name>`; none when unset.
+ #[serde(default)]
+ pub default_space: Option<String>,
+ /// Ids to try, in order, when the default is offline. Empty: every
+ /// online computer you can use, oldest first.
+ #[serde(default)]
+ pub fallback: Vec<String>,
+ /// false: only the default, then this device.
+ #[serde(default = "fallback_on_default")]
+ pub fallback_on: bool,
+ /// Unix seconds the relay saved it (ignored on write).
+ #[serde(default)]
+ pub updated_at: u64,
+}
+
+fn fallback_on_default() -> bool {
+ true
+}
+
+/// One entry of [`DefaultSpace::order`].
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub struct DefaultSpaceStep {
+ /// The Space id.
+ pub space: String,
+ /// Its display name.
+ #[serde(default)]
+ pub name: String,
+ /// Connected and sharing now.
+ #[serde(default)]
+ pub online: bool,
+ /// `default`, `fallback` or `here`.
+ #[serde(default)]
+ pub role: String,
+}
+
+/// `GET /v1/spaces/default`: where "my default Space" resolves now.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub struct DefaultSpace {
+ /// The first online entry of the order; none with reason `here` when
+ /// this device is the answer.
+ #[serde(default)]
+ pub space: Option<String>,
+ /// `default`, `fallback`, `here` or `unset`.
+ #[serde(default)]
+ pub reason: String,
+ /// The chosen default, online or not.
+ #[serde(default)]
+ pub default_space: Option<String>,
+ /// Whether the default is online (none when unset).
+ #[serde(default)]
+ pub default_online: Option<bool>,
+ /// The order the relay tried.
+ #[serde(default)]
+ pub order: Vec<DefaultSpaceStep>,
+}
+
/// `PATCH /v1/machines/{id}` body.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct MachinePatch {
@@ -1055,6 +1115,66 @@ impl RelayClient {
.await
}
+ /// The account's default Space settings (`GET /v1/spaces/settings`).
+ /// A relay that predates them answers [`RELAY_NEEDS_UPDATE`]
+ /// ([`is_relay_outdated`]).
+ pub async fn spaces_settings(&self, account_token: &str) -> Result<SpacesSettings> {
+ self.spaces_route(
+ self.http.get(self.url("/v1/spaces/settings")),
+ account_token,
+ )
+ .await
+ }
+
+ /// Replaces the account's default Space settings (`PUT`, whole object).
+ pub async fn set_spaces_settings(
+ &self,
+ account_token: &str,
+ settings: &SpacesSettings,
+ ) -> Result<SpacesSettings> {
+ self.spaces_route(
+ self.http
+ .put(self.url("/v1/spaces/settings"))
+ .json(settings),
+ account_token,
+ )
+ .await
+ }
+
+ /// Where the default Space resolves now (`GET /v1/spaces/default`).
+ /// `here` is this computer's own machine id, when it has one.
+ pub async fn resolve_default_space(
+ &self,
+ account_token: &str,
+ here: Option<&str>,
+ ) -> Result<DefaultSpace> {
+ let mut url = self.url("/v1/spaces/default");
+ if let Some(h) = here.filter(|h| !h.is_empty()) {
+ url.push_str("?here=");
+ url.push_str(h);
+ }
+ self.spaces_route(self.http.get(url), account_token).await
+ }
+
+ /// One request to a `/v1/spaces/...` route, mapping "no such route" to
+ /// [`RELAY_NEEDS_UPDATE`].
+ async fn spaces_route<T: serde::de::DeserializeOwned>(
+ &self,
+ req: reqwest::RequestBuilder,
+ account_token: &str,
+ ) -> Result<T> {
+ match self.send_once::<T>(req, account_token).await {
+ Ok(r) => Ok(r),
+ Err((Error::NotFound(m), _)) if m.trim_end() == "relay:" => {
+ Err(Error::Relay(RELAY_NEEDS_UPDATE.into()))
+ }
+ Err((Error::Relay(m), _)) if m.starts_with("HTTP 405") => {
+ Err(Error::Relay(RELAY_NEEDS_UPDATE.into()))
+ }
+ Err((e, _)) => Err(e),
+ }
+ }
+
/// Vouches for a machine that registered without proof (S5): shows it
/// as "new" no longer. Owner only, from an enrolled device
/// ([`RelayClient::with_device_session`]); a machine cannot confirm
@@ -1070,13 +1190,27 @@ impl RelayClient {
}
/// Deletes the machine and revokes its token (owner or machine token).
+ /// The Spaces it provides stay on the account, detached: they come
+ /// back when the computer registers again under the same id.
pub async fn delete(&self, credential: &str, id: &str) -> Result<()> {
- let _: serde_json::Value = self
- .send(
- self.http.delete(self.url(&format!("/v1/machines/{id}"))),
- credential,
- )
- .await?;
+ self.delete_machine(credential, id, false).await
+ }
+
+ /// [`RelayClient::delete`], and with `delete_spaces` (owner only) the
+ /// records of the Spaces it provides go too
+ /// (`DELETE /v1/machines/{id}?spaces=delete`). Their files are the
+ /// caller's to delete through the computer first.
+ pub async fn delete_machine(
+ &self,
+ credential: &str,
+ id: &str,
+ delete_spaces: bool,
+ ) -> Result<()> {
+ let mut url = self.url(&format!("/v1/machines/{id}"));
+ if delete_spaces {
+ url.push_str("?spaces=delete");
+ }
+ let _: serde_json::Value = self.send(self.http.delete(url), credential).await?;
Ok(())
}
@@ -1446,6 +1580,115 @@ mod tests {
assert_eq!(e.to_string(), "relay: the Cua relay needs an update");
}
+ /// The default-Space routes and `spaces=delete`, against a mock relay
+ /// that records what it was sent.
+ #[tokio::test]
+ async fn default_space_routes_send_what_the_contract_says() {
+ use axum::extract::{Query, State};
+ use std::collections::HashMap;
+ use std::sync::{Arc, Mutex};
+ type Log = Arc<Mutex<Vec<String>>>;
+ let log: Log = Arc::default();
+ let app = axum::Router::new()
+ .route(
+ "/v1/spaces/settings",
+ axum::routing::get(|| async {
+ axum::Json(serde_json::json!({"default_space": "relay:abc",
+ "fallback": ["relay:def"], "fallback_on": false, "updated_at": 7}))
+ })
+ .put(|State(l): State<Log>, body: String| async move {
+ l.lock().unwrap().push(format!("PUT {body}"));
+ axum::Json(serde_json::json!({"default_space": null,
+ "fallback": [], "fallback_on": true, "updated_at": 9}))
+ }),
+ )
+ .route(
+ "/v1/spaces/default",
+ axum::routing::get(
+ |State(l): State<Log>, Query(q): Query<HashMap<String, String>>| async move {
+ l.lock().unwrap().push(format!("here={:?}", q.get("here")));
+ axum::Json(serde_json::json!({"space": "relay:def", "reason": "fallback",
+ "default_space": "relay:abc", "default_online": false,
+ "order": [{"space": "relay:abc", "name": "Studio", "online": false, "role": "default"},
+ {"space": "relay:def", "name": "PC", "online": true, "role": "fallback"}]}))
+ },
+ ),
+ )
+ .route(
+ "/v1/machines/m1",
+ axum::routing::delete(
+ |State(l): State<Log>, Query(q): Query<HashMap<String, String>>| async move {
+ l.lock().unwrap().push(format!("DELETE spaces={:?}", q.get("spaces")));
+ axum::Json(serde_json::json!({"ok": true}))
+ },
+ ),
+ )
+ .with_state(log.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let client = RelayClient::new(&format!("http://{addr}")).unwrap();
+
+ let got = client.spaces_settings("tok").await.unwrap();
+ assert_eq!(got.default_space.as_deref(), Some("relay:abc"));
+ assert_eq!(got.fallback, vec!["relay:def".to_string()]);
+ assert!(!got.fallback_on && got.updated_at == 7);
+
+ let put = SpacesSettings {
+ default_space: None,
+ fallback: vec![],
+ fallback_on: true,
+ updated_at: 0,
+ };
+ assert_eq!(
+ client
+ .set_spaces_settings("tok", &put)
+ .await
+ .unwrap()
+ .updated_at,
+ 9
+ );
+
+ let d = client
+ .resolve_default_space("tok", Some("here1"))
+ .await
+ .unwrap();
+ assert_eq!(d.reason, "fallback");
+ assert_eq!(d.default_online, Some(false));
+ assert_eq!(d.order.len(), 2);
+ assert_eq!(d.order[1].role, "fallback");
+ client.resolve_default_space("tok", None).await.unwrap();
+
+ client.delete("tok", "m1").await.unwrap();
+ client.delete_machine("tok", "m1", true).await.unwrap();
+
+ let log = log.lock().unwrap().clone();
+ let put_body: serde_json::Value =
+ serde_json::from_str(log[0].strip_prefix("PUT ").unwrap()).unwrap();
+ assert_eq!(put_body["default_space"], serde_json::Value::Null);
+ assert_eq!(put_body["fallback_on"], true);
+ assert_eq!(
+ &log[1..],
+ [
+ "here=Some(\"here1\")",
+ "here=None",
+ "DELETE spaces=None",
+ "DELETE spaces=Some(\"delete\")"
+ ]
+ );
+
+ // A relay that predates the routes (its own 404 has no JSON error).
+ let old = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let old_addr = old.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(old, axum::Router::new()).await.unwrap() });
+ let e = RelayClient::new(&format!("http://{old_addr}"))
+ .unwrap()
+ .spaces_settings("tok")
+ .await
+ .unwrap_err();
+ assert!(is_relay_outdated(&e), "{e:?}");
+ }
+
#[tokio::test]
async fn a_plan_limit_refusal_is_one_plain_sentence_and_is_not_retried() {
use std::sync::Arc;
diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rs
index 6425f42700..8c9909e46f 100644
--- a/libs/cua/crates/cua-host/src/testing.rs
+++ b/libs/cua/crates/cua-host/src/testing.rs
@@ -15,7 +15,7 @@
//! rest are answered 502.
use crate::relay::{ConnectedClient, Identity, Machine};
-use axum::extract::{Path, State};
+use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
@@ -87,6 +87,10 @@ struct State_ {
ignore_meta_patches: bool,
/// Answers `POST /v1/machines/{id}/leave` as a relay that predates it.
without_leave: bool,
+ /// The account default Space settings last saved, by account id.
+ spaces_settings: BTreeMap<String, serde_json::Value>,
+ /// Answers the `/v1/spaces/...` routes as a relay that predates them.
+ without_spaces_settings: bool,
/// A relay (or its control plane) that refuses to change who a computer
/// is shared with, with this code (`share_outside_team`).
refuse_shares: Option<String>,
@@ -562,7 +566,19 @@ async fn list(State(s): State<S>, headers: HeaderMap) -> Response {
let Some(Caller::Account(who)) = caller(&st, &headers) else {
return err(StatusCode::UNAUTHORIZED, "account token required");
};
- let machines: Vec<Machine> = st.machines.values().filter_map(|r| view(r, &who)).collect();
+ // A Space whose computer was removed is detached: hidden until the
+ // computer registers again.
+ let machines: Vec<Machine> = st
+ .machines
+ .values()
+ .filter(|r| {
+ r.machine
+ .host
+ .as_deref()
+ .is_none_or(|h| h.is_empty() || st.machines.contains_key(h))
+ })
+ .filter_map(|r| view(r, &who))
+ .collect();
Json(serde_json::json!({ "machines": machines })).into_response()
}
@@ -666,7 +682,12 @@ async fn patch(
Json(rec.machine.clone()).into_response()
}
-async fn delete(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+async fn delete(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Path(id): Path<String>,
+ Query(q): Query<BTreeMap<String, String>>,
+) -> Response {
let mut st = s.lock().unwrap();
if let Some(code) = st.fail_deletes.pop_front() {
return err(
@@ -678,9 +699,167 @@ async fn delete(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>)
return r;
}
st.machines.remove(&id);
+ // The Spaces it provides stay, detached; `?spaces=delete` removes them.
+ if q.get("spaces").map(String::as_str) == Some("delete") {
+ st.machines
+ .retain(|_, r| r.machine.host.as_deref() != Some(id.as_str()));
+ }
StatusCode::NO_CONTENT.into_response()
}
+/// The account (and device gate) behind a `/v1/spaces/...` call.
+#[allow(clippy::result_large_err)]
+fn spaces_caller(st: &State_, headers: &HeaderMap) -> Result<Identity, Response> {
+ if st.without_spaces_settings {
+ return Err(StatusCode::NOT_FOUND.into_response());
+ }
+ st.gate(headers)?;
+ match caller(st, headers) {
+ Some(Caller::Account(who)) => Ok(who),
+ Some(Caller::Machine(_)) => {
+ Err(err(StatusCode::FORBIDDEN, "a machine token cannot do this"))
+ }
+ None => Err(err(StatusCode::UNAUTHORIZED, "account token required")),
+ }
+}
+
+fn settings_of(st: &State_, who: &Identity) -> serde_json::Value {
+ st.spaces_settings.get(&who.id).cloned().unwrap_or_else(|| {
+ serde_json::json!({"default_space": null, "fallback": [], "fallback_on": true, "updated_at": 0})
+ })
+}
+
+async fn spaces_settings_get(State(s): State<S>, headers: HeaderMap) -> Response {
+ let st = s.lock().unwrap();
+ match spaces_caller(&st, &headers) {
+ Ok(who) => Json(settings_of(&st, &who)).into_response(),
+ Err(r) => r,
+ }
+}
+
+async fn spaces_settings_put(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Json(mut body): Json<serde_json::Value>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let who = match spaces_caller(&st, &headers) {
+ Ok(w) => w,
+ Err(r) => return r,
+ };
+ let machine_of = |id: &str| {
+ id.strip_prefix("relay:")
+ .map(|r| r.split('/').next().unwrap_or(r).to_string())
+ };
+ let mut ids: Vec<String> = body["fallback"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|v| v.as_str().map(str::to_string))
+ .collect();
+ if let Some(d) = body["default_space"].as_str() {
+ ids.insert(0, d.to_string());
+ }
+ for (i, id) in ids.iter().enumerate() {
+ let Some(m) = machine_of(id) else {
+ return err(StatusCode::BAD_REQUEST, "bad Space id");
+ };
+ if ids[..i].contains(id) {
+ return err(StatusCode::BAD_REQUEST, "duplicate Space");
+ }
+ match st.machines.get(&m).and_then(|r| view(r, &who)) {
+ Some(_) => {}
+ None => return err(StatusCode::FORBIDDEN, "no such computer for you"),
+ }
+ }
+ body["updated_at"] = serde_json::json!(now_secs());
+ st.spaces_settings.insert(who.id.clone(), body.clone());
+ Json(body).into_response()
+}
+
+async fn spaces_default(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Query(q): Query<BTreeMap<String, String>>,
+) -> Response {
+ let st = s.lock().unwrap();
+ let who = match spaces_caller(&st, &headers) {
+ Ok(w) => w,
+ Err(r) => return r,
+ };
+ let settings = settings_of(&st, &who);
+ let mine: Vec<(String, Machine)> = st
+ .machines
+ .values()
+ .filter(|r| {
+ r.machine
+ .host
+ .as_deref()
+ .is_none_or(|h| h.is_empty() || st.machines.contains_key(h))
+ })
+ .filter_map(|r| view(r, &who))
+ .map(|m| (format!("relay:{}", m.id), m))
+ .collect();
+ let default = settings["default_space"].as_str().map(str::to_string);
+ let step = |id: &str, role: &str| {
+ let m = mine.iter().find(|(i, _)| i == id).map(|(_, m)| m);
+ serde_json::json!({"space": id, "name": m.map(|m| m.name.clone()).unwrap_or_default(),
+ "online": m.is_some_and(|m| m.online && m.sharing), "role": role})
+ };
+ let mut order = Vec::new();
+ if let Some(d) = &default {
+ order.push(step(d, "default"));
+ }
+ let here = q.get("here").map(|h| format!("relay:{h}"));
+ let fallback: Vec<String> = if settings["fallback_on"].as_bool() == Some(false) {
+ vec![]
+ } else if let Some(list) = settings["fallback"].as_array().filter(|l| !l.is_empty()) {
+ list.iter()
+ .filter_map(|v| v.as_str().map(str::to_string))
+ .collect()
+ } else {
+ let mut all: Vec<_> = mine
+ .iter()
+ .filter(|(_, m)| m.role == "owner" && m.host.as_deref().is_none_or(str::is_empty))
+ .map(|(i, m)| (m.connected_at.unwrap_or(0), i.clone()))
+ .collect();
+ all.sort();
+ all.into_iter().map(|(_, i)| i).collect()
+ };
+ for f in fallback {
+ if Some(&f) != default.as_ref() && Some(&f) != here.as_ref() {
+ order.push(step(&f, "fallback"));
+ }
+ }
+ if let Some(h) = &here
+ && mine.iter().any(|(i, _)| i == h)
+ {
+ order.push(step(h, "here"));
+ }
+ let first = order.iter().find(|o| o["online"] == true).cloned();
+ let (space, reason) = match &first {
+ Some(o) => (
+ o["space"].clone(),
+ o["role"].as_str().unwrap_or("here").to_string(),
+ ),
+ None if default.is_none() && order.is_empty() => (serde_json::Value::Null, "unset".into()),
+ None => (serde_json::Value::Null, "here".to_string()),
+ };
+ let reason = if default.is_none() && reason == "fallback" {
+ "unset".into()
+ } else {
+ reason
+ };
+ Json(serde_json::json!({
+ "space": if reason == "here" && here.is_none() { serde_json::Value::Null } else { space },
+ "reason": reason,
+ "default_space": default,
+ "default_online": default.as_ref().map(|d| step(d, "default")["online"] == true),
+ "order": order,
+ }))
+ .into_response()
+}
+
async fn leave(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {
let mut st = s.lock().unwrap();
if st.without_leave {
@@ -1272,6 +1451,11 @@ impl FakeRelay {
.route("/v1/machines/{id}/stop-sharing", post(stop))
.route("/v1/machines/{id}/start-sharing", post(start))
.route("/v1/machines/{id}/leave", post(leave))
+ .route(
+ "/v1/spaces/settings",
+ get(spaces_settings_get).put(spaces_settings_put),
+ )
+ .route("/v1/spaces/default", get(spaces_default))
.route("/v1/devices", get(device_list).post(device_register))
.route("/v1/devices/session", post(device_session))
.route("/v1/devices/approve", post(device_approve))
@@ -1466,6 +1650,12 @@ impl FakeRelay {
self.state.lock().unwrap().without_leave = on;
}
+ /// Answers the `/v1/spaces/...` routes the way a relay that predates
+ /// them does (404, no body), or as the current relay again.
+ pub fn without_spaces_settings(&self, on: bool) {
+ self.state.lock().unwrap().without_spaces_settings = on;
+ }
+
/// Machine registrations received so far (refused ones too).
pub fn register_calls(&self) -> usize {
self.state.lock().unwrap().register_calls
diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rs
index 20341bb88e..7fb80657b8 100644
--- a/libs/cua/crates/cua-sdk/src/native/host.rs
+++ b/libs/cua/crates/cua-sdk/src/native/host.rs
@@ -125,6 +125,92 @@ impl From<cua_host::Machine> for RelayMachine {
}
}
+/// The account's default Space and the order to try when it is offline.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct SpacesSettings {
+ /// `relay:<machine>` or `relay:<machine>/<name>`; none when unset.
+ pub default_space: Option<String>,
+ /// The order to try when the default is offline; empty means every
+ /// online computer you can use, oldest first.
+ pub fallback: Vec<String>,
+ /// false: only the default, then this device.
+ pub fallback_on: bool,
+ /// Unix seconds the relay saved it (ignored when writing).
+ pub updated_at: u64,
+}
+
+impl From<cua_host::SpacesSettings> for SpacesSettings {
+ fn from(s: cua_host::SpacesSettings) -> Self {
+ Self {
+ default_space: s.default_space.filter(|d| !d.is_empty()),
+ fallback: s.fallback,
+ fallback_on: s.fallback_on,
+ updated_at: s.updated_at,
+ }
+ }
+}
+
+impl From<SpacesSettings> for cua_host::SpacesSettings {
+ fn from(s: SpacesSettings) -> Self {
+ Self {
+ default_space: s.default_space.filter(|d| !d.trim().is_empty()),
+ fallback: s.fallback,
+ fallback_on: s.fallback_on,
+ updated_at: s.updated_at,
+ }
+ }
+}
+
+/// One entry of the order [`Devices::resolve_default_space`] tried.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DefaultSpaceStep {
+ /// The Space id.
+ pub space: String,
+ /// Its display name.
+ pub name: String,
+ /// Connected and sharing now.
+ pub online: bool,
+ /// `default`, `fallback` or `here`.
+ pub role: String,
+}
+
+/// Where the default Space resolves now.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DefaultSpace {
+ /// The first online entry; none when this device is the answer
+ /// (`reason` `here`).
+ pub space: Option<String>,
+ /// `default`, `fallback`, `here` or `unset`.
+ pub reason: String,
+ /// The chosen default, online or not.
+ pub default_space: Option<String>,
+ /// Whether the default is online; none when unset.
+ pub default_online: Option<bool>,
+ /// The order the relay tried.
+ pub order: Vec<DefaultSpaceStep>,
+}
+
+impl From<cua_host::DefaultSpace> for DefaultSpace {
+ fn from(d: cua_host::DefaultSpace) -> Self {
+ Self {
+ space: d.space.filter(|s| !s.is_empty()),
+ reason: d.reason,
+ default_space: d.default_space.filter(|s| !s.is_empty()),
+ default_online: d.default_online,
+ order: d
+ .order
+ .into_iter()
+ .map(|s| DefaultSpaceStep {
+ space: s.space,
+ name: s.name,
+ online: s.online,
+ role: s.role,
+ })
+ .collect(),
+ }
+ }
+}
+
/// A one-time code that adds a machine to the account ("Add a machine"
/// by link or QR code).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
@@ -1324,6 +1410,64 @@ impl Devices {
.await
}
+ /// The account's default Space and fallback order. A relay that
+ /// predates them answers "the Cua relay needs an update".
+ pub async fn spaces_settings(&self) -> Result<SpacesSettings> {
+ let auth = self.auth.clone();
+ let tokens = self.tokens.clone();
+ run(async move {
+ let session = auth.session().await?;
+ let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
+ Ok(cua_host::RelayClient::new(auth.relay_url())?
+ .with_device_session(Some(session))
+ .spaces_settings(&token)
+ .await?
+ .into())
+ })
+ .await
+ }
+
+ /// Replaces the account's default Space settings (the whole object;
+ /// `updated_at` is set by the relay). Returns what the relay saved.
+ pub async fn set_spaces_settings(&self, settings: SpacesSettings) -> Result<SpacesSettings> {
+ let auth = self.auth.clone();
+ let tokens = self.tokens.clone();
+ run(async move {
+ let session = auth.session().await?;
+ let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
+ Ok(cua_host::RelayClient::new(auth.relay_url())?
+ .with_device_session(Some(session))
+ .set_spaces_settings(&token, &settings.into())
+ .await?
+ .into())
+ })
+ .await
+ }
+
+ /// Where the default Space resolves now: the first online entry of the
+ /// default, the fallback order, then this computer (its own relay
+ /// machine id, when it has one). Creates nothing.
+ pub async fn resolve_default_space(&self) -> Result<DefaultSpace> {
+ let auth = self.auth.clone();
+ let tokens = self.tokens.clone();
+ run(async move {
+ let session = auth.session().await?;
+ let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
+ let here = cua_host::Host::new(cua_daemon::cua_home())
+ .config()
+ .ok()
+ .flatten()
+ .and_then(|c| c.machine_id)
+ .filter(|id| !id.is_empty());
+ Ok(cua_host::RelayClient::new(auth.relay_url())?
+ .with_device_session(Some(session))
+ .resolve_default_space(&token, here.as_deref())
+ .await?
+ .into())
+ })
+ .await
+ }
+
/// Vouches for `machine_id`, a machine that registered without an
/// enrolled device's signature or MFA (from this enrolled device) (S5).
/// Clears [`RelayMachine::confirmed`]'s "new" flag for every account
diff --git a/libs/cua/crates/cua-sdk/src/native/spaces.rs b/libs/cua/crates/cua-sdk/src/native/spaces.rs
index 59f821a069..bf92f2b7c9 100644
--- a/libs/cua/crates/cua-sdk/src/native/spaces.rs
+++ b/libs/cua/crates/cua-sdk/src/native/spaces.rs
@@ -5159,6 +5159,33 @@ impl Spaces {
.await
}
+ /// [`Spaces::relay_unregister`] for one of your computers
+ /// (`relay:<machine>`), choosing what happens to the Spaces it
+ /// provides: with `delete_spaces` false they stay on the account,
+ /// detached (they come back when the computer registers again); with
+ /// true they are deleted too, files first (through the computer while
+ /// it answers), then their records. Returns false when it was not on
+ /// the relay.
+ pub async fn relay_unregister_computer(
+ &self,
+ space: String,
+ delete_spaces: bool,
+ ) -> Result<bool> {
+ let host = self.host.clone();
+ run(async move {
+ let v = host
+ .tool_value(
+ "relay_unregister_space",
+ json!({"space": space, "delete_spaces": delete_spaces}),
+ )
+ .await?;
+ Ok(v.get("unregistered")
+ .and_then(Value::as_bool)
+ .unwrap_or(false))
+ })
+ .await
+ }
+
/// A connected handle to a registered Space.
pub async fn space(&self, space: String) -> Result<Arc<Space>> {
let host = self.host.clone();
diff --git a/libs/cua/crates/cua-spaces-contract/src/inputs.rs b/libs/cua/crates/cua-spaces-contract/src/inputs.rs
index 4a67fc5e4e..9b56e1bd40 100644
--- a/libs/cua/crates/cua-spaces-contract/src/inputs.rs
+++ b/libs/cua/crates/cua-spaces-contract/src/inputs.rs
@@ -269,6 +269,19 @@ pub struct SpaceOnly {
pub space: SpaceArg,
}
+/// `relay_unregister_space`: take a Space or a computer off the relay.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
+pub struct RelayUnregisterSpace {
+ /// Space id or name.
+ pub space: SpaceArg,
+ /// For one of your computers: also delete the Spaces it provides, their
+ /// files first (through the computer while it answers), then their
+ /// records. Default false: they stay on your account, detached, and come
+ /// back when the computer registers again.
+ #[serde(default)]
+ pub delete_spaces: Option<bool>,
+}
+
/// `stop_space`: turn a Space off.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct StopSpace {
diff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rs
index 5fdae3756b..1ad698256f 100644
--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs
@@ -786,7 +786,7 @@ pub fn tools() -> Vec<Tool> {
.with::<i::RemoveSpace>(),
Spec {
category: Category::Lifecycle,
- result: "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your computers provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay computer the relay cannot reach now `status` (`offline` or `not sharing`)), each with `phase`: `ready`, or `offline` for a relay computer the relay cannot reach now (a computer that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).",
+ result: "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your computers provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay computer the relay cannot reach now `status` (`offline` or `not sharing`)), `parent` (a Space one of your computers provides: that computer's Space id, `relay:<computer>`; null for a computer or any other Space) and `default` (true for the Space the account chose as its default, false for every other; false for all when signed out or the relay does not answer), each with `phase`: `ready`, or `offline` for a relay computer the relay cannot reach now (a computer that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).",
errors: &["relay", "unauthenticated"],
instructions: "Every registered Space (cloud, local, direct and relay) with its id (local:<name>, cloud:<name>, direct:<host:port>, relay:<computer-id>), provider, spacesd version (empty without one) and supported features as of the last handshake. The signed-in account's computers on the relay are listed too: those are the names `create_space` accepts as on=\"host:<computer>\". A Space a computer provides carries `host` (that computer's id) and `host_name`; group them under it when you show them. A Space in your cloud carries `cloud` (the provider: aws, gcp, modal), `cloud_place` (account and region, to show with it) and `cloud_delete` (where delete_space can delete it: here, host:<computer>, or elsewhere). A durable Space (create_space durable=true) carries `durable` (its name, by which it is found wherever it runs now).",
capabilities: &["space.discover"],
@@ -2010,7 +2010,7 @@ pub fn tools() -> Vec<Tool> {
category: Category::Sharing,
result: "JSON: `space` and `unregistered` (false when it was not on the relay).",
errors: &["relay", "unauthenticated", "permission_denied", "invalid_argument"],
- instructions: "Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead.",
+ instructions: "Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead. Removing one of your computers keeps the Spaces it provides on your account, detached (hidden, and refused until the computer registers again with the same id, which brings them back unchanged); `delete_spaces: true` deletes them too, files first (through the computer while it answers), then their records.",
capabilities: &["space.relay"],
host_requires: &[host::RELAY_ACCOUNT],
annotations: Annotations::mutating_idempotent(),
@@ -2018,7 +2018,7 @@ pub fn tools() -> Vec<Tool> {
rust_symbol: "Spaces::relay_unregister",
..Spec::new("relay_unregister_space", "Take a Space off the relay.")
}
- .with::<i::SpaceOnly>(),
+ .with::<i::RelayUnregisterSpace>(),
// --- your cloud ------------------------------------------------------
Spec {
category: Category::Cloud,
diff --git a/libs/cua/crates/cua-spaces/src/mcp/tools.rs b/libs/cua/crates/cua-spaces/src/mcp/tools.rs
index 9340b580d8..a4a36592b6 100644
--- a/libs/cua/crates/cua-spaces/src/mcp/tools.rs
+++ b/libs/cua/crates/cua-spaces/src/mcp/tools.rs
@@ -208,6 +208,7 @@ async fn dispatch(
.into_iter()
.map(|h| h.space)
.collect();
+ let default = spaces.default_space_id().await;
let rows: Vec<Value> = spaces
.list_all()
.await?
@@ -222,7 +223,10 @@ async fn dispatch(
} else {
PHASE_READY
};
- with(info, row_extra(info, &direct_hosts, phase))
+ with(
+ info,
+ row_extra(info, &direct_hosts, phase, default.as_deref()),
+ )
})
.collect();
Ok(ToolOutcome::json(&rows))
@@ -291,7 +295,7 @@ async fn dispatch(
};
let row = |created: SpaceCreated| match created {
SpaceCreated::Ready { info, reused } => {
- let mut extra = row_extra(&info, &[], PHASE_READY);
+ let mut extra = row_extra(&info, &[], PHASE_READY, None);
extra["reused"] = json!(reused);
with(&info, extra)
}
@@ -983,8 +987,10 @@ async fn dispatch(
}
#[cfg(feature = "spaces-agents")]
"relay_unregister_space" => {
- let a: i::SpaceOnly = args(tool, a)?;
- let unregistered = spaces.relay_unregister(&a.space).await?;
+ let a: i::RelayUnregisterSpace = args(tool, a)?;
+ let unregistered = spaces
+ .remove_computer(&a.space, a.delete_spaces.unwrap_or(false))
+ .await?;
let space = spaces.resolve(&a.space)?.to_string();
Ok(ToolOutcome::json(
&json!({"space": space, "unregistered": unregistered}),
@@ -1068,8 +1074,18 @@ async fn hotspot_start(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutc
Ok(ToolOutcome::json(&status))
}
-fn row_extra(info: &crate::SpaceInfo, direct_hosts: &[String], phase: &str) -> Value {
- let mut extra = json!({ "phase": phase, "clipboard": info.clipboard.as_str() });
+fn row_extra(
+ info: &crate::SpaceInfo,
+ direct_hosts: &[String],
+ phase: &str,
+ default: Option<&str>,
+) -> Value {
+ let mut extra = json!({
+ "phase": phase,
+ "clipboard": info.clipboard.as_str(),
+ "parent": info.parent_space_id(),
+ "default": default == Some(info.id.as_str()),
+ });
let via = if direct_hosts.contains(&info.id) || info.host.starts_with("direct:") {
Some("direct")
} else if !info.host.is_empty() {
diff --git a/libs/cua/crates/cua-spaces/src/relay.rs b/libs/cua/crates/cua-spaces/src/relay.rs
index 6f899282a7..eeea10e87c 100644
--- a/libs/cua/crates/cua-spaces/src/relay.rs
+++ b/libs/cua/crates/cua-spaces/src/relay.rs
@@ -104,6 +104,16 @@ pub(crate) struct RelayBearer {
/// removing it from the account counts it as a stale entry.
const LIVE_PROBE: std::time::Duration = std::time::Duration::from_secs(6);
+/// How long deleting one child Space through its computer may take when a
+/// computer is removed with its Spaces.
+const CHILD_DELETE: std::time::Duration = std::time::Duration::from_secs(20);
+
+/// How long the account's default Space is kept before the relay is asked
+/// again (lists mark it from this).
+const DEFAULT_TTL: std::time::Duration = std::time::Duration::from_secs(30);
+/// The most a list waits for the default (never holds a list up).
+const DEFAULT_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
+
type BoxError = Box<dyn std::error::Error + Send + Sync>;
impl cua_spacesd_client::BearerProvider for RelayBearer {
@@ -238,6 +248,7 @@ impl crate::Spaces {
pub(crate) async fn forget_relay_machine(
&self,
machine_id: &str,
+ delete_spaces: bool,
) -> crate::Result<Option<RelayMachine>> {
use crate::Error;
let id = format!("relay:{machine_id}");
@@ -290,7 +301,10 @@ impl crate::Spaces {
}
#[cfg(feature = "spaces-agents")]
self.detach_attached_driver(machine_id).await;
- match client.delete(&token, machine_id).await {
+ match client
+ .delete_machine(&token, machine_id, delete_spaces)
+ .await
+ {
Ok(()) | Err(cua_host::Error::NotFound(_)) => {}
Err(e) => return Err(e.into()),
}
@@ -298,6 +312,48 @@ impl crate::Spaces {
Ok(Some(m))
}
+ /// Removes one of your computers from the relay. With `delete_spaces`
+ /// the Spaces it provides are deleted first, files included, through the
+ /// computer while it answers (best effort), and then their records go
+ /// with it; without, they stay on the account, detached. Returns false
+ /// when it was not on the relay.
+ ///
+ /// Kept apart from [`crate::Spaces::relay_unregister_computer`] (which
+ /// only changes what the relay forgets) because deleting a Space can
+ /// itself unregister a computer.
+ pub async fn remove_computer(&self, space: &str, delete_spaces: bool) -> crate::Result<bool> {
+ if delete_spaces && let Ok(crate::SpaceId::Relay { machine_id }) = self.resolve(space) {
+ self.delete_children_through_computer(&machine_id).await;
+ }
+ self.relay_unregister_computer(space, delete_spaces).await
+ }
+
+ /// Deletes the Spaces `machine_id` provides, files included, through
+ /// the computer while it answers. Best effort: one that cannot be
+ /// reached is logged, and the relay forgets its record either way
+ /// (`spaces=delete`).
+ pub(crate) async fn delete_children_through_computer(&self, machine_id: &str) {
+ let children: Vec<String> = self
+ .inner
+ .relay_cache
+ .lock()
+ .expect("relay cache")
+ .iter()
+ .filter(|m| m.host.as_deref() == Some(machine_id))
+ .map(|m| format!("relay:{}", m.id))
+ .collect();
+ for child in children {
+ let done = tokio::time::timeout(CHILD_DELETE, self.delete(&child)).await;
+ match done {
+ Ok(Ok(_)) => {}
+ Ok(Err(e)) => {
+ tracing::warn!(space = %child, error = %e, "child Space not deleted on its computer")
+ }
+ Err(_) => tracing::warn!(space = %child, "child Space delete timed out"),
+ }
+ }
+ }
+
/// [`adopt_machine_name`] for this runtime: its cached directory too.
pub(crate) fn adopt_relay_machine_name(&self, machine_id: &str, name: &str) {
if let Some(account) = self.relay_account() {
@@ -330,6 +386,76 @@ impl crate::Spaces {
}
}
+ async fn relay_client_and_token(&self) -> crate::Result<(cua_host::RelayClient, String)> {
+ let relay = self.relay()?;
+ let token = relay.tokens.access_token().await?;
+ Ok((relay.client().await?, token))
+ }
+
+ /// The account's default Space settings, from the relay.
+ pub async fn spaces_settings(&self) -> crate::Result<cua_host::SpacesSettings> {
+ let (client, token) = self.relay_client_and_token().await?;
+ Ok(client.spaces_settings(&token).await?)
+ }
+
+ /// Replaces the account's default Space settings (the whole object).
+ pub async fn set_spaces_settings(
+ &self,
+ settings: &cua_host::SpacesSettings,
+ ) -> crate::Result<cua_host::SpacesSettings> {
+ let (client, token) = self.relay_client_and_token().await?;
+ let saved = client.set_spaces_settings(&token, settings).await?;
+ *self.inner.default_cache.lock().expect("default cache") = Some((
+ std::time::Instant::now(),
+ saved.default_space.clone().filter(|d| !d.is_empty()),
+ ));
+ Ok(saved)
+ }
+
+ /// Where "my default Space" resolves now. `here` is this computer's
+ /// relay machine id (filled from this install's host setup when not
+ /// given).
+ pub async fn resolve_default_space(
+ &self,
+ here: Option<&str>,
+ ) -> crate::Result<cua_host::DefaultSpace> {
+ let (client, token) = self.relay_client_and_token().await?;
+ let own = self.this_relay_machine_id();
+ let here = here.map(str::to_string).or(own);
+ Ok(client
+ .resolve_default_space(&token, here.as_deref())
+ .await?)
+ }
+
+ /// The default Space's id, for marking it in a list: from a short
+ /// cache, else asked of the relay within [`DEFAULT_WAIT`]. Signed out,
+ /// a relay that is down or too old, or a slow answer is `None` (and
+ /// remembered for a moment): a list never waits on it or fails on it.
+ pub async fn default_space_id(&self) -> Option<String> {
+ if let Some((at, id)) = self
+ .inner
+ .default_cache
+ .lock()
+ .expect("default cache")
+ .clone()
+ && at.elapsed() < DEFAULT_TTL
+ {
+ return id;
+ }
+ let id = match self.relay_account() {
+ None => None,
+ Some(_) => tokio::time::timeout(DEFAULT_WAIT, self.spaces_settings())
+ .await
+ .ok()
+ .and_then(Result::ok)
+ .and_then(|s| s.default_space)
+ .filter(|d| !d.is_empty()),
+ };
+ *self.inner.default_cache.lock().expect("default cache") =
+ Some((std::time::Instant::now(), id.clone()));
+ id
+ }
+
/// Forgets `relay:<machine_id>` on this device: the cached row, any
/// registry entry, its thumbnail and connection, and (with sharing) the
/// Space attached as it.
diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rs
index a78286b514..54c19d6361 100644
--- a/libs/cua/crates/cua-spaces/src/share.rs
+++ b/libs/cua/crates/cua-spaces/src/share.rs
@@ -1019,6 +1019,18 @@ impl Spaces {
/// A host that is connected now is taken off with `cua host remove` on
/// it instead.
pub async fn relay_unregister(&self, space: &str) -> Result<bool> {
+ self.relay_unregister_computer(space, false).await
+ }
+
+ /// [`Spaces::relay_unregister`]. A computer's own Spaces stay on the
+ /// account, detached (they come back when it registers again);
+ /// `delete_spaces` deletes them instead, first through the computer
+ /// while it answers (their files go), then their records on the relay.
+ pub async fn relay_unregister_computer(
+ &self,
+ space: &str,
+ delete_spaces: bool,
+ ) -> Result<bool> {
// A Space that is already gone here but was left on the relay (its
// delete could not reach the relay, CUA-2841): its machine is still
// remembered, so `relay-unregister local:<name>` removes it.
@@ -1039,7 +1051,7 @@ impl Spaces {
};
let canonical = id.to_string();
if let SpaceId::Relay { machine_id } = &id {
- let removed = self.forget_relay_machine(machine_id).await?;
+ let removed = self.forget_relay_machine(machine_id, delete_spaces).await?;
if removed.is_some() {
self.audit_share("forget", &canonical, &format!("machine={machine_id}"));
}
diff --git a/libs/cua/crates/cua-spaces/src/space.rs b/libs/cua/crates/cua-spaces/src/space.rs
index 3693b6f827..9f72c483f4 100644
--- a/libs/cua/crates/cua-spaces/src/space.rs
+++ b/libs/cua/crates/cua-spaces/src/space.rs
@@ -746,6 +746,17 @@ fn is_zero(n: &u64) -> bool {
}
impl SpaceInfo {
+ /// For a Space one of your computers provides: that computer's Space
+ /// id (`relay:<machine>`, or `direct:<addr>` for a host added by its
+ /// direct address). `None` for a computer and every other Space.
+ pub fn parent_space_id(&self) -> Option<String> {
+ match self.host.as_str() {
+ "" => None,
+ h if h.starts_with("direct:") => Some(h.to_string()),
+ h => Some(format!("relay:{h}")),
+ }
+ }
+
/// The name people see: [`Self::display_name`] when it was renamed,
/// else [`Self::name`].
pub fn shown_name(&self) -> &str {
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 1e4f0ba987..3ef7844677 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -407,6 +407,7 @@ impl SpacesBuilder {
relay: std::sync::RwLock::new(self.relay),
resources: crate::resources::Hub::new(),
relay_cache: std::sync::Mutex::new(Vec::new()),
+ default_cache: std::sync::Mutex::new(None),
team_facts: std::sync::Mutex::new(Default::default()),
relay_reported: std::sync::Mutex::new(relay_reported),
reported_saves: Default::default(),
@@ -651,6 +652,9 @@ pub(crate) struct Inner {
pub(crate) resources: Arc<crate::resources::Hub>,
/// The last directory listing (so `list` and `resolve` stay sync).
pub(crate) relay_cache: std::sync::Mutex<Vec<crate::relay::RelayMachine>>,
+ /// The account's default Space as the relay last said (or none), and
+ /// when it was read: lists mark it without asking every time.
+ pub(crate) default_cache: std::sync::Mutex<Option<(std::time::Instant, Option<String>)>>,
/// Team names and roles from the Spaces API ([`crate::sharing`]).
pub(crate) team_facts: std::sync::Mutex<crate::sharing::TeamFacts>,
/// What each relay machine's cua-spacesd said about itself when this
@@ -1318,7 +1322,7 @@ impl Spaces {
&& !m.online
&& crate::relay::is_registered_space(&m)
{
- self.forget_relay_machine(machine_id).await?;
+ self.forget_relay_machine(machine_id, false).await?;
}
// A Space this device attached to the relay as a machine of its own
// takes that machine with it (as `delete` does): `rm` must not leave
@@ -3527,7 +3531,7 @@ impl Spaces {
// its record leaves the relay directory.
None => match row {
Some(m) if m.role == "owner" && crate::relay::is_registered_space(&m) => {
- self.forget_relay_machine(machine_id).await?;
+ self.forget_relay_machine(machine_id, false).await?;
format!("Removed {id} from your relay directory.")
}
Some(m) if m.role != "owner" => format!(
diff --git a/libs/cua/crates/cua-spaces/tests/default_space.rs b/libs/cua/crates/cua-spaces/tests/default_space.rs
new file mode 100644
index 0000000000..afd4b2126d
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/tests/default_space.rs
@@ -0,0 +1,147 @@
+//! The account's default Space and removing a computer: settings saved on
+//! the relay and read back, the default marked in lists from a short cache
+//! (never holding a list up when signed out or the relay is down), and a
+//! computer taken off the relay detaching its Spaces, or deleting them with
+//! `delete_spaces`. Hermetic: the fake relay directory
+//! (`cua_host::testing::FakeRelay`) and a throwaway cua home.
+
+use cua_host::testing::FakeRelay;
+use cua_spaces::relay::StaticToken;
+use cua_spaces::{RelayAccount, Spaces};
+use std::path::Path;
+use std::sync::Arc;
+
+const TOKEN: &str = "owner-token";
+const COMPUTER: &str = "aaaa111122223333";
+const CHILD: &str = "bbbb111122223333";
+
+fn signed_in(home: &Path, relay: &FakeRelay) -> Spaces {
+ Spaces::builder()
+ .home(home)
+ .relay(RelayAccount::new(
+ &relay.url,
+ Arc::new(StaticToken(TOKEN.into())),
+ ))
+ .build()
+}
+
+async fn register(relay: &FakeRelay, id: &str, name: &str, host: Option<&str>) {
+ cua_host::RelayClient::new(&relay.url)
+ .unwrap()
+ .register(
+ TOKEN,
+ &cua_host::relay::RegisterRequest {
+ id: id.into(),
+ name: name.into(),
+ allow: vec![],
+ host: host.map(str::to_string),
+ meta: Default::default(),
+ },
+ )
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn the_default_is_saved_resolved_and_marked_without_holding_a_list_up() {
+ let relay = FakeRelay::start().await;
+ relay.add_account(TOKEN, "user-1", Some("[email protected]"));
+ register(&relay, COMPUTER, "studio", None).await;
+ relay.set_online(COMPUTER, true, "1.0.0");
+ let home = tempfile::tempdir().unwrap();
+ let app = signed_in(home.path(), &relay);
+
+ // Nothing chosen: no default, settings are empty.
+ assert_eq!(app.default_space_id().await, None);
+ let s = app.spaces_settings().await.unwrap();
+ assert!(s.default_space.is_none() && s.fallback.is_empty() && s.fallback_on);
+
+ // Set it: the relay keeps it, resolution finds the online computer, and
+ // the next list marks it at once (the save refreshed the cache).
+ let want = format!("relay:{COMPUTER}");
+ let saved = app
+ .set_spaces_settings(&cua_host::SpacesSettings {
+ default_space: Some(want.clone()),
+ fallback: vec![],
+ fallback_on: true,
+ updated_at: 0,
+ })
+ .await
+ .unwrap();
+ assert_eq!(saved.default_space.as_deref(), Some(want.as_str()));
+ assert!(saved.updated_at > 0);
+ assert_eq!(app.default_space_id().await.as_deref(), Some(want.as_str()));
+ let d = app.resolve_default_space(None).await.unwrap();
+ assert_eq!(d.reason, "default");
+ assert_eq!(d.space.as_deref(), Some(want.as_str()));
+ assert_eq!(d.default_online, Some(true));
+
+ // A computer the account cannot see is refused with the relay's reason.
+ let e = app
+ .set_spaces_settings(&cua_host::SpacesSettings {
+ default_space: Some("relay:ffff000000000000".into()),
+ fallback: vec![],
+ fallback_on: true,
+ updated_at: 0,
+ })
+ .await
+ .unwrap_err();
+ assert!(e.to_string().contains("no such computer"), "{e}");
+
+ // A relay that predates the routes, and signing out: no default, no error.
+ relay.without_spaces_settings(true);
+ let fresh = signed_in(home.path(), &relay);
+ assert_eq!(fresh.default_space_id().await, None);
+ let e = fresh.spaces_settings().await.unwrap_err();
+ assert!(e.to_string().contains("needs an update"), "{e}");
+ let signed_out = Spaces::builder().home(home.path()).build();
+ assert_eq!(signed_out.default_space_id().await, None);
+}
+
+#[tokio::test]
+async fn removing_a_computer_detaches_its_spaces_or_deletes_them() {
+ for delete_spaces in [false, true] {
+ let relay = FakeRelay::start().await;
+ relay.add_account(TOKEN, "user-1", Some("[email protected]"));
+ register(&relay, COMPUTER, "studio", None).await;
+ register(&relay, CHILD, "research", Some(COMPUTER)).await;
+ let home = tempfile::tempdir().unwrap();
+ let app = signed_in(home.path(), &relay);
+ let listed = |app: &Spaces| {
+ let app = app.clone();
+ async move {
+ app.relay_machines()
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|m| m.id)
+ .collect::<Vec<_>>()
+ }
+ };
+ assert_eq!(listed(&app).await.len(), 2);
+
+ // Both are offline in the fake: the computer goes, taking its
+ // Spaces with it only when asked.
+ assert!(
+ app.remove_computer(&format!("relay:{COMPUTER}"), delete_spaces)
+ .await
+ .unwrap()
+ );
+ assert!(relay.machine(COMPUTER).is_none());
+ assert!(
+ listed(&app).await.is_empty(),
+ "a detached Space is hidden (delete_spaces={delete_spaces})"
+ );
+ assert_eq!(
+ relay.machine(CHILD).is_some(),
+ !delete_spaces,
+ "its record stays when detached and goes with delete_spaces"
+ );
+
+ if !delete_spaces {
+ // The computer registers again under the same id: they are back.
+ register(&relay, COMPUTER, "studio", None).await;
+ assert_eq!(listed(&app).await.len(), 2);
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.in
index 32ac25619a..2a1096345d 100644
--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in
+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in
@@ -237,6 +237,7 @@
"spaces.cancel",
"spaces.children",
"spaces.create",
+ "spaces.default",
"spaces.delete",
"spaces.egress",
"spaces.gpus",
diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
index 881ab05b58..1c15bfc08c 100644
--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
@@ -1075,12 +1075,18 @@ external fun uniffi_cua_sdk_checksum_method_devices_rename(
): Short
external fun uniffi_cua_sdk_checksum_method_devices_rename_machine(
): Short
+external fun uniffi_cua_sdk_checksum_method_devices_resolve_default_space(
+): Short
external fun uniffi_cua_sdk_checksum_method_devices_revoke(
): Short
external fun uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code(
): Short
+external fun uniffi_cua_sdk_checksum_method_devices_set_spaces_settings(
+): Short
external fun uniffi_cua_sdk_checksum_method_devices_snapshot(
): Short
+external fun uniffi_cua_sdk_checksum_method_devices_spaces_settings(
+): Short
external fun uniffi_cua_sdk_checksum_method_host_configure(
): Short
external fun uniffi_cua_sdk_checksum_method_host_migrate_service(
@@ -1607,6 +1613,8 @@ external fun uniffi_cua_sdk_checksum_method_spaces_relay_register(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_relay_unregister(
): Short
+external fun uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer(
+): Short
external fun uniffi_cua_sdk_checksum_method_spaces_remove(
): Short
external fun uniffi_cua_sdk_checksum_method_spaces_rename(
@@ -2076,12 +2084,18 @@ external fun uniffi_cua_sdk_fn_method_devices_rename(`ptr`: Long,`id`: RustBuffe
): Long
external fun uniffi_cua_sdk_fn_method_devices_rename_machine(`ptr`: Long,`machineId`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_devices_resolve_default_space(`ptr`: Long,
+): Long
external fun uniffi_cua_sdk_fn_method_devices_revoke(`ptr`: Long,`id`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(`ptr`: Long,`id`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_devices_set_spaces_settings(`ptr`: Long,`settings`: RustBuffer.ByValue,
+): Long
external fun uniffi_cua_sdk_fn_method_devices_snapshot(`ptr`: Long,`auditLimit`: Int,
): Long
+external fun uniffi_cua_sdk_fn_method_devices_spaces_settings(`ptr`: Long,
+): Long
external fun uniffi_cua_sdk_fn_clone_host(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
): Long
external fun uniffi_cua_sdk_fn_free_host(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
@@ -2706,6 +2720,8 @@ external fun uniffi_cua_sdk_fn_method_spaces_relay_register(`ptr`: Long,`space`:
): Long
external fun uniffi_cua_sdk_fn_method_spaces_relay_unregister(`ptr`: Long,`space`: RustBuffer.ByValue,
): Long
+external fun uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(`ptr`: Long,`space`: RustBuffer.ByValue,`deleteSpaces`: Byte,
+): Long
external fun uniffi_cua_sdk_fn_method_spaces_remove(`ptr`: Long,`space`: RustBuffer.ByValue,
): Long
external fun uniffi_cua_sdk_fn_method_spaces_rename(`ptr`: Long,`space`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,
@@ -3613,15 +3629,24 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_devices_rename_machine() != 63088.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_devices_resolve_default_space() != 5493.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_devices_revoke() != 27802.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() != 3143.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_devices_set_spaces_settings() != 38780.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_devices_snapshot() != 26132.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_devices_spaces_settings() != 1866.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_host_configure() != 36828.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -4411,6 +4436,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister() != 53366.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer() != 32336.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cua_sdk_checksum_method_spaces_remove() != 23086.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -9408,6 +9436,13 @@ public interface DevicesInterface {
*/
suspend fun `renameMachine`(`machineId`: kotlin.String, `name`: kotlin.String): RelayMachine
+ /**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+ suspend fun `resolveDefaultSpace`(): DefaultSpace
+
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -9419,6 +9454,12 @@ public interface DevicesInterface {
*/
suspend fun `revokePairingCode`(`id`: kotlin.String)
+ /**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+ suspend fun `setSpacesSettings`(`settings`: SpacesSettings): SpacesSettings
+
/**
* The account's devices, the grace period, the newest `audit_limit`
* audit events and the machines' names. Only the device list must
@@ -9426,6 +9467,12 @@ public interface DevicesInterface {
*/
suspend fun `snapshot`(`auditLimit`: kotlin.UInt): DevicesSnapshot
+ /**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+ suspend fun `spacesSettings`(): SpacesSettings
+
companion object
}
@@ -9768,6 +9815,32 @@ open class Devices: Disposable, AutoCloseable, DevicesInterface
}
+ /**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `resolveDefaultSpace`() : DefaultSpace {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_devices_resolve_default_space(
+ uniffiHandle,
+
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeDefaultSpace.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -9818,6 +9891,31 @@ open class Devices: Disposable, AutoCloseable, DevicesInterface
}
+ /**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `setSpacesSettings`(`settings`: SpacesSettings) : SpacesSettings {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_devices_set_spaces_settings(
+ uniffiHandle,
+ FfiConverterTypeSpacesSettings.lower(`settings`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSpacesSettings.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* The account's devices, the grace period, the newest `audit_limit`
* audit events and the machines' names. Only the device list must
@@ -9844,6 +9942,31 @@ open class Devices: Disposable, AutoCloseable, DevicesInterface
}
+ /**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `spacesSettings`() : SpacesSettings {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_devices_spaces_settings(
+ uniffiHandle,
+
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeSpacesSettings.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
@@ -21544,6 +21667,17 @@ public interface SpacesInterface {
*/
suspend fun `relayUnregister`(`space`: kotlin.String): kotlin.Boolean
+ /**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+ suspend fun `relayUnregisterComputer`(`space`: kotlin.String, `deleteSpaces`: kotlin.Boolean): kotlin.Boolean
+
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -23514,6 +23648,36 @@ open class Spaces: Disposable, AutoCloseable, SpacesInterface
}
+ /**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+ @Throws(CuaException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `relayUnregisterComputer`(`space`: kotlin.String, `deleteSpaces`: kotlin.Boolean) : kotlin.Boolean {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(
+ uniffiHandle,
+ FfiConverterString.lower(`space`),FfiConverterBoolean.lower(`deleteSpaces`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_i8(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_i8(future, continuation) },
+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_i8(future) },
+ // lift function
+ { FfiConverterBoolean.lift(it) },
+ // Error FFI converter
+ CuaException.ErrorHandler,
+ )
+ }
+
+
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -33491,6 +33655,141 @@ public object FfiConverterTypeCursorArt: FfiConverterRustBuffer<CursorArt> {
+/**
+ * Where the default Space resolves now.
+ */
+data class DefaultSpace (
+ /**
+ * The first online entry; none when this device is the answer
+ * (`reason` `here`).
+ */
+ var `space`: kotlin.String?
+ ,
+ /**
+ * `default`, `fallback`, `here` or `unset`.
+ */
+ var `reason`: kotlin.String
+ ,
+ /**
+ * The chosen default, online or not.
+ */
+ var `defaultSpace`: kotlin.String?
+ ,
+ /**
+ * Whether the default is online; none when unset.
+ */
+ var `defaultOnline`: kotlin.Boolean?
+ ,
+ /**
+ * The order the relay tried.
+ */
+ var `order`: List<DefaultSpaceStep>
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeDefaultSpace: FfiConverterRustBuffer<DefaultSpace> {
+ override fun read(buf: ByteBuffer): DefaultSpace {
+ return DefaultSpace(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalString.read(buf),
+ FfiConverterOptionalBoolean.read(buf),
+ FfiConverterSequenceTypeDefaultSpaceStep.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: DefaultSpace) = (
+ FfiConverterOptionalString.allocationSize(value.`space`) +
+ FfiConverterString.allocationSize(value.`reason`) +
+ FfiConverterOptionalString.allocationSize(value.`defaultSpace`) +
+ FfiConverterOptionalBoolean.allocationSize(value.`defaultOnline`) +
+ FfiConverterSequenceTypeDefaultSpaceStep.allocationSize(value.`order`)
+ )
+
+ override fun write(value: DefaultSpace, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`space`, buf)
+ FfiConverterString.write(value.`reason`, buf)
+ FfiConverterOptionalString.write(value.`defaultSpace`, buf)
+ FfiConverterOptionalBoolean.write(value.`defaultOnline`, buf)
+ FfiConverterSequenceTypeDefaultSpaceStep.write(value.`order`, buf)
+ }
+}
+
+
+
+/**
+ * One entry of the order [`Devices::resolve_default_space`] tried.
+ */
+data class DefaultSpaceStep (
+ /**
+ * The Space id.
+ */
+ var `space`: kotlin.String
+ ,
+ /**
+ * Its display name.
+ */
+ var `name`: kotlin.String
+ ,
+ /**
+ * Connected and sharing now.
+ */
+ var `online`: kotlin.Boolean
+ ,
+ /**
+ * `default`, `fallback` or `here`.
+ */
+ var `role`: kotlin.String
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeDefaultSpaceStep: FfiConverterRustBuffer<DefaultSpaceStep> {
+ override fun read(buf: ByteBuffer): DefaultSpaceStep {
+ return DefaultSpaceStep(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterBoolean.read(buf),
+ FfiConverterString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: DefaultSpaceStep) = (
+ FfiConverterString.allocationSize(value.`space`) +
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterBoolean.allocationSize(value.`online`) +
+ FfiConverterString.allocationSize(value.`role`)
+ )
+
+ override fun write(value: DefaultSpaceStep, buf: ByteBuffer) {
+ FfiConverterString.write(value.`space`, buf)
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterBoolean.write(value.`online`, buf)
+ FfiConverterString.write(value.`role`, buf)
+ }
+}
+
+
+
/**
* `Devices.enroll`'s result.
*/
@@ -48212,6 +48511,70 @@ public object FfiConverterTypeSpacesHostLoad: FfiConverterRustBuffer<SpacesHostL
+/**
+ * The account's default Space and the order to try when it is offline.
+ */
+data class SpacesSettings (
+ /**
+ * `relay:<machine>` or `relay:<machine>/<name>`; none when unset.
+ */
+ var `defaultSpace`: kotlin.String?
+ ,
+ /**
+ * The order to try when the default is offline; empty means every
+ * online computer you can use, oldest first.
+ */
+ var `fallback`: List<kotlin.String>
+ ,
+ /**
+ * false: only the default, then this device.
+ */
+ var `fallbackOn`: kotlin.Boolean
+ ,
+ /**
+ * Unix seconds the relay saved it (ignored when writing).
+ */
+ var `updatedAt`: kotlin.ULong
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSpacesSettings: FfiConverterRustBuffer<SpacesSettings> {
+ override fun read(buf: ByteBuffer): SpacesSettings {
+ return SpacesSettings(
+ FfiConverterOptionalString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ FfiConverterBoolean.read(buf),
+ FfiConverterULong.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SpacesSettings) = (
+ FfiConverterOptionalString.allocationSize(value.`defaultSpace`) +
+ FfiConverterSequenceString.allocationSize(value.`fallback`) +
+ FfiConverterBoolean.allocationSize(value.`fallbackOn`) +
+ FfiConverterULong.allocationSize(value.`updatedAt`)
+ )
+
+ override fun write(value: SpacesSettings, buf: ByteBuffer) {
+ FfiConverterOptionalString.write(value.`defaultSpace`, buf)
+ FfiConverterSequenceString.write(value.`fallback`, buf)
+ FfiConverterBoolean.write(value.`fallbackOn`, buf)
+ FfiConverterULong.write(value.`updatedAt`, buf)
+ }
+}
+
+
+
/**
* One row of [`SPACES_TOOL_METHODS`].
*/
@@ -55255,6 +55618,34 @@ public object FfiConverterSequenceTypeCursorArt: FfiConverterRustBuffer<List<Cur
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeDefaultSpaceStep: FfiConverterRustBuffer<List<DefaultSpaceStep>> {
+ override fun read(buf: ByteBuffer): List<DefaultSpaceStep> {
+ val len = buf.getInt()
+ return List<DefaultSpaceStep>(len) {
+ FfiConverterTypeDefaultSpaceStep.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<DefaultSpaceStep>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeDefaultSpaceStep.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<DefaultSpaceStep>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeDefaultSpaceStep.write(it, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.py
index 1b59f8f048..0988c5eddd 100644
--- a/libs/cua/python/src/cua/_native.py
+++ b/libs/cua/python/src/cua/_native.py
@@ -753,12 +753,18 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_devices_rename_machine() != 63088:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_devices_resolve_default_space() != 5493:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_devices_revoke() != 27802:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() != 3143:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_devices_set_spaces_settings() != 38780:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_devices_snapshot() != 26132:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_devices_spaces_settings() != 1866:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_forkbatch_collect() != 56883:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_forkbatch_next() != 11244:
@@ -1297,6 +1303,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister() != 53366:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer() != 32336:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_remove() != 23086:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_sdk_checksum_method_spaces_remove_prewarm() != 56425:
@@ -2993,6 +3001,10 @@ _UniffiLib.uniffi_cua_sdk_fn_method_devices_rename_machine.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_devices_rename_machine.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_devices_resolve_default_space.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_devices_resolve_default_space.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -3003,11 +3015,20 @@ _UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke_pairing_code.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke_pairing_code.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_devices_set_spaces_settings.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_devices_set_spaces_settings.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_devices_snapshot.argtypes = (
ctypes.c_uint64,
ctypes.c_uint32,
)
_UniffiLib.uniffi_cua_sdk_fn_method_devices_snapshot.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_devices_spaces_settings.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_devices_spaces_settings.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_forkbatch_collect.argtypes = (
ctypes.c_uint64,
)
@@ -4419,6 +4440,12 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_relay_unregister.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_relay_unregister.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.c_int8,
+)
+_UniffiLib.uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_sdk_fn_method_spaces_remove.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -5477,15 +5504,24 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_devices_rename.restype = ctypes.c_uint
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_rename_machine.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_rename_machine.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_resolve_default_space.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_resolve_default_space.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_set_spaces_settings.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_set_spaces_settings.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_snapshot.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_devices_snapshot.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_spaces_settings.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_spaces_settings.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_forkbatch_collect.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_forkbatch_collect.restype = ctypes.c_uint16
@@ -6293,6 +6329,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_spaces_relay_register.restype = ctypes
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer.argtypes = (
+)
+_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_remove.argtypes = (
)
_UniffiLib.uniffi_cua_sdk_checksum_method_spaces_remove.restype = ctypes.c_uint16
@@ -12808,6 +12847,137 @@ class _UniffiFfiConverterTypeCursorArt(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.write(value.outline_color, buf)
_UniffiFfiConverterFloat64.write(value.outline_width, buf)
+@dataclass
+class DefaultSpaceStep:
+ """
+ One entry of the order [`Devices::resolve_default_space`] tried.
+"""
+ def __init__(self, *, space:str, name:str, online:bool, role:str):
+ self.space = space
+ self.name = name
+ self.online = online
+ self.role = role
+
+
+
+
+ def __str__(self):
+ return "DefaultSpaceStep(space={}, name={}, online={}, role={})".format(self.space, self.name, self.online, self.role)
+ def __eq__(self, other):
+ if self.space != other.space:
+ return False
+ if self.name != other.name:
+ return False
+ if self.online != other.online:
+ return False
+ if self.role != other.role:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeDefaultSpaceStep(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return DefaultSpaceStep(
+ space=_UniffiFfiConverterString.read(buf),
+ name=_UniffiFfiConverterString.read(buf),
+ online=_UniffiFfiConverterBoolean.read(buf),
+ role=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.space)
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterBoolean.check_lower(value.online)
+ _UniffiFfiConverterString.check_lower(value.role)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.space, buf)
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterBoolean.write(value.online, buf)
+ _UniffiFfiConverterString.write(value.role, buf)
+
+class _UniffiFfiConverterSequenceTypeDefaultSpaceStep(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeDefaultSpaceStep.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeDefaultSpaceStep.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeDefaultSpaceStep.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class DefaultSpace:
+ """
+ Where the default Space resolves now.
+"""
+ def __init__(self, *, space:typing.Optional[str], reason:str, default_space:typing.Optional[str], default_online:typing.Optional[bool], order:typing.List[DefaultSpaceStep]):
+ self.space = space
+ self.reason = reason
+ self.default_space = default_space
+ self.default_online = default_online
+ self.order = order
+
+
+
+
+ def __str__(self):
+ return "DefaultSpace(space={}, reason={}, default_space={}, default_online={}, order={})".format(self.space, self.reason, self.default_space, self.default_online, self.order)
+ def __eq__(self, other):
+ if self.space != other.space:
+ return False
+ if self.reason != other.reason:
+ return False
+ if self.default_space != other.default_space:
+ return False
+ if self.default_online != other.default_online:
+ return False
+ if self.order != other.order:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeDefaultSpace(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return DefaultSpace(
+ space=_UniffiFfiConverterOptionalString.read(buf),
+ reason=_UniffiFfiConverterString.read(buf),
+ default_space=_UniffiFfiConverterOptionalString.read(buf),
+ default_online=_UniffiFfiConverterOptionalBoolean.read(buf),
+ order=_UniffiFfiConverterSequenceTypeDefaultSpaceStep.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.space)
+ _UniffiFfiConverterString.check_lower(value.reason)
+ _UniffiFfiConverterOptionalString.check_lower(value.default_space)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.default_online)
+ _UniffiFfiConverterSequenceTypeDefaultSpaceStep.check_lower(value.order)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.space, buf)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ _UniffiFfiConverterOptionalString.write(value.default_space, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.default_online, buf)
+ _UniffiFfiConverterSequenceTypeDefaultSpaceStep.write(value.order, buf)
+
@dataclass
class RelayDevice:
"""
@@ -28110,6 +28280,57 @@ class _UniffiFfiConverterTypeSpacesHost(_UniffiConverterRustBuffer):
_UniffiFfiConverterSequenceTypeSpacesHostLimit.write(value.limits, buf)
_UniffiFfiConverterOptionalTypeSpacesHostLoad.write(value.load, buf)
+@dataclass
+class SpacesSettings:
+ """
+ The account's default Space and the order to try when it is offline.
+"""
+ def __init__(self, *, default_space:typing.Optional[str], fallback:typing.List[str], fallback_on:bool, updated_at:int):
+ self.default_space = default_space
+ self.fallback = fallback
+ self.fallback_on = fallback_on
+ self.updated_at = updated_at
+
+
+
+
+ def __str__(self):
+ return "SpacesSettings(default_space={}, fallback={}, fallback_on={}, updated_at={})".format(self.default_space, self.fallback, self.fallback_on, self.updated_at)
+ def __eq__(self, other):
+ if self.default_space != other.default_space:
+ return False
+ if self.fallback != other.fallback:
+ return False
+ if self.fallback_on != other.fallback_on:
+ return False
+ if self.updated_at != other.updated_at:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSpacesSettings(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SpacesSettings(
+ default_space=_UniffiFfiConverterOptionalString.read(buf),
+ fallback=_UniffiFfiConverterSequenceString.read(buf),
+ fallback_on=_UniffiFfiConverterBoolean.read(buf),
+ updated_at=_UniffiFfiConverterUInt64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.default_space)
+ _UniffiFfiConverterSequenceString.check_lower(value.fallback)
+ _UniffiFfiConverterBoolean.check_lower(value.fallback_on)
+ _UniffiFfiConverterUInt64.check_lower(value.updated_at)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.default_space, buf)
+ _UniffiFfiConverterSequenceString.write(value.fallback, buf)
+ _UniffiFfiConverterBoolean.write(value.fallback_on, buf)
+ _UniffiFfiConverterUInt64.write(value.updated_at, buf)
+
@dataclass
class SpacesToolMethod:
"""
@@ -32843,6 +33064,13 @@ class DevicesProtocol(typing.Protocol):
Renames `machine_id`, a machine the account owns, on the relay (from
this enrolled device). When it is this machine's own registration,
its host setup takes the new name too.
+"""
+ raise NotImplementedError
+ async def resolve_default_space(self, ) -> DefaultSpace:
+ """
+ Where the default Space resolves now: the first online entry of the
+ default, the fallback order, then this computer (its own relay
+ machine id, when it has one). Creates nothing.
"""
raise NotImplementedError
async def revoke(self, id: str) -> RelayDevice:
@@ -32854,6 +33082,12 @@ class DevicesProtocol(typing.Protocol):
async def revoke_pairing_code(self, id: str) -> None:
"""
Revokes an unused pairing code (`pc_…`).
+"""
+ raise NotImplementedError
+ async def set_spaces_settings(self, settings: SpacesSettings) -> SpacesSettings:
+ """
+ Replaces the account's default Space settings (the whole object;
+ `updated_at` is set by the relay). Returns what the relay saved.
"""
raise NotImplementedError
async def snapshot(self, audit_limit: int) -> DevicesSnapshot:
@@ -32861,6 +33095,12 @@ class DevicesProtocol(typing.Protocol):
The account's devices, the grace period, the newest `audit_limit`
audit events and the machines' names. Only the device list must
succeed; the rest is empty when the relay refuses it.
+"""
+ raise NotImplementedError
+ async def spaces_settings(self, ) -> SpacesSettings:
+ """
+ The account's default Space and fallback order. A relay that
+ predates them answers "the Cua relay needs an update".
"""
raise NotImplementedError
@@ -33106,6 +33346,25 @@ class Devices(DevicesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def resolve_default_space(self, ) -> DefaultSpace:
+ """
+ Where the default Space resolves now: the first online entry of the
+ default, the fallback order, then this computer (its own relay
+ machine id, when it has one). Creates nothing.
+"""
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeDefaultSpace.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_devices_resolve_default_space(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def revoke(self, id: str) -> RelayDevice:
"""
Revokes a device (from this enrolled device). Revoking this device
@@ -33147,6 +33406,27 @@ class Devices(DevicesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def set_spaces_settings(self, settings: SpacesSettings) -> SpacesSettings:
+ """
+ Replaces the account's default Space settings (the whole object;
+ `updated_at` is set by the relay). Returns what the relay saved.
+"""
+
+ _UniffiFfiConverterTypeSpacesSettings.check_lower(settings)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeSpacesSettings.lower(settings),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSpacesSettings.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_devices_set_spaces_settings(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def snapshot(self, audit_limit: int) -> DevicesSnapshot:
"""
The account's devices, the grace period, the newest `audit_limit`
@@ -33169,6 +33449,24 @@ class Devices(DevicesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def spaces_settings(self, ) -> SpacesSettings:
+ """
+ The account's default Space and fallback order. A relay that
+ predates them answers "the Cua relay needs an update".
+"""
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeSpacesSettings.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_devices_spaces_settings(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
@@ -44184,6 +44482,17 @@ class SpacesProtocol(typing.Protocol):
"""
Takes `space` off the relay (its driver leaves; every share goes).
Returns false when it was not on the relay.
+"""
+ raise NotImplementedError
+ async def relay_unregister_computer(self, space: str,delete_spaces: bool) -> bool:
+ """
+ [`Spaces::relay_unregister`] for one of your computers
+ (`relay:<machine>`), choosing what happens to the Spaces it
+ provides: with `delete_spaces` false they stay on the account,
+ detached (they come back when the computer registers again); with
+ true they are deleted too, files first (through the computer while
+ it answers), then their records. Returns false when it was not on
+ the relay.
"""
raise NotImplementedError
async def remove(self, space: str) -> None:
@@ -45914,6 +46223,35 @@ class Spaces(SpacesProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def relay_unregister_computer(self, space: str,delete_spaces: bool) -> bool:
+ """
+ [`Spaces::relay_unregister`] for one of your computers
+ (`relay:<machine>`), choosing what happens to the Spaces it
+ provides: with `delete_spaces` false they stay on the account,
+ detached (they come back when the computer registers again); with
+ true they are deleted too, files first (through the computer while
+ it answers), then their records. Returns false when it was not on
+ the relay.
+"""
+
+ _UniffiFfiConverterString.check_lower(space)
+
+ _UniffiFfiConverterBoolean.check_lower(delete_spaces)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(space),
+ _UniffiFfiConverterBoolean.lower(delete_spaces),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterBoolean.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_sdk_rust_future_poll_i8,
+ _UniffiLib.ffi_cua_sdk_rust_future_complete_i8,
+ _UniffiLib.ffi_cua_sdk_rust_future_free_i8,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def remove(self, space: str) -> None:
"""
Unregisters a Space (the sandbox is not touched).
@@ -49622,6 +49960,8 @@ __all__ = [
"CuaConfig",
"CuaInfo",
"CursorArt",
+ "DefaultSpaceStep",
+ "DefaultSpace",
"RelayDevice",
"DeviceEnrollment",
"RelayAuditEvent",
@@ -49796,6 +50136,7 @@ __all__ = [
"SpacesHostLimit",
"SpacesHostLoad",
"SpacesHost",
+ "SpacesSettings",
"SpacesToolMethod",
"SpacesdFeature",
"SpacesdCapabilities",
diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.json
index 053049f037..be7e69af92 100644
--- a/libs/cua/spaces-contract/manifest.json
+++ b/libs/cua/spaces-contract/manifest.json
@@ -402,7 +402,7 @@
"sdk_symbol": "SpacesConnection.spaces()",
"rust_symbol": "Spaces::list",
"notes": [],
- "result": "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your computers provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay computer the relay cannot reach now `status` (`offline` or `not sharing`)), each with `phase`: `ready`, or `offline` for a relay computer the relay cannot reach now (a computer that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).",
+ "result": "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your computers provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay computer the relay cannot reach now `status` (`offline` or `not sharing`)), `parent` (a Space one of your computers provides: that computer's Space id, `relay:<computer>`; null for a computer or any other Space) and `default` (true for the Space the account chose as its default, false for every other; false for all when signed out or the relay does not answer), each with `phase`: `ready`, or `offline` for a relay computer the relay cannot reach now (a computer that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).",
"errors": [
"relay",
"unauthenticated"
@@ -6833,7 +6833,7 @@
"name": "relay_unregister_space",
"category": "sharing",
"description": "Take a Space off the relay.",
- "instructions": "Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead.",
+ "instructions": "Takes the Space off the relay: its driver leaves and its computer is removed, with every share. A `relay:<computer>` id removes that computer's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a computer that is no longer connected. A host that is connected now is taken off with `cua host remove` on that computer instead. Removing one of your computers keeps the Spaces it provides on your account, detached (hidden, and refused until the computer registers again with the same id, which brings them back unchanged); `delete_spaces: true` deletes them too, files first (through the computer while it answers), then their records.",
"platforms": [
"macos",
"windows",
@@ -6871,6 +6871,10 @@
],
"input_schema": {
"properties": {
+ "delete_spaces": {
+ "description": "For one of your computers: also delete the Spaces it provides, their\nfiles first (through the computer while it answers), then their\nrecords. Default false: they stay on your account, detached, and come\nback when the computer registers again.",
+ "type": "boolean"
+ },
"space": {
"description": "Space id or name.",
"type": "string"
diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
index a995d0b14f..2a85ef6aea 100644
--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
@@ -3362,6 +3362,13 @@ public protocol DevicesProtocol: AnyObject, Sendable {
*/
func renameMachine(machineId: String, name: String) async throws -> RelayMachine
+ /**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+ func resolveDefaultSpace() async throws -> DefaultSpace
+
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -3373,6 +3380,12 @@ public protocol DevicesProtocol: AnyObject, Sendable {
*/
func revokePairingCode(id: String) async throws
+ /**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+ func setSpacesSettings(settings: SpacesSettings) async throws -> SpacesSettings
+
/**
* The account's devices, the grace period, the newest `audit_limit`
* audit events and the machines' names. Only the device list must
@@ -3380,6 +3393,12 @@ public protocol DevicesProtocol: AnyObject, Sendable {
*/
func snapshot(auditLimit: UInt32) async throws -> DevicesSnapshot
+ /**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+ func spacesSettings() async throws -> SpacesSettings
+
}
/**
* This device as a client of the signed-in account on a relay: its
@@ -3635,6 +3654,28 @@ open func renameMachine(machineId: String, name: String)async throws -> RelayMa
)
}
+ /**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+open func resolveDefaultSpace()async throws -> DefaultSpace {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_devices_resolve_default_space(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeDefaultSpace_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -3676,6 +3717,27 @@ open func revokePairingCode(id: String)async throws {
)
}
+ /**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+open func setSpacesSettings(settings: SpacesSettings)async throws -> SpacesSettings {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_devices_set_spaces_settings(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeSpacesSettings_lower(settings)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSpacesSettings_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* The account's devices, the grace period, the newest `audit_limit`
* audit events and the machines' names. Only the device list must
@@ -3698,6 +3760,27 @@ open func snapshot(auditLimit: UInt32)async throws -> DevicesSnapshot {
)
}
+ /**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+open func spacesSettings()async throws -> SpacesSettings {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_devices_spaces_settings(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeSpacesSettings_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
}
@@ -11892,6 +11975,17 @@ public protocol SpacesProtocol: AnyObject, Sendable {
*/
func relayUnregister(space: String) async throws -> Bool
+ /**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+ func relayUnregisterComputer(space: String, deleteSpaces: Bool) async throws -> Bool
+
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -13574,6 +13668,32 @@ open func relayUnregister(space: String)async throws -> Bool {
)
}
+ /**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+open func relayUnregisterComputer(space: String, deleteSpaces: Bool)async throws -> Bool {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(space),FfiConverterBool.lower(deleteSpaces)
+ )
+ },
+ pollFunc: ffi_cua_sdk_rust_future_poll_i8,
+ completeFunc: ffi_cua_sdk_rust_future_complete_i8,
+ freeFunc: ffi_cua_sdk_rust_future_free_i8,
+ liftFunc: FfiConverterBool.lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -23863,6 +23983,196 @@ public func FfiConverterTypeCursorArt_lower(_ value: CursorArt) -> RustBuffer {
}
+/**
+ * Where the default Space resolves now.
+ */
+public struct DefaultSpace: Equatable, Hashable {
+ /**
+ * The first online entry; none when this device is the answer
+ * (`reason` `here`).
+ */
+ public var space: String?
+ /**
+ * `default`, `fallback`, `here` or `unset`.
+ */
+ public var reason: String
+ /**
+ * The chosen default, online or not.
+ */
+ public var defaultSpace: String?
+ /**
+ * Whether the default is online; none when unset.
+ */
+ public var defaultOnline: Bool?
+ /**
+ * The order the relay tried.
+ */
+ public var order: [DefaultSpaceStep]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The first online entry; none when this device is the answer
+ * (`reason` `here`).
+ */space: String?,
+ /**
+ * `default`, `fallback`, `here` or `unset`.
+ */reason: String,
+ /**
+ * The chosen default, online or not.
+ */defaultSpace: String?,
+ /**
+ * Whether the default is online; none when unset.
+ */defaultOnline: Bool?,
+ /**
+ * The order the relay tried.
+ */order: [DefaultSpaceStep]) {
+ self.space = space
+ self.reason = reason
+ self.defaultSpace = defaultSpace
+ self.defaultOnline = defaultOnline
+ self.order = order
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension DefaultSpace: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDefaultSpace: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DefaultSpace {
+ return
+ try DefaultSpace(
+ space: FfiConverterOptionString.read(from: &buf),
+ reason: FfiConverterString.read(from: &buf),
+ defaultSpace: FfiConverterOptionString.read(from: &buf),
+ defaultOnline: FfiConverterOptionBool.read(from: &buf),
+ order: FfiConverterSequenceTypeDefaultSpaceStep.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: DefaultSpace, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.space, into: &buf)
+ FfiConverterString.write(value.reason, into: &buf)
+ FfiConverterOptionString.write(value.defaultSpace, into: &buf)
+ FfiConverterOptionBool.write(value.defaultOnline, into: &buf)
+ FfiConverterSequenceTypeDefaultSpaceStep.write(value.order, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDefaultSpace_lift(_ buf: RustBuffer) throws -> DefaultSpace {
+ return try FfiConverterTypeDefaultSpace.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDefaultSpace_lower(_ value: DefaultSpace) -> RustBuffer {
+ return FfiConverterTypeDefaultSpace.lower(value)
+}
+
+
+/**
+ * One entry of the order [`Devices::resolve_default_space`] tried.
+ */
+public struct DefaultSpaceStep: Equatable, Hashable {
+ /**
+ * The Space id.
+ */
+ public var space: String
+ /**
+ * Its display name.
+ */
+ public var name: String
+ /**
+ * Connected and sharing now.
+ */
+ public var online: Bool
+ /**
+ * `default`, `fallback` or `here`.
+ */
+ public var role: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The Space id.
+ */space: String,
+ /**
+ * Its display name.
+ */name: String,
+ /**
+ * Connected and sharing now.
+ */online: Bool,
+ /**
+ * `default`, `fallback` or `here`.
+ */role: String) {
+ self.space = space
+ self.name = name
+ self.online = online
+ self.role = role
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension DefaultSpaceStep: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDefaultSpaceStep: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DefaultSpaceStep {
+ return
+ try DefaultSpaceStep(
+ space: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ online: FfiConverterBool.read(from: &buf),
+ role: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: DefaultSpaceStep, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.space, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterBool.write(value.online, into: &buf)
+ FfiConverterString.write(value.role, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDefaultSpaceStep_lift(_ buf: RustBuffer) throws -> DefaultSpaceStep {
+ return try FfiConverterTypeDefaultSpaceStep.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDefaultSpaceStep_lower(_ value: DefaultSpaceStep) -> RustBuffer {
+ return FfiConverterTypeDefaultSpaceStep.lower(value)
+}
+
+
/**
* `Devices.enroll`'s result.
*/
@@ -43819,6 +44129,97 @@ public func FfiConverterTypeSpacesHostLoad_lower(_ value: SpacesHostLoad) -> Rus
}
+/**
+ * The account's default Space and the order to try when it is offline.
+ */
+public struct SpacesSettings: Equatable, Hashable {
+ /**
+ * `relay:<machine>` or `relay:<machine>/<name>`; none when unset.
+ */
+ public var defaultSpace: String?
+ /**
+ * The order to try when the default is offline; empty means every
+ * online computer you can use, oldest first.
+ */
+ public var fallback: [String]
+ /**
+ * false: only the default, then this device.
+ */
+ public var fallbackOn: Bool
+ /**
+ * Unix seconds the relay saved it (ignored when writing).
+ */
+ public var updatedAt: UInt64
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `relay:<machine>` or `relay:<machine>/<name>`; none when unset.
+ */defaultSpace: String?,
+ /**
+ * The order to try when the default is offline; empty means every
+ * online computer you can use, oldest first.
+ */fallback: [String],
+ /**
+ * false: only the default, then this device.
+ */fallbackOn: Bool,
+ /**
+ * Unix seconds the relay saved it (ignored when writing).
+ */updatedAt: UInt64) {
+ self.defaultSpace = defaultSpace
+ self.fallback = fallback
+ self.fallbackOn = fallbackOn
+ self.updatedAt = updatedAt
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SpacesSettings: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSpacesSettings: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SpacesSettings {
+ return
+ try SpacesSettings(
+ defaultSpace: FfiConverterOptionString.read(from: &buf),
+ fallback: FfiConverterSequenceString.read(from: &buf),
+ fallbackOn: FfiConverterBool.read(from: &buf),
+ updatedAt: FfiConverterUInt64.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SpacesSettings, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.defaultSpace, into: &buf)
+ FfiConverterSequenceString.write(value.fallback, into: &buf)
+ FfiConverterBool.write(value.fallbackOn, into: &buf)
+ FfiConverterUInt64.write(value.updatedAt, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpacesSettings_lift(_ buf: RustBuffer) throws -> SpacesSettings {
+ return try FfiConverterTypeSpacesSettings.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSpacesSettings_lower(_ value: SpacesSettings) -> RustBuffer {
+ return FfiConverterTypeSpacesSettings.lower(value)
+}
+
+
/**
* One row of [`SPACES_TOOL_METHODS`].
*/
@@ -51221,6 +51622,31 @@ fileprivate struct FfiConverterSequenceTypeCursorArt: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeDefaultSpaceStep: FfiConverterRustBuffer {
+ typealias SwiftType = [DefaultSpaceStep]
+
+ public static func write(_ value: [DefaultSpaceStep], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeDefaultSpaceStep.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [DefaultSpaceStep] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [DefaultSpaceStep]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeDefaultSpaceStep.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -54300,15 +54726,24 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_devices_rename_machine() != 63088) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_devices_resolve_default_space() != 5493) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_devices_revoke() != 27802) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() != 3143) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_devices_set_spaces_settings() != 38780) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_devices_snapshot() != 26132) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_devices_spaces_settings() != 1866) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_host_configure() != 36828) {
return InitializationResult.apiChecksumMismatch
}
@@ -55098,6 +55533,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_sdk_checksum_method_spaces_relay_unregister() != 53366) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer() != 32336) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_sdk_checksum_method_spaces_remove() != 23086) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
index 8198356826..96da7ee5a6 100644
--- a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
+++ b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h
@@ -864,6 +864,11 @@ uint64_t uniffi_cua_sdk_fn_method_devices_rename(uint64_t ptr, RustBuffer id, Ru
uint64_t uniffi_cua_sdk_fn_method_devices_rename_machine(uint64_t ptr, RustBuffer machine_id, RustBuffer name
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_RESOLVE_DEFAULT_SPACE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_RESOLVE_DEFAULT_SPACE
+uint64_t uniffi_cua_sdk_fn_method_devices_resolve_default_space(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_REVOKE
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_REVOKE
uint64_t uniffi_cua_sdk_fn_method_devices_revoke(uint64_t ptr, RustBuffer id
@@ -874,11 +879,21 @@ uint64_t uniffi_cua_sdk_fn_method_devices_revoke(uint64_t ptr, RustBuffer id
uint64_t uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(uint64_t ptr, RustBuffer id
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SET_SPACES_SETTINGS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SET_SPACES_SETTINGS
+uint64_t uniffi_cua_sdk_fn_method_devices_set_spaces_settings(uint64_t ptr, RustBuffer settings
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SNAPSHOT
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SNAPSHOT
uint64_t uniffi_cua_sdk_fn_method_devices_snapshot(uint64_t ptr, uint32_t audit_limit
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SPACES_SETTINGS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SPACES_SETTINGS
+uint64_t uniffi_cua_sdk_fn_method_devices_spaces_settings(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_CLONE_HOST
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_CLONE_HOST
uint64_t uniffi_cua_sdk_fn_clone_host(uint64_t handle, RustCallStatus *_Nonnull out_status
@@ -2439,6 +2454,11 @@ uint64_t uniffi_cua_sdk_fn_method_spaces_relay_register(uint64_t ptr, RustBuffer
uint64_t uniffi_cua_sdk_fn_method_spaces_relay_unregister(uint64_t ptr, RustBuffer space
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_RELAY_UNREGISTER_COMPUTER
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_RELAY_UNREGISTER_COMPUTER
+uint64_t uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(uint64_t ptr, RustBuffer space, int8_t delete_spaces
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_REMOVE
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACES_REMOVE
uint64_t uniffi_cua_sdk_fn_method_spaces_remove(uint64_t ptr, RustBuffer space
@@ -4488,6 +4508,12 @@ uint16_t uniffi_cua_sdk_checksum_method_devices_rename(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_RENAME_MACHINE
uint16_t uniffi_cua_sdk_checksum_method_devices_rename_machine(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_RESOLVE_DEFAULT_SPACE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_RESOLVE_DEFAULT_SPACE
+uint16_t uniffi_cua_sdk_checksum_method_devices_resolve_default_space(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_REVOKE
@@ -4500,12 +4526,24 @@ uint16_t uniffi_cua_sdk_checksum_method_devices_revoke(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_REVOKE_PAIRING_CODE
uint16_t uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_SET_SPACES_SETTINGS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_SET_SPACES_SETTINGS
+uint16_t uniffi_cua_sdk_checksum_method_devices_set_spaces_settings(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_SNAPSHOT
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_SNAPSHOT
uint16_t uniffi_cua_sdk_checksum_method_devices_snapshot(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_SPACES_SETTINGS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_SPACES_SETTINGS
+uint16_t uniffi_cua_sdk_checksum_method_devices_spaces_settings(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_HOST_CONFIGURE
@@ -6084,6 +6122,12 @@ uint16_t uniffi_cua_sdk_checksum_method_spaces_relay_register(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_RELAY_UNREGISTER
uint16_t uniffi_cua_sdk_checksum_method_spaces_relay_unregister(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_RELAY_UNREGISTER_COMPUTER
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_RELAY_UNREGISTER_COMPUTER
+uint16_t uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_SPACES_REMOVE
diff --git a/libs/cua/typescript/src/native/cua_sdk-ffi.ts b/libs/cua/typescript/src/native/cua_sdk-ffi.ts
index fa8650d4b0..e9964bab00 100644
--- a/libs/cua/typescript/src/native/cua_sdk-ffi.ts
+++ b/libs/cua/typescript/src/native/cua_sdk-ffi.ts
@@ -1353,6 +1353,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_devices_resolve_default_space": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_devices_revoke": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -1363,11 +1368,21 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_devices_set_spaces_settings": {
+ 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,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_devices_spaces_settings": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_forkbatch_collect": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -2713,6 +2728,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_fn_method_spaces_remove": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -3978,6 +3998,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_devices_resolve_default_space": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_devices_revoke": {
args: [],
ret: FfiType.UInt16,
@@ -3988,11 +4013,21 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_devices_set_spaces_settings": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_devices_snapshot": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_devices_spaces_settings": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_forkbatch_collect": {
args: [],
ret: FfiType.UInt16,
@@ -5338,6 +5373,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_sdk_checksum_method_spaces_remove": {
args: [],
ret: FfiType.UInt16,
@@ -6355,9 +6395,12 @@ interface NativeModuleInterface {
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_rename_machine(uniffiSelf: bigint, machineId: Uint8Array, name: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_devices_resolve_default_space(uniffiSelf: bigint): 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_set_spaces_settings(uniffiSelf: bigint, settings: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_devices_snapshot(uniffiSelf: bigint, auditLimit: number): bigint;
+ uniffi_cua_sdk_fn_method_devices_spaces_settings(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_forkbatch_collect(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_forkbatch_next(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_framesink_on_frame(uniffiSelf: bigint, frame: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;
@@ -6627,6 +6670,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_fn_method_spaces_prewarms(uniffiSelf: bigint): bigint;
uniffi_cua_sdk_fn_method_spaces_relay_register(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_relay_unregister(uniffiSelf: bigint, space: Uint8Array): bigint;
+ uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(uniffiSelf: bigint, space: Uint8Array, deleteSpaces: number): bigint;
uniffi_cua_sdk_fn_method_spaces_remove(uniffiSelf: bigint, space: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_remove_prewarm(uniffiSelf: bigint, id: Uint8Array): bigint;
uniffi_cua_sdk_fn_method_spaces_rename(uniffiSelf: bigint, space: Uint8Array, name: Uint8Array): bigint;
@@ -6880,9 +6924,12 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_devices_relay_url(): number;
uniffi_cua_sdk_checksum_method_devices_rename(): number;
uniffi_cua_sdk_checksum_method_devices_rename_machine(): number;
+ uniffi_cua_sdk_checksum_method_devices_resolve_default_space(): 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_set_spaces_settings(): number;
uniffi_cua_sdk_checksum_method_devices_snapshot(): number;
+ uniffi_cua_sdk_checksum_method_devices_spaces_settings(): number;
uniffi_cua_sdk_checksum_method_forkbatch_collect(): number;
uniffi_cua_sdk_checksum_method_forkbatch_next(): number;
uniffi_cua_sdk_checksum_method_framesink_on_frame(): number;
@@ -7152,6 +7199,7 @@ interface NativeModuleInterface {
uniffi_cua_sdk_checksum_method_spaces_prewarms(): number;
uniffi_cua_sdk_checksum_method_spaces_relay_register(): number;
uniffi_cua_sdk_checksum_method_spaces_relay_unregister(): number;
+ uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer(): number;
uniffi_cua_sdk_checksum_method_spaces_remove(): number;
uniffi_cua_sdk_checksum_method_spaces_remove_prewarm(): number;
uniffi_cua_sdk_checksum_method_spaces_rename(): number;
diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.ts
index e0f90bdff4..42b6273052 100644
--- a/libs/cua/typescript/src/native/cua_sdk.ts
+++ b/libs/cua/typescript/src/native/cua_sdk.ts
@@ -7281,6 +7281,146 @@ const FfiConverterTypeCursorArt = (() => {
return new FFIConverter();
})();
+/**
+ * One entry of the order [`Devices::resolve_default_space`] tried.
+ */
+export type DefaultSpaceStep = {
+ /**
+ * The Space id.
+ */
+ space: string,
+ /**
+ * Its display name.
+ */
+ name: string,
+ /**
+ * Connected and sharing now.
+ */
+ online: boolean,
+ /**
+ * `default`, `fallback` or `here`.
+ */
+ role: string
+}
+
+/**
+ * Generated factory for {@link DefaultSpaceStep} record objects.
+ */
+export const DefaultSpaceStep = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DefaultSpaceStep, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DefaultSpaceStep>,
+ });
+})();
+
+const FfiConverterTypeDefaultSpaceStep = (() => {
+ type TypeName = DefaultSpaceStep;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ space: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ online: FfiConverterBool.read(from),
+ role: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.space, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterBool.write(value.online, into);
+ FfiConverterString.write(value.role, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.space) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterBool.allocationSize(value.online) +
+ FfiConverterString.allocationSize(value.role);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * Where the default Space resolves now.
+ */
+export type DefaultSpace = {
+ /**
+ * The first online entry; none when this device is the answer
+ * (`reason` `here`).
+ */
+ space?: string,
+ /**
+ * `default`, `fallback`, `here` or `unset`.
+ */
+ reason: string,
+ /**
+ * The chosen default, online or not.
+ */
+ defaultSpace?: string,
+ /**
+ * Whether the default is online; none when unset.
+ */
+ defaultOnline?: boolean,
+ /**
+ * The order the relay tried.
+ */
+ order: Array<DefaultSpaceStep>
+}
+
+/**
+ * Generated factory for {@link DefaultSpace} record objects.
+ */
+export const DefaultSpace = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DefaultSpace, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DefaultSpace>,
+ });
+})();
+
+const FfiConverterTypeDefaultSpace = (() => {
+ type TypeName = DefaultSpace;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ space: FfiConverterOptionalString.read(from),
+ reason: FfiConverterString.read(from),
+ defaultSpace: FfiConverterOptionalString.read(from),
+ defaultOnline: FfiConverterOptionalBoolean.read(from),
+ order: FfiConverterSequenceTypeDefaultSpaceStep.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.space, into);
+ FfiConverterString.write(value.reason, into);
+ FfiConverterOptionalString.write(value.defaultSpace, into);
+ FfiConverterOptionalBoolean.write(value.defaultOnline, into);
+ FfiConverterSequenceTypeDefaultSpaceStep.write(value.order, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.space) +
+ FfiConverterString.allocationSize(value.reason) +
+ FfiConverterOptionalString.allocationSize(value.defaultSpace) +
+ FfiConverterOptionalBoolean.allocationSize(value.defaultOnline) +
+ FfiConverterSequenceTypeDefaultSpaceStep.allocationSize(value.order);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* A client device of the account, as the relay lists it.
*/
@@ -23184,6 +23324,73 @@ const FfiConverterTypeSpacesHost = (() => {
return new FFIConverter();
})();
+/**
+ * The account's default Space and the order to try when it is offline.
+ */
+export type SpacesSettings = {
+ /**
+ * `relay:<machine>` or `relay:<machine>/<name>`; none when unset.
+ */
+ defaultSpace?: string,
+ /**
+ * The order to try when the default is offline; empty means every
+ * online computer you can use, oldest first.
+ */
+ fallback: Array<string>,
+ /**
+ * false: only the default, then this device.
+ */
+ fallbackOn: boolean,
+ /**
+ * Unix seconds the relay saved it (ignored when writing).
+ */
+ updatedAt: bigint
+}
+
+/**
+ * Generated factory for {@link SpacesSettings} record objects.
+ */
+export const SpacesSettings = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SpacesSettings, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SpacesSettings>,
+ });
+})();
+
+const FfiConverterTypeSpacesSettings = (() => {
+ type TypeName = SpacesSettings;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ defaultSpace: FfiConverterOptionalString.read(from),
+ fallback: FfiConverterSequenceString.read(from),
+ fallbackOn: FfiConverterBool.read(from),
+ updatedAt: FfiConverterUInt64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.defaultSpace, into);
+ FfiConverterSequenceString.write(value.fallback, into);
+ FfiConverterBool.write(value.fallbackOn, into);
+ FfiConverterUInt64.write(value.updatedAt, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.defaultSpace) +
+ FfiConverterSequenceString.allocationSize(value.fallback) +
+ FfiConverterBool.allocationSize(value.fallbackOn) +
+ FfiConverterUInt64.allocationSize(value.updatedAt);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One row of [`SPACES_TOOL_METHODS`].
*/
@@ -28968,6 +29175,12 @@ export interface DevicesLike {
* its host setup takes the new name too.
*/
renameMachine(machineId: string, name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RelayMachine>;
+/**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+ resolveDefaultSpace(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DefaultSpace>;
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -28977,12 +29190,22 @@ export interface DevicesLike {
* Revokes an unused pairing code (`pc_…`).
*/
revokePairingCode(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+/**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+ setSpacesSettings(settings: SpacesSettings, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacesSettings>;
/**
* The account's devices, the grace period, the newest `audit_limit`
* audit events and the machines' names. Only the device list must
* succeed; the rest is empty when the relay refuses it.
*/
snapshot(auditLimit: number, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DevicesSnapshot>;
+/**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+ spacesSettings(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SpacesSettings>;
}
/**
* @deprecated Use `DevicesLike` instead.
@@ -29344,6 +29567,43 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Where the default Space resolves now: the first online entry of the
+ * default, the fallback order, then this computer (its own relay
+ * machine id, when it has one). Creates nothing.
+ */
+ async resolveDefaultSpace(asyncOpts_?: { signal: AbortSignal }): Promise<DefaultSpace> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_devices_resolve_default_space(
+ 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:*/ FfiConverterTypeDefaultSpace.lift.bind(FfiConverterTypeDefaultSpace),
+ /*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;
+ }
+ }
+
/**
* Revokes a device (from this enrolled device). Revoking this device
* also deletes its key.
@@ -29410,6 +29670,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Replaces the account's default Space settings (the whole object;
+ * `updated_at` is set by the relay). Returns what the relay saved.
+ */
+ async setSpacesSettings(settings: SpacesSettings, asyncOpts_?: { signal: AbortSignal }): Promise<SpacesSettings> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_devices_set_spaces_settings(
+ uniffiTypeDevicesObjectFactory.clonePointer(this),FfiConverterTypeSpacesSettings.lower(settings, 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:*/ FfiConverterTypeSpacesSettings.lift.bind(FfiConverterTypeSpacesSettings),
+ /*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
@@ -29447,6 +29743,42 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * The account's default Space and fallback order. A relay that
+ * predates them answers "the Cua relay needs an update".
+ */
+ async spacesSettings(asyncOpts_?: { signal: AbortSignal }): Promise<SpacesSettings> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_devices_spaces_settings(
+ 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:*/ FfiConverterTypeSpacesSettings.lift.bind(FfiConverterTypeSpacesSettings),
+ /*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;
+ }
+ }
+
uniffiDestroy(): void {
const ptr = (this as any)[destructorGuardSymbol];
@@ -42380,6 +42712,16 @@ export interface SpacesLike {
* Returns false when it was not on the relay.
*/
relayUnregister(space: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<boolean>;
+/**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+ relayUnregisterComputer(space: string, deleteSpaces: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<boolean>;
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -44845,6 +45187,47 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * [`Spaces::relay_unregister`] for one of your computers
+ * (`relay:<machine>`), choosing what happens to the Spaces it
+ * provides: with `delete_spaces` false they stay on the account,
+ * detached (they come back when the computer registers again); with
+ * true they are deleted too, files first (through the computer while
+ * it answers), then their records. Returns false when it was not on
+ * the relay.
+ */
+ async relayUnregisterComputer(space: string, deleteSpaces: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<boolean> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_sdk_fn_method_spaces_relay_unregister_computer(
+ uniffiTypeSpacesObjectFactory.clonePointer(this),FfiConverterString.lower(space, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(deleteSpaces, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_i8,
+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_i8,
+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_i8,
+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_i8,
+ // 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:*/ FfiConverterBool.lift.bind(FfiConverterBool),
+ /*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;
+ }
+ }
+
/**
* Unregisters a Space (the sandbox is not touched).
*/
@@ -48462,6 +48845,9 @@ const FfiConverterSequenceTypeCloudSweepItem = new FfiConverterArray(FfiConverte
// FfiConverter for Array<number>
const FfiConverterSequenceUInt16 = new FfiConverterArray(FfiConverterUInt16);
+// FfiConverter for Array<DefaultSpaceStep>
+const FfiConverterSequenceTypeDefaultSpaceStep = new FfiConverterArray(FfiConverterTypeDefaultSpaceStep);
+
// FfiConverter for Array<RelayDevice>
const FfiConverterSequenceTypeRelayDevice = new FfiConverterArray(FfiConverterTypeRelayDevice);
@@ -49333,15 +49719,24 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_devices_rename_machine() !== 63088) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_rename_machine");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_resolve_default_space() !== 5493) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_resolve_default_space");
+ }
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_set_spaces_settings() !== 38780) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_set_spaces_settings");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_devices_snapshot() !== 26132) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_snapshot");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_spaces_settings() !== 1866) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_spaces_settings");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_forkbatch_collect() !== 56883) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_forkbatch_collect");
}
@@ -50149,6 +50544,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_relay_unregister() !== 53366) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_relay_unregister");
}
+ if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer() !== 32336) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_relay_unregister_computer");
+ }
if (nativeModule().uniffi_cua_sdk_checksum_method_spaces_remove() !== 23086) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spaces_remove");
}
@@ -50578,6 +50976,8 @@ export default Object.freeze({
FfiConverterTypeCuaInfo,
FfiConverterTypeCuaMode,
FfiConverterTypeCursorArt,
+ FfiConverterTypeDefaultSpace,
+ FfiConverterTypeDefaultSpaceStep,
FfiConverterTypeDeviceEnrollment,
FfiConverterTypeDevices,
FfiConverterTypeDevicesSnapshot,
@@ -50791,6 +51191,7 @@ export default Object.freeze({
FfiConverterTypeSpacesHostLoad,
FfiConverterTypeSpacesListListener,
FfiConverterTypeSpacesListWatch,
+ FfiConverterTypeSpacesSettings,
FfiConverterTypeSpacesToolMethod,
FfiConverterTypeSpacesdCapabilities,
FfiConverterTypeSpacesdClient,
diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.json
index 9d16b5f15d..6dfc27dec3 100644
--- a/scripts/docs-generators/cli-specs/cua.json
+++ b/scripts/docs-generators/cli-specs/cua.json
@@ -13700,11 +13700,11 @@
"usage": "cua computers [OPTIONS]"
},
{
- "abstract": "Your computers on the relay: remove one that is gone",
+ "abstract": "Now `cua spaces` (kept for one release)",
"aliases": [],
"arguments": [],
"flags": [],
- "hidden": false,
+ "hidden": true,
"hidden_aliases": [],
"name": "machines",
"options": [],
@@ -13712,7 +13712,7 @@
"subcommands": [
{
"abstract": "Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). A computer that is connected now is refused: run `cua host remove` on it",
- "after_help": "Examples:\n cua machines rm old-laptop\n cua machines rm relay:0123abcd4567ef89 --yes --json",
+ "after_help": "Examples:\n cua spaces rm old-laptop\n cua spaces rm relay:0123abcd4567ef89 --yes --json",
"aliases": [],
"arguments": [
{
@@ -16236,7 +16236,30 @@
"type": "string"
}
],
- "flags": [],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "For one of your computers: also delete the Spaces it provides and their files (through the computer while it is reachable). Without it they stay on your account, detached, and come back if the computer is added again",
+ "hidden": false,
+ "name": "delete-spaces",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ },
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Remove a computer without asking",
+ "hidden": false,
+ "name": "yes",
+ "repeatable": false,
+ "short_name": "y",
+ "takes_value": false
+ }
+ ],
"hidden": false,
"hidden_aliases": [],
"name": "rm",
@@ -16245,6 +16268,82 @@
"subcommands": [],
"usage": "cua spaces rm [OPTIONS] <SPACE>"
},
+ {
+ "abstract": "Your default Space: where \"my Space\" goes when you do not say. With no argument it prints the Space it resolves to now and the order it tries (online or not); with a Space it sets the default",
+ "after_help": "Examples:\n cua spaces default\n cua spaces default studio\n cua spaces default studio --fallback office-pc,relay:0123abcd4567ef89\n # Only the default, then this computer\n cua spaces default --no-fallback\n # Back to trying every online computer, oldest first\n cua spaces default --fallback-on\n cua spaces default --clear",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "The Space to make your default: a name or id (as `cua spaces ls` shows)",
+ "hidden": false,
+ "is_optional": true,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Have no default",
+ "hidden": false,
+ "name": "clear",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ },
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "When the default is offline, use this computer instead of trying the others",
+ "hidden": false,
+ "name": "no-fallback",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ },
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Try the others again when the default is offline (every online computer, oldest first, unless `--fallback` names an order)",
+ "hidden": false,
+ "name": "fallback-on",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ }
+ ],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "default",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "Spaces to try, in this order, when the default is offline (names or ids, comma separated)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "fallback",
+ "possible_values": [],
+ "repeatable": true,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "SPACES"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua spaces default [OPTIONS] [SPACE]"
+ },
{
"abstract": "Give a Space a new name; its id stays the same. Lowercase letters, digits and dashes, as at create. A Space you shared, or one of your computers provides, is renamed on the relay too, so your other devices and the people it is shared with see the new name. Only its owner can rename a Space",
"after_help": "Examples:\n cua spaces rename local:studio design-review\n cua spaces rename relay:space-0123456789abcdef ci-runner",
diff --git a/scripts/docs-generators/cua-cli.ts b/scripts/docs-generators/cua-cli.ts
index 9be60fdc0e..36cb03eb3c 100644
--- a/scripts/docs-generators/cua-cli.ts
+++ b/scripts/docs-generators/cua-cli.ts
@@ -103,7 +103,7 @@ export const CLI_GROUPS: CliGroup[] = [
slug: 'computers-and-teams',
title: 'Computers and teams',
summary: 'Your computers, unattended access on this computer, teams and your remote use this month',
- commands: ['machines', 'host', 'devices', 'team', 'usage'],
+ commands: ['host', 'devices', 'team', 'usage'],
},
{
slug: 'sharing-and-networks',
diff --git a/scripts/docs-generators/cua-sdk.ts b/scripts/docs-generators/cua-sdk.ts
index 2d373f2b7f..14b26a0584 100644
--- a/scripts/docs-generators/cua-sdk.ts
+++ b/scripts/docs-generators/cua-sdk.ts
@@ -605,9 +605,9 @@ export const PAGES: PageSpec[] = [
title: 'Relay registration',
description: 'Register a Space with the relay so other devices reach it, and unregister it.',
intro:
- '`Spaces.relay_register` makes a Space reachable from your other devices through the relay; `Spaces.relay_unregister` stops that.',
+ '`Spaces.relay_register` makes a Space reachable from your other devices through the relay; `Spaces.relay_unregister` stops that. `Spaces.relay_unregister_computer` takes one of your computers off the relay: its Spaces stay on it, detached, unless `delete_spaces` deletes them first.',
items: ['SpaceRelayRegistration'],
- members: [{ object: 'Spaces', title: 'Relay registration', methods: ['relay_register', 'relay_unregister'] }],
+ members: [{ object: 'Spaces', title: 'Relay registration', methods: ['relay_register', 'relay_unregister', 'relay_unregister_computer'] }],
},
{
slug: 'spaces/elastic',
@@ -916,6 +916,15 @@ export const PAGES: PageSpec[] = [
'`auth.devices(relay_url, name)` returns this device on the relay, its key in the session\'s credential store (shared with the `cua` CLI and daemon). A device lists and reaches the account\'s machines once enrolled: right after a fresh sign-in (a sign-in through `Auth.begin_login` re-registers a device that already has a key), or by a one-time code approved from an enrolled device (`cua devices approve`). A new key of the same machine replaces its old record. Enrollment lasts 30 days, then one approval or a fresh sign-in re-verifies it. Nothing here prompts; gate `approve` behind presence in your UI.',
items: ['Devices', 'DevicesSnapshot', 'RelayDevice', 'RelayAuditEvent', 'DeviceEnrollment'],
},
+ {
+ slug: 'spaces/default-space',
+ title: 'Default Space',
+ description: "The account's default Space, the order to try when it is offline, and where a new task runs now.",
+ intro:
+ 'The relay keeps one default Space per account: where a new task runs unless you pick another. `Devices.spaces_settings` reads it, `set_spaces_settings` replaces it, and `resolve_default_space` says where a task goes now: the default when it is online, else the next online computer in `fallback` (while `fallback_on`), else this computer. A new computer is never made. `cua spaces default` is the same from the CLI.',
+ members: [{ object: 'Devices', title: 'Default Space', methods: ['spaces_settings', 'set_spaces_settings', 'resolve_default_space'] }],
+ items: ['SpacesSettings', 'DefaultSpace', 'DefaultSpaceStep'],
+ },
{
slug: 'spaces/machine-health',
title: 'Computer health',