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): real Teams screen, api.cua.ai and app.cua.ai (0.8.1) (#5113)

Francesco Bonacci8c02482e3d10
diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.ts
index 09a09ee18b..c18208bb7d 100644
--- a/apps/cua-spaces-desktop/src/bridge/settings.ts
+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts
@@ -44,6 +44,8 @@ export function settingsPage(model: AppModel, parts: HostParts) {
agents: coding.rows ?? undefined,
agentsBusy: coding.busy,
agentsPending: coding.pending,
+ // Teams from the Spaces API (read by `settings.get`).
+ teams: model.teams.input(),
// No Cua Cloud billing in the apps (the row stays hidden).
billing: undefined,
loginItem:
@@ -112,6 +114,8 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
const load = async () => {
parts().loginItem.read();
if (!model.servicesIn) return;
+ // Teams: the account's organizations (a failure shows in its row).
+ await bounded(10, () => model.teams.reload());
if (model.agents.coding.rows === null) await bounded(10, () => model.agents.coding.reload());
const [lume, linux] = await Promise.all([bounded(5, () => model.backend.lumeSource()), bounded(5, () => model.backend.linuxSource())]);
if (lume !== null) model.lumeSource = lume;
@@ -121,6 +125,10 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
/** A choice row changed (`AppModel.choose`). */
const choose = async (row: string, option: string): Promise<void> => {
switch (row) {
+ case "team-current":
+ // Settings, Teams: the team to work in (saved; the option is its id).
+ save({ currentTeamId: option });
+ return;
case "notch":
// "Spaces tab in the notch" (shown) or the menu bar only (hide); the notch follows `settings.changed`.
save({ menuBar: option === "hide" });
diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.ts
index cd1cb92d02..cbab4b8ccb 100644
--- a/apps/cua-spaces-desktop/src/model/app-model.ts
+++ b/apps/cua-spaces-desktop/src/model/app-model.ts
@@ -37,6 +37,7 @@ import { AgentsModel, type AgentSetupRunning, type ToolRunner } from "./agents";
import { ChecklistModel } from "./checklist";
import type { CloudModel } from "./cloud";
import type { DevicesModel } from "./devices";
+import { TeamsModel } from "./teams";
import { NotchActivity } from "./activity";
import { daemonAnswered, isCancelled, words } from "./errors";
import type { HostModel } from "./host";
@@ -96,6 +97,8 @@ export class AppModel {
readonly startup: StartupModel;
readonly host: HostModel;
readonly devices: DevicesModel;
+ /** Settings, Teams: the account's organizations from the Spaces API. */
+ readonly teams: TeamsModel;
readonly cloud: CloudModel;
readonly account: AccountRunning | null;
readonly telemetry: TelemetryRunning | null;
@@ -183,6 +186,13 @@ export class AppModel {
this.startup = d.startup;
this.host = d.host;
this.devices = d.devices;
+ this.teams = new TeamsModel({
+ native: d.native as unknown as ConstructorParameters<typeof TeamsModel>[0]["native"],
+ account: () => this.account,
+ identity: () => this.identity,
+ currentTeamId: () => this.settings.currentTeamId,
+ });
+ this.teams.onChange = () => this.changed("settings");
this.cloud = d.cloud;
this.account = d.account;
this.telemetry = d.telemetry;
@@ -798,6 +808,7 @@ export class AppModel {
this.identity = who ?? this.account.identity();
this.host.identity = this.identity;
this.devices.signedIn = this.identity !== null;
+ this.teams.reset();
this.signInUrl = null;
this.setSignIn(new this.native.AppSignInPhase.Idle());
// Relay sharing paused while signed out comes back for its owner.
@@ -846,6 +857,7 @@ export class AppModel {
this.identity = null;
this.host.identity = null;
this.devices.signedIn = false;
+ this.teams.reset();
// Signed out: relay sharing stops (the setup stays to resume).
await this.host.reconcileAccount();
await this.devices.refresh();
diff --git a/apps/cua-spaces-desktop/src/model/teams.ts b/apps/cua-spaces-desktop/src/model/teams.ts
new file mode 100644
index 0000000000..aab164a611
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/model/teams.ts
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Settings, Teams: the account's organizations from the Spaces API
+// (api.cua.ai; api.staging.cua.ai under CUA_ENV=staging) through the app
+// export's `appTeams`, with the account's token: each team with its members
+// and pending invites. The app administers nothing; invites, roles and
+// billing are the account app's (app.cua.ai, `appAccountAppUrl`). The words
+// are the core's (`teams::rows`, in the Settings page).
+import type { AppTeamsInput, AppTeamsState } from "../native/generated/index";
+import { words } from "./errors";
+import type { AccountRunning } from "./services";
+
+/** What the model hands over: the native export, the account and who is signed in. */
+export interface TeamsDeps {
+ native: {
+ appTeams(token: string): Promise<AppTeamsInput>;
+ appAccountAppUrl(): string;
+ AppTeamsState: {
+ SignedOut: new () => AppTeamsState;
+ Loading: new () => AppTeamsState;
+ Failed: new (v: { message: string }) => AppTeamsState;
+ };
+ };
+ account: () => AccountRunning | null;
+ identity: () => string | null;
+ /** The saved current team (`AppSettings.currentTeamId`). */
+ currentTeamId?: () => string | undefined;
+}
+
+/** A read this recent is not repeated by opening Settings again. */
+export const TEAMS_FRESH_MS = 30_000;
+
+export class TeamsModel {
+ /** Where Teams stand (`undefined`: nothing read for this account yet). */
+ private state: AppTeamsState | undefined;
+ private readAt = 0;
+ private generation = 0;
+ onChange: () => void = () => {};
+
+ constructor(private readonly deps: TeamsDeps, private readonly now: () => number = Date.now) {}
+
+ /** Settings' Teams input: the read, or "loading" / "signed out" before it. */
+ input(): AppTeamsInput {
+ const { native } = this.deps;
+ const signedOut = this.deps.identity() === null;
+ const state = signedOut ? new native.AppTeamsState.SignedOut() : (this.state ?? new native.AppTeamsState.Loading());
+ return { accountAppUrl: native.appAccountAppUrl(), state, currentTeamId: this.deps.currentTeamId?.() };
+ }
+
+ /** The account changed (signed in, out, or another one): forget the last read. */
+ reset(): void {
+ this.generation += 1;
+ this.state = undefined;
+ this.readAt = 0;
+ }
+
+ /** Reads the teams (at most every 30 s unless `force`). A failure says so in the row. */
+ async reload(force = false): Promise<void> {
+ const { native } = this.deps;
+ const account = this.deps.account();
+ if (!account || this.deps.identity() === null) {
+ this.reset();
+ return;
+ }
+ if (!force && this.state && this.now() - this.readAt < TEAMS_FRESH_MS) return;
+ const generation = this.generation;
+ try {
+ const token = await account.accessToken(false);
+ if (!token) throw new Error("Sign in to see your teams");
+ const read = await native.appTeams(token);
+ if (generation !== this.generation) return;
+ this.state = read.state;
+ } catch (error) {
+ if (generation !== this.generation) return;
+ this.state = new native.AppTeamsState.Failed({ message: words(error) });
+ }
+ this.readAt = this.now();
+ this.onChange();
+ }
+}
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
index e476cc9db0..024a6821d1 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
@@ -412,6 +412,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_spaces_ffi_fn_func_app_account_app_url": {
+ args: [],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_spaces_ffi_fn_func_app_agent_key_form": {
args: [FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.RustBuffer,
@@ -1502,6 +1507,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_spaces_ffi_fn_func_app_teams": {
+ args: [FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_spaces_ffi_fn_func_app_telemetry_creates": {
args: [FfiType.RustBuffer, FfiType.RustBuffer, FfiType.Int64],
ret: FfiType.RustBuffer,
@@ -2092,6 +2102,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_spaces_ffi_checksum_func_app_account_app_url": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form": {
args: [],
ret: FfiType.UInt16,
@@ -3182,6 +3197,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_spaces_ffi_checksum_func_app_teams": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_spaces_ffi_checksum_func_app_telemetry_creates": {
args: [],
ret: FfiType.UInt16,
@@ -3948,6 +3968,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_fn_func_app_about_refresh_notice(report: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_about_restart_daemon(check: Uint8Array, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_spaces_ffi_fn_func_app_about_view(input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_account_app_url(uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_agent_key_form(input: Uint8Array, form: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_agent_key_form_input_from_json(json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_agent_key_name_problem(name: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -4166,6 +4187,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_fn_func_app_stream_pip_click(open: Uint8Array, row: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_stream_pip_reduce(open: Uint8Array, event: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_stream_section(input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_teams(accountToken: Uint8Array): bigint;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_creates(state: Uint8Array, action: Uint8Array, nowMs: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_enroll(state: Uint8Array, action: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_experiments_changed(before: Uint8Array, after: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -4284,6 +4306,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_checksum_func_app_about_refresh_notice(): number;
uniffi_cua_spaces_ffi_checksum_func_app_about_restart_daemon(): number;
uniffi_cua_spaces_ffi_checksum_func_app_about_view(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_account_app_url(): number;
uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form(): number;
uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form_input_from_json(): number;
uniffi_cua_spaces_ffi_checksum_func_app_agent_key_name_problem(): number;
@@ -4502,6 +4525,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_checksum_func_app_stream_pip_click(): number;
uniffi_cua_spaces_ffi_checksum_func_app_stream_pip_reduce(): number;
uniffi_cua_spaces_ffi_checksum_func_app_stream_section(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_teams(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_creates(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_enroll(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_experiments_changed(): number;
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
index 5df36adf77..70b76dd4fb 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
@@ -142,6 +142,28 @@ export function appAboutView(input: AppAboutInput): AppAboutView {
));
}
+/**
+ * The account app for this environment (`CUA_ACCOUNT_APP_URL`, else
+ * `https://app.cua.ai`, or `https://app.staging.cua.ai` under
+ * `CUA_ENV=staging`): billing, plans and team administration, which the
+ * apps open in the browser.
+ */
+export function appAccountAppUrl(): string {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterString.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_account_app_url(
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
/**
* The add or replace sheet.
*/
@@ -4670,6 +4692,44 @@ export function appStreamSection(input: AppStreamSectionInput): AppStreamSection
));
}
+/**
+ * The account's Teams (the organizations of `GET /v1/me` on the Spaces
+ * API for this environment, `api.cua.ai` or `api.staging.cua.ai`), each
+ * with its members and pending invites, read with `account_token`.
+ * Both Spaces apps read Teams here; Settings words them
+ * (`app_settings_page`'s `teams`).
+ */
+export async function appTeams(accountToken: string, asyncOpts_?: { signal: AbortSignal }): Promise<AppTeamsInput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_teams(FfiConverterString.lower(accountToken, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_spaces_ffi_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_spaces_ffi_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:*/ FfiConverterTypeAppTeamsInput.lift.bind(FfiConverterTypeAppTeamsInput),
+ /*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 events one step of the Spaces being created means, at `now_ms`
* (call with the state before it).
@@ -27044,16 +27104,15 @@ export type AppOnboardingCopy = {
*/
openSettings: string,
/**
- * The Sign in page's Teams line ("Teams · coming soon").
+ * The Sign in page's Teams line ("Teams · manage them at app.cua.ai").
*/
teams: string,
/**
- * Its link ("Join the waitlist").
+ * Its link ("Open the account app").
*/
teamsLink: string,
/**
- * The link's URL: the website's Teams waitlist (the app collects
- * nothing).
+ * The link's URL: the account app, which administers teams.
*/
teamsUrl: string
}
@@ -32289,7 +32348,11 @@ export type AppSettings = {
* is opened (on by default); off, it waits for Connect
* ([`crate::spaces::cover`]).
*/
- autoConnect: boolean
+ autoConnect: boolean,
+ /**
+ * Settings, Teams: the team (organization id) the account works in.
+ */
+ currentTeamId?: string
}
/**
@@ -32327,7 +32390,8 @@ const FfiConverterTypeAppSettings = (() => {
dismissedAccess: FfiConverterSequenceString.read(from),
keyvaultSiteIcons: FfiConverterBool.read(from),
teleportChoices: FfiConverterSequenceTypeAppRememberedChoice.read(from),
- autoConnect: FfiConverterBool.read(from)
+ autoConnect: FfiConverterBool.read(from),
+ currentTeamId: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -32346,6 +32410,7 @@ const FfiConverterTypeAppSettings = (() => {
FfiConverterBool.write(value.keyvaultSiteIcons, into);
FfiConverterSequenceTypeAppRememberedChoice.write(value.teleportChoices, into);
FfiConverterBool.write(value.autoConnect, into);
+ FfiConverterOptionalString.write(value.currentTeamId, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.hotkey) +
@@ -32362,7 +32427,8 @@ const FfiConverterTypeAppSettings = (() => {
FfiConverterSequenceString.allocationSize(value.dismissedAccess) +
FfiConverterBool.allocationSize(value.keyvaultSiteIcons) +
FfiConverterSequenceTypeAppRememberedChoice.allocationSize(value.teleportChoices) +
- FfiConverterBool.allocationSize(value.autoConnect);
+ FfiConverterBool.allocationSize(value.autoConnect) +
+ FfiConverterOptionalString.allocationSize(value.currentTeamId);
}
};
@@ -32586,6 +32652,445 @@ const FfiConverterTypeAppSignInPhase = (() => {
return new FFIConverter();
})();
+export type AppTeamPersonInput = {
+ email: string,
+ /**
+ * `owner`, `admin` or `member`.
+ */
+ role: string
+}
+
+/**
+ * Generated factory for {@link AppTeamPersonInput} record objects.
+ */
+export const AppTeamPersonInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppTeamPersonInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppTeamPersonInput>,
+ });
+})();
+
+const FfiConverterTypeAppTeamPersonInput = (() => {
+ type TypeName = AppTeamPersonInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ email: FfiConverterString.read(from),
+ role: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.email, into);
+ FfiConverterString.write(value.role, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.email) +
+ FfiConverterString.allocationSize(value.role);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type AppTeamInput = {
+ id: string,
+ /**
+ * The org's slug.
+ */
+ alias: string,
+ /**
+ * Its display name (empty: use the alias).
+ */
+ name: string,
+ /**
+ * The account's role in it.
+ */
+ role: string,
+ /**
+ * `free`, `teams`, ...
+ */
+ plan: string,
+ /**
+ * Paid seats.
+ */
+ seats: bigint,
+ members: Array<AppTeamPersonInput>,
+ /**
+ * Pending invites' emails (only owners and admins can read them).
+ */
+ invites: Array<string>
+}
+
+/**
+ * Generated factory for {@link AppTeamInput} record objects.
+ */
+export const AppTeamInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppTeamInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppTeamInput>,
+ });
+})();
+
+const FfiConverterTypeAppTeamInput = (() => {
+ type TypeName = AppTeamInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ id: FfiConverterString.read(from),
+ alias: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ role: FfiConverterString.read(from),
+ plan: FfiConverterString.read(from),
+ seats: FfiConverterInt64.read(from),
+ members: FfiConverterSequenceTypeAppTeamPersonInput.read(from),
+ invites: FfiConverterSequenceString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.id, into);
+ FfiConverterString.write(value.alias, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.role, into);
+ FfiConverterString.write(value.plan, into);
+ FfiConverterInt64.write(value.seats, into);
+ FfiConverterSequenceTypeAppTeamPersonInput.write(value.members, into);
+ FfiConverterSequenceString.write(value.invites, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.id) +
+ FfiConverterString.allocationSize(value.alias) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.role) +
+ FfiConverterString.allocationSize(value.plan) +
+ FfiConverterInt64.allocationSize(value.seats) +
+ FfiConverterSequenceTypeAppTeamPersonInput.allocationSize(value.members) +
+ FfiConverterSequenceString.allocationSize(value.invites);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+
+// Enum: AppTeamsState
+export enum AppTeamsState_Tags {
+ SignedOut = "SignedOut",
+ Unread = "Unread",
+ Loading = "Loading",
+ Failed = "Failed",
+ Ready = "Ready"
+}
+export const AppTeamsState = (() => {
+
+ type SignedOut__interface = {
+ tag: AppTeamsState_Tags.SignedOut
+ };
+ /**
+ * Not signed in.
+ */
+ class SignedOut_ extends UniffiEnum implements SignedOut__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "AppTeamsState";
+ readonly tag = AppTeamsState_Tags.SignedOut;
+ constructor() {
+ super("AppTeamsState", "SignedOut");
+ }
+
+ static new(): SignedOut_ {
+ return new SignedOut_();
+ }
+
+ static instanceOf(obj: any): obj is SignedOut_ {
+ return obj.tag === AppTeamsState_Tags.SignedOut;
+ }
+
+ }
+
+ type Unread__interface = {
+ tag: AppTeamsState_Tags.Unread
+ };
+ /**
+ * Signed in, but this host does not read teams: only the links.
+ */
+ class Unread_ extends UniffiEnum implements Unread__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "AppTeamsState";
+ readonly tag = AppTeamsState_Tags.Unread;
+ constructor() {
+ super("AppTeamsState", "Unread");
+ }
+
+ static new(): Unread_ {
+ return new Unread_();
+ }
+
+ static instanceOf(obj: any): obj is Unread_ {
+ return obj.tag === AppTeamsState_Tags.Unread;
+ }
+
+ }
+
+ type Loading__interface = {
+ tag: AppTeamsState_Tags.Loading
+ };
+ /**
+ * Being read.
+ */
+ class Loading_ extends UniffiEnum implements Loading__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "AppTeamsState";
+ readonly tag = AppTeamsState_Tags.Loading;
+ constructor() {
+ super("AppTeamsState", "Loading");
+ }
+
+ static new(): Loading_ {
+ return new Loading_();
+ }
+
+ static instanceOf(obj: any): obj is Loading_ {
+ return obj.tag === AppTeamsState_Tags.Loading;
+ }
+
+ }
+
+ type Failed__interface = {
+ tag: AppTeamsState_Tags.Failed;
+ inner:
+Readonly<{message: string}>
+ };
+ /**
+ * The read failed.
+ */
+ class Failed_ extends UniffiEnum implements Failed__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "AppTeamsState";
+ readonly tag = AppTeamsState_Tags.Failed;
+ readonly inner:
+Readonly<{message: string}>;
+ constructor(
+inner: {message: string }) {
+ super("AppTeamsState", "Failed");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {message: string }): Failed_ {
+ return new Failed_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Failed_ {
+ return obj.tag === AppTeamsState_Tags.Failed;
+ }
+
+ }
+
+ type Ready__interface = {
+ tag: AppTeamsState_Tags.Ready;
+ inner:
+Readonly<{teams: Array<AppTeamInput>}>
+ };
+ /**
+ * The account's teams (maybe none).
+ */
+ class Ready_ extends UniffiEnum implements Ready__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "AppTeamsState";
+ readonly tag = AppTeamsState_Tags.Ready;
+ readonly inner:
+Readonly<{teams: Array<AppTeamInput>}>;
+ constructor(
+inner: {teams: Array<AppTeamInput> }) {
+ super("AppTeamsState", "Ready");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {teams: Array<AppTeamInput> }): Ready_ {
+ return new Ready_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Ready_ {
+ return obj.tag === AppTeamsState_Tags.Ready;
+ }
+
+ }
+
+ function instanceOf(obj: any): obj is AppTeamsState {
+ return obj[uniffiTypeNameSymbol] === "AppTeamsState";
+ }
+
+ return Object.freeze({
+ instanceOf,
+ SignedOut: SignedOut_,
+ Unread: Unread_,
+ Loading: Loading_,
+ Failed: Failed_,
+ Ready: Ready_
+ });
+
+})();
+export type AppTeamsState = InstanceType<
+ typeof AppTeamsState['SignedOut' | 'Unread' | 'Loading' | 'Failed' | 'Ready']
+>;
+
+// FfiConverter for enum AppTeamsState
+const FfiConverterTypeAppTeamsState = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = AppTeamsState;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return new AppTeamsState.SignedOut();
+ case 2: return new AppTeamsState.Unread();
+ case 3: return new AppTeamsState.Loading();
+ case 4: return new AppTeamsState.Failed({message: FfiConverterString.read(from) });
+ case 5: return new AppTeamsState.Ready({teams: FfiConverterSequenceTypeAppTeamInput.read(from) });
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value.tag) {
+ case AppTeamsState_Tags.SignedOut: {
+ ordinalConverter.write(1, into);
+ return;
+ }
+ case AppTeamsState_Tags.Unread: {
+ ordinalConverter.write(2, into);
+ return;
+ }
+ case AppTeamsState_Tags.Loading: {
+ ordinalConverter.write(3, into);
+ return;
+ }
+ case AppTeamsState_Tags.Failed: {
+ ordinalConverter.write(4, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.message, into);
+ return;
+ }
+ case AppTeamsState_Tags.Ready: {
+ ordinalConverter.write(5, into);
+ const inner = value.inner;
+ FfiConverterSequenceTypeAppTeamInput.write(inner.teams, into);
+ return;
+ }
+ default:
+ // Throwing from here means that AppTeamsState_Tags hasn't matched an ordinal.
+ throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ allocationSize(value: TypeName): number {
+ switch (value.tag) {
+ case AppTeamsState_Tags.SignedOut: {
+ return ordinalConverter.allocationSize(1);
+ }
+ case AppTeamsState_Tags.Unread: {
+ return ordinalConverter.allocationSize(2);
+ }
+ case AppTeamsState_Tags.Loading: {
+ return ordinalConverter.allocationSize(3);
+ }
+ case AppTeamsState_Tags.Failed: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(4);
+ size += FfiConverterString.allocationSize(inner.message);
+ return size;
+ }
+ case AppTeamsState_Tags.Ready: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(5);
+ size += FfiConverterSequenceTypeAppTeamInput.allocationSize(inner.teams);
+ return size;
+ }
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ }
+ return new FFIConverter();
+})();
+
+export type AppTeamsInput = {
+ /**
+ * The account app for this environment (`https://app.cua.ai`, or
+ * `https://app.staging.cua.ai` under `CUA_ENV=staging`).
+ */
+ accountAppUrl: string,
+ state: AppTeamsState,
+ /**
+ * The saved current team (`AppSettings::current_team_id`).
+ */
+ currentTeamId?: string
+}
+
+/**
+ * Generated factory for {@link AppTeamsInput} record objects.
+ */
+export const AppTeamsInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppTeamsInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppTeamsInput>,
+ });
+})();
+
+const FfiConverterTypeAppTeamsInput = (() => {
+ type TypeName = AppTeamsInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ accountAppUrl: FfiConverterString.read(from),
+ state: FfiConverterTypeAppTeamsState.read(from),
+ currentTeamId: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.accountAppUrl, into);
+ FfiConverterTypeAppTeamsState.write(value.state, into);
+ FfiConverterOptionalString.write(value.currentTeamId, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.accountAppUrl) +
+ FfiConverterTypeAppTeamsState.allocationSize(value.state) +
+ FfiConverterOptionalString.allocationSize(value.currentTeamId);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type AppSettingsInput = {
/**
* The signed-in account.
@@ -32632,6 +33137,12 @@ export type AppSettingsInput = {
* Agents with an action running.
*/
agentsPending: Array<string>,
+ /**
+ * Teams from the Spaces API (the host reads them), with the account
+ * app's URL. None: the Teams section shows the production account
+ * app's links only.
+ */
+ teams?: AppTeamsInput,
/**
* The account's Cua Cloud billing, once read (signed in).
*/
@@ -32713,6 +33224,7 @@ const FfiConverterTypeAppSettingsInput = (() => {
agents: FfiConverterOptionalSequenceTypeAppAgentSettingsRow.read(from),
agentsBusy: FfiConverterBool.read(from),
agentsPending: FfiConverterSequenceString.read(from),
+ teams: FfiConverterOptionalTypeAppTeamsInput.read(from),
billing: FfiConverterOptionalTypeAppBillingStatus.read(from),
loginItem: FfiConverterOptionalTypeAppLoginItemInput.read(from),
experiments: FfiConverterTypeAppExperiments.read(from),
@@ -32737,6 +33249,7 @@ const FfiConverterTypeAppSettingsInput = (() => {
FfiConverterOptionalSequenceTypeAppAgentSettingsRow.write(value.agents, into);
FfiConverterBool.write(value.agentsBusy, into);
FfiConverterSequenceString.write(value.agentsPending, into);
+ FfiConverterOptionalTypeAppTeamsInput.write(value.teams, into);
FfiConverterOptionalTypeAppBillingStatus.write(value.billing, into);
FfiConverterOptionalTypeAppLoginItemInput.write(value.loginItem, into);
FfiConverterTypeAppExperiments.write(value.experiments, into);
@@ -32760,6 +33273,7 @@ const FfiConverterTypeAppSettingsInput = (() => {
FfiConverterOptionalSequenceTypeAppAgentSettingsRow.allocationSize(value.agents) +
FfiConverterBool.allocationSize(value.agentsBusy) +
FfiConverterSequenceString.allocationSize(value.agentsPending) +
+ FfiConverterOptionalTypeAppTeamsInput.allocationSize(value.teams) +
FfiConverterOptionalTypeAppBillingStatus.allocationSize(value.billing) +
FfiConverterOptionalTypeAppLoginItemInput.allocationSize(value.loginItem) +
FfiConverterTypeAppExperiments.allocationSize(value.experiments) +
@@ -58649,6 +59163,15 @@ const FfiConverterSequenceTypeAppAgentSettingsRow = new FfiConverterArray(FfiCon
// FfiConverter for Array<AppAgentSettingsRow> | undefined
const FfiConverterOptionalSequenceTypeAppAgentSettingsRow = new FfiConverterOptional(FfiConverterSequenceTypeAppAgentSettingsRow);
+// FfiConverter for Array<AppTeamPersonInput>
+const FfiConverterSequenceTypeAppTeamPersonInput = new FfiConverterArray(FfiConverterTypeAppTeamPersonInput);
+
+// FfiConverter for Array<AppTeamInput>
+const FfiConverterSequenceTypeAppTeamInput = new FfiConverterArray(FfiConverterTypeAppTeamInput);
+
+// FfiConverter for AppTeamsInput | undefined
+const FfiConverterOptionalTypeAppTeamsInput = new FfiConverterOptional(FfiConverterTypeAppTeamsInput);
+
// FfiConverter for AppBillingStatus | undefined
const FfiConverterOptionalTypeAppBillingStatus = new FfiConverterOptional(FfiConverterTypeAppBillingStatus);
@@ -59007,6 +59530,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_about_view() !== 65075) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_about_view");
}
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_account_app_url() !== 9943) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_account_app_url");
+ }
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form() !== 42778) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form");
}
@@ -59661,6 +60187,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_stream_section() !== 40082) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_stream_section");
}
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_teams() !== 64616) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_teams");
+ }
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_telemetry_creates() !== 25911) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_telemetry_creates");
}
@@ -60357,6 +60886,10 @@ export default Object.freeze({
FfiConverterTypeAppSwitcherTheme,
FfiConverterTypeAppSystemNote,
FfiConverterTypeAppTabView,
+ FfiConverterTypeAppTeamInput,
+ FfiConverterTypeAppTeamPersonInput,
+ FfiConverterTypeAppTeamsInput,
+ FfiConverterTypeAppTeamsState,
FfiConverterTypeAppTelemetryInput,
FfiConverterTypeAppTelemetrySignal,
FfiConverterTypeAppTeleportCapability,
diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.ts
index 732f8504e9..10d9f5acbc 100644
--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts
+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts
@@ -476,14 +476,14 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
// MARK: Settings
- it("lays out General with the Teams waitlist, Welcome and What is collected, and the runtimes", async () => {
+ it("lays out General with Teams, Welcome and What is collected, and the runtimes", async () => {
const s = (await call("settings.get")) as {
page: { sections: { id: string; rows: { id: string }[] }[] };
updateChannel: unknown;
globalShortcut: unknown;
};
const rows = s.page.sections.flatMap((x) => x.rows.map((r) => r.id));
- expect(rows).toEqual(expect.arrayContaining(["account", "notch", "auto-connect", "welcome", "teams", "telemetry", "telemetry-note", "launch-at-login"]));
+ expect(rows).toEqual(expect.arrayContaining(["account", "notch", "auto-connect", "welcome", "teams", "teams-manage", "teams-billing", "telemetry", "telemetry-note", "launch-at-login"]));
expect(rows).toEqual(expect.arrayContaining(["macos-runtime", "linux-runtime"]));
expect(s.updateChannel).toBe("stable");
// Another app holds ⌘⇧Space: the page says so.
@@ -497,6 +497,8 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
expect(model.settings.menuBar).toBe(true);
await call("settings.choose", { row: "auto-connect", option: "off" });
expect(model.settings.autoConnect).toBe(false);
+ await call("settings.choose", { row: "team-current", option: "org-2" });
+ expect(model.settings.currentTeamId).toBe("org-2");
await call("settings.choose", { row: "default-location", option: "cloud" });
expect(model.settings.defaultLocation).toBe(native.AppLocation.Cloud);
await call("settings.choose", { row: "telemetry", option: "off" });
diff --git a/apps/cua-spaces-desktop/test/teams.test.ts b/apps/cua-spaces-desktop/test/teams.test.ts
new file mode 100644
index 0000000000..66a268f8cd
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/teams.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Settings, Teams: the Spaces API read through the app export's `appTeams`
+// with the account's token, kept per account, and a failure said in the row
+// rather than thrown.
+import { describe, expect, it, vi } from "vitest";
+import type { AppTeamsInput } from "../src/native/generated/index";
+import { TEAMS_FRESH_MS, TeamsModel, type TeamsDeps } from "../src/model/teams";
+
+/** The enum's variants as plain tagged objects (the real ones come from the addon). */
+const tagged = (tag: string) =>
+ class {
+ readonly tag = tag;
+ constructor(readonly inner?: unknown) {}
+ };
+
+const READ = {
+ accountAppUrl: "https://app.cua.ai",
+ state: { tag: "Ready", inner: { teams: [{ id: "o1", alias: "acme", name: "", role: "owner", plan: "teams", seats: 3, members: [], invites: ["[email protected]"] }] } },
+} as unknown as AppTeamsInput;
+
+function context(o: { signedIn?: boolean; fail?: string; current?: string } = {}) {
+ let clock = 1_000;
+ const accessToken = vi.fn(async () => "acct-token");
+ const appTeams = vi.fn(async (_token: string) => {
+ if (o.fail) throw new Error(o.fail);
+ return READ;
+ });
+ const deps = {
+ native: {
+ appTeams,
+ appAccountAppUrl: () => "https://app.cua.ai",
+ AppTeamsState: { SignedOut: tagged("SignedOut"), Loading: tagged("Loading"), Failed: tagged("Failed") },
+ },
+ account: () => ({ accessToken }),
+ identity: () => (o.signedIn === false ? null : "[email protected]"),
+ currentTeamId: () => o.current,
+ } as unknown as TeamsDeps;
+ const model = new TeamsModel(deps, () => clock);
+ const changed = vi.fn();
+ model.onChange = changed;
+ return { model, appTeams, accessToken, changed, advance: (ms: number) => (clock += ms) };
+}
+
+const tag = (m: TeamsModel) => (m.input().state as unknown as { tag: string }).tag;
+
+describe("Settings, Teams", () => {
+ it("reads the account's teams with its token and hands them to the core's page", async () => {
+ const { model, appTeams, changed } = context();
+ expect(tag(model)).toBe("Loading");
+ await model.reload();
+ expect(appTeams).toHaveBeenCalledWith("acct-token");
+ expect(model.input()).toMatchObject({ accountAppUrl: "https://app.cua.ai", state: { tag: "Ready" } });
+ expect(changed).toHaveBeenCalledTimes(1);
+ });
+
+ it("hands the saved current team to the core's page", async () => {
+ const { model } = context({ current: "o2" });
+ await model.reload();
+ expect(model.input()).toMatchObject({ currentTeamId: "o2" });
+ expect(context().model.input().currentTeamId).toBeUndefined();
+ });
+
+ it("does not read again within 30 s, unless forced", async () => {
+ const { model, appTeams, advance } = context();
+ await model.reload();
+ await model.reload();
+ expect(appTeams).toHaveBeenCalledTimes(1);
+ advance(TEAMS_FRESH_MS + 1);
+ await model.reload();
+ expect(appTeams).toHaveBeenCalledTimes(2);
+ await model.reload(true);
+ expect(appTeams).toHaveBeenCalledTimes(3);
+ });
+
+ it("reads nothing while signed out", async () => {
+ const { model, appTeams } = context({ signedIn: false });
+ await model.reload();
+ expect(appTeams).not.toHaveBeenCalled();
+ expect(tag(model)).toBe("SignedOut");
+ });
+
+ it("says a failed read in the row and keeps the app usable", async () => {
+ const { model } = context({ fail: "Spaces API: HTTP 503" });
+ await model.reload();
+ expect(model.input().state).toMatchObject({ tag: "Failed", inner: { message: expect.stringContaining("503") } });
+ });
+
+ it("forgets the last account's teams when the account changes", async () => {
+ const { model } = context();
+ await model.reload();
+ model.reset();
+ expect(tag(model)).toBe("Loading");
+ });
+});
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift
index 2498d1155b..0fa3bb5dfe 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift
@@ -124,6 +124,7 @@ public enum AppEnvironment {
// Fixtures (UI tests, captures) keep the classic UI
// unless they turn the New UI on.
appVersion: fixtures ? nil : info.version)
+ if fixtures { model.teamsReader = FixtureTeams() }
if !fixtures {
LiveLocalNetworkPermission().request()
// Signed out is nil (setup signs in first); anything else (no
@@ -139,6 +140,7 @@ public enum AppEnvironment {
}
onboarding.accountToken = token
model.host.accountToken = token
+ model.teamsReader = LiveTeams(token: token)
// The keychain check first (the bundled `cua`, without a prompt),
// then the daemon and the SDK, all off the main thread.
startup.keychain = bundledCua.map { BundledCuaKeychain(cua: $0) }
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index 3baeb7e08b..7b8e3d317b 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -124,6 +124,11 @@ public final class AppModel {
public private(set) var billingStatus: AppBillingStatus?
/// Cua Cloud billing (nil: no Billing row).
let billing: BillingRunning?
+ /// Reads the account's Teams from the Spaces API (nil: Settings shows
+ /// the account app's links only). Set by `AppEnvironment`.
+ public var teamsReader: TeamsReading?
+ /// Where Settings' Teams stand: not read yet, read, or failed.
+ public private(set) var teamsState: AppTeamsState = .signedOut
/// This app as a login item (nil: no Launch at login row).
let loginItem: LoginItemControlling?
/// What the system reports for it (nil until read).
@@ -1197,6 +1202,7 @@ public final class AppModel {
// Relay sharing paused while signed out comes back for its
// owner (another account is asked to set it up again).
await host.reconcileAccount()
+ await reloadTeams()
} catch {
guard signInAttempt == current, signIn != .idle else { return }
signInFailed(LiveSpacesBackend.words(error))
@@ -1229,6 +1235,7 @@ public final class AppModel {
host.identity = nil
onboarding.host.identity = nil
devices.signedIn = false
+ teamsState = .signedOut
// Signed out: relay sharing stops (the setup stays to resume).
await host.reconcileAccount()
await devices.refresh()
@@ -1242,6 +1249,7 @@ public final class AppModel {
identity: identity, apiKeyClient: nil, signIn: signIn, canSignOut: account != nil && identity != nil,
menuBar: settings.menuBar, defaultLocation: settings.defaultLocation, locationLockedBy: nil,
telemetry: telemetryInput, agents: agentRows, agentsBusy: agentsBusy, agentsPending: agentsPending,
+ teams: teamsSettingsInput,
billing: identity == nil ? nil : billingStatus, loginItem: loginItemInput,
experiments: settings.experiments, keyvaultAutoWipe: keyvault.autoWipe,
keyvaultUnlockPrompt: keyvault.unlockPromptShows,
@@ -1249,6 +1257,30 @@ public final class AppModel {
autoConnect: settings.autoConnect, lumeSource: lumeSource, linuxSource: linuxSource))
}
+ /// Teams for Settings: the account's organizations with their people
+ /// (the Spaces API), and the account app's address for this environment.
+ var teamsSettingsInput: AppTeamsInput {
+ AppTeamsInput(accountAppUrl: appAccountAppUrl(), state: identity == nil ? .signedOut : teamsState,
+ currentTeamId: settings.currentTeamId)
+ }
+
+ /// Reads the account's Teams (Settings, Teams). A failure says so in the
+ /// row; the account app's links stay.
+ func reloadTeams() async {
+ guard identity != nil, let teamsReader else {
+ teamsState = .signedOut
+ return
+ }
+ if case .ready = teamsState {} else { teamsState = .loading }
+ do {
+ let input = try await teamsReader.teams()
+ guard identity != nil else { return }
+ teamsState = input.state
+ } catch {
+ teamsState = .failed(message: LiveSpacesBackend.words(error))
+ }
+ }
+
/// Settings, General with Settings, Storage after General while the Cua
/// Volume experiment is on (the core's rule).
public var settingsPageWithStorage: AppSettingsPage {
@@ -1366,6 +1398,7 @@ public final class AppModel {
readLoginItem()
await storage.load()
await reloadBilling()
+ await reloadTeams()
await reloadAgents()
await keyvault.refresh()
}
@@ -1378,7 +1411,7 @@ public final class AppModel {
billingStatus = try? await billing.status()
}
- /// Opens a website page (Manage billing, Add credit, the Teams waitlist).
+ /// Opens a website page (Manage billing, Add credit, the account app's Teams page).
public func openBillingPage(_ raw: String) {
guard let url = URL(string: raw), url.scheme == "https" || url.scheme == "http" else { return }
BillingBrowser.open(url)
@@ -1402,6 +1435,10 @@ public final class AppModel {
/// A choice row changed.
public func choose(row: String, option: String) async {
switch row {
+ case "team-current":
+ // Settings, Teams: the team to work in (saved; the option is its id).
+ settings.currentTeamId = option
+ saveSettings()
case "notch":
settings.menuBar = option == "hide"
saveSettings()
@@ -1459,9 +1496,9 @@ public final class AppModel {
case "welcome": onboarding.restart()
case "launch-at-login-approve":
loginItem?.openSystemSettings()
- case "billing", "teams":
- // A website page: billing (hidden while the apps do not offer
- // Cua Cloud) or the Teams waitlist.
+ case "billing", "teams-manage", "teams-billing":
+ // The account app (app.cua.ai): invites, roles and plans for
+ // teams, billing.
if let url = settingsPage.sections.flatMap(\.rows).first(where: { $0.id == row })?.linkUrl {
openBillingPage(url)
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
index 13038fc796..371e43420d 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
@@ -291,12 +291,52 @@ public final class FixtureBilling: BillingRunning, @unchecked Sendable {
current = AppBillingStatus(
billingEnabled: enabled, card: nil,
credit: AppBillingCredit(balanceUsdCents: balanceCents),
- billingUrl: "https://run.cua.ai/billing")
+ billingUrl: "https://app.cua.ai/billing")
}
public func status() async throws -> AppBillingStatus { current }
}
+// MARK: - Teams
+
+/// The account's Teams from the Spaces API (api.cua.ai, api.staging.cua.ai
+/// under `CUA_ENV=staging`) through the app core: its organizations with
+/// their members and pending invites. The app administers nothing; invites,
+/// roles and billing are the account app's (app.cua.ai).
+public protocol TeamsReading: AnyObject, Sendable {
+ func teams() async throws -> AppTeamsInput
+}
+
+/// Reads Teams with the account's access token (`force`: refresh it).
+public final class LiveTeams: TeamsReading, @unchecked Sendable {
+ let token: @Sendable (Bool) async throws -> String?
+ public init(token: @escaping @Sendable (Bool) async throws -> String?) { self.token = token }
+
+ public func teams() async throws -> AppTeamsInput {
+ guard let token = try await token(false) else {
+ throw CuaError.Unauthenticated(message: "Sign in to see your teams")
+ }
+ return try await appTeams(accountToken: token)
+ }
+}
+
+/// A fixture account's team (captures, tests).
+public final class FixtureTeams: TeamsReading, @unchecked Sendable {
+ public var current: AppTeamsInput
+
+ public init(_ teams: [AppTeamInput]? = nil) {
+ current = AppTeamsInput(accountAppUrl: "https://app.cua.ai", state: .ready(teams: teams ?? [
+ AppTeamInput(
+ id: "o1", alias: "acme", name: "Acme Inc", role: "owner", plan: "teams", seats: 3,
+ members: [AppTeamPersonInput(email: "[email protected]", role: "owner"),
+ AppTeamPersonInput(email: "[email protected]", role: "member")],
+ invites: ["[email protected]"]),
+ ]), currentTeamId: nil)
+ }
+
+ public func teams() async throws -> AppTeamsInput { current }
+}
+
/// Opens the website billing page (Settings' Manage billing, a refused
/// cloud Space's Add credit). In debug builds `CUA_SPACES_BROWSER` names
/// another app to open it with (captures use their own window, never the
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift
index 90ae568d41..a2f0536387 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift
@@ -82,8 +82,8 @@ public struct OnboardingView: View {
.task { if !onboarding.state.driveChecked { await onboarding.checkDrive() } }
}
- /// The Sign in page's Teams line: the website's waitlist (the app
- /// collects nothing).
+ /// The Sign in page's Teams line: a link to the account app (app.cua.ai),
+ /// which administers teams.
@ViewBuilder private var teamsLine: some View {
let copy = onboarding.copy
HStack(spacing: 4) {
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-auto-connect-off.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-auto-connect-off.png
index fc3ba0debf..aa3e8af6e5 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-auto-connect-off.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-auto-connect-off.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png
index ff279a1872..cf08f99851 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-login-approval.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-login-approval.png
index 1839339ab5..6adacda6d1 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-login-approval.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-login-approval.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-storage.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-storage.png
index b7494b42dd..7f49ab5453 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-storage.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-storage.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings.png
index b10693a774..259475ab52 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
index be2ae231e3..74b9888042 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
@@ -409,7 +409,7 @@ struct ViewModelTests {
})
#expect(!model.settingsPageWithStorage.sections.map(\.id).contains("storage"))
model.chooseExperiment(row: "experiment:cua_volume", option: "on")
- #expect(model.settingsPageWithStorage.sections.map(\.id).prefix(3) == ["account", "general", "storage"])
+ #expect(model.settingsPageWithStorage.sections.map(\.id).prefix(4) == ["account", "teams", "general", "storage"])
#expect(appSettingsLoad(path: model.settingsPath).experiments.cuaVolume, "saved")
#expect(model.onboarding.state.experiments.cuaVolume)
let toggled = telemetry.recorded.compactMap { s -> String? in
@@ -472,7 +472,7 @@ struct ViewModelTests {
let model = makeModel(account: account, agents: agents)
await model.loadSettings()
let page = model.settingsPage
- #expect(page.sections.map(\.id) == ["account", "general", "runtimes", "privacy", "agents"])
+ #expect(page.sections.map(\.id) == ["account", "teams", "general", "runtimes", "privacy", "agents"])
// Settings, Runtimes: macOS VMs picks runtime.lume.
let runtime = page.sections.first { $0.id == "runtimes" }!.rows[0]
#expect(runtime.options.map(\.id) == ["auto", "builtin", "system"])
@@ -1308,29 +1308,41 @@ struct ViewModelTests {
#expect(notch.view.phase == .closed)
}
- /// Settings hides Cua Cloud billing and offers the Teams waitlist (the
- /// website); a cloud create refused for want of credit shows one line
- /// and no Add credit.
- @Test func billingIsHiddenAndTeamsOpensTheWaitlist() async throws {
+ /// Settings hides Cua Cloud billing and shows the real Teams section
+ /// (the Spaces API: name with alias fallback, members, pending invites
+ /// marked "(Invited)", the account app for invites and billing); a cloud
+ /// create refused for want of credit shows one line and no Add credit.
+ @Test func billingIsHiddenAndTeamsComeFromTheSpacesAPI() async throws {
var opened: [URL] = []
BillingBrowser.open = { opened.append($0) }
let model = makeModel(account: FixtureAccount(identity: "[email protected]"),
billing: FixtureBilling(balanceCents: 742))
+ model.teamsReader = FixtureTeams([
+ AppTeamInput(id: "o1", alias: "acme", name: "", role: "owner", plan: "teams", seats: 3,
+ members: [AppTeamPersonInput(email: "[email protected]", role: "owner"),
+ AppTeamPersonInput(email: "[email protected]", role: "member")],
+ invites: ["[email protected]"]),
+ ])
await model.loadSettings()
let rows = model.settingsPage.sections.flatMap(\.rows)
#expect(!rows.contains { $0.id == "billing" })
#expect(!rows.contains { $0.id == "default-location" })
- let teams = rows.first { $0.id == "teams" }
- #expect(teams?.value == "Coming soon" && teams?.button == "Join the waitlist")
- await model.press(row: "teams")
- #expect(opened.map(\.absoluteString) == ["https://cua.ai/teams"])
+ #expect(!rows.contains { $0.value == "Coming soon" || $0.button == "Join the waitlist" })
+ let team = model.settingsPage.sections.first { $0.id == "teams" }!.rows
+ #expect(team[0].label == "acme", "the alias stands in for a missing name")
+ #expect(team[0].value == "Owner \u{b7} Teams plan \u{b7} 3 seats")
+ #expect(team.first { $0.label == "[email protected]" }?.value == "(Invited)")
+ #expect(team.first { $0.label == "[email protected]" }?.value == "Member")
+ await model.press(row: "teams-manage")
+ await model.press(row: "teams-billing")
+ #expect(opened.map(\.absoluteString) == ["https://app.cua.ai/team", "https://app.cua.ai/billing"])
var creates = appCreatesReduce(state: AppCreatesState(pending: [], deleting: [], powering: []),
action: .start(id: "pending:1", name: "cloud", os: .linux, provider: .cloud,
now: 0, image: nil, kind: nil, hostArch: nil, gpu: false,
host: nil, hostName: nil))
creates = appCreatesReduce(state: creates, action: .fail(
- id: "pending:1", error: "You're out of Cua Cloud credit. Add credit at https://run.cua.ai/billing",
+ id: "pending:1", error: "You're out of Cua Cloud credit. Add credit at https://app.cua.ai/billing",
errorVariant: ""))
let space = appCreatesCompose(spaces: [], state: creates)[0]
#expect(space.detail == "You're out of Cua Cloud credit.")
diff --git a/apps/cua-spaces-web/src/__tests__/native-parity.test.tsx b/apps/cua-spaces-web/src/__tests__/native-parity.test.tsx
index 4d6d74f939..bf94fa0da4 100644
--- a/apps/cua-spaces-web/src/__tests__/native-parity.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/native-parity.test.tsx
@@ -83,20 +83,24 @@ describe.skipIf(!wasmBuilt)("as the SwiftUI app (real routes, wasm core)", () =>
it("General is the core's page: Teams, Welcome, the notch's words and the privacy line with its link", async () => {
const { router, calls } = await mount("/settings");
- const account = await waitFor(() => {
- const r = document.querySelector<HTMLElement>('[data-setting-row="teams"]');
- if (!r) throw new Error("no Teams row");
+ const teams = await waitFor(() => {
+ const r = document.querySelector<HTMLElement>('[data-setting-row="teams-manage"]');
+ if (!r) throw new Error("no Teams rows");
return r;
});
- expect(account.textContent).toContain("Coming soon");
- expect(within(account).getByText("Join the waitlist")).toBeTruthy();
+ // The real Teams section: no waitlist, and invites and billing are the account app's.
+ expect(document.body.textContent).not.toContain("Coming soon");
+ expect(document.body.textContent).not.toContain("waitlist");
+ expect(within(teams).getByText("Manage team")).toBeTruthy();
const note = document.querySelector<HTMLElement>('[data-setting-row="telemetry-note"]')!;
expect(note.textContent).toMatch(/^Features used, sandbox types, durations and error categories/);
expect(within(note).getByText("What is collected")).toBeTruthy();
expect(document.body.textContent).not.toContain("Crash reports and feature counts");
- // The Teams waitlist opens the website.
- fireEvent.click(within(account).getByText("Join the waitlist"));
- await waitFor(() => expect(calls.some(([op, a]) => op === "session.openExternal" && String((a as { url: string }).url).includes("cua.ai"))).toBe(true));
+ // Manage team opens the account app in the browser.
+ fireEvent.click(within(teams).getByText("Manage team"));
+ await waitFor(() =>
+ expect(calls.some(([op, a]) => op === "session.openExternal" && (a as { url: string }).url === "https://app.cua.ai/team")).toBe(true),
+ );
// Welcome's Show again starts the first run over (this UI's, off the Mac).
const welcome = document.querySelector<HTMLElement>('[data-setting-row="welcome"]')!;
fireEvent.click(within(welcome).getByText("Show again"));
diff --git a/apps/cua-spaces-web/src/bridge/onboarding.ts b/apps/cua-spaces-web/src/bridge/onboarding.ts
index 587a961ff6..53f40ee374 100644
--- a/apps/cua-spaces-web/src/bridge/onboarding.ts
+++ b/apps/cua-spaces-web/src/bridge/onboarding.ts
@@ -300,9 +300,9 @@ const FALLBACK_COPY: OnboardingCopy = {
signInWaiting: "Waiting for the browser…",
permissionsTitle: "Grant in System Settings",
openSettings: "Open Settings",
- teams: "Teams · coming soon",
- teamsLink: "Join the waitlist",
- teamsUrl: "https://cua.ai/teams",
+ teams: "Teams · manage them at app.cua.ai",
+ teamsLink: "Open the account app",
+ teamsUrl: "https://app.cua.ai/welcome",
};
const FALLBACK_IMAGES: SandboxImage[] = [
diff --git a/apps/cua-spaces-web/src/routes/settings/index.tsx b/apps/cua-spaces-web/src/routes/settings/index.tsx
index 539af4f087..4ad5eeb086 100644
--- a/apps/cua-spaces-web/src/routes/settings/index.tsx
+++ b/apps/cua-spaces-web/src/routes/settings/index.tsx
@@ -59,7 +59,7 @@ const APPEARANCE: { value: ThemePreference; label: React.ReactNode }[] = [
const fail = toastError;
/** Settings, General: the core's page as the SwiftUI app draws it when the
- * core is loaded (Account with Teams, General, Runtimes, Privacy, the
+ * core is loaded (Account, Teams, General, Runtimes, Privacy, the
* Keyvault, AI agents), with this UI's own rows (appearance, keyboard shortcuts);
* without the core, the same settings drawn by hand. */
function SettingsPage() {
@@ -75,6 +75,7 @@ function CoreGeneralPage({ page }: { page: CorePage }) {
const { preference, setPreference } = useTheme();
const section = (id: string): CoreSection | undefined => page.sections.find((x) => x.id === id);
const account = section("account");
+ const teams = section("teams");
const general = section("general");
const runtimes = section("runtimes");
const privacy = section("privacy");
@@ -107,7 +108,9 @@ function CoreGeneralPage({ page }: { page: CorePage }) {
return void signIn().catch(fail("Couldn't start sign-in"));
case "sign-in-code":
return cancelSignIn();
- case "teams":
+ // The account app (app.cua.ai): invites, roles and plans, billing.
+ case "teams-manage":
+ case "teams-billing":
case "billing":
return row.linkUrl ? void openExternal(row.linkUrl) : undefined;
case "welcome":
@@ -130,6 +133,12 @@ function CoreGeneralPage({ page }: { page: CorePage }) {
</SettingsGroup>
) : null}
+ {teams ? (
+ <SettingsGroup title={teams.title}>
+ {rows(teams)}
+ </SettingsGroup>
+ ) : null}
+
<SettingsGroup title={general?.title ?? "General"}>
<LaunchAtLoginRows />
{/* The notch is the macOS app's. */}
diff --git a/apps/cua-spaces/src/components/SettingsPanel.test.tsx b/apps/cua-spaces/src/components/SettingsPanel.test.tsx
index e892ebff60..6c265d1001 100644
--- a/apps/cua-spaces/src/components/SettingsPanel.test.tsx
+++ b/apps/cua-spaces/src/components/SettingsPanel.test.tsx
@@ -406,12 +406,12 @@ describe("SettingsPanel Privacy", () => {
expect(screen.getByTitle("Set by env DO_NOT_TRACK")).toBeInTheDocument();
});
- it("lists Account, General, Privacy, AI agents and Experiments in order, with Show again", async () => {
+ it("lists Account, Teams, General, Privacy, AI agents and Experiments in order, with Show again", async () => {
const onShowWelcome = vi.fn();
renderPanel({ telemetry: fakeTelemetry(), onShowWelcome });
await screen.findByText("Share anonymous usage data");
const titles = screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent);
- expect(titles).toEqual(["Account", "General", "Privacy", "AI agents", "Experiments"]);
+ expect(titles).toEqual(["Account", "Teams", "General", "Privacy", "AI agents", "Experiments"]);
await userEvent.click(screen.getByRole("button", { name: "Show again" }));
expect(onShowWelcome).toHaveBeenCalled();
});
@@ -449,7 +449,7 @@ describe("SettingsPanel Experiments", () => {
await user.click(experiments.getByRole("switch", { name: "Cua Volume" }));
expect(await screen.findByRole("region", { name: "Storage" })).toBeInTheDocument();
const titles = screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent);
- expect(titles.slice(0, 3)).toEqual(["Account", "General", "Storage"]);
+ expect(titles.slice(0, 4)).toEqual(["Account", "Teams", "General", "Storage"]);
expect(JSON.parse(window.localStorage.getItem("cua.settings.experiments") ?? "{}")).toMatchObject({
cuaVolume: true,
});
@@ -461,7 +461,7 @@ describe("SettingsPanel Experiments", () => {
});
describe("SettingsPanel billing and Teams", () => {
- it("hides Cua Cloud billing and opens the Teams waitlist", async () => {
+ it("hides Cua Cloud billing and opens the account app for Teams", async () => {
const auth = {
beginSignIn: vi.fn(),
signOut: vi.fn(),
@@ -480,11 +480,11 @@ describe("SettingsPanel billing and Teams", () => {
billingUrl: "https://run.cua.ai/billing",
}),
});
- expect(await screen.findByText("Coming soon")).toBeInTheDocument();
+ expect(await screen.findByRole("region", { name: "Teams" })).toBeInTheDocument();
expect(screen.queryByText("$7.42 credit left")).toBeNull();
expect(screen.queryByRole("button", { name: "Manage billing" })).toBeNull();
- await userEvent.click(screen.getByRole("button", { name: "Join the waitlist" }));
- expect(props.onOpenExternal).toHaveBeenCalledWith("https://cua.ai/teams");
+ await userEvent.click(screen.getByRole("button", { name: "Manage team" }));
+ expect(props.onOpenExternal).toHaveBeenCalledWith("https://app.cua.ai/team");
});
});
diff --git a/apps/cua-spaces/src/components/SettingsPanel.tsx b/apps/cua-spaces/src/components/SettingsPanel.tsx
index 24b30859e2..92acc660e4 100644
--- a/apps/cua-spaces/src/components/SettingsPanel.tsx
+++ b/apps/cua-spaces/src/components/SettingsPanel.tsx
@@ -426,6 +426,8 @@ export function SettingsPanel({
return;
case "billing":
case "teams":
+ case "teams-manage":
+ case "teams-billing":
if (row.linkUrl) onOpenExternal(row.linkUrl);
return;
}
diff --git a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx
index 1a77c9bf66..f4685dfb50 100644
--- a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx
+++ b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx
@@ -509,15 +509,15 @@ describe("MainWindow", () => {
expect(screen.getByRole("radiogroup", { name: "Spaces tab in the notch" })).toBeInTheDocument();
});
- it("Settings has no default-location choice and opens the Teams waitlist", async () => {
+ it("Settings has no default-location choice and opens the account app for Teams", async () => {
const openExternal = vi.fn(async () => {});
setup({ openExternal });
await screen.findByRole("option", { name: /aurora/ });
fireEvent.keyDown(window, { key: ",", metaKey: true });
await screen.findByRole("radiogroup", { name: "Spaces tab in the notch" });
expect(screen.queryByRole("radiogroup", { name: "New Spaces run on" })).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "Join the waitlist" }));
- expect(openExternal).toHaveBeenCalledWith("https://cua.ai/teams");
+ fireEvent.click(screen.getByRole("button", { name: "Manage team" }));
+ expect(openExternal).toHaveBeenCalledWith("https://app.cua.ai/team");
});
});
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index 0690381a39..08acbc8579 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -99,8 +99,7 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b
| [Keyvault screens](/cua-sdk/reference/spaces/app-core/keyvault-screens) | The Keyvault page, sidebar, the vault list (apps, sites and items with their locks), the unlock prompt and the approval prompt. *Cua Spaces app export.* |
| [Onboarding and settings](/cua-sdk/reference/spaces/app-core/onboarding-settings) | First-run onboarding, its card miniatures, the settings file and the hotkey label. *Cua Spaces app export.* |
| [About, updates and launch](/cua-sdk/reference/spaces/app-core/about) | The About window and its update channel, what the apps do once they launch (the bundled cua install), and the daemon and refresh reports they read. *Cua Spaces app export.* |
-| [Cua Cloud billing](/cua-sdk/reference/spaces/app-core/billing) | The Billing row in Settings and the out-of-credit notice on a refused cloud Space. *Cua Spaces app export.* |
-| [Relay usage](/cua-sdk/reference/spaces/app-core/relay) | The Relay usage row in Settings and the notice past the monthly relay allowance. *Cua Spaces app export.* |
+| [App core: billing, relay usage and Teams](/cua-sdk/reference/spaces/account-app-core) | The Billing and Relay usage rows in Settings, the out-of-credit and relay allowance notices, and the Teams section. *Cua Spaces app export.* |
| [This machine](/cua-sdk/reference/spaces/app-core/this-machine) | The This machine roster entry, its page and the host setup form. *Cua Spaces app export.* |
| [Window, menu bar and Settings](/cua-sdk/reference/spaces/app-core/window) | The window chrome, a Space's toolbar and sections, the menu bar menu and Settings. *Cua Spaces app export.* |
| [Devices](/cua-sdk/reference/spaces/app-core/devices) | Settings &gt; Devices: this device's enrollment, the account's devices, Recent Access, and the enroll and approval sheets. *Cua Spaces app export.* |
@@ -143,4 +142,4 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b
291 items, 385 methods. The [Types](/cua-sdk/reference/types) page lists them.
-The Cua Spaces app export adds 767 items and 38 methods.
+The Cua Spaces app export adds 773 items and 38 methods.
diff --git a/docs/content/docs/cua-sdk/reference/spaces/account-app-core.mdx b/docs/content/docs/cua-sdk/reference/spaces/account-app-core.mdx
new file mode 100644
index 0000000000..a0302c0907
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/account-app-core.mdx
@@ -0,0 +1,287 @@
+---
+title: "App core: billing, relay usage and Teams"
+description: "The Billing and Relay usage rows in Settings, the out-of-credit and relay allowance notices, and the Teams section."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs --namespace cua_spaces_ffi (UniFFI metadata of libcua_spaces_ffi)
+ Version: 0.4.1
+*/}
+
+import { Callout } from 'fumadocs-ui/components/callout';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<Callout title="Cua Spaces app export">
+These APIs are part of the Cua Spaces app export for building Spaces UIs. They are source-available under FSL-1.1-MIT and ship for Swift only (`import CuaSpacesFFI`); the Rust tab shows the `cua-spaces-ffi` crate they come from. The open source SDK packages for Python, TypeScript and Kotlin do not include them.
+</Callout>
+
+The apps take no payment details: the website handles credit and cards. `app_billing_status` turns `Fleet.billing_status` into the core's `AppBillingStatus`, which Settings shows as the credit left and "Manage billing" (the website billing page). A cloud Space that Fleet refuses for want of credit (`CuaError::CloudCreditExhausted`) shows `AppCreditNotice`: one line and "Add credit", which opens the same page. Local Spaces never depend on it. `app_relay_usage` reads the account's relay allowance this month from the relay (`GET /v1/usage`, as `cua usage` does); `app_relay_usage_view` derives the Settings row and, past the allowance, `AppRelayAllowanceNotice`: one line with Upgrade. Nothing stops at the limit. `app_teams` turns the account's `AppTeamsInput` into the Teams rows of Settings: the signed-in state, each team with its people and the role of each.
+
+## `AppCreditNotice` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `text` | `String` | | `OUT_OF_CREDIT`. |
+| `button` | `String` | | `ADD_CREDIT`. |
+| `url` | `String` | | The website billing page. |
+
+## `AppBillingCard` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `brand` | `String` | | `visa`, `mastercard`, ... |
+| `last4` | `String` | | Last four digits. |
+
+## `AppBillingCredit` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `balance_usd_cents` / `balanceUsdCents` | `i64` | | What is left, US cents. |
+
+## `AppBillingStatus` record
+
+Returned by [`app_billing_status`](#app_billing_status).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `billing_enabled` / `billingEnabled` | `bool` | | Billing is on for this account (off: Settings shows no Billing row). |
+| `card` | [`Option<AppBillingCard>`](#appbillingcard-record) | | The saved default card. |
+| `credit` | [`Option<AppBillingCredit>`](#appbillingcredit-record) | | The account's credit, when it has any. |
+| `billing_url` / `billingUrl` | `Option<String>` | | The website billing page (credit, cards, plans). |
+
+## `AppRelayAllowanceNotice` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `text` | `String` | | "You've used your free relay allowance for this month. ..." |
+| `upgrade` | `String` | | `UPGRADE`. |
+| `upgrade_url` / `upgradeUrl` | `Option<String>` | | What Upgrade opens; none: no Upgrade button. |
+| `dismiss` | `String` | | `DISMISS`. |
+| `dismiss_key` / `dismissKey` | `String` | | What a dismissal remembers: the month and the reasons. A new month, or another limit reached, shows the notice again. |
+
+## `AppRelayUsage` record
+
+Returned by [`app_relay_usage`](#app_relay_usage).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `metered` | `bool` | | The relay meters this account (false: no allowance applies). |
+| `period` | `String` | | The month counted (`2026-10`). |
+| `plan` | `String` | | `free`, `pro`, `team`, ... |
+| `team` | [`Option<AppRelayUsageTeam>`](#apprelayusageteam-record) | | The team whose allowance is pooled. |
+| `live_sessions` / `liveSessions` | `u32` | | Live sessions now. |
+| `live_sessions_limit` / `liveSessionsLimit` | `Option<u32>` | | Live sessions allowed at once (none: no limit). |
+| `hours_used` / `hoursUsed` | `f64` | | Relay hours used this month (the team's, when pooled). |
+| `hours_limit` / `hoursLimit` | `Option<f64>` | | Relay hours allowed this month (none: no limit). |
+| `my_hours_used` / `myHoursUsed` | `f64` | | This account's own relay hours this month. |
+| `soft_limit_reached` / `softLimitReached` | `bool` | | Past the allowance (sessions keep working). |
+| `reasons` | `Vec<String>` | | What is past it: `sessions` and/or `hours`. |
+| `upgrade_url` / `upgradeUrl` | `Option<String>` | | Where to get more (https only; see `checked`). |
+
+## `AppRelayUsageTeam` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `id` | `String` | | Team id. |
+| `seats` | `u32` | | Seats sharing the allowance. |
+
+## `AppRelayUsageView` record
+
+Returned by [`app_relay_usage_view`](#app_relay_usage_view).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `label` | `String` | | `ROW_LABEL`. |
+| `line` | `String` | | "Live sessions 1 of 2 · Relay hours 6.5 of 20 this month", then the team pool when there is one. |
+| `plan` | `String` | | "Free plan" (empty when the relay names none). |
+| `notice` | [`Option<AppRelayAllowanceNotice>`](#apprelayallowancenotice-record) | | Past the allowance. |
+
+## `AppTeamInput` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `id` | `String` | | |
+| `alias` | `String` | | The org's slug. |
+| `name` | `String` | | Its display name (empty: use the alias). |
+| `role` | `String` | | The account's role in it. |
+| `plan` | `String` | | `free`, `teams`, ... |
+| `seats` | `i64` | | Paid seats. |
+| `members` | [`Vec<AppTeamPersonInput>`](#appteampersoninput-record) | | |
+| `invites` | `Vec<String>` | | Pending invites' emails (only owners and admins can read them). |
+
+## `AppTeamPersonInput` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `email` | `String` | | |
+| `role` | `String` | | `owner`, `admin` or `member`. |
+
+## `AppTeamsInput` record
+
+Returned by [`app_teams`](#app_teams).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `account_app_url` / `accountAppUrl` | `String` | | The account app for this environment (`https://app.cua.ai`, or `https://app.staging.cua.ai` under `CUA_ENV=staging`). |
+| `state` | [`AppTeamsState`](#appteamsstate-enum) | | |
+| `current_team_id` / `currentTeamId` | `Option<String>` | | The saved current team (`AppSettings::current_team_id`). |
+
+## `AppTeamsState` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.signedOut
+.unread
+.loading
+.failed(message: String)
+.ready(teams: [AppTeamInput])
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+AppTeamsState::SignedOut
+AppTeamsState::Unread
+AppTeamsState::Loading
+AppTeamsState::Failed { message: String }
+AppTeamsState::Ready { teams: Vec<AppTeamInput> }
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `SignedOut` | Not signed in. |
+| `Unread` | Signed in, but this host does not read teams: only the links. |
+| `Loading` | Being read. |
+| `Failed` | The read failed. Fields: `message: String` |
+| `Ready` | The account's teams (maybe none). Fields: `teams: Vec<AppTeamInput>` |
+
+## `app_billing_status`
+
+The SDK's billing status as the app core takes it (Settings' Billing
+row).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appBillingStatus(status: FleetBillingStatus) -> AppBillingStatus
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_billing_status(status: FleetBillingStatus) -> AppBillingStatus
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `status` | [`FleetBillingStatus`](/cua-sdk/reference/fleet/images#fleetbillingstatus-record) | required |
+
+**Returns** [`AppBillingStatus`](#appbillingstatus-record)
+
+## `app_relay_usage`
+
+The account's relay allowance this month (`GET /v1/usage` on the relay
+`devices` uses, as `cua usage` reads it) with `account_token`; none
+from a relay that meters nothing. Both Spaces apps read it here.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appRelayUsage(devices: Devices, accountToken: String) async throws -> AppRelayUsage?
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn app_relay_usage(devices: Arc<Devices>, account_token: String) -> Result<Option<AppRelayUsage>, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `devices` | [`Devices`](/cua-sdk/reference/spaces/devices#devices) | required |
+| `account_token` | `String` | required |
+
+**Returns** [`Option<AppRelayUsage>`](#apprelayusage-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## `app_relay_usage_view`
+
+Settings' "Relay usage" row and the notice past the allowance; none
+when the relay meters nothing.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appRelayUsageView(usage: AppRelayUsage) -> AppRelayUsageView?
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_relay_usage_view(usage: AppRelayUsage) -> Option<AppRelayUsageView>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `usage` | [`AppRelayUsage`](#apprelayusage-record) | required |
+
+**Returns** [`Option<AppRelayUsageView>`](#apprelayusageview-record)
+
+## `app_teams`
+
+The account's Teams (the organizations of `GET /v1/me` on the Spaces
+API for this environment, `api.cua.ai` or `api.staging.cua.ai`), each
+with its members and pending invites, read with `account_token`.
+Both Spaces apps read Teams here; Settings words them
+(`app_settings_page`'s `teams`).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appTeams(accountToken: String) async throws -> AppTeamsInput
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn app_teams(account_token: String) -> Result<AppTeamsInput, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `account_token` | `String` | required |
+
+**Returns** [`AppTeamsInput`](#appteamsinput-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## All items
+
+16 items, across this page and its subpages, grouped by page (each item's section is on its page). Methods are listed on their object.
+
+**App core: billing, relay usage and Teams**: [`app_billing_status`](#app_billing_status), [`app_relay_usage`](#app_relay_usage), [`app_relay_usage_view`](#app_relay_usage_view), [`app_teams`](#app_teams), [`AppBillingCard`](#appbillingcard-record), [`AppBillingCredit`](#appbillingcredit-record), [`AppBillingStatus`](#appbillingstatus-record), [`AppCreditNotice`](#appcreditnotice-record), [`AppRelayAllowanceNotice`](#apprelayallowancenotice-record), [`AppRelayUsage`](#apprelayusage-record), [`AppRelayUsageTeam`](#apprelayusageteam-record), [`AppRelayUsageView`](#apprelayusageview-record), [`AppTeamInput`](#appteaminput-record), [`AppTeamPersonInput`](#appteampersoninput-record), [`AppTeamsInput`](#appteamsinput-record), [`AppTeamsState`](#appteamsstate-enum)
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/billing.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/billing.mdx
deleted file mode 100644
index b6b4fbae8f..0000000000
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/billing.mdx
+++ /dev/null
@@ -1,80 +0,0 @@
----
-title: "Cua Cloud billing"
-description: "The Billing row in Settings and the out-of-credit notice on a refused cloud Space."
----
-
-{/*
- AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
- Generated by: pnpm --dir docs docs:generate:cua-sdk
- Source: cua-bindgen docs --namespace cua_spaces_ffi (UniFFI metadata of libcua_spaces_ffi)
- Version: 0.4.1
-*/}
-
-import { Callout } from 'fumadocs-ui/components/callout';
-import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
-
-<Callout title="Cua Spaces app export">
-These APIs are part of the Cua Spaces app export for building Spaces UIs. They are source-available under FSL-1.1-MIT and ship for Swift only (`import CuaSpacesFFI`); the Rust tab shows the `cua-spaces-ffi` crate they come from. The open source SDK packages for Python, TypeScript and Kotlin do not include them.
-</Callout>
-
-The apps take no payment details: the website handles credit and cards. `app_billing_status` turns `Fleet.billing_status` into the core's `AppBillingStatus`, which Settings shows as the credit left and "Manage billing" (the website billing page). A cloud Space that Fleet refuses for want of credit (`CuaError::CloudCreditExhausted`) shows `AppCreditNotice`: one line and "Add credit", which opens the same page. Local Spaces never depend on it.
-
-## `AppCreditNotice` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `text` | `String` | | `OUT_OF_CREDIT`. |
-| `button` | `String` | | `ADD_CREDIT`. |
-| `url` | `String` | | The website billing page. |
-
-## `AppBillingCard` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `brand` | `String` | | `visa`, `mastercard`, ... |
-| `last4` | `String` | | Last four digits. |
-
-## `AppBillingCredit` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `balance_usd_cents` / `balanceUsdCents` | `i64` | | What is left, US cents. |
-
-## `AppBillingStatus` record
-
-Returned by [`app_billing_status`](#app_billing_status).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `billing_enabled` / `billingEnabled` | `bool` | | Billing is on for this account (off: Settings shows no Billing row). |
-| `card` | [`Option<AppBillingCard>`](#appbillingcard-record) | | The saved default card. |
-| `credit` | [`Option<AppBillingCredit>`](#appbillingcredit-record) | | The account's credit, when it has any. |
-| `billing_url` / `billingUrl` | `Option<String>` | | The website billing page (credit, cards, plans). |
-
-## `app_billing_status`
-
-The SDK's billing status as the app core takes it (Settings' Billing
-row).
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-func appBillingStatus(status: FleetBillingStatus) -> AppBillingStatus
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub fn app_billing_status(status: FleetBillingStatus) -> AppBillingStatus
-```
-
-</Tab>
-</Tabs>
-
-| Parameter | Type | Default |
-| --- | --- | --- |
-| `status` | [`FleetBillingStatus`](/cua-sdk/reference/fleet/images#fleetbillingstatus-record) | required |
-
-**Returns** [`AppBillingStatus`](#appbillingstatus-record)
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
index 92f06deaf2..8bdea7b54e 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
@@ -43,20 +43,46 @@ pub fn cua_spaces_register()
</Tab>
</Tabs>
+## `app_account_app_url`
+
+The account app for this environment (`CUA_ACCOUNT_APP_URL`, else
+`https://app.cua.ai`, or `https://app.staging.cua.ai` under
+`CUA_ENV=staging`): billing, plans and team administration, which the
+apps open in the browser.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appAccountAppUrl() -> String
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_account_app_url() -> String
+```
+
+</Tab>
+</Tabs>
+
+**Returns** `String`
+
## All items
-630 items, across this page and its subpages, grouped by page (each item's section is on its page). Methods are listed on their object.
+620 items, across this page and its subpages, grouped by page (each item's section is on its page). Methods are listed on their object.
**[About, updates and launch](/cua-sdk/reference/spaces/app-core/about)**: `app_about_after_launch`, `app_about_allowed_channels`, `app_about_input_from_json`, `app_about_refresh_notice`, `app_about_restart_daemon`, `app_about_view`, `app_daemon_check_from_json`, `app_launch_input_from_json`, `app_refresh_report_from_json`, `AppAboutInput`, `AppAboutLink`, `AppAboutLinkId`, `AppAboutUpdates`, `AppAboutView`, `AppCliInstaller`, `AppCliInstallPlan`, `AppCliInstallRequest`, `AppDaemonCheck`, `AppInstallMethod`, `AppLaunchInput`, `AppLaunchPlan`, `AppRefreshReport`, `AppUpdateChannel`
+**Spaces app core**: [`app_account_app_url`](#app_account_app_url), [`cua_spaces_register`](#cua_spaces_register)
+
**[Settings, Agents](/cua-sdk/reference/spaces/app-core/agent-keys)**: `app_agent_key_form`, `app_agent_key_form_input_from_json`, `app_agent_key_name_problem`, `app_agent_key_remove_confirm`, `app_agent_keys_input_from_json`, `app_agent_keys_view`, `app_agent_settings_rows`, `app_agent_setup_outcome`, `app_agent_setup_outcomes_from_json`, `app_agent_setup_status`, `app_agent_setup_statuses_from_json`, `app_agent_setup_summary`, `AppAgentKeyConfirm`, `AppAgentKeyFormInput`, `AppAgentKeyFormView`, `AppAgentKeyInput`, `AppAgentKeyRow`, `AppAgentKeysInput`, `AppAgentKeysView`, `AppAgentSettingsRow`, `AppAgentSetupOutcomeInput`, `AppAgentSetupStatus`, `AppAgentSetupSummary`
**[Spaces](/cua-sdk/reference/spaces/app-core/spaces)**: `app_agent_name`, `app_ambient_dots`, `app_group_windows_by_app`, `app_hosted_rows`, `app_roster_initial`, `app_roster_reduce`, `app_rows_to_spaces`, `app_sidebar`, `app_space_accepts_drop`, `app_space_detail`, `app_space_detail_for`, `app_space_detail_with`, `app_space_rows_from_json`, `app_spaces_from_json`, `app_status_line`, `app_this_machine_space`, `app_without_this_relay_machine`, `AppAgentStatus`, `AppAmbientDots`, `AppFactWarning`, `AppHostSummaryInput`, `AppNewSpaceOn`, `AppNotice`, `AppNoticeKind`, `AppOpenApp`, `AppOpenWindow`, `AppRemoteWindow`, `AppRemoteWindowGroup`, `AppRosterAction`, `AppRosterState`, `AppSidebarRow`, `AppSidebarSection`, `AppSidebarView`, `AppSpace`, `AppSpaceAgentRun`, `AppSpaceDetail`, `AppSpaceKind`, `AppSpaceOs`, `AppSpaceProgress`, `AppSpaceProvider`, `AppSpaceRow`, `AppSpaceSdkRef`, `AppSpaceStatus`, `AppThumbnailScene`, `AppWindowMode`
**[Devices](/cua-sdk/reference/spaces/app-core/devices)**: `app_approve_open`, `app_approve_reduce`, `app_approve_sheet_action_from_json`, `app_approve_view`, `app_confirm_presence`, `app_devices_clean_name`, `app_devices_input`, `app_devices_input_from_json`, `app_devices_view`, `app_enroll_action_from_json`, `app_enroll_initial`, `app_enroll_reduce`, `app_enroll_state_from_json`, `app_enroll_view`, `app_machine_access_notice`, `AppActivityRow`, `AppApprovalPrompt`, `AppApproveRequest`, `AppApproveSheetAction`, `AppApproveSheetState`, `AppApproveSheetView`, `AppAuditInput`, `AppBannerTone`, `AppDeviceAction`, `AppDeviceBanner`, `AppDeviceConfirm`, `AppDeviceInput`, `AppDeviceRow`, `AppDevicesInput`, `AppDevicesLabels`, `AppDevicesView`, `AppEnrollAction`, `AppEnrollmentKind`, `AppEnrollMethod`, `AppEnrollOption`, `AppEnrollPhase`, `AppEnrollState`, `AppEnrollView`, `AppMachineAccessNotice`, `AppMachineInput`, `AppThisDevice`, `AppUnconfirmedMachine`
-**[Cua Cloud billing](/cua-sdk/reference/spaces/app-core/billing)**: `app_billing_status`, `AppBillingCard`, `AppBillingCredit`, `AppBillingStatus`, `AppCreditNotice`
-
**[Teleport picker](/cua-sdk/reference/spaces/app-core/teleport)**: `app_catalog_entries_from_json`, `app_catalog_entry`, `app_picker_can_plan`, `app_picker_consent`, `app_picker_initial`, `app_picker_plan_sensitive`, `app_picker_primary`, `app_picker_progress`, `app_picker_reduce`, `app_picker_review`, `app_picker_sections`, `app_picker_sensitive_options`, `app_picker_status`, `AppCatalogEntry`, `AppEntrySection`, `AppPickerAction`, `AppPickerEvent`, `AppPickerPrimary`, `AppPickerState`, `AppPickerStep`, `AppPickerTab`
**[Window, menu bar and Settings](/cua-sdk/reference/spaces/app-core/window)**: `app_chrome_input_from_json`, `app_delete_failed_text`, `app_display_name`, `app_display_path`, `app_drop_sending_text`, `app_drop_sent_text`, `app_format_bytes`, `app_login_item_launch_plan`, `app_main_chrome`, `app_menu`, `app_menu_bar`, `app_menu_bar_with_keyvault`, `app_menu_input_from_json`, `app_openable_count`, `app_sent_file`, `app_sent_files_from_json`, `app_settings_input_from_json`, `app_settings_page`, `app_space_detail_copy`, `AppChromeInput`, `AppDeleteConfirm`, `AppDetailAction`, `AppDetailActionId`, `AppDetailCopy`, `AppFact`, `AppFactCopy`, `AppLoginItemInput`, `AppLoginItemPlan`, `AppLoginItemStatus`, `AppMainChrome`, `AppMenuInput`, `AppMenuItem`, `AppMenuItemId`, `AppSentFileInfo`, `AppSettingsInput`, `AppSettingsOption`, `AppSettingsPage`, `AppSettingsRow`, `AppSettingsRowKind`, `AppSettingsSection`, `AppSignInPhase`, `AppTelemetryInput`
@@ -81,8 +107,6 @@ pub fn cua_spaces_register()
**[Teleport picker grid](/cua-sdk/reference/spaces/app-core/teleport-grid)**: `app_picker_app_grid`, `app_picker_grid_primary`, `app_picker_grid_step`, `app_picker_grid_tabs`, `app_picker_remote_grid`, `app_picker_window_grid`, `AppPickerGrid`, `AppPickerGridPrimary`, `AppPickerGridTab`, `AppPickerGridTabItem`, `AppPickerTile`, `AppPickerTileIcon`, `AppPickerTileSection`, `AppPickerTileThumbnail`
-**[Relay usage](/cua-sdk/reference/spaces/app-core/relay)**: `app_relay_usage`, `app_relay_usage_view`, `AppRelayAllowanceNotice`, `AppRelayUsage`, `AppRelayUsageTeam`, `AppRelayUsageView`
-
**[Teleport review](/cua-sdk/reference/spaces/app-core/teleport-review)**: `app_review_remember`, `app_review_remember_key`, `app_review_remembered`, `AppConsentItem`, `AppConsentKind`, `AppInstallCuaPrompt`, `AppPlanStepView`, `AppRememberedChoice`, `AppReviewChoice`, `AppReviewDomain`, `AppReviewToggle`, `AppReviewView`, `AppSendSource`, `AppVaultSource`
**[Keyvault](/cua-sdk/reference/spaces/app-core/keyvault)**: `app_sensitive_group_sdk`, `AppSensitiveGroup`, `AppSensitiveOption`, `KeyvaultClient`, `KeyvaultOverview`, `kv_credential_form`, `kv_duration`, `kv_labels`, `kv_overview_from_json`, `kv_passphrase_check`, `kv_prune_dismissed`, `kv_recovery_key_text`, `kv_sharing_label`, `kv_signed_in_spaces`, `kv_space_access_key`, `kv_visible_sharing_label`, `KvAccessRequest`, `KvAuditEntry`, `KvCaller`, `KvCommand`, `KvCredentialForm`, `KvDelivery`, `KvDomainCount`, `KvFavicon`, `KvFormMode`, `KvGrant`, `KvInventory`, `KvItem`, `KvItemPolicy`, `KvLabels`, `KvMethod`, `KvOutcome`, `KvPassphraseCheck`, `KvPending`, `KvRule`, `KvRuleCaller`, `KvSelector`, `KvSigning`, `KvStatus`, `KvStrength`, `KvVerification`
@@ -101,6 +125,4 @@ pub fn cua_spaces_register()
**[Image catalog](/cua-sdk/reference/spaces/app-core/images)**: `AppImageDistro`, `AppImageFieldView`, `AppImageGroup`, `AppImageSizes`, `AppImageSuggestion`, `AppImageTier`, `AppPlatformSize`, `AppSandboxImage`, `AppSuggestionGroup`
-**Spaces app core**: [`cua_spaces_register`](#cua_spaces_register)
-
**[Keyvault screens](/cua-sdk/reference/spaces/app-core/keyvault-screens)**: `kv_approval_approve_command`, `kv_approval_deny_command`, `kv_approval_open`, `kv_approval_reduce`, `kv_approval_view`, `kv_delete_command`, `kv_delete_confirm`, `kv_list`, `kv_live_copy_spaces`, `kv_lock_command`, `kv_page`, `kv_sidebar`, `kv_unlock_command`, `kv_unlock_prompt`, `kv_unlock_prompt_always`, `kv_vault_prune`, `kv_vault_reduce`, `kv_vault_source`, `kv_vault_view`, `KvAccessKind`, `KvAccessRow`, `KvApprovalAction`, `KvApprovalRow`, `KvApprovalState`, `KvApprovalView`, `KvAppRow`, `KvCategory`, `KvCategoryRow`, `KvDecision`, `KvDecisionTone`, `KvDeleteConfirm`, `KvKind`, `KvListView`, `KvLock`, `KvPage`, `KvPendingRow`, `KvRecentRow`, `KvSelection`, `KvSidebar`, `KvSigningBadge`, `KvTone`, `KvTri`, `KvUnlockPrompt`, `KvVaultAction`, `KvVaultApp`, `KvVaultFiles`, `KvVaultRow`, `KvVaultSelection`, `KvVaultSite`, `KvVaultSource`, `KvVaultState`, `KvVaultView`
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json b/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json
index 58c590eb3b..e2bfdfd18e 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json
@@ -21,8 +21,6 @@
"keyvault-screens",
"onboarding-settings",
"about",
- "billing",
- "relay",
"this-machine",
"window",
"devices",
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx
index 80cc4e3baf..454d35a0e4 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx
@@ -192,9 +192,9 @@ Returned by [`app_onboarding_copy`](#app_onboarding_copy).
| `agents_driver_image` / `agentsDriverImage` | `String` | | The card's miniature, for accessibility. |
| `permissions_title` / `permissionsTitle` | `String` | | Over the permission rows (Done, after host setup). |
| `open_settings` / `openSettings` | `String` | | The permission rows' button. |
-| `teams` | `String` | | The Sign in page's Teams line ("Teams · coming soon"). |
-| `teams_link` / `teamsLink` | `String` | | Its link ("Join the waitlist"). |
-| `teams_url` / `teamsUrl` | `String` | | The link's URL: the website's Teams waitlist (the app collects nothing). |
+| `teams` | `String` | | The Sign in page's Teams line ("Teams · manage them at app.cua.ai"). |
+| `teams_link` / `teamsLink` | `String` | | Its link ("Open the account app"). |
+| `teams_url` / `teamsUrl` | `String` | | The link's URL: the account app, which administers teams. |
## `AppOnboardingState` record
@@ -337,6 +337,7 @@ Returned by [`app_settings_choose_experiment`](/cua-sdk/reference/spaces/app-cor
| `keyvault_site_icons` / `keyvaultSiteIcons` | `bool` | | Keyvault rows may load a site's icon from Google's favicon service when the source browser had none (Settings, Keyvault; on by default). Off, only icons read locally are shown. |
| `teleport_choices` / `teleportChoices` | [`Vec<AppRememberedChoice>`](/cua-sdk/reference/spaces/app-core/teleport-review#apprememberedchoice-record) | | The sites the user sent to each Space last time, per app (`crate.teleport.review.remember`): the review starts from them. |
| `auto_connect` / `autoConnect` | `bool` | | Settings, General: a running Space's desktop streams as soon as it is opened (on by default); off, it waits for Connect (`crate.spaces.cover`). |
+| `current_team_id` / `currentTeamId` | `Option<String>` | | Settings, Teams: the team (organization id) the account works in when it is in several (`crate.teams.current`); `None` or an id the account left: its first owned team. |
## `AppOnboardingAction` enum
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/relay.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/relay.mdx
deleted file mode 100644
index 0ee033aa51..0000000000
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/relay.mdx
+++ /dev/null
@@ -1,125 +0,0 @@
----
-title: "Relay usage"
-description: "The Relay usage row in Settings and the notice past the monthly relay allowance."
----
-
-{/*
- AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
- Generated by: pnpm --dir docs docs:generate:cua-sdk
- Source: cua-bindgen docs --namespace cua_spaces_ffi (UniFFI metadata of libcua_spaces_ffi)
- Version: 0.4.1
-*/}
-
-import { Callout } from 'fumadocs-ui/components/callout';
-import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
-
-<Callout title="Cua Spaces app export">
-These APIs are part of the Cua Spaces app export for building Spaces UIs. They are source-available under FSL-1.1-MIT and ship for Swift only (`import CuaSpacesFFI`); the Rust tab shows the `cua-spaces-ffi` crate they come from. The open source SDK packages for Python, TypeScript and Kotlin do not include them.
-</Callout>
-
-`app_relay_usage` reads the account's relay allowance this month from the relay (`GET /v1/usage`, as `cua usage` does) with the session's `Devices` and an account token. `app_relay_usage_view` derives the Settings row (`AppRelayUsageView`) and, past the allowance, `AppRelayAllowanceNotice`: one line with Upgrade, dismissed per month and reason. Nothing stops at the limit.
-
-## `AppRelayAllowanceNotice` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `text` | `String` | | "You've used your free relay allowance for this month. ..." |
-| `upgrade` | `String` | | `UPGRADE`. |
-| `upgrade_url` / `upgradeUrl` | `Option<String>` | | What Upgrade opens; none: no Upgrade button. |
-| `dismiss` | `String` | | `DISMISS`. |
-| `dismiss_key` / `dismissKey` | `String` | | What a dismissal remembers: the month and the reasons. A new month, or another limit reached, shows the notice again. |
-
-## `AppRelayUsage` record
-
-Returned by [`app_relay_usage`](#app_relay_usage).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `metered` | `bool` | | The relay meters this account (false: no allowance applies). |
-| `period` | `String` | | The month counted (`2026-10`). |
-| `plan` | `String` | | `free`, `pro`, `team`, ... |
-| `team` | [`Option<AppRelayUsageTeam>`](#apprelayusageteam-record) | | The team whose allowance is pooled. |
-| `live_sessions` / `liveSessions` | `u32` | | Live sessions now. |
-| `live_sessions_limit` / `liveSessionsLimit` | `Option<u32>` | | Live sessions allowed at once (none: no limit). |
-| `hours_used` / `hoursUsed` | `f64` | | Relay hours used this month (the team's, when pooled). |
-| `hours_limit` / `hoursLimit` | `Option<f64>` | | Relay hours allowed this month (none: no limit). |
-| `my_hours_used` / `myHoursUsed` | `f64` | | This account's own relay hours this month. |
-| `soft_limit_reached` / `softLimitReached` | `bool` | | Past the allowance (sessions keep working). |
-| `reasons` | `Vec<String>` | | What is past it: `sessions` and/or `hours`. |
-| `upgrade_url` / `upgradeUrl` | `Option<String>` | | Where to get more (https only; see `checked`). |
-
-## `AppRelayUsageTeam` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `id` | `String` | | Team id. |
-| `seats` | `u32` | | Seats sharing the allowance. |
-
-## `AppRelayUsageView` record
-
-Returned by [`app_relay_usage_view`](#app_relay_usage_view).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `label` | `String` | | `ROW_LABEL`. |
-| `line` | `String` | | "Live sessions 1 of 2 · Relay hours 6.5 of 20 this month", then the team pool when there is one. |
-| `plan` | `String` | | "Free plan" (empty when the relay names none). |
-| `notice` | [`Option<AppRelayAllowanceNotice>`](#apprelayallowancenotice-record) | | Past the allowance. |
-
-## `app_relay_usage`
-
-The account's relay allowance this month (`GET /v1/usage` on the relay
-`devices` uses, as `cua usage` reads it) with `account_token`; none
-from a relay that meters nothing. Both Spaces apps read it here.
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-func appRelayUsage(devices: Devices, accountToken: String) async throws -> AppRelayUsage?
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub async fn app_relay_usage(devices: Arc<Devices>, account_token: String) -> Result<Option<AppRelayUsage>, CuaError>
-```
-
-</Tab>
-</Tabs>
-
-| Parameter | Type | Default |
-| --- | --- | --- |
-| `devices` | [`Devices`](/cua-sdk/reference/spaces/devices#devices) | required |
-| `account_token` | `String` | required |
-
-**Returns** [`Option<AppRelayUsage>`](#apprelayusage-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
-
-## `app_relay_usage_view`
-
-Settings' "Relay usage" row and the notice past the allowance; none
-when the relay meters nothing.
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-func appRelayUsageView(usage: AppRelayUsage) -> AppRelayUsageView?
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub fn app_relay_usage_view(usage: AppRelayUsage) -> Option<AppRelayUsageView>
-```
-
-</Tab>
-</Tabs>
-
-| Parameter | Type | Default |
-| --- | --- | --- |
-| `usage` | [`AppRelayUsage`](#apprelayusage-record) | required |
-
-**Returns** [`Option<AppRelayUsageView>`](#apprelayusageview-record)
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/spaces.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/spaces.mdx
index 099012ae69..7ee617c056 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/spaces.mdx
@@ -584,7 +584,7 @@ Returned by [`app_space_detail`](#app_space_detail), [`app_space_detail_for`](#a
| `actions` | [`Vec<AppDetailAction>`](/cua-sdk/reference/spaces/app-core/window#appdetailaction-record) | | Toolbar buttons, in order (none for this machine). |
| `confirm` | [`AppDeleteConfirm`](/cua-sdk/reference/spaces/app-core/window#appdeleteconfirm-record) | | What Delete asks first. |
| `sections` | `Vec<String>` | | The sections under the facts, in order (Stream, Agents, Teleport). |
-| `credit_notice` / `creditNotice` | [`Option<AppCreditNotice>`](/cua-sdk/reference/spaces/app-core/billing#appcreditnotice-record) | | A cloud Space refused for want of credit: one line and "Add credit" (the website billing page). |
+| `credit_notice` / `creditNotice` | [`Option<AppCreditNotice>`](/cua-sdk/reference/spaces/account-app-core#appcreditnotice-record) | | A cloud Space refused for want of credit: one line and "Add credit" (the website billing page). |
| `power_error` / `powerError` | `Option<String>` | | Why turning it off or on failed, shown inline under the preview. |
| `access` | [`Option<AppMachineAccessNotice>`](/cua-sdk/reference/spaces/app-core/devices#appmachineaccessnotice-record) | | Signed in, but this device is not enrolled: a machine reached through the relay is listed with its Connect greyed out under this line and its one action (`detail_for`). |
| `desktop_note` / `desktopNote` | `Option<String>` | | One of your machines that does not share its desktop: the line shown in place of its desktop, Stream, Agents and Teleport (`desktop_note`). |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx
index b98209b970..5f447d1e82 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx
@@ -594,7 +594,8 @@ Returned by [`app_settings_input_from_json`](#app_settings_input_from_json).
| `agents` | [`Option<Vec<AppAgentSettingsRow>>`](/cua-sdk/reference/spaces/app-core/agent-keys#appagentsettingsrow-record) | | Coding agents (none while detecting). |
| `agents_busy` / `agentsBusy` | `bool` | | "Configure all" is running. |
| `agents_pending` / `agentsPending` | `Vec<String>` | | Agents with an action running. |
-| `billing` | [`Option<AppBillingStatus>`](/cua-sdk/reference/spaces/app-core/billing#appbillingstatus-record) | | The account's Cua Cloud billing, once read (signed in). |
+| `teams` | [`Option<AppTeamsInput>`](/cua-sdk/reference/spaces/account-app-core#appteamsinput-record) | | Teams from the Spaces API (the host reads them), with the account app's URL. None: the Teams section shows the production account app's links only. |
+| `billing` | [`Option<AppBillingStatus>`](/cua-sdk/reference/spaces/account-app-core#appbillingstatus-record) | | The account's Cua Cloud billing, once read (signed in). |
| `login_item` / `loginItem` | [`Option<AppLoginItemInput>`](#apploginiteminput-record) | | Launch at login, once the system was asked (none: no rows). |
| `experiments` | [`AppExperiments`](/cua-sdk/reference/spaces/app-core/experiments#appexperiments-record) | | Settings, Experiments (what the page mentions follows them). |
| `keyvault_auto_wipe` / `keyvaultAutoWipe` | `Option<bool>` | | The Keyvault's auto-wipe, once the broker told it (none: no Keyvault section). |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/meta.json b/docs/content/docs/cua-sdk/reference/spaces/meta.json
index 9065b3f025..104de1f93d 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/meta.json
+++ b/docs/content/docs/cua-sdk/reference/spaces/meta.json
@@ -17,6 +17,7 @@
"app-core",
"volume-app-core",
"agents-app-core",
+ "account-app-core",
"machines-app-core",
"app-checklist-palette",
"devices",
diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdx
index f6b271fa16..53358efa3f 100644
--- a/docs/content/docs/cua-sdk/reference/types.mdx
+++ b/docs/content/docs/cua-sdk/reference/types.mdx
@@ -50,7 +50,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f
292 items. Methods are listed on their object.
-The 767 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items), [Machines page](/cua-sdk/reference/spaces/machines-app-core), [Getting started and the command palette](/cua-sdk/reference/spaces/app-checklist-palette).
+The 773 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items), [App core: billing, relay usage and Teams](/cua-sdk/reference/spaces/account-app-core#all-items), [Machines page](/cua-sdk/reference/spaces/machines-app-core), [Getting started and the command palette](/cua-sdk/reference/spaces/app-checklist-palette).
| Item | Kind | Summary |
| --- | --- | --- |
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index 0f032f7109..d66267a3e9 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -40,7 +40,10 @@ use std::{
pub const DEFAULT_OIDC_ISSUER: &str = "https://auth.cua.ai/realms/cyclops-cs";
/// Public OAuth client of the cua CLI and apps (`CUA_OIDC_CLIENT_ID`).
pub const DEFAULT_CLIENT_ID: &str = "cua-cli";
-const DEFAULT_SCOPE: &str = "openid profile offline_access";
+/// `organization:*` lists every organization (team) the user belongs to in
+/// the token. Keycloak's plain `organization` scope leaves the claim empty
+/// once a user is in two or more, so the clients saw no team at all.
+const DEFAULT_SCOPE: &str = "openid profile offline_access organization:*";
const DEVICE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
/// Refresh this long before expiry.
const REFRESH_SKEW_SECS: i64 = 60;
@@ -2134,6 +2137,17 @@ impl Session {
#[cfg(test)]
mod tests {
+ #[test]
+ fn default_scope_asks_for_every_organization() {
+ let scopes: Vec<&str> = super::DEFAULT_SCOPE.split_whitespace().collect();
+ assert!(scopes.contains(&"organization:*"));
+ assert!(scopes.contains(&"offline_access"));
+ assert_eq!(
+ super::Oidc::new("https://i.example", "c").scope,
+ super::DEFAULT_SCOPE
+ );
+ }
+
use super::*;
/// A cargo test binary is ad-hoc signed, like every development build:
diff --git a/libs/cua/crates/cua-home/src/env.rs b/libs/cua/crates/cua-home/src/env.rs
index 9d6ad51fba..de74b1f88c 100644
--- a/libs/cua/crates/cua-home/src/env.rs
+++ b/libs/cua/crates/cua-home/src/env.rs
@@ -9,7 +9,8 @@
//! |---------------|-----------------------|------------------------------------------|---------------------------------------------|
//! | OIDC issuer | `CUA_OIDC_ISSUER` | `https://auth.cua.ai/realms/cyclops-cs` | `https://auth.staging.cua.ai/realms/cua-staging` |
//! | Relay | `CUA_RELAY_URL` | `https://relay.cua.ai` | `https://relay.staging.cua.ai` |
-//! | Spaces API | `CUA_SPACES_API_URL` | `https://api.spaces.cua.ai` | `https://api.staging.cua.ai` |
+//! | Spaces API | `CUA_SPACES_API_URL` | `https://api.cua.ai` | `https://api.staging.cua.ai` |
+//! | Account app | `CUA_ACCOUNT_APP_URL` | `https://app.cua.ai` | `https://app.staging.cua.ai` |
//! | Spaces site | `CUA_SPACES_SITE_URL` | `https://spaces.cua.ai` | `https://spaces.staging.cua.ai` |
//! | cua home | `CUA_HOME` | `~/.cua` | `~/.cua/envs/staging` |
//!
@@ -107,11 +108,20 @@ impl CuaEnv {
/// The default Spaces control plane (entitlements) API.
pub fn spaces_api_url(self) -> &'static str {
match self {
- Self::Prod => "https://api.spaces.cua.ai",
+ Self::Prod => "https://api.cua.ai",
Self::Staging => "https://api.staging.cua.ai",
}
}
+ /// The account app: billing, plans, team administration and invites
+ /// (the apps open it in the browser).
+ pub fn account_app_url(self) -> &'static str {
+ match self {
+ Self::Prod => "https://app.cua.ai",
+ Self::Staging => "https://app.staging.cua.ai",
+ }
+ }
+
/// The default Spaces site (pairing links are `<site>/add/<code>`).
pub fn spaces_site_url(self) -> &'static str {
match self {
@@ -152,6 +162,8 @@ pub struct Endpoints {
pub spaces_api_url: String,
/// `CUA_SPACES_SITE_URL`, else the environment's Spaces site.
pub spaces_site_url: String,
+ /// `CUA_ACCOUNT_APP_URL`, else the environment's account app.
+ pub account_app_url: String,
}
impl Endpoints {
@@ -175,6 +187,7 @@ impl Endpoints {
relay_url: setting("CUA_RELAY_URL", env.relay_url()),
spaces_api_url: setting("CUA_SPACES_API_URL", env.spaces_api_url()),
spaces_site_url: setting("CUA_SPACES_SITE_URL", env.spaces_site_url()),
+ account_app_url: setting("CUA_ACCOUNT_APP_URL", env.account_app_url()),
}
}
}
@@ -199,6 +212,12 @@ pub fn spaces_site_url() -> String {
Endpoints::current().spaces_site_url
}
+/// `CUA_ACCOUNT_APP_URL`, else the environment's account app
+/// (`https://app.cua.ai`, `https://app.staging.cua.ai`).
+pub fn account_app_url() -> String {
+ Endpoints::current().account_app_url
+}
+
/// The cua home a non-production environment uses when `CUA_HOME` is not
/// set: `None` for production or when `CUA_HOME` is set.
pub fn env_home() -> Option<PathBuf> {
@@ -256,7 +275,8 @@ mod tests {
assert_eq!(e.env, CuaEnv::Prod);
assert_eq!(e.oidc_issuer, "https://auth.cua.ai/realms/cyclops-cs");
assert_eq!(e.relay_url, "https://relay.cua.ai");
- assert_eq!(e.spaces_api_url, "https://api.spaces.cua.ai");
+ assert_eq!(e.spaces_api_url, "https://api.cua.ai");
+ assert_eq!(e.account_app_url, "https://app.cua.ai");
assert_eq!(e.spaces_site_url, "https://spaces.cua.ai");
assert_eq!(CuaEnv::Prod.keyring_service(), "run.cua.ai");
assert_eq!(CuaEnv::Prod.home_subdir(), None);
@@ -274,6 +294,7 @@ mod tests {
);
assert_eq!(e.relay_url, "https://relay.staging.cua.ai");
assert_eq!(e.spaces_api_url, "https://api.staging.cua.ai");
+ assert_eq!(e.account_app_url, "https://app.staging.cua.ai");
assert_eq!(e.spaces_site_url, "https://spaces.staging.cua.ai");
assert_eq!(CuaEnv::Staging.keyring_service(), "staging.run.cua.ai");
assert_eq!(CuaEnv::Staging.home_subdir(), Some("envs/staging"));
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index ba1560cce4..ed59d8370c 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -44,6 +44,7 @@ pub mod relay;
pub mod service;
#[cfg(test)]
mod setup_tests;
+pub mod spaces_api;
pub mod team;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
diff --git a/libs/cua/crates/cua-host/src/spaces_api.rs b/libs/cua/crates/cua-host/src/spaces_api.rs
new file mode 100644
index 0000000000..740e8dc84a
--- /dev/null
+++ b/libs/cua/crates/cua-host/src/spaces_api.rs
@@ -0,0 +1,429 @@
+//! The Spaces API (`https://api.cua.ai`, `https://api.staging.cua.ai`
+//! under `CUA_ENV=staging`): the account's identity and entitlements
+//! (`GET /v1/me`), its organizations (Teams) with members and pending
+//! invites, and pairing codes. Account, billing and team administration
+//! (invites, roles, plans, the Stripe portal) live in the account app
+//! (`https://app.cua.ai`); the apps only read the team and link out.
+//!
+//! The contract is trycua/cloud `src/services/spaces-control-plane`. The
+//! bearer is the account's access token (audience `cua-spaces-api`).
+
+use crate::{Error, Result};
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+/// One organization (a Team) the account belongs to, from `GET /v1/me`.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiOrg {
+ #[serde(default)]
+ pub id: String,
+ /// The org's slug (always set by the API; the apps' fallback name).
+ #[serde(default)]
+ pub alias: String,
+ /// The display name, when the org has one.
+ #[serde(default)]
+ pub name: String,
+ /// `owner`, `admin` or `member`.
+ #[serde(default)]
+ pub role: String,
+ /// `free`, `pro`, `teams`, ...
+ #[serde(default)]
+ pub plan: String,
+ #[serde(default)]
+ pub status: String,
+ #[serde(default)]
+ pub seats: i64,
+}
+
+/// `GET /v1/me`.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiMe {
+ #[serde(default)]
+ pub sub: String,
+ #[serde(default)]
+ pub email: String,
+ #[serde(default)]
+ pub orgs: Vec<ApiOrg>,
+ #[serde(default)]
+ pub entitlements: ApiEntitlements,
+}
+
+/// The parts of the entitlements the apps read. Unknown plans mean free
+/// and missing features mean not entitled.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiEntitlements {
+ #[serde(default)]
+ pub plan: String,
+ #[serde(default)]
+ pub status: String,
+ #[serde(default)]
+ pub warnings: Vec<String>,
+}
+
+/// A member of an org.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiMember {
+ #[serde(default)]
+ pub sub: String,
+ #[serde(default)]
+ pub email: String,
+ #[serde(default)]
+ pub role: String,
+}
+
+/// A pending invite.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiInvite {
+ #[serde(default)]
+ pub id: String,
+ #[serde(default)]
+ pub email: String,
+}
+
+/// A one-time pairing code (`POST /v1/pairing-codes`).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiPairing {
+ #[serde(default)]
+ pub id: String,
+ #[serde(default)]
+ pub code: String,
+ #[serde(default)]
+ pub expires_at: String,
+}
+
+/// One org with its people.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct TeamDetail {
+ pub org: ApiOrg,
+ pub members: Vec<ApiMember>,
+ /// Empty for plain members: only owners and admins may list invites.
+ pub invites: Vec<ApiInvite>,
+}
+
+/// The account's Teams: who it is, its plan, and every org it is in.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct TeamsSnapshot {
+ pub email: String,
+ pub plan: String,
+ pub teams: Vec<TeamDetail>,
+}
+
+/// A Spaces API client.
+#[derive(Clone)]
+pub struct SpacesApiClient {
+ base: String,
+ http: reqwest::Client,
+}
+
+fn http_error(status: u16, body: &str) -> Error {
+ let detail = serde_json::from_str::<serde_json::Value>(body)
+ .ok()
+ .and_then(|v| {
+ let e = v.get("error")?.as_str()?.to_string();
+ let d = v.get("detail").and_then(|d| d.as_str()).unwrap_or("");
+ Some(if d.is_empty() { e } else { format!("{e}: {d}") })
+ })
+ .unwrap_or_else(|| body.trim().chars().take(200).collect());
+ let msg = format!(
+ "Spaces API: HTTP {status}{}",
+ if detail.is_empty() {
+ String::new()
+ } else {
+ format!(" ({detail})")
+ }
+ );
+ match status {
+ 401 => Error::Unauthenticated(msg),
+ 403 => Error::PermissionDenied(msg),
+ 404 => Error::NotFound(msg),
+ 409 => Error::Conflict(msg),
+ _ => Error::Internal(msg),
+ }
+}
+
+impl SpacesApiClient {
+ /// A client for the API at `base` (`https://api.cua.ai`).
+ pub fn new(base: &str) -> Result<Self> {
+ let url = url::Url::parse(base.trim())
+ .map_err(|e| Error::InvalidArgument(format!("Spaces API URL {base:?}: {e}")))?;
+ let loopback = matches!(url.host_str(), Some("127.0.0.1" | "localhost"));
+ if url.scheme() != "https" && !loopback {
+ return Err(Error::InvalidArgument(format!(
+ "Spaces API URL {base:?}: use https"
+ )));
+ }
+ let http = reqwest::Client::builder()
+ .timeout(Duration::from_secs(15))
+ .build()
+ .map_err(|e| Error::Internal(e.to_string()))?;
+ Ok(Self {
+ base: base.trim().trim_end_matches('/').to_string(),
+ http,
+ })
+ }
+
+ /// The client for the current environment (`CUA_SPACES_API_URL`, else
+ /// api.cua.ai, or api.staging.cua.ai under `CUA_ENV=staging`).
+ pub fn current() -> Result<Self> {
+ Self::new(&cua_home::env::spaces_api_url())
+ }
+
+ async fn send<T: serde::de::DeserializeOwned>(
+ &self,
+ req: reqwest::RequestBuilder,
+ token: &str,
+ ) -> Result<T> {
+ let resp = req
+ .bearer_auth(token)
+ .send()
+ .await
+ .map_err(|e| Error::Internal(format!("Spaces API {}: {e}", self.base)))?;
+ let status = resp.status();
+ let body = resp
+ .text()
+ .await
+ .map_err(|e| Error::Internal(e.to_string()))?;
+ if !status.is_success() {
+ return Err(http_error(status.as_u16(), &body));
+ }
+ serde_json::from_str(if body.trim().is_empty() {
+ "null"
+ } else {
+ &body
+ })
+ .map_err(|e| Error::Internal(format!("bad Spaces API response: {e}")))
+ }
+
+ async fn get<T: serde::de::DeserializeOwned>(&self, path: &str, token: &str) -> Result<T> {
+ self.send(self.http.get(format!("{}{path}", self.base)), token)
+ .await
+ }
+
+ /// `GET /v1/me`: the account, its plan and its orgs.
+ pub async fn me(&self, token: &str) -> Result<ApiMe> {
+ self.get("/v1/me", token).await
+ }
+
+ /// `GET /v1/me/entitlements` (the raw answer).
+ pub async fn entitlements(&self, token: &str) -> Result<serde_json::Value> {
+ self.get("/v1/me/entitlements", token).await
+ }
+
+ /// `GET /v1/orgs/{org}/members`.
+ pub async fn members(&self, token: &str, org: &str) -> Result<Vec<ApiMember>> {
+ #[derive(Deserialize)]
+ struct R {
+ #[serde(default)]
+ members: Vec<ApiMember>,
+ }
+ Ok(self
+ .get::<R>(&format!("/v1/orgs/{org}/members"), token)
+ .await?
+ .members)
+ }
+
+ /// `GET /v1/orgs/{org}/invites` (owners and admins).
+ pub async fn invites(&self, token: &str, org: &str) -> Result<Vec<ApiInvite>> {
+ #[derive(Deserialize)]
+ struct R {
+ #[serde(default)]
+ invites: Vec<ApiInvite>,
+ }
+ Ok(self
+ .get::<R>(&format!("/v1/orgs/{org}/invites"), token)
+ .await?
+ .invites)
+ }
+
+ /// `POST /v1/pairing-codes`: a one-time code to enroll a machine, for
+ /// the account or (`org` set) for one of its teams.
+ pub async fn create_pairing(&self, token: &str, org: Option<&str>) -> Result<ApiPairing> {
+ let body = match org {
+ Some(o) => serde_json::json!({ "org": o }),
+ None => serde_json::json!({}),
+ };
+ self.send(
+ self.http
+ .post(format!("{}/v1/pairing-codes", self.base))
+ .json(&body),
+ token,
+ )
+ .await
+ }
+
+ /// The account's Teams: `/v1/me`, then each org's members and pending
+ /// invites. A plain member cannot list invites (403): they read as
+ /// none. An org whose people cannot be read keeps its row without them.
+ pub async fn teams(&self, token: &str) -> Result<TeamsSnapshot> {
+ let me = self.me(token).await?;
+ let mut teams = Vec::with_capacity(me.orgs.len());
+ for org in me.orgs.iter().cloned() {
+ let key = if org.alias.is_empty() {
+ org.id.clone()
+ } else {
+ org.alias.clone()
+ };
+ let members = match self.members(token, &key).await {
+ Ok(m) => m,
+ Err(e @ Error::Unauthenticated(_)) => return Err(e),
+ Err(e) => {
+ tracing::warn!("team {key}: members unavailable: {e}");
+ Vec::new()
+ }
+ };
+ let invites = match self.invites(token, &key).await {
+ Ok(i) => i,
+ Err(e @ Error::Unauthenticated(_)) => return Err(e),
+ Err(Error::PermissionDenied(_)) => Vec::new(),
+ Err(e) => {
+ tracing::warn!("team {key}: invites unavailable: {e}");
+ Vec::new()
+ }
+ };
+ teams.push(TeamDetail {
+ org,
+ members,
+ invites,
+ });
+ }
+ Ok(TeamsSnapshot {
+ email: me.email,
+ plan: me.entitlements.plan,
+ teams,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::{
+ Json, Router,
+ extract::Path,
+ http::{HeaderMap, StatusCode},
+ routing::{get, post},
+ };
+ use serde_json::{Value, json};
+
+ async fn serve(app: Router) -> String {
+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = l.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
+ format!("http://{addr}")
+ }
+
+ fn authed(h: &HeaderMap) -> bool {
+ h.get("authorization").and_then(|v| v.to_str().ok()) == Some("Bearer tok")
+ }
+
+ fn api() -> Router {
+ Router::new()
+ .route(
+ "/v1/me",
+ get(|h: HeaderMap| async move {
+ if !authed(&h) {
+ return (StatusCode::UNAUTHORIZED, Json(json!({"error":"unauthorized"})));
+ }
+ (
+ StatusCode::OK,
+ Json(json!({
+ "sub":"u1","email":"[email protected]",
+ "orgs":[
+ {"id":"o1","alias":"acme","name":"Acme Inc","role":"owner","plan":"teams","status":"active","seats":3},
+ {"id":"o2","alias":"side","role":"member","plan":"free","status":"none","seats":0}
+ ],
+ "entitlements":{"sub":"u1","plan":"pro","status":"active","warnings":[],"later":1}
+ })),
+ )
+ }),
+ )
+ .route(
+ "/v1/orgs/{org}/members",
+ get(|Path(org): Path<String>| async move {
+ Json(json!({"members":[
+ {"sub":"u1","email":"[email protected]","role":"owner"},
+ {"sub":format!("m-{org}"),"email":"[email protected]","role":"member"}
+ ]}))
+ }),
+ )
+ .route(
+ "/v1/orgs/{org}/invites",
+ get(|Path(org): Path<String>| async move {
+ if org == "side" {
+ return (StatusCode::FORBIDDEN, Json(json!({"error":"forbidden"})));
+ }
+ (StatusCode::OK, Json(json!({"invites":[{"id":"i1","email":"[email protected]"}]})))
+ }),
+ )
+ .route(
+ "/v1/pairing-codes",
+ post(|Json(b): Json<Value>| async move {
+ (
+ StatusCode::CREATED,
+ Json(json!({"id":"p1","code":"ABCD","expires_at":"2026-10-14T00:00:00Z","org":b["org"]})),
+ )
+ }),
+ )
+ }
+
+ #[tokio::test]
+ async fn teams_read_orgs_members_and_pending_invites() {
+ let c = SpacesApiClient::new(&serve(api()).await).unwrap();
+ let t = c.teams("tok").await.unwrap();
+ assert_eq!(
+ (t.email.as_str(), t.plan.as_str()),
+ ("[email protected]", "pro")
+ );
+ assert_eq!(t.teams.len(), 2);
+ let acme = &t.teams[0];
+ assert_eq!(
+ (
+ acme.org.name.as_str(),
+ acme.org.alias.as_str(),
+ acme.org.seats
+ ),
+ ("Acme Inc", "acme", 3)
+ );
+ assert_eq!(acme.members.len(), 2);
+ assert_eq!(
+ acme.invites,
+ vec![ApiInvite {
+ id: "i1".into(),
+ email: "[email protected]".into()
+ }]
+ );
+ // A plain member is refused the invite list: none, not an error.
+ assert!(t.teams[1].invites.is_empty());
+ assert_eq!(t.teams[1].org.name, "");
+ }
+
+ #[tokio::test]
+ async fn a_refused_token_is_unauthenticated() {
+ let c = SpacesApiClient::new(&serve(api()).await).unwrap();
+ let e = c.teams("nope").await.unwrap_err();
+ assert!(
+ matches!(e, Error::Unauthenticated(ref m) if m.contains("HTTP 401")),
+ "{e}"
+ );
+ }
+
+ #[tokio::test]
+ async fn pairing_codes_can_target_a_team() {
+ let c = SpacesApiClient::new(&serve(api()).await).unwrap();
+ let p = c.create_pairing("tok", Some("acme")).await.unwrap();
+ assert_eq!((p.id.as_str(), p.code.as_str()), ("p1", "ABCD"));
+ }
+
+ #[test]
+ fn only_https_or_loopback_bases() {
+ assert!(SpacesApiClient::new("https://api.cua.ai/").is_ok());
+ assert!(SpacesApiClient::new("http://api.cua.ai").is_err());
+ assert!(SpacesApiClient::new("nonsense").is_err());
+ }
+
+ #[test]
+ fn errors_carry_the_api_detail() {
+ let e = http_error(410, r#"{"error":"gone","detail":"retired"}"#);
+ assert!(e.to_string().contains("HTTP 410 (gone: retired)"), "{e}");
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
index 8cfff40a6b..fd5f490a4d 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/experiments.json
@@ -65,7 +65,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces and agents available after a restart.",
@@ -174,7 +177,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces, agents and Cua Volume available after a restart.",
@@ -300,7 +306,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces, agents and Cua Volume available after a restart.",
@@ -431,7 +440,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces, agents and Cua Volume available after a restart.",
@@ -563,7 +575,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces, agents and Cua Volume available after a restart.",
@@ -681,7 +696,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces, agents and Cua Volume available after a restart.",
@@ -796,7 +814,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces and agents available after a restart.",
@@ -919,7 +940,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces and agents available after a restart.",
@@ -1037,7 +1061,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces and agents available after a restart.",
@@ -1153,7 +1180,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces and agents available after a restart.",
@@ -1271,7 +1301,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- launch-at-login toggle: Launch Cua Spaces at login {*On|Off}",
"- launch-at-login-note note: Keeps your Spaces and agents available after a restart.",
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json
index 2e39f553b8..5ee27278b9 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/main-window.json
@@ -667,7 +667,10 @@
"= Settings",
"# Account (account)",
"- sign-in text: Cua account [Sign in to Cua]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Sign in to see your teams",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- notch choice: Spaces tab in the notch {*Show|Hide}",
"- welcome text: Welcome [Show again]",
@@ -682,7 +685,10 @@
"- api-key text: Signed in via API key = client-123",
"- sign-in text: Cua account [Try again]",
"- sign-in-error error: The code expired",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Sign in to see your teams",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- notch choice: Spaces tab in the notch {Show|*Hide}",
"- welcome text: Welcome [Show again]",
@@ -698,7 +704,10 @@
"= Settings",
"# Account (account)",
"- sign-in-code text: Enter this code in your browser = WXYZ-1234 [Cancel]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Sign in to see your teams",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- notch choice: Spaces tab in the notch {*Show|Hide}",
"- welcome text: Welcome [Show again]",
@@ -719,7 +728,10 @@
"= Settings",
"# Account (account)",
"- account text: [email protected] [Sign out]",
- "- teams text: Teams = Coming soon [Join the waitlist] < https://cua.ai/teams>",
+ "# Teams (teams)",
+ "- teams text: Teams = Manage your team in the account app",
+ "- teams-manage text: Invite people, roles and plans [Manage team] < https://app.cua.ai/team>",
+ "- teams-billing text: Billing [Billing and plans] < https://app.cua.ai/billing>",
"# General (general)",
"- notch choice: Spaces tab in the notch {*Show|Hide}",
"- welcome text: Welcome [Show again]",
diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
index f1524c1818..0ad7179b60 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
@@ -86,6 +86,7 @@ pub mod relay_usage;
pub mod settings;
pub mod share;
pub mod spaces;
+pub mod teams;
pub mod telemetry;
pub mod teleport;
mod util;
diff --git a/libs/cua/crates/cua-spaces-app-core/src/onboarding.rs b/libs/cua/crates/cua-spaces-app-core/src/onboarding.rs
index b4b804e3fa..ef66fa9afc 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/onboarding.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/onboarding.rs
@@ -1058,12 +1058,11 @@ pub struct OnboardingCopy {
pub permissions_title: String,
/// The permission rows' button.
pub open_settings: String,
- /// The Sign in page's Teams line ("Teams · coming soon").
+ /// The Sign in page's Teams line ("Teams · manage them at app.cua.ai").
pub teams: String,
- /// Its link ("Join the waitlist").
+ /// Its link ("Open the account app").
pub teams_link: String,
- /// The link's URL: the website's Teams waitlist (the app collects
- /// nothing).
+ /// The link's URL: the account app, which administers teams.
pub teams_url: String,
}
@@ -1101,7 +1100,7 @@ pub fn copy() -> OnboardingCopy {
crate::settings::TEAMS_VALUE.to_lowercase()
),
teams_link: crate::settings::TEAMS_BUTTON.into(),
- teams_url: crate::settings::TEAMS_WAITLIST_URL.into(),
+ teams_url: crate::settings::TEAMS_URL.into(),
}
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/settings.rs b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
index c08eeb3f50..b0210075dd 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/settings.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
@@ -80,6 +80,10 @@ pub struct AppSettings {
/// is opened (on by default); off, it waits for Connect
/// ([`crate::spaces::cover`]).
pub auto_connect: bool,
+ /// Settings, Teams: the team (organization id) the account works in
+ /// when it is in several ([`crate::teams::current`]); `None` or an id
+ /// the account left: its first owned team.
+ pub current_team_id: Option<String>,
}
impl Default for AppSettings {
@@ -100,6 +104,7 @@ impl Default for AppSettings {
keyvault_site_icons: true,
teleport_choices: vec![],
auto_connect: true,
+ current_team_id: None,
}
}
}
@@ -230,18 +235,18 @@ pub fn format_hotkey(c: &KeyCombo) -> Option<String> {
}
/// What telemetry's docs say is collected.
-/// The Teams waitlist on the website (Settings' Teams row, the Sign in
-/// page's line). The app collects nothing itself.
-pub const TEAMS_WAITLIST_URL: &str = "https://cua.ai/teams";
+/// Where the Sign in page's Teams line links: the account app, which
+/// administers teams (Settings shows the real Teams section, [`crate::teams`]).
+pub const TEAMS_URL: &str = "https://app.cua.ai/welcome";
-/// The Teams row's label.
+/// The Sign in page's Teams line's label.
pub const TEAMS_LABEL: &str = "Teams";
/// Its value.
-pub const TEAMS_VALUE: &str = "Coming soon";
+pub const TEAMS_VALUE: &str = "manage them at app.cua.ai";
-/// Its button.
-pub const TEAMS_BUTTON: &str = "Join the waitlist";
+/// Its link.
+pub const TEAMS_BUTTON: &str = "Open the account app";
pub const TELEMETRY_DOCS_URL: &str = "https://cua.ai/docs/cua-sdk/concepts/telemetry";
@@ -312,6 +317,11 @@ pub struct SettingsInput {
pub agents_busy: bool,
/// Agents with an action running.
pub agents_pending: Vec<String>,
+ /// Teams from the Spaces API (the host reads them), with the account
+ /// app's URL. None: the Teams section shows the production account
+ /// app's links only.
+ #[serde(default)]
+ pub teams: Option<crate::teams::TeamsInput>,
/// The account's Cua Cloud billing, once read (signed in).
pub billing: Option<crate::billing::BillingStatus>,
/// Launch at login, once the system was asked (none: no rows).
@@ -359,6 +369,7 @@ impl Default for SettingsInput {
agents: None,
agents_busy: false,
agents_pending: vec![],
+ teams: None,
billing: None,
login_item: None,
experiments: Experiments::default(),
@@ -666,14 +677,6 @@ pub fn page(input: &SettingsInput) -> SettingsPage {
account.push(row("sign-in-error", Error, message));
}
}
- // Teams: a waitlist on the website (the app collects nothing). Row id
- // `teams`; the button opens `link_url`.
- let mut teams = row("teams", Text, TEAMS_LABEL);
- teams.value = Some(TEAMS_VALUE.into());
- teams.button = Some(TEAMS_BUTTON.into());
- teams.link_url = Some(TEAMS_WAITLIST_URL.into());
- account.push(teams);
-
let mut notch = row("notch", Choice, "Spaces tab in the notch");
notch.options = vec![
opt("show", "Show", !input.menu_bar),
@@ -723,6 +726,26 @@ pub fn page(input: &SettingsInput) -> SettingsPage {
button_help: None,
rows: account,
},
+ SettingsSection {
+ id: "teams".into(),
+ title: crate::teams::TEAMS_TITLE.into(),
+ button: None,
+ button_enabled: false,
+ button_help: None,
+ // Each team with its members and pending invites, then the
+ // account app's links (invites, roles, billing).
+ rows: crate::teams::rows(&input.teams.clone().unwrap_or_else(|| {
+ crate::teams::TeamsInput {
+ account_app_url: crate::teams::ACCOUNT_APP_URL.into(),
+ state: if input.identity.is_some() {
+ crate::teams::TeamsState::Unread
+ } else {
+ crate::teams::TeamsState::SignedOut
+ },
+ current_team_id: None,
+ }
+ })),
+ },
SettingsSection {
id: "general".into(),
title: "General".into(),
@@ -1009,7 +1032,7 @@ mod tests {
fn the_page_lists_account_general_privacy_agents() {
let p = page(&SettingsInput::default());
let ids: Vec<_> = p.sections.iter().map(|s| s.id.as_str()).collect();
- assert_eq!(ids, ["account", "general", "agents"]);
+ assert_eq!(ids, ["account", "teams", "general", "agents"]);
let p = page(&SettingsInput {
identity: Some("[email protected]".into()),
can_sign_out: true,
@@ -1017,7 +1040,7 @@ mod tests {
..Default::default()
});
let ids: Vec<_> = p.sections.iter().map(|s| s.id.as_str()).collect();
- assert_eq!(ids, ["account", "general", "privacy", "agents"]);
+ assert_eq!(ids, ["account", "teams", "general", "privacy", "agents"]);
assert_eq!(p.sections[0].rows[0].button.as_deref(), Some("Sign out"));
let sign_in: SignInPhase =
serde_json::from_str(r#"{"kind":"waiting","userCode":"AB-CD"}"#).unwrap();
@@ -1042,9 +1065,11 @@ mod tests {
});
assert_eq!(
ids(&p),
- ["account", "general", "privacy", "keyvault", "agents"]
+ [
+ "account", "teams", "general", "privacy", "keyvault", "agents"
+ ]
);
- let kv = &p.sections[3];
+ let kv = &p.sections[4];
assert_eq!(kv.title, "Keyvault");
let toggle = &kv.rows[0];
assert_eq!(
@@ -1200,14 +1225,14 @@ mod tests {
let ids =
|p: &SettingsPage| -> Vec<String> { p.sections.iter().map(|s| s.id.clone()).collect() };
let note = |p: &SettingsPage| {
- p.sections[1]
+ p.sections[2]
.rows
.iter()
.find(|r| r.id == "launch-at-login-note")
.map(|r| r.label.clone())
};
let off = with_storage(&page(&input), &storage, &input.experiments);
- assert_eq!(ids(&off), ["account", "general", "agents"]);
+ assert_eq!(ids(&off), ["account", "teams", "general", "agents"]);
assert_eq!(note(&off).as_deref(), Some(NOTE_WITHOUT_VOLUME));
let on = SettingsInput {
experiments: Experiments {
@@ -1217,7 +1242,10 @@ mod tests {
..input
};
let p = with_storage(&page(&on), &storage, &on.experiments);
- assert_eq!(ids(&p), ["account", "general", "storage", "agents"]);
+ assert_eq!(
+ ids(&p),
+ ["account", "teams", "general", "storage", "agents"]
+ );
assert_eq!(note(&p).as_deref(), Some(NOTE));
// A settings file from before experiments: all off.
let old: AppSettings = serde_json::from_str(r#"{"menuBar":true}"#).unwrap();
diff --git a/libs/cua/crates/cua-spaces-app-core/src/teams.rs b/libs/cua/crates/cua-spaces-app-core/src/teams.rs
new file mode 100644
index 0000000000..858a2e2428
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/teams.rs
@@ -0,0 +1,430 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Teams as every app shows them: the account's organizations from the
+//! Spaces API (`GET /v1/me`, `/v1/orgs/{org}/members`, `/invites`), as
+//! Settings rows. A team is its name (the org's `name`, else its alias),
+//! then its people: members with their role, pending invites marked
+//! "(Invited)". The apps administer nothing: invites, roles and billing
+//! live in the account app (`app.cua.ai`), one link away. The data is read
+//! by the host (`app_teams`); this module only words it.
+
+use crate::settings::{
+ SettingsOption, SettingsRow,
+ SettingsRowKind::{Choice, Text},
+ row,
+};
+use serde::{Deserialize, Serialize};
+
+/// The production account app: billing, plans, team administration.
+pub const ACCOUNT_APP_URL: &str = "https://app.cua.ai";
+
+/// The Settings section.
+pub const TEAMS_TITLE: &str = "Teams";
+
+/// What a pending invite's row says instead of a role.
+pub const INVITED: &str = "(Invited)";
+
+/// The button that opens the account app's team page.
+pub const MANAGE_TEAM: &str = "Manage team";
+
+/// The button that opens the account app's billing page.
+pub const MANAGE_BILLING: &str = "Billing and plans";
+
+/// The line when the account is in no team.
+pub const NO_TEAMS: &str =
+ "You're not in a team yet. Create one or accept an invite in the account app.";
+
+/// A person on a team.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TeamPersonInput {
+ pub email: String,
+ /// `owner`, `admin` or `member`.
+ pub role: String,
+}
+
+/// One team, as the Spaces API describes it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TeamInput {
+ pub id: String,
+ /// The org's slug.
+ pub alias: String,
+ /// Its display name (empty: use the alias).
+ pub name: String,
+ /// The account's role in it.
+ pub role: String,
+ /// `free`, `teams`, ...
+ pub plan: String,
+ /// Paid seats.
+ pub seats: i64,
+ pub members: Vec<TeamPersonInput>,
+ /// Pending invites' emails (only owners and admins can read them).
+ pub invites: Vec<String>,
+}
+
+/// Where Teams stand.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(
+ tag = "kind",
+ rename_all = "lowercase",
+ rename_all_fields = "camelCase"
+)]
+pub enum TeamsState {
+ /// Not signed in.
+ #[default]
+ SignedOut,
+ /// Signed in, but this host does not read teams: only the links.
+ Unread,
+ /// Being read.
+ Loading,
+ /// The read failed.
+ Failed { message: String },
+ /// The account's teams (maybe none).
+ Ready { teams: Vec<TeamInput> },
+}
+
+/// Settings' Teams input.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TeamsInput {
+ /// The account app for this environment (`https://app.cua.ai`, or
+ /// `https://app.staging.cua.ai` under `CUA_ENV=staging`).
+ pub account_app_url: String,
+ pub state: TeamsState,
+ /// The saved current team (`AppSettings::current_team_id`).
+ #[serde(default)]
+ pub current_team_id: Option<String>,
+}
+
+/// The settings row of the team picker; its options are team ids.
+pub const CURRENT_TEAM_ROW: &str = "team-current";
+
+/// The team the account works in: the saved one while the account is still
+/// in it, else its first owned team, else its first team.
+pub fn current<'a>(teams: &'a [TeamInput], saved: Option<&str>) -> Option<&'a TeamInput> {
+ saved
+ .and_then(|id| teams.iter().find(|t| t.id == id))
+ .or_else(|| teams.iter().find(|t| t.role == "owner"))
+ .or_else(|| teams.first())
+}
+
+impl TeamInput {
+ /// The name shown: `name`, else the alias, else the id.
+ pub fn display_name(&self) -> &str {
+ [&self.name, &self.alias, &self.id]
+ .into_iter()
+ .map(|s| s.trim())
+ .find(|s| !s.is_empty())
+ .unwrap_or("Team")
+ }
+}
+
+fn role_label(role: &str) -> String {
+ match role {
+ "owner" => "Owner".into(),
+ "admin" => "Admin".into(),
+ "member" | "" => "Member".into(),
+ other => {
+ let mut c = other.chars();
+ c.next()
+ .map(|f| f.to_uppercase().collect::<String>() + c.as_str())
+ .unwrap_or_default()
+ }
+ }
+}
+
+fn plan_label(plan: &str) -> &'static str {
+ match plan {
+ "teams" | "team" => "Teams plan",
+ "pro" => "Pro plan",
+ // An unknown plan is Free.
+ _ => "Free plan",
+ }
+}
+
+fn base(input: &TeamsInput) -> String {
+ let url = input.account_app_url.trim().trim_end_matches('/');
+ if url.starts_with("https://") {
+ url.to_string()
+ } else {
+ ACCOUNT_APP_URL.to_string()
+ }
+}
+
+/// The Settings rows for Teams (the section's body).
+pub fn rows(input: &TeamsInput) -> Vec<SettingsRow> {
+ let app = base(input);
+ let mut out = Vec::new();
+ match &input.state {
+ TeamsState::SignedOut => {
+ let mut r = row("teams", Text, "Teams");
+ r.value = Some("Sign in to see your teams".into());
+ out.push(r);
+ }
+ TeamsState::Unread => {
+ let mut r = row("teams", Text, "Teams");
+ r.value = Some("Manage your team in the account app".into());
+ out.push(r);
+ }
+ TeamsState::Loading => {
+ let mut r = row("teams", Text, "Teams");
+ r.value = Some("Loading\u{2026}".into());
+ out.push(r);
+ }
+ TeamsState::Failed { message } => {
+ let mut r = row("teams", Text, "Teams");
+ r.value = Some(format!("Couldn't load your teams: {message}"));
+ out.push(r);
+ }
+ TeamsState::Ready { teams } if teams.is_empty() => {
+ let mut r = row("teams", Text, "Teams");
+ r.value = Some(NO_TEAMS.into());
+ out.push(r);
+ }
+ TeamsState::Ready { teams } => {
+ let cur = current(teams, input.current_team_id.as_deref());
+ if teams.len() > 1 {
+ // Several teams: pick the one to work in.
+ let mut pick = row(CURRENT_TEAM_ROW, Choice, "Current team");
+ pick.options = teams
+ .iter()
+ .map(|t| SettingsOption {
+ id: t.id.clone(),
+ label: t.display_name().to_string(),
+ active: cur.is_some_and(|c| c.id == t.id),
+ })
+ .collect();
+ out.push(pick);
+ }
+ for t in teams
+ .iter()
+ .filter(|t| teams.len() == 1 || cur.is_some_and(|c| c.id == t.id))
+ {
+ let seats = match t.seats {
+ 0 => String::new(),
+ 1 => " \u{b7} 1 seat".into(),
+ n => format!(" \u{b7} {n} seats"),
+ };
+ let mut head = row(&format!("team:{}", t.id), Text, t.display_name());
+ head.value = Some(format!(
+ "{} \u{b7} {}{seats}",
+ role_label(&t.role),
+ plan_label(&t.plan)
+ ));
+ out.push(head);
+ for (i, m) in t.members.iter().enumerate() {
+ let mut r = row(&format!("team:{}:member:{i}", t.id), Text, &m.email);
+ r.value = Some(role_label(&m.role));
+ out.push(r);
+ }
+ for (i, email) in t.invites.iter().enumerate() {
+ let mut r = row(&format!("team:{}:invite:{i}", t.id), Text, email);
+ r.value = Some(INVITED.into());
+ out.push(r);
+ }
+ }
+ }
+ }
+ // Invites, roles and billing are the account app's.
+ let mut manage = row("teams-manage", Text, "Invite people, roles and plans");
+ manage.button = Some(MANAGE_TEAM.into());
+ manage.link_url = Some(format!("{app}/team"));
+ out.push(manage);
+ let mut billing = row("teams-billing", Text, "Billing");
+ billing.button = Some(MANAGE_BILLING.into());
+ billing.link_url = Some(format!("{app}/billing"));
+ out.push(billing);
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn team(name: &str, alias: &str) -> TeamInput {
+ TeamInput {
+ id: "o1".into(),
+ alias: alias.into(),
+ name: name.into(),
+ role: "owner".into(),
+ plan: "teams".into(),
+ seats: 3,
+ members: vec![
+ TeamPersonInput {
+ email: "[email protected]".into(),
+ role: "owner".into(),
+ },
+ TeamPersonInput {
+ email: "[email protected]".into(),
+ role: "member".into(),
+ },
+ ],
+ invites: vec!["[email protected]".into()],
+ }
+ }
+
+ fn input(teams: Vec<TeamInput>) -> TeamsInput {
+ TeamsInput {
+ account_app_url: "https://app.cua.ai/".into(),
+ state: TeamsState::Ready { teams },
+ current_team_id: None,
+ }
+ }
+
+ #[test]
+ fn a_team_shows_its_name_then_members_then_invites() {
+ let rows = rows(&input(vec![team("Acme Inc", "acme")]));
+ let flat: Vec<(String, Option<String>)> = rows
+ .iter()
+ .map(|r| (r.label.clone(), r.value.clone()))
+ .collect();
+ assert_eq!(
+ flat[0],
+ (
+ "Acme Inc".into(),
+ Some("Owner \u{b7} Teams plan \u{b7} 3 seats".into())
+ )
+ );
+ assert_eq!(flat[1], ("[email protected]".into(), Some("Owner".into())));
+ assert_eq!(flat[2], ("[email protected]".into(), Some("Member".into())));
+ assert_eq!(flat[3], ("[email protected]".into(), Some("(Invited)".into())));
+ }
+
+ #[test]
+ fn the_name_falls_back_to_the_alias() {
+ let rows = rows(&input(vec![team("", "acme")]));
+ assert_eq!(rows[0].label, "acme");
+ assert_eq!(team(" ", "").display_name(), "o1");
+ }
+
+ #[test]
+ fn invites_and_billing_open_the_account_app() {
+ let rows = rows(&input(vec![team("Acme", "acme")]));
+ let manage = rows.iter().find(|r| r.id == "teams-manage").unwrap();
+ assert_eq!(manage.link_url.as_deref(), Some("https://app.cua.ai/team"));
+ let billing = rows.iter().find(|r| r.id == "teams-billing").unwrap();
+ assert_eq!(
+ billing.link_url.as_deref(),
+ Some("https://app.cua.ai/billing")
+ );
+ }
+
+ #[test]
+ fn staging_links_stay_on_staging_and_junk_falls_back_to_production() {
+ let mut i = input(vec![]);
+ i.account_app_url = "https://app.staging.cua.ai".into();
+ let r = rows(&i);
+ assert_eq!(
+ r.last().unwrap().link_url.as_deref(),
+ Some("https://app.staging.cua.ai/billing")
+ );
+ i.account_app_url = "javascript:alert(1)".into();
+ assert_eq!(
+ rows(&i).last().unwrap().link_url.as_deref(),
+ Some("https://app.cua.ai/billing")
+ );
+ }
+
+ #[test]
+ fn no_teams_signed_out_loading_and_failed_each_say_so() {
+ let say = |s: TeamsState| {
+ rows(&TeamsInput {
+ account_app_url: String::new(),
+ state: s,
+ current_team_id: None,
+ })[0]
+ .value
+ .clone()
+ .unwrap()
+ };
+ assert_eq!(say(TeamsState::Ready { teams: vec![] }), NO_TEAMS);
+ assert!(say(TeamsState::SignedOut).contains("Sign in"));
+ assert!(say(TeamsState::Loading).contains("Loading"));
+ assert!(say(TeamsState::Unread).contains("account app"));
+ assert!(
+ say(TeamsState::Failed {
+ message: "offline".into()
+ })
+ .contains("offline")
+ );
+ assert!(!NO_TEAMS.to_lowercase().contains("waitlist"));
+ }
+
+ #[test]
+ fn nothing_says_coming_soon() {
+ for r in rows(&input(vec![team("A", "a")])) {
+ let all = format!("{} {:?} {:?}", r.label, r.value, r.button).to_lowercase();
+ assert!(
+ !all.contains("waitlist") && !all.contains("coming soon"),
+ "{all}"
+ );
+ }
+ }
+
+ fn named(id: &str, role: &str) -> TeamInput {
+ TeamInput {
+ id: id.into(),
+ alias: id.into(),
+ name: String::new(),
+ role: role.into(),
+ plan: "free".into(),
+ seats: 0,
+ members: vec![],
+ invites: vec![],
+ }
+ }
+
+ #[test]
+ fn the_current_team_is_the_saved_one_else_the_first_owned_else_the_first() {
+ let teams = vec![
+ named("a", "member"),
+ named("b", "owner"),
+ named("c", "owner"),
+ ];
+ assert_eq!(current(&teams, Some("c")).unwrap().id, "c");
+ assert_eq!(current(&teams, None).unwrap().id, "b");
+ // A saved team the account left falls back.
+ assert_eq!(current(&teams, Some("gone")).unwrap().id, "b");
+ let members = vec![named("a", "member"), named("z", "admin")];
+ assert_eq!(current(&members, None).unwrap().id, "a");
+ assert!(current(&[], Some("a")).is_none());
+ }
+
+ #[test]
+ fn two_teams_show_a_picker_and_the_chosen_teams_people() {
+ let mut a = team("Acme", "acme");
+ a.id = "a".into();
+ let mut b = team("Beta", "beta");
+ b.id = "b".into();
+ b.role = "member".into();
+ b.members.truncate(1);
+ b.invites.clear();
+ let mut i = input(vec![a, b]);
+ let r = rows(&i);
+ let pick = r.iter().find(|r| r.id == CURRENT_TEAM_ROW).unwrap();
+ assert_eq!(pick.kind, Choice);
+ let opts: Vec<(&str, bool)> = pick
+ .options
+ .iter()
+ .map(|o| (o.id.as_str(), o.active))
+ .collect();
+ // Default: the first owned team.
+ assert_eq!(opts, [("a", true), ("b", false)]);
+ assert!(r.iter().any(|r| r.id == "team:a"));
+ assert!(!r.iter().any(|r| r.id == "team:b"));
+ i.current_team_id = Some("b".into());
+ let r = rows(&i);
+ let pick = r.iter().find(|r| r.id == CURRENT_TEAM_ROW).unwrap();
+ assert!(pick.options[1].active && !pick.options[0].active);
+ assert!(r.iter().any(|r| r.id == "team:b"));
+ assert!(!r.iter().any(|r| r.id == "team:a"));
+ }
+
+ #[test]
+ fn one_team_has_no_picker() {
+ let r = rows(&input(vec![team("Acme", "acme")]));
+ assert!(!r.iter().any(|r| r.id == CURRENT_TEAM_ROW));
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
index bd0debaa07..5d5d20787a 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -1914,6 +1914,62 @@ fn relay_usage(u: cua_host::RelayUsage) -> AppRelayUsage {
})
}
+/// The account's Teams (the organizations of `GET /v1/me` on the Spaces
+/// API for this environment, `api.cua.ai` or `api.staging.cua.ai`), each
+/// with its members and pending invites, read with `account_token`.
+/// Both Spaces apps read Teams here; Settings words them
+/// (`app_settings_page`'s `teams`).
+#[uniffi::export]
+pub async fn app_teams(account_token: String) -> Result<AppTeamsInput> {
+ cua_sdk::support::run(async move {
+ let snapshot = cua_host::spaces_api::SpacesApiClient::current()?
+ .teams(&account_token)
+ .await?;
+ Ok(teams_input(snapshot, cua_home::env::account_app_url()))
+ })
+ .await
+}
+
+fn teams_input(s: cua_host::spaces_api::TeamsSnapshot, account_app_url: String) -> AppTeamsInput {
+ core::teams::TeamsInput {
+ account_app_url,
+ state: core::teams::TeamsState::Ready {
+ teams: s
+ .teams
+ .into_iter()
+ .map(|t| core::teams::TeamInput {
+ id: t.org.id,
+ alias: t.org.alias,
+ name: t.org.name,
+ role: t.org.role,
+ plan: t.org.plan,
+ seats: t.org.seats,
+ members: t
+ .members
+ .into_iter()
+ .map(|m| core::teams::TeamPersonInput {
+ email: m.email,
+ role: m.role,
+ })
+ .collect(),
+ invites: t.invites.into_iter().map(|i| i.email).collect(),
+ })
+ .collect(),
+ },
+ // The apps fill the saved team in from their settings.
+ current_team_id: None,
+ }
+}
+
+/// The account app for this environment (`CUA_ACCOUNT_APP_URL`, else
+/// `https://app.cua.ai`, or `https://app.staging.cua.ai` under
+/// `CUA_ENV=staging`): billing, plans and team administration, which the
+/// apps open in the browser.
+#[uniffi::export]
+pub fn app_account_app_url() -> String {
+ cua_home::env::account_app_url()
+}
+
/// Settings' "Relay usage" row and the notice past the allowance; none
/// when the relay meters nothing.
#[uniffi::export]
@@ -2795,6 +2851,45 @@ mod keyvault_home_tests {
}
}
+#[cfg(test)]
+mod teams_tests {
+ use super::*;
+ use cua_host::spaces_api::{ApiInvite, ApiMember, ApiOrg, TeamDetail, TeamsSnapshot};
+
+ #[test]
+ fn a_snapshot_becomes_the_cores_teams_input() {
+ let snapshot = TeamsSnapshot {
+ email: "[email protected]".into(),
+ plan: "pro".into(),
+ teams: vec![TeamDetail {
+ org: ApiOrg {
+ id: "o1".into(),
+ alias: "acme".into(),
+ name: "".into(),
+ role: "admin".into(),
+ plan: "teams".into(),
+ status: "active".into(),
+ seats: 3,
+ },
+ members: vec![ApiMember {
+ sub: "u1".into(),
+ email: "[email protected]".into(),
+ role: "admin".into(),
+ }],
+ invites: vec![ApiInvite {
+ id: "i1".into(),
+ email: "[email protected]".into(),
+ }],
+ }],
+ };
+ let input = teams_input(snapshot, "https://app.cua.ai".into());
+ let rows = core::teams::rows(&input);
+ assert_eq!(rows[0].label, "acme");
+ assert_eq!(rows[2].label, "[email protected]");
+ assert_eq!(rows[2].value.as_deref(), Some("(Invited)"));
+ }
+}
+
#[cfg(test)]
mod relay_usage_tests {
use super::*;
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index fc8c800851..d7c1e4a140 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -5765,12 +5765,11 @@ pub struct AppOnboardingCopy {
pub permissions_title: String,
/// The permission rows' button.
pub open_settings: String,
- /// The Sign in page's Teams line ("Teams · coming soon").
+ /// The Sign in page's Teams line ("Teams · manage them at app.cua.ai").
pub teams: String,
- /// Its link ("Join the waitlist").
+ /// Its link ("Open the account app").
pub teams_link: String,
- /// The link's URL: the website's Teams waitlist (the app collects
- /// nothing).
+ /// The link's URL: the account app, which administers teams.
pub teams_url: String,
}
@@ -6426,6 +6425,10 @@ pub struct AppSettings {
/// is opened (on by default); off, it waits for Connect
/// ([`crate::spaces::cover`]).
pub auto_connect: bool,
+ /// Settings, Teams: the team (organization id) the account works in
+ /// when it is in several ([`crate::teams::current`]); `None` or an id
+ /// the account left: its first owned team.
+ pub current_team_id: Option<String>,
}
/// A pressed key combination.
@@ -6505,6 +6508,10 @@ pub struct AppSettingsInput {
pub agents_busy: bool,
/// Agents with an action running.
pub agents_pending: Vec<String>,
+ /// Teams from the Spaces API (the host reads them), with the account
+ /// app's URL. None: the Teams section shows the production account
+ /// app's links only.
+ pub teams: Option<AppTeamsInput>,
/// The account's Cua Cloud billing, once read (signed in).
pub billing: Option<AppBillingStatus>,
/// Launch at login, once the system was asked (none: no rows).
@@ -9271,6 +9278,63 @@ pub struct AppPaletteEntry {
pub keywords: Option<String>,
}
+/// A person on a team.
+pub type AppTeamPersonInput = core::teams::TeamPersonInput;
+#[uniffi::remote(Record)]
+pub struct AppTeamPersonInput {
+ pub email: String,
+ /// `owner`, `admin` or `member`.
+ pub role: String,
+}
+
+/// One team, as the Spaces API describes it.
+pub type AppTeamInput = core::teams::TeamInput;
+#[uniffi::remote(Record)]
+pub struct AppTeamInput {
+ pub id: String,
+ /// The org's slug.
+ pub alias: String,
+ /// Its display name (empty: use the alias).
+ pub name: String,
+ /// The account's role in it.
+ pub role: String,
+ /// `free`, `teams`, ...
+ pub plan: String,
+ /// Paid seats.
+ pub seats: i64,
+ pub members: Vec<AppTeamPersonInput>,
+ /// Pending invites' emails (only owners and admins can read them).
+ pub invites: Vec<String>,
+}
+
+/// `teams::TeamsState`.
+pub type AppTeamsState = core::teams::TeamsState;
+#[uniffi::remote(Enum)]
+pub enum AppTeamsState {
+ /// Not signed in.
+ SignedOut,
+ /// Signed in, but this host does not read teams: only the links.
+ Unread,
+ /// Being read.
+ Loading,
+ /// The read failed.
+ Failed { message: String },
+ /// The account's teams (maybe none).
+ Ready { teams: Vec<AppTeamInput> },
+}
+
+/// Settings' Teams input.
+pub type AppTeamsInput = core::teams::TeamsInput;
+#[uniffi::remote(Record)]
+pub struct AppTeamsInput {
+ /// The account app for this environment (`https://app.cua.ai`, or
+ /// `https://app.staging.cua.ai` under `CUA_ENV=staging`).
+ pub account_app_url: String,
+ pub state: AppTeamsState,
+ /// The saved current team (`AppSettings::current_team_id`).
+ pub current_team_id: Option<String>,
+}
+
/// The team whose allowance is pooled.
pub type AppRelayUsageTeam = core::relay_usage::RelayUsageTeam;
#[uniffi::remote(Record)]
diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.py
index 29ddbfaa48..e81636e179 100644
--- a/libs/cua/scripts/generate-app-core-ffi.py
+++ b/libs/cua/scripts/generate-app-core-ffi.py
@@ -68,6 +68,7 @@ TYPES = [
("machines.rs", "machines", ["DeviceIn", "MachinesPageInput", "MachinePageRow"]),
("checklist.rs", "checklist", ["ChecklistStep", "ChecklistState", "ChecklistAction", "ChecklistSeen", "ChecklistTransition", "ChecklistRow", "ChecklistView"]),
("palette.rs", "palette", ["Keybinding", "PaletteEntry"]),
+ ("teams.rs", "teams", ["TeamPersonInput", "TeamInput", "TeamsState", "TeamsInput"]),
("relay_usage.rs", "relay_usage", ["RelayUsageTeam", "RelayUsage", "RelayAllowanceNotice", "RelayUsageView"]),
]
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 3cbc7558d5..e01c7fd8d9 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -22002,16 +22002,15 @@ public struct AppOnboardingCopy: Equatable, Hashable {
*/
public var openSettings: String
/**
- * The Sign in page's Teams line ("Teams · coming soon").
+ * The Sign in page's Teams line ("Teams · manage them at app.cua.ai").
*/
public var teams: String
/**
- * Its link ("Join the waitlist").
+ * Its link ("Open the account app").
*/
public var teamsLink: String
/**
- * The link's URL: the website's Teams waitlist (the app collects
- * nothing).
+ * The link's URL: the account app, which administers teams.
*/
public var teamsUrl: String
@@ -22091,14 +22090,13 @@ public struct AppOnboardingCopy: Equatable, Hashable {
* The permission rows' button.
*/openSettings: String,
/**
- * The Sign in page's Teams line ("Teams · coming soon").
+ * The Sign in page's Teams line ("Teams · manage them at app.cua.ai").
*/teams: String,
/**
- * Its link ("Join the waitlist").
+ * Its link ("Open the account app").
*/teamsLink: String,
/**
- * The link's URL: the website's Teams waitlist (the app collects
- * nothing).
+ * The link's URL: the account app, which administers teams.
*/teamsUrl: String) {
self.back = back
self.skip = skip
@@ -27854,6 +27852,12 @@ public struct AppSettings: Equatable, Hashable {
* ([`crate::spaces::cover`]).
*/
public var autoConnect: Bool
+ /**
+ * Settings, Teams: the team (organization id) the account works in
+ * when it is in several ([`crate::teams::current`]); `None` or an id
+ * the account left: its first owned team.
+ */
+ public var currentTeamId: String?
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -27919,7 +27923,12 @@ public struct AppSettings: Equatable, Hashable {
* Settings, General: a running Space's desktop streams as soon as it
* is opened (on by default); off, it waits for Connect
* ([`crate::spaces::cover`]).
- */autoConnect: Bool) {
+ */autoConnect: Bool,
+ /**
+ * Settings, Teams: the team (organization id) the account works in
+ * when it is in several ([`crate::teams::current`]); `None` or an id
+ * the account left: its first owned team.
+ */currentTeamId: String?) {
self.hotkey = hotkey
self.menuBar = menuBar
self.theme = theme
@@ -27935,6 +27944,7 @@ public struct AppSettings: Equatable, Hashable {
self.keyvaultSiteIcons = keyvaultSiteIcons
self.teleportChoices = teleportChoices
self.autoConnect = autoConnect
+ self.currentTeamId = currentTeamId
}
@@ -27967,7 +27977,8 @@ public struct FfiConverterTypeAppSettings: FfiConverterRustBuffer {
dismissedAccess: FfiConverterSequenceString.read(from: &buf),
keyvaultSiteIcons: FfiConverterBool.read(from: &buf),
teleportChoices: FfiConverterSequenceTypeAppRememberedChoice.read(from: &buf),
- autoConnect: FfiConverterBool.read(from: &buf)
+ autoConnect: FfiConverterBool.read(from: &buf),
+ currentTeamId: FfiConverterOptionString.read(from: &buf)
)
}
@@ -27987,6 +27998,7 @@ public struct FfiConverterTypeAppSettings: FfiConverterRustBuffer {
FfiConverterBool.write(value.keyvaultSiteIcons, into: &buf)
FfiConverterSequenceTypeAppRememberedChoice.write(value.teleportChoices, into: &buf)
FfiConverterBool.write(value.autoConnect, into: &buf)
+ FfiConverterOptionString.write(value.currentTeamId, into: &buf)
}
}
@@ -28052,6 +28064,12 @@ public struct AppSettingsInput: Equatable, Hashable {
* Agents with an action running.
*/
public var agentsPending: [String]
+ /**
+ * Teams from the Spaces API (the host reads them), with the account
+ * app's URL. None: the Teams section shows the production account
+ * app's links only.
+ */
+ public var teams: AppTeamsInput?
/**
* The account's Cua Cloud billing, once read (signed in).
*/
@@ -28137,6 +28155,11 @@ public struct AppSettingsInput: Equatable, Hashable {
/**
* Agents with an action running.
*/agentsPending: [String],
+ /**
+ * Teams from the Spaces API (the host reads them), with the account
+ * app's URL. None: the Teams section shows the production account
+ * app's links only.
+ */teams: AppTeamsInput?,
/**
* The account's Cua Cloud billing, once read (signed in).
*/billing: AppBillingStatus?,
@@ -28185,6 +28208,7 @@ public struct AppSettingsInput: Equatable, Hashable {
self.agents = agents
self.agentsBusy = agentsBusy
self.agentsPending = agentsPending
+ self.teams = teams
self.billing = billing
self.loginItem = loginItem
self.experiments = experiments
@@ -28224,6 +28248,7 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {
agents: FfiConverterOptionSequenceTypeAppAgentSettingsRow.read(from: &buf),
agentsBusy: FfiConverterBool.read(from: &buf),
agentsPending: FfiConverterSequenceString.read(from: &buf),
+ teams: FfiConverterOptionTypeAppTeamsInput.read(from: &buf),
billing: FfiConverterOptionTypeAppBillingStatus.read(from: &buf),
loginItem: FfiConverterOptionTypeAppLoginItemInput.read(from: &buf),
experiments: FfiConverterTypeAppExperiments.read(from: &buf),
@@ -28249,6 +28274,7 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {
FfiConverterOptionSequenceTypeAppAgentSettingsRow.write(value.agents, into: &buf)
FfiConverterBool.write(value.agentsBusy, into: &buf)
FfiConverterSequenceString.write(value.agentsPending, into: &buf)
+ FfiConverterOptionTypeAppTeamsInput.write(value.teams, into: &buf)
FfiConverterOptionTypeAppBillingStatus.write(value.billing, into: &buf)
FfiConverterOptionTypeAppLoginItemInput.write(value.loginItem, into: &buf)
FfiConverterTypeAppExperiments.write(value.experiments, into: &buf)
@@ -32274,6 +32300,252 @@ public func FfiConverterTypeAppTabView_lower(_ value: AppTabView) -> RustBuffer
}
+public struct AppTeamInput: Equatable, Hashable {
+ public var id: String
+ /**
+ * The org's slug.
+ */
+ public var alias: String
+ /**
+ * Its display name (empty: use the alias).
+ */
+ public var name: String
+ /**
+ * The account's role in it.
+ */
+ public var role: String
+ /**
+ * `free`, `teams`, ...
+ */
+ public var plan: String
+ /**
+ * Paid seats.
+ */
+ public var seats: Int64
+ public var members: [AppTeamPersonInput]
+ /**
+ * Pending invites' emails (only owners and admins can read them).
+ */
+ public var invites: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(id: String,
+ /**
+ * The org's slug.
+ */alias: String,
+ /**
+ * Its display name (empty: use the alias).
+ */name: String,
+ /**
+ * The account's role in it.
+ */role: String,
+ /**
+ * `free`, `teams`, ...
+ */plan: String,
+ /**
+ * Paid seats.
+ */seats: Int64, members: [AppTeamPersonInput],
+ /**
+ * Pending invites' emails (only owners and admins can read them).
+ */invites: [String]) {
+ self.id = id
+ self.alias = alias
+ self.name = name
+ self.role = role
+ self.plan = plan
+ self.seats = seats
+ self.members = members
+ self.invites = invites
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppTeamInput: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppTeamInput: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppTeamInput {
+ return
+ try AppTeamInput(
+ id: FfiConverterString.read(from: &buf),
+ alias: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ role: FfiConverterString.read(from: &buf),
+ plan: FfiConverterString.read(from: &buf),
+ seats: FfiConverterInt64.read(from: &buf),
+ members: FfiConverterSequenceTypeAppTeamPersonInput.read(from: &buf),
+ invites: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppTeamInput, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.id, into: &buf)
+ FfiConverterString.write(value.alias, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.role, into: &buf)
+ FfiConverterString.write(value.plan, into: &buf)
+ FfiConverterInt64.write(value.seats, into: &buf)
+ FfiConverterSequenceTypeAppTeamPersonInput.write(value.members, into: &buf)
+ FfiConverterSequenceString.write(value.invites, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamInput_lift(_ buf: RustBuffer) throws -> AppTeamInput {
+ return try FfiConverterTypeAppTeamInput.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamInput_lower(_ value: AppTeamInput) -> RustBuffer {
+ return FfiConverterTypeAppTeamInput.lower(value)
+}
+
+
+public struct AppTeamPersonInput: Equatable, Hashable {
+ public var email: String
+ /**
+ * `owner`, `admin` or `member`.
+ */
+ public var role: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(email: String,
+ /**
+ * `owner`, `admin` or `member`.
+ */role: String) {
+ self.email = email
+ self.role = role
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppTeamPersonInput: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppTeamPersonInput: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppTeamPersonInput {
+ return
+ try AppTeamPersonInput(
+ email: FfiConverterString.read(from: &buf),
+ role: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppTeamPersonInput, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.email, into: &buf)
+ FfiConverterString.write(value.role, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamPersonInput_lift(_ buf: RustBuffer) throws -> AppTeamPersonInput {
+ return try FfiConverterTypeAppTeamPersonInput.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamPersonInput_lower(_ value: AppTeamPersonInput) -> RustBuffer {
+ return FfiConverterTypeAppTeamPersonInput.lower(value)
+}
+
+
+public struct AppTeamsInput: Equatable, Hashable {
+ /**
+ * The account app for this environment (`https://app.cua.ai`, or
+ * `https://app.staging.cua.ai` under `CUA_ENV=staging`).
+ */
+ public var accountAppUrl: String
+ public var state: AppTeamsState
+ /**
+ * The saved current team (`AppSettings::current_team_id`).
+ */
+ public var currentTeamId: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The account app for this environment (`https://app.cua.ai`, or
+ * `https://app.staging.cua.ai` under `CUA_ENV=staging`).
+ */accountAppUrl: String, state: AppTeamsState,
+ /**
+ * The saved current team (`AppSettings::current_team_id`).
+ */currentTeamId: String?) {
+ self.accountAppUrl = accountAppUrl
+ self.state = state
+ self.currentTeamId = currentTeamId
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppTeamsInput: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppTeamsInput: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppTeamsInput {
+ return
+ try AppTeamsInput(
+ accountAppUrl: FfiConverterString.read(from: &buf),
+ state: FfiConverterTypeAppTeamsState.read(from: &buf),
+ currentTeamId: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppTeamsInput, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.accountAppUrl, into: &buf)
+ FfiConverterTypeAppTeamsState.write(value.state, into: &buf)
+ FfiConverterOptionString.write(value.currentTeamId, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamsInput_lift(_ buf: RustBuffer) throws -> AppTeamsInput {
+ return try FfiConverterTypeAppTeamsInput.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamsInput_lower(_ value: AppTeamsInput) -> RustBuffer {
+ return FfiConverterTypeAppTeamsInput.lower(value)
+}
+
+
public struct AppTelemetryInput: Equatable, Hashable {
/**
* Usage data is shared.
@@ -52150,6 +52422,115 @@ public func FfiConverterTypeAppSwitcherTheme_lower(_ value: AppSwitcherTheme) ->
}
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum AppTeamsState: Equatable, Hashable {
+
+ /**
+ * Not signed in.
+ */
+ case signedOut
+ /**
+ * Signed in, but this host does not read teams: only the links.
+ */
+ case unread
+ /**
+ * Being read.
+ */
+ case loading
+ /**
+ * The read failed.
+ */
+ case failed(message: String
+ )
+ /**
+ * The account's teams (maybe none).
+ */
+ case ready(teams: [AppTeamInput]
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppTeamsState: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppTeamsState: FfiConverterRustBuffer {
+ typealias SwiftType = AppTeamsState
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppTeamsState {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .signedOut
+
+ case 2: return .unread
+
+ case 3: return .loading
+
+ case 4: return .failed(message: try FfiConverterString.read(from: &buf)
+ )
+
+ case 5: return .ready(teams: try FfiConverterSequenceTypeAppTeamInput.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: AppTeamsState, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .signedOut:
+ writeInt(&buf, Int32(1))
+
+
+ case .unread:
+ writeInt(&buf, Int32(2))
+
+
+ case .loading:
+ writeInt(&buf, Int32(3))
+
+
+ case let .failed(message):
+ writeInt(&buf, Int32(4))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .ready(teams):
+ writeInt(&buf, Int32(5))
+ FfiConverterSequenceTypeAppTeamInput.write(teams, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamsState_lift(_ buf: RustBuffer) throws -> AppTeamsState {
+ return try FfiConverterTypeAppTeamsState.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppTeamsState_lower(_ value: AppTeamsState) -> RustBuffer {
+ return FfiConverterTypeAppTeamsState.lower(value)
+}
+
+
// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
@@ -58014,6 +58395,30 @@ fileprivate struct FfiConverterOptionTypeAppStreamDisplay: FfiConverterRustBuffe
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppTeamsInput: FfiConverterRustBuffer {
+ typealias SwiftType = AppTeamsInput?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppTeamsInput.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppTeamsInput.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -61848,6 +62253,56 @@ fileprivate struct FfiConverterSequenceTypeAppTabView: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeAppTeamInput: FfiConverterRustBuffer {
+ typealias SwiftType = [AppTeamInput]
+
+ public static func write(_ value: [AppTeamInput], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeAppTeamInput.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppTeamInput] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [AppTeamInput]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeAppTeamInput.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeAppTeamPersonInput: FfiConverterRustBuffer {
+ typealias SwiftType = [AppTeamPersonInput]
+
+ public static func write(_ value: [AppTeamPersonInput], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeAppTeamPersonInput.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppTeamPersonInput] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [AppTeamPersonInput]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeAppTeamPersonInput.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -63018,6 +63473,18 @@ public func appAboutView(input: AppAboutInput) -> AppAboutView {
)
})
}
+/**
+ * The account app for this environment (`CUA_ACCOUNT_APP_URL`, else
+ * `https://app.cua.ai`, or `https://app.staging.cua.ai` under
+ * `CUA_ENV=staging`): billing, plans and team administration, which the
+ * apps open in the browser.
+ */
+public func appAccountAppUrl() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_account_app_url($0
+ )
+})
+}
/**
* The add or replace sheet.
*/
@@ -65351,6 +65818,27 @@ public func appStreamSection(input: AppStreamSectionInput) -> AppStreamSection
)
})
}
+/**
+ * The account's Teams (the organizations of `GET /v1/me` on the Spaces
+ * API for this environment, `api.cua.ai` or `api.staging.cua.ai`), each
+ * with its members and pending invites, read with `account_token`.
+ * Both Spaces apps read Teams here; Settings words them
+ * (`app_settings_page`'s `teams`).
+ */
+public func appTeams(accountToken: String)async throws -> AppTeamsInput {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_spaces_ffi_fn_func_app_teams(FfiConverterString.lower(accountToken)
+ )
+ },
+ pollFunc: ffi_cua_spaces_ffi_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_spaces_ffi_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_spaces_ffi_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeAppTeamsInput_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
/**
* The events one step of the Spaces being created means, at `now_ms`
* (call with the state before it).
@@ -66190,6 +66678,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_about_view() != 65075) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_app_account_app_url() != 9943) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_app_agent_key_form() != 42778) {
return InitializationResult.apiChecksumMismatch
}
@@ -66841,6 +67332,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_stream_section() != 40082) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_app_teams() != 64616) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_app_telemetry_creates() != 25911) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
index 4d7b4ad10f..e72c6d9827 100644
--- a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
+++ b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
@@ -688,6 +688,12 @@ int8_t uniffi_cua_spaces_ffi_fn_func_app_about_restart_daemon(RustBuffer check,
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ABOUT_VIEW
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ABOUT_VIEW
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_about_view(RustBuffer input, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ACCOUNT_APP_URL
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ACCOUNT_APP_URL
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_account_app_url(RustCallStatus *_Nonnull out_status
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_AGENT_KEY_FORM
@@ -1795,6 +1801,11 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_stream_pip_reduce(RustBuffer open,
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_stream_section(RustBuffer input, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TEAMS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TEAMS
+uint64_t uniffi_cua_spaces_ffi_fn_func_app_teams(RustBuffer account_token
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TELEMETRY_CREATES
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TELEMETRY_CREATES
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_telemetry_creates(RustBuffer state, RustBuffer action, int64_t now_ms, RustCallStatus *_Nonnull out_status
@@ -2448,6 +2459,12 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_about_restart_daemon(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ABOUT_VIEW
uint16_t uniffi_cua_spaces_ffi_checksum_func_app_about_view(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ACCOUNT_APP_URL
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ACCOUNT_APP_URL
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_account_app_url(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_AGENT_KEY_FORM
@@ -3750,6 +3767,12 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_stream_pip_reduce(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_STREAM_SECTION
uint16_t uniffi_cua_spaces_ffi_checksum_func_app_stream_section(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_TEAMS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_TEAMS
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_teams(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_TELEMETRY_CREATES
diff --git a/scripts/docs-generators/cua-sdk.ts b/scripts/docs-generators/cua-sdk.ts
index d9ca50bcce..10e48b6391 100644
--- a/scripts/docs-generators/cua-sdk.ts
+++ b/scripts/docs-generators/cua-sdk.ts
@@ -997,23 +997,14 @@ export const PAGES: PageSpec[] = [
spaces: true,
},
{
- slug: 'spaces/app-core/billing',
- title: 'Cua Cloud billing',
- description: 'The Billing row in Settings and the out-of-credit notice on a refused cloud Space.',
+ slug: 'spaces/account-app-core',
+ title: 'App core: billing, relay usage and Teams',
+ description: 'The Billing and Relay usage rows in Settings, the out-of-credit and relay allowance notices, and the Teams section.',
intro:
- 'The apps take no payment details: the website handles credit and cards. `app_billing_status` turns `Fleet.billing_status` into the core\'s `AppBillingStatus`, which Settings shows as the credit left and "Manage billing" (the website billing page). A cloud Space that Fleet refuses for want of credit (`CuaError::CloudCreditExhausted`) shows `AppCreditNotice`: one line and "Add credit", which opens the same page. Local Spaces never depend on it.',
+ 'The apps take no payment details: the website handles credit and cards. `app_billing_status` turns `Fleet.billing_status` into the core\'s `AppBillingStatus`, which Settings shows as the credit left and "Manage billing" (the website billing page). A cloud Space that Fleet refuses for want of credit (`CuaError::CloudCreditExhausted`) shows `AppCreditNotice`: one line and "Add credit", which opens the same page. Local Spaces never depend on it. `app_relay_usage` reads the account\'s relay allowance this month from the relay (`GET /v1/usage`, as `cua usage` does); `app_relay_usage_view` derives the Settings row and, past the allowance, `AppRelayAllowanceNotice`: one line with Upgrade. Nothing stops at the limit. `app_teams` turns the account\'s `AppTeamsInput` into the Teams rows of Settings: the signed-in state, each team with its people and the role of each.',
items: ['AppCreditNotice'],
- prefixes: ['AppBilling', 'app_billing_'],
- spaces: true,
- },
- {
- slug: 'spaces/app-core/relay',
- title: 'Relay usage',
- description: 'The Relay usage row in Settings and the notice past the monthly relay allowance.',
- intro:
- '`app_relay_usage` reads the account\'s relay allowance this month from the relay (`GET /v1/usage`, as `cua usage` does) with the session\'s `Devices` and an account token. `app_relay_usage_view` derives the Settings row (`AppRelayUsageView`) and, past the allowance, `AppRelayAllowanceNotice`: one line with Upgrade, dismissed per month and reason. Nothing stops at the limit.',
- items: [],
- prefixes: ['AppRelay', 'app_relay_'],
+ prefixes: ['AppBilling', 'app_billing_', 'AppRelay', 'app_relay_', 'AppTeam', 'app_teams'],
+ catalog: true,
spaces: true,
},
{