Skip to content

armgit / cua

Public Imported from GitHub
0

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

fix(spaces): Teams clients use Keycloak orgs via the Spaces API (#5157)

Francesco Bonacci49a89ff38a06
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.ts
index a6d449a018..f6f5df339d 100644
--- a/apps/cua-spaces-desktop/src/bridge/methods.ts
+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts
@@ -29,7 +29,7 @@ export const METHODS = [
"about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",
"devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",
- "devices.revokePairingCode", "storage.get", "storage.run",
+ "devices.revokePairingCode", "teams.list", "storage.get", "storage.run",
"notifications.list", "notifications.markAllRead",
"telemetry.track", "spaces.usage", "spaces.windows", "stream.pip",
"spaces.thumbnail",
diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.ts
index c18208bb7d..49378aeac2 100644
--- a/apps/cua-spaces-desktop/src/bridge/settings.ts
+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts
@@ -9,7 +9,7 @@
// runtimes, launch at login, usage data, the update channel, the
// experiments, Welcome's "Show again", the coding agents (`model.agents`)
// and the Keyvault's switches (`model.keyvault`).
-import type { AppLoginItemStatus, AppSettingsInput, AppTelemetryInput } from "../native/generated/index";
+import type { AppLoginItemStatus, AppSettingsInput, AppTeamInput, AppTelemetryInput } from "../native/generated/index";
import type { AppModel } from "../model/app-model";
import { words } from "../model/errors";
import { bounded } from "../model/time";
@@ -179,6 +179,17 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
};
return {
+ // "Add a machine" and "Share": the account's Teams (Settings, Teams) and the current one.
+ "teams.list": async () => {
+ if (model.servicesIn) await bounded(10, () => model.teams.reload());
+ const input = model.teams.input();
+ const state = input.state as { tag: string; inner?: { teams?: AppTeamInput[] } };
+ const teams = state.tag === "Ready" ? (state.inner?.teams ?? []) : [];
+ return {
+ teams: teams.map((t) => ({ id: t.id, alias: t.alias, name: t.name, role: t.role, plan: t.plan })),
+ currentTeamId: input.currentTeamId ?? null,
+ };
+ },
"settings.get": async () => {
await load();
return settingsState(model, parts());
diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.ts
index 10d9f5acbc..419072b318 100644
--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts
+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts
@@ -188,6 +188,7 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
["devices.createPairingCode", { team: null }],
["devices.pairingCodes", {}],
["devices.revokePairingCode", { id: "pc_fixture1" }],
+ ["teams.list", {}],
["storage.get", {}],
["storage.run", { request: { kind: "clear-cache" } }],
["notifications.list", {}],
diff --git a/apps/cua-spaces-desktop/test/host-fixtures.ts b/apps/cua-spaces-desktop/test/host-fixtures.ts
index 8b7f024b7d..d16e0811af 100644
--- a/apps/cua-spaces-desktop/test/host-fixtures.ts
+++ b/apps/cua-spaces-desktop/test/host-fixtures.ts
@@ -305,7 +305,7 @@ export const HOST_METHODS = [
"volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal",
"about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine",
- "devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode",
+ "devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode", "teams.list",
"storage.get", "storage.run", "notifications.list", "notifications.markAllRead",
"host.setUp", "host.action", "host.openSettings", "settings.get", "settings.choose",
"onboarding.get", "onboarding.complete",
@@ -317,7 +317,7 @@ export const HOST_OPS = [
"volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal",
"about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine",
- "devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode",
+ "devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode", "teams.list",
"storage.get", "storage.run", "notifications.list", "notifications.markAllRead",
"host.setUp", "host.action", "host.openSettings", "settings.get", "settings.set", "settings.choose", "experiments.set", "session.completeOnboarding",
];
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
index cb2ad42d55..f45272a7df 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
@@ -102,6 +102,16 @@ extension WebUIBridge {
await model.press(row: "launch-at-login-approve")
return NSNull()
+ // "Add a machine" and "Share": the account's Teams (Settings, Teams)
+ // and the current one.
+ case "teams.list":
+ await model.reloadTeams()
+ var teams: [[String: Any]] = []
+ if case .ready(let list) = model.teamsState {
+ teams = list.map { ["id": $0.id, "alias": $0.alias, "name": $0.name, "role": $0.role, "plan": $0.plan] }
+ }
+ return ["teams": teams, "currentTeamId": model.settings.currentTeamId.map { $0 as Any } ?? NSNull()] as [String: Any]
+
// Settings, Devices
case "devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",
"devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index d08de4c100..1ccc2a7718 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -88,7 +88,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",
"devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",
- "devices.revokePairingCode", "storage.get", "storage.run",
+ "devices.revokePairingCode", "teams.list", "storage.get", "storage.run",
"notifications.list", "notifications.markAllRead",
"telemetry.track", "spaces.usage", "spaces.windows", "stream.pip",
// A Space's thumbnail (WebUIBridge+Thumbnails.swift).
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
index 9f966424ee..18ad212846 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
@@ -228,6 +228,7 @@ struct BridgeContractTests {
("loginItem.get", [:]), ("loginItem.set", ["on": true]),
("devices.get", [:]), ("devices.enroll", [:]), ("devices.checkEnrolled", [:]),
("devices.createPairingCode", ["team": NSNull()]), ("devices.pairingCodes", [:]),
+ ("teams.list", [:]),
("devices.revokePairingCode", ["id": "pc_fixture1"]),
("storage.get", [:]), ("storage.run", ["request": ["kind": "clear-cache"]]),
("notifications.list", [:]), ("notifications.markAllRead", [:]),
diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.md
index 5c4b6b0925..20bd5ad512 100644
--- a/apps/cua-spaces-web/src/bridge/README.md
+++ b/apps/cua-spaces-web/src/bridge/README.md
@@ -429,6 +429,7 @@ mechanism. Types are in `contracts/settings.ts`, `contracts/devices.ts` and
| `devices.createPairingCode` | `{ team? }` | `PairingCode` (camelCase: `id`, `code`, `url`, `installSh`, `installPowershell`, `state`, `team`, `createdAt`, `expiresAt`, `usedAt`, `machine`) | `devices_create_pairing_code` | `DevicesRunning.createPairingCode` (the SDK's `Devices.createPairingCode`) |
| `devices.pairingCodes` | `{}` | `PairingCode[]`, newest first, without `code`, `url` and the commands | `devices_pairing_codes` | `DevicesRunning.pairingCodes` |
| `devices.revokePairingCode` | `{ id }` | `null` | `devices_revoke_pairing_code` | `DevicesRunning.revokePairingCode` |
+| `teams.list` | `{}` | `TeamsList` (`teams`: `id`, `alias`, `name`, `role`, `plan`; `currentTeamId`) | `teams_list` | the app's Teams (Settings, Teams) |
| `storage.get` | `{}` | `StorageInput` (`volume_storage`, `volume_mount_status`, `volume_cache_stats` as the tools answer) | `agents_tool` | `StorageModel.load` inputs |
| `storage.run` | `{ request: StorageRequest }` | `DriveCheckInput` for test, save and adopt; else `null` | `agents_tool` (`volume_*`), `drive_reveal`, `host_open_settings` | `StorageModel`'s request runner |
| `notifications.list` | `{}` | `NotificationInput[]` (camelCase) | `agents_tool` `notifications_list` | `PersistentModel.feed` |
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
index 650de99f4f..d83572c83a 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
@@ -118,6 +118,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"devices.createPairingCode": { team: null },
"devices.pairingCodes": {},
"devices.revokePairingCode": { id: "pc_demo0" },
+ "teams.list": {},
"storage.get": {},
"storage.run": { request: { kind: "clear-cache" } },
"notifications.list": {},
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
index 592b9fe45a..bb96aa2595 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
@@ -102,6 +102,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {
"devices.createPairingCode": { team: null },
"devices.pairingCodes": {},
"devices.revokePairingCode": { id: "pc_demo0" },
+ "teams.list": {},
"storage.get": {},
"storage.run": { request: { kind: "clear-cache" } },
"notifications.list": {},
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
index aa65115020..a10b5d07ac 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
@@ -290,6 +290,14 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {
// Listed without the codes, as the relay lists them.
return pairing.map(({ code: c }) => ({ ...c, code: null, url: null, installSh: null, installPowershell: null }));
},
+ // The demo account owns a team on the Teams plan, and is a member of another.
+ "teams.list": () => ({
+ teams: [
+ { id: "0f1e2d3c-0000-4000-8000-0000000000a1", alias: "acme", name: "Acme", role: "owner", plan: "teams" },
+ { id: "0f1e2d3c-0000-4000-8000-0000000000b2", alias: "side", name: "", role: "member", plan: "teams" },
+ ],
+ currentTeamId: null,
+ }),
"devices.revokePairingCode": ({ id }) => {
const p = pairing.find((x) => x.code.id === id);
if (!p) throw new HostError(`no pairing code ${id}`, "not_found");
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index 116b0e01e9..cb313ada90 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -2526,6 +2526,51 @@
"cache"
]
},
+ "TeamsList": {
+ "type": "object",
+ "properties": {
+ "teams": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "alias": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "role": {
+ "type": "string"
+ },
+ "plan": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "alias",
+ "name",
+ "role",
+ "plan"
+ ]
+ }
+ },
+ "currentTeamId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "teams",
+ "currentTeamId"
+ ]
+ },
"VolumeOverview": {
"type": "object",
"properties": {
@@ -4843,6 +4888,9 @@
"type": "string"
}
},
+ "teams.list": {
+ "$ref": "#/$defs/TeamsList"
+ },
"telemetry.track": {
"type": "null"
},
@@ -6239,6 +6287,9 @@
"type": "string"
}
},
+ "teams.list": {
+ "$ref": "#/$defs/TeamsList"
+ },
"telemetry.track": {
"type": "null"
},
diff --git a/apps/cua-spaces-web/src/bridge/contracts/devices.ts b/apps/cua-spaces-web/src/bridge/contracts/devices.ts
index 5c3f21c87a..5e2bf48034 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/devices.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/devices.ts
@@ -270,3 +270,24 @@ export interface ApproveSheetView {
error: string | null;
request: ApproveRequest | null;
}
+
+/** One of the account's Teams (an organization of `GET /v1/me`). */
+export interface TeamChoice {
+ /** The organization id (`team:<id>` shares with it). */
+ id: string;
+ /** Its slug. */
+ alias: string;
+ /** Its display name (empty: use the alias). */
+ name: string;
+ /** `owner`, `admin` or `member`. */
+ role: string;
+ /** `free`, `teams`, ...: team machines need `teams`. */
+ plan: string;
+}
+
+/** `teams.list`: the account's Teams and the one it works in. */
+export interface TeamsList {
+ teams: TeamChoice[];
+ /** The saved current team (Settings, Teams), or null. */
+ currentTeamId: string | null;
+}
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index e5d574c8b2..7c9c441d51 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -23,7 +23,7 @@
*/
import type { AgentDetailInput, AgentEventsPage, AgentOpenFile, AgentSetupRow, PersistentAgent, SpaceAgentRun } from "./agents";
-import type { DeviceInput, DevicesInput, EnrollResult, MachineAccessNotice, PairingCode } from "./devices";
+import type { DeviceInput, DevicesInput, EnrollResult, MachineAccessNotice, PairingCode, TeamChoice, TeamsList } from "./devices";
import type {
CancelOutcome,
DaemonStatus,
@@ -304,6 +304,16 @@ const PairingCodeShape = ref(
}),
);
+const TeamsListShape = ref(
+ "TeamsList",
+ obj<TeamsList>()({
+ teams: list(
+ obj<TeamChoice>()({ id: str, alias: str, name: str, role: str, plan: str }),
+ ),
+ currentTeamId: nullable(str),
+ }),
+);
+
const DriveMountShape = ref(
"DriveMountInput",
obj<DriveMountInput>()({
@@ -832,6 +842,7 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"devices.createPairingCode": PairingCodeShape,
"devices.pairingCodes": list(PairingCodeShape),
"devices.revokePairingCode": nul,
+ "teams.list": TeamsListShape,
"storage.get": StorageShape,
"storage.run": nullable(DriveCheckShape),
"notifications.list": list(NotificationShape),
@@ -1138,6 +1149,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"devices.createPairingCode": PairingCodeShape,
"devices.pairingCodes": list(PairingCodeShape),
"devices.revokePairingCode": nul,
+ "teams.list": TeamsListShape,
"storage.get": StorageShape,
"storage.run": nullable(DriveCheckShape),
"notifications.list": list(NotificationShape),
diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.ts
index 3c7c22273a..66c3451c53 100644
--- a/apps/cua-spaces-web/src/bridge/coverage.ts
+++ b/apps/cua-spaces-web/src/bridge/coverage.ts
@@ -150,6 +150,7 @@ export const HOST_COVERAGE = {
"devices.createPairingCode": { webkit: { methods: ["devices.createPairingCode"] }, tauri: ST["devices.createPairingCode"] },
"devices.pairingCodes": { webkit: { methods: ["devices.pairingCodes"] }, tauri: ST["devices.pairingCodes"] },
"devices.revokePairingCode": { webkit: { methods: ["devices.revokePairingCode"] }, tauri: ST["devices.revokePairingCode"] },
+ "teams.list": { webkit: { methods: ["teams.list"] }, tauri: ST["teams.list"] },
"storage.get": { webkit: { methods: ["storage.get"] }, tauri: ST["storage.get"] },
"storage.run": { webkit: { methods: ["storage.run"] }, tauri: ST["storage.run"] },
// Notifications (ops/notifications.ts).
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index 4b28edcdaa..a5c29efdbe 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -106,7 +106,8 @@ export { useThisMachine, type HostFailure, type HostFormView as HostSetupFormVie
export type { HostFormAction, HostSetupRequest } from "./ops/host-setup";
export type { TelemetrySignal } from "./ops/telemetry";
export { useStartup, type StartupHook } from "./startup";
-export { expiresInText, PAIRING_POLL_MS, pairingUnsupported, usePairingCode, type PairingHook, type PairingPhase } from "./pairing";
+export { defaultTeam, eligibleTeams, teamName, useTeamChoices, type TeamChoices } from "./teams";
+export { expiresInText, FINISHING_SETUP, PAIRING_POLL_MS, pairingUnsupported, usePairingCode, type PairingHook, type PairingPhase } from "./pairing";
export { READY_STARTUP, type StartupAction, type StartupPhase, type StartupState } from "./ops/startup";
export {
CHECKLIST_STEPS,
diff --git a/apps/cua-spaces-web/src/bridge/ops/settings.ts b/apps/cua-spaces-web/src/bridge/ops/settings.ts
index d0ab683f81..894fb83156 100644
--- a/apps/cua-spaces-web/src/bridge/ops/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/settings.ts
@@ -11,7 +11,7 @@
import { UnsupportedOperationError } from "../adapter";
import type { LoginItemStatus } from "../contracts/host";
-import type { DevicesInput, EnrollResult, PairingCode } from "../contracts/devices";
+import type { DevicesInput, EnrollResult, PairingCode, TeamsList } from "../contracts/devices";
import type {
AboutInput,
DriveCacheInput,
@@ -65,6 +65,9 @@ export interface SettingsOperations {
"devices.pairingCodes": { args: Empty; result: PairingCode[] };
/** Revokes an unused pairing code (`pc_…`). */
"devices.revokePairingCode": { args: { id: string }; result: null };
+ /** The account's Teams (organizations of `GET /v1/me`) and the current one:
+ * "Add a machine" and "Share" offer them. */
+ "teams.list": { args: Empty; result: TeamsList };
/** The Cua Volume's storage, mount and cache (`volume_storage`, `volume_mount_status`, `volume_cache_stats`). */
"storage.get": { args: Empty; result: StorageInput };
@@ -93,6 +96,7 @@ export const SETTINGS_OPERATIONS = [
"devices.createPairingCode",
"devices.pairingCodes",
"devices.revokePairingCode",
+ "teams.list",
"storage.get",
"storage.run",
] as const satisfies readonly SettingsOpName[];
@@ -195,6 +199,7 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): string
await invoke("devices_revoke_pairing_code", { id });
return null;
},
+ "teams.list": () => invoke<TeamsList>("teams_list"),
"storage.get": storage,
"storage.run": async ({ request }) => {
@@ -249,6 +254,7 @@ export const SETTINGS_TAURI_COMMANDS = {
"devices.createPairingCode": ["devices_create_pairing_code"],
"devices.pairingCodes": ["devices_pairing_codes"],
"devices.revokePairingCode": ["devices_revoke_pairing_code"],
+ "teams.list": ["teams_list"],
"storage.get": ["get_environment", "agents_tool"],
"storage.run": ["agents_tool", "drive_reveal", "host_open_settings"],
} as const satisfies Record<SettingsOpName, readonly string[]>;
diff --git a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
index cfd06dce20..270da1e842 100644
--- a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
@@ -80,6 +80,7 @@ export const WEBKIT_PAGE_OPS = [
"devices.createPairingCode",
"devices.pairingCodes",
"devices.revokePairingCode",
+ "teams.list",
"storage.get",
"storage.run",
"notifications.list",
@@ -252,6 +253,7 @@ export function webkitPageOps(request: Request, toHostStatus: (h: WkHostState) =
"devices.createPairingCode": ({ team }) => request("devices.createPairingCode", { team: team ?? null }),
"devices.pairingCodes": list("devices.pairingCodes"),
"devices.revokePairingCode": none("devices.revokePairingCode"),
+ "teams.list": call("teams.list"),
"storage.get": call("storage.get"),
"storage.run": call("storage.run"),
"notifications.list": list("notifications.list"),
diff --git a/apps/cua-spaces-web/src/bridge/pairing.ts b/apps/cua-spaces-web/src/bridge/pairing.ts
index ca295510a9..28f9fc1b9c 100644
--- a/apps/cua-spaces-web/src/bridge/pairing.ts
+++ b/apps/cua-spaces-web/src/bridge/pairing.ts
@@ -7,6 +7,11 @@
* the other computer uses it, and revokes it on request
* (`devices.revokePairingCode`). The relay holds the code's state; this
* only asks.
+ *
+ * With `team` (an organization id) the machine that used the code is then
+ * made a team machine (`sharing.share` with `team:<id>`): pairing alone
+ * never puts a machine in a team. Right after a Teams checkout that can take
+ * up to a minute ("Finishing setup…"); the host retries meanwhile.
*/
import { useEffect, useRef, useState } from "react";
@@ -26,8 +31,16 @@ export interface PairingState {
code: PairingCode | null;
/** Why no code could be made; `unsupported`: the host or relay can't make them. */
error: { message: string; unsupported: boolean } | null;
+ /**
+ * With a `team`, after the code was used: `adding` (show "Finishing
+ * setup…"), `added`, or `failed` with the reason. Null otherwise.
+ */
+ team?: { phase: "adding" | "added" | "failed"; error: string | null } | null;
}
+/** What "Add a machine" shows while a paired machine joins its team. */
+export const FINISHING_SETUP = "Finishing setup…";
+
export interface PairingHook extends PairingState {
/** Unix ms, ticking each second while a code is active (for the countdown). */
now: number;
@@ -138,7 +151,10 @@ export function usePairingCode({
const code: PairingCode = { ...s.code, state: listed.state, usedAt: listed.usedAt, machine: listed.machine };
return { ...s, phase, code };
});
- if (listed.state === "used") usedRef.current?.(listed);
+ if (listed.state === "used") {
+ usedRef.current?.(listed);
+ if (team && listed.machine) void addToTeam(listed.machine);
+ }
} catch {
// A missed read: the next one tries again.
} finally {
@@ -150,7 +166,19 @@ export function usePairingCode({
stopped = true;
clearInterval(timer);
};
- }, [adapter, watching, pollMs]);
+ }, [adapter, watching, pollMs, team]);
+
+ // The machine that used the code becomes a machine of `team`.
+ const addToTeam = async (machine: string) => {
+ if (!adapter || !team) return;
+ setState((s) => ({ ...s, team: { phase: "adding", error: null } }));
+ try {
+ await adapter.call("sharing.share", { spaceId: `relay:${machine}`, who: `team:${team}`, role: "editor" });
+ setState((s) => ({ ...s, team: { phase: "added", error: null } }));
+ } catch (e: unknown) {
+ setState((s) => ({ ...s, team: { phase: "failed", error: e instanceof Error ? e.message : String(e) } }));
+ }
+ };
const revoke = async () => {
const code = state.code;
diff --git a/apps/cua-spaces-web/src/bridge/teams.ts b/apps/cua-spaces-web/src/bridge/teams.ts
new file mode 100644
index 0000000000..e959bb33fb
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/teams.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The account's Teams for "Add a machine" and "Share" (`teams.list`: the
+ * organizations of `GET /v1/me` and the current team of Settings, Teams).
+ * Only teams on the Teams plan (team machines) where the account is an
+ * owner or admin can take a machine, so only those are offered.
+ */
+
+import { useEffect, useState } from "react";
+
+import type { TeamChoice, TeamsList } from "./contracts/devices";
+import { useBridge } from "./hooks";
+
+/** The teams a machine or Space can be added to: Teams plan, owner or admin. */
+export function eligibleTeams(list: TeamsList | null | undefined): TeamChoice[] {
+ return (list?.teams ?? []).filter((t) => t.plan === "teams" && (t.role === "owner" || t.role === "admin"));
+}
+
+/** The current team when it can take machines, else none. */
+export function defaultTeam(list: TeamsList | null | undefined): string | null {
+ const id = list?.currentTeamId ?? null;
+ return id && eligibleTeams(list).some((t) => t.id === id) ? id : null;
+}
+
+/** A team's name: its display name, else its alias. */
+export function teamName(t: Pick<TeamChoice, "name" | "alias" | "id">): string {
+ return t.name || t.alias || t.id;
+}
+
+export interface TeamChoices {
+ /** The teams offered (current team first). */
+ teams: TeamChoice[];
+ /** The current team, when it is offered. */
+ current: string | null;
+ /** Every team of the account (to name `team:<id>` rows). */
+ all: TeamChoice[];
+}
+
+const NONE: TeamChoices = { teams: [], current: null, all: [] };
+
+/** The teams to offer, read once while `enabled` (none on a host without Teams). */
+export function useTeamChoices(enabled: boolean): TeamChoices {
+ const { data: adapter } = useBridge();
+ const [choices, setChoices] = useState<TeamChoices>(NONE);
+ useEffect(() => {
+ if (!adapter || !enabled) return;
+ let stopped = false;
+ adapter.call("teams.list", {}).then(
+ (list) => {
+ if (stopped) return;
+ const current = defaultTeam(list);
+ const teams = eligibleTeams(list).sort((a, b) => Number(b.id === current) - Number(a.id === current));
+ setChoices({ teams, current, all: list.teams });
+ },
+ () => {
+ if (!stopped) setChoices(NONE);
+ },
+ );
+ return () => {
+ stopped = true;
+ };
+ }, [adapter, enabled]);
+ return choices;
+}
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index 4d1cb4d6f2..1af35f9001 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -116,6 +116,7 @@ export const WEBKIT_METHODS = [
"devices.createPairingCode",
"devices.pairingCodes",
"devices.revokePairingCode",
+ "teams.list",
"storage.get",
"storage.run",
"notifications.list",
diff --git a/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx b/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx
index 873769eb83..d1d1836ff5 100644
--- a/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx
+++ b/apps/cua-spaces-web/src/components/__tests__/add-machine-dialog.test.tsx
@@ -27,7 +27,7 @@ function host(options: DemoOptions = {}, override: Record<string, (args: Record<
return { adapter, calls };
}
-function Harness() {
+function Harness({ team = null }: { team?: string | null }) {
const { data: machines = [], setupGuide } = useMachines();
return (
<>
@@ -36,15 +36,15 @@ function Harness() {
<li key={m.id}>{m.name}</li>
))}
</ul>
- <AddMachineDialog open onOpenChange={() => {}} guide={setupGuide} pollMs={20} />
+ <AddMachineDialog open onOpenChange={() => {}} guide={setupGuide} pollMs={20} team={team} />
</>
);
}
-async function mount(adapter: DataAdapter) {
+async function mount(adapter: DataAdapter, team: string | null = null) {
render(
<BridgeProvider adapter={adapter} core={unavailableCore("test: no core")}>
- <Harness />
+ <Harness team={team} />
</BridgeProvider>,
);
await act(() => new Promise((r) => setTimeout(r, 10)));
@@ -83,6 +83,73 @@ describe("Add a machine by link or QR code", () => {
expect(screen.queryByText("Revoke link")).toBeNull();
});
+ it("adds the new machine to the team once it joined (pairing alone does not)", async () => {
+ const org = "0f1e2d3c-0000-4000-8000-000000000001";
+ const shared: Record<string, unknown>[] = [];
+ let finish: () => void = () => {};
+ const { adapter } = host({}, {
+ "sharing.share": (args) => {
+ shared.push(args);
+ // A plan bought a moment ago: the host is still retrying.
+ return new Promise((r) => (finish = () => r([])));
+ },
+ });
+ await mount(adapter, org);
+ await waitFor(() => expect(document.querySelector('[data-pairing-team="adding"]')?.textContent).toContain("Finishing setup…"), { timeout: 3000 });
+ expect(shared).toHaveLength(1);
+ expect(shared[0]).toMatchObject({ who: `team:${org}`, role: "editor" });
+ expect(String(shared[0]?.spaceId)).toMatch(/^relay:/);
+ finish();
+ await waitFor(() => expect(document.querySelector('[data-pairing-team="added"]')?.textContent).toMatch(/Your team can use it now\./));
+ });
+
+ it("lets you choose the team, the current one by default, and adds the machine to it", async () => {
+ const acme = "0f1e2d3c-0000-4000-8000-0000000000a1";
+ const shared: Record<string, unknown>[] = [];
+ const { adapter } = host({}, {
+ "teams.list": () =>
+ Promise.resolve({
+ teams: [
+ { id: acme, alias: "acme", name: "Acme", role: "owner", plan: "teams" },
+ { id: "0f1e2d3c-0000-4000-8000-0000000000b2", alias: "side", name: "", role: "member", plan: "teams" },
+ ],
+ currentTeamId: acme,
+ }),
+ "sharing.share": (args) => {
+ shared.push(args);
+ return Promise.resolve([]);
+ },
+ });
+ await mount(adapter);
+ // Offered: just me, or Acme (the member-only team is not); Acme is the current team.
+ await waitFor(() => expect(document.querySelector("[data-add-machine-team]")?.getAttribute("data-add-machine-team")).toBe(acme));
+ await waitFor(() => expect(document.querySelector('[data-pairing-team="added"]')).toBeTruthy(), { timeout: 3000 });
+ expect(shared[0]).toMatchObject({ who: `team:${acme}` });
+ });
+
+ it("adds the machine to no team when there is none to choose", async () => {
+ const shared: unknown[] = [];
+ const { adapter } = host({}, {
+ "teams.list": () => Promise.resolve({ teams: [], currentTeamId: null }),
+ "sharing.share": (args) => {
+ shared.push(args);
+ return Promise.resolve([]);
+ },
+ });
+ await mount(adapter);
+ await waitFor(() => expect(phase()).toBe("used"), { timeout: 3000 });
+ expect(document.querySelector("[data-add-machine-team]")).toBeNull();
+ expect(shared).toHaveLength(0);
+ });
+
+ it("says when the machine could not join the team", async () => {
+ const { adapter } = host({}, {
+ "sharing.share": () => Promise.reject(new Error("Teams are not available on this server yet. Try again later, or update Cua.")),
+ });
+ await mount(adapter, "acme");
+ await waitFor(() => expect(document.querySelector('[data-pairing-team="failed"]')?.textContent).toMatch(/isn't on your team yet: Teams are not available/), { timeout: 3000 });
+ });
+
it("revokes the link, then makes a new one", async () => {
const { adapter, calls } = host();
await mount(adapter);
diff --git a/apps/cua-spaces-web/src/components/__tests__/share-sheet-teams.test.tsx b/apps/cua-spaces-web/src/components/__tests__/share-sheet-teams.test.tsx
new file mode 100644
index 0000000000..d1f280b98b
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/__tests__/share-sheet-teams.test.tsx
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { BridgeProvider, defaultTeam, eligibleTeams, useShareSheet } from "@/bridge";
+import type { DataAdapter } from "@/bridge/adapter";
+import { createDemoAdapter } from "@/bridge/adapters/demo";
+import type { CoreClient } from "@/bridge/core";
+import type { ShareInput, ShareSheetAction, ShareSheetState } from "@/bridge/contracts/share";
+import ShareSheet from "@/components/share-sheet";
+
+afterEach(cleanup);
+
+const ACME = "0f1e2d3c-0000-4000-8000-0000000000a1";
+const TEAMS = {
+ teams: [
+ { id: "0f1e2d3c-0000-4000-8000-0000000000c3", alias: "beta", name: "Beta", role: "admin", plan: "teams" },
+ { id: ACME, alias: "acme", name: "Acme", role: "owner", plan: "teams" },
+ // A member cannot add machines; a free team has no team machines.
+ { id: "0f1e2d3c-0000-4000-8000-0000000000b2", alias: "side", name: "", role: "member", plan: "teams" },
+ { id: "0f1e2d3c-0000-4000-8000-0000000000d4", alias: "free", name: "Free", role: "owner", plan: "free" },
+ ],
+ currentTeamId: ACME,
+};
+
+/** A small stand-in for the core's share state machine (`share.*`). */
+function shareCore(): CoreClient {
+ const reduce = (input: ShareInput, s: ShareSheetState, a: ShareSheetAction): ShareSheetState => {
+ switch (a.type) {
+ case "set-who":
+ return { ...s, who: a.who };
+ case "submit":
+ return { ...s, busy: true, request: { kind: "share", space: input.spaceId, who: s.who, role: s.role } };
+ case "done":
+ return { ...s, busy: false, who: "", request: null };
+ case "failed":
+ return { ...s, busy: false, error: a.error, request: null };
+ default:
+ return s;
+ }
+ };
+ const call = <T,>(method: string, args: Record<string, unknown> = {}): T => {
+ const input = args.input as ShareInput;
+ const state = args.state as ShareSheetState;
+ switch (method) {
+ case "share.initial":
+ return { who: "", role: "viewer", busy: false, error: null, request: null } as T;
+ case "share.reduce":
+ return reduce(input, state, args.action as ShareSheetAction) as T;
+ case "share.view":
+ return {
+ title: `Share ${input.spaceName}`,
+ rows: input.shares.map((r) => ({ who: r.who, role: r.role, connected: false })),
+ emptyText: "Not shared",
+ who: state.who,
+ whoPlaceholder: "Email",
+ hint: null,
+ role: state.role,
+ roles: [{ id: "viewer", label: "Can view" }, { id: "editor", label: "Can use" }],
+ shareLabel: "Share",
+ canShare: state.who !== "",
+ removeLabel: "Remove",
+ doneLabel: "Done",
+ disabledReason: null,
+ busy: state.busy,
+ error: state.error,
+ request: state.request,
+ } as T;
+ default:
+ throw new Error(`no ${method}`);
+ }
+ };
+ return { status: "ready", methods: ["share.initial", "share.reduce", "share.view"], call, tryCall: () => undefined };
+}
+
+function host() {
+ const base = createDemoAdapter({ latencyMs: 0, stepMs: 0, signedIn: true, onboarded: true });
+ const shared: Record<string, unknown>[] = [];
+ const adapter = Object.assign(Object.create(base) as DataAdapter, {
+ call: ((op: string, args: Record<string, unknown>) => {
+ if (op === "teams.list") return Promise.resolve(TEAMS);
+ if (op === "sharing.list") return Promise.resolve([]);
+ if (op === "sharing.share") {
+ shared.push(args);
+ return Promise.resolve([{ who: args.who, role: "editor" }]);
+ }
+ return (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);
+ }) as DataAdapter["call"],
+ });
+ return { adapter, shared };
+}
+
+function Opener() {
+ const { open } = useShareSheet();
+ return (
+ <button type="button" onClick={() => void open({ id: "relay:abc", name: "Build box", sdk: undefined }, true)}>
+ open
+ </button>
+ );
+}
+
+describe("Teams in Share and Add a machine", () => {
+ it("offers only teams that can take machines, the current one by default", () => {
+ expect(eligibleTeams(TEAMS).map((t) => t.alias)).toEqual(["beta", "acme"]);
+ expect(defaultTeam(TEAMS)).toBe(ACME);
+ expect(defaultTeam({ ...TEAMS, currentTeamId: "0f1e2d3c-0000-4000-8000-0000000000b2" })).toBeNull();
+ });
+
+ it("shares a Space with a team without typing team:<id>, and names the team's row", async () => {
+ const { adapter, shared } = host();
+ render(
+ <BridgeProvider adapter={adapter} core={shareCore()}>
+ <Opener />
+ <ShareSheet />
+ </BridgeProvider>,
+ );
+ await act(() => new Promise((r) => setTimeout(r, 10)));
+ fireEvent.click(screen.getByText("open"));
+ await waitFor(() => expect(document.querySelector("[data-share-teams]")).toBeTruthy());
+ const offered = [...document.querySelectorAll("[data-share-team]")].map((b) => b.textContent);
+ // The current team first; no member-only or free team.
+ expect(offered).toEqual(["Share with Acme", "Share with Beta"]);
+ fireEvent.click(screen.getByText("Share with Acme"));
+ await waitFor(() => expect(shared).toHaveLength(1));
+ expect(shared[0]).toMatchObject({ spaceId: "relay:abc", who: `team:${ACME}` });
+ await waitFor(() => expect(document.querySelector(`[data-share-row="team:${ACME}"]`)?.textContent).toContain("Acme (team)"));
+ // Shared with Acme: only Beta is offered now.
+ expect([...document.querySelectorAll("[data-share-team]")].map((b) => b.textContent)).toEqual(["Share with Beta"]);
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx b/apps/cua-spaces-web/src/components/add-machine-dialog.tsx
index d85abb0e93..4f405fecec 100644
--- a/apps/cua-spaces-web/src/components/add-machine-dialog.tsx
+++ b/apps/cua-spaces-web/src/components/add-machine-dialog.tsx
@@ -2,13 +2,14 @@
// Copyright (c) 2026 Cua AI, Inc.
import { CheckIcon, ChevronRightIcon, CopyIcon, ExternalLinkIcon, LoaderCircleIcon } from "lucide-react";
-import { useState, type ReactNode } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import { encode } from "uqr";
-import { expiresInText, useMachines, usePairingCode, useSession, type HostFormField, type HostSetupGuide, type Machine, type PairingHook } from "@/bridge";
+import { expiresInText, FINISHING_SETUP, teamName, useMachines, useTeamChoices, usePairingCode, useSession, type HostFormField, type HostSetupGuide, type Machine, type PairingHook } from "@/bridge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";
import { Segmented } from "@/components/ui/segmented";
+import { Select } from "@/components/ui/select";
import { toast } from "@/components/ui/toast";
import { cn } from "@/lib/utils";
@@ -40,12 +41,15 @@ export function AddMachineDialog({
onOpenChange,
guide,
pollMs,
+ team = null,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
guide: HostSetupGuide;
/** How often to ask whether the link was used (tests). */
pollMs?: number;
+ /** The team (organization id) chosen at first; default: the current team, when it can take machines. */
+ team?: string | null;
}) {
const { data: session, signIn } = useSession();
const { data: listed, refresh } = useMachines();
@@ -54,7 +58,15 @@ export function AddMachineDialog({
// Signed in but not enrolled: this device can't vouch for a new machine
// (known once the machines are read).
const notice = machines.find((m) => m.current)?.accessNotice ?? null;
- const pairing = usePairingCode({ open, enabled: signedIn && listed !== undefined && !notice, pollMs, onUsed: () => void refresh().catch(() => {}) });
+ // Which team the new machine joins (none: just this account). The
+ // account's teams that can take machines, the current one first.
+ const choices = useTeamChoices(open && signedIn);
+ const [picked, setPicked] = useState<string | null | undefined>(undefined);
+ useEffect(() => {
+ if (!open) setPicked(undefined);
+ }, [open]);
+ const chosen = picked !== undefined ? picked : (team ?? choices.current);
+ const pairing = usePairingCode({ open, enabled: signedIn && listed !== undefined && !notice, pollMs, team: chosen, onUsed: () => void refresh().catch(() => {}) });
const fail = (title: string) => (e: unknown) => toast(title, { description: e instanceof Error ? e.message : String(e) });
// Any reason there is no link: the manual steps are the way, so show them.
@@ -90,7 +102,24 @@ export function AddMachineDialog({
</Button>
</Notice>
) : (
- <PairingPanel pairing={pairing} machines={machines} />
+ <>
+ {choices.teams.length > 0 && pairing.phase !== "used" ? (
+ <div className="mt-4 flex items-center gap-2 text-[13px]" data-add-machine-team={chosen ?? "me"}>
+ <span className="text-muted-foreground">Add it for</span>
+ <Select
+ aria-label="Add it for"
+ className="h-8 min-w-40"
+ value={chosen ?? "me"}
+ options={[
+ { value: "me", label: "Just me" },
+ ...choices.teams.map((t) => ({ value: t.id, label: `${teamName(t)} (team)` })),
+ ]}
+ onValueChange={(v) => setPicked(v === "me" ? null : v)}
+ />
+ </div>
+ ) : null}
+ <PairingPanel pairing={pairing} machines={machines} />
+ </>
)}
{pairing.phase === "used" ? null : <ManualSteps guide={guide} open={manualOnly} />}
@@ -127,10 +156,25 @@ function PairingPanel({ pairing, machines }: { pairing: PairingHook; machines: M
if (phase === "used") {
const name = machines.find((m) => m.id === code.machine)?.name;
+ const team = pairing.team;
+ if (team?.phase === "adding") {
+ return (
+ <div className="mt-5 flex items-center gap-2 text-[13px] text-muted-foreground" data-pairing-team="adding">
+ <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden /> {FINISHING_SETUP}
+ </div>
+ );
+ }
return (
- <div className="mt-5 flex items-center gap-2.5 rounded-lg border bg-card px-3 py-3 text-[13px]" data-pairing-added>
+ <div className="mt-5 flex items-center gap-2.5 rounded-lg border bg-card px-3 py-3 text-[13px]" data-pairing-added data-pairing-team={team?.phase}>
<CheckIcon className="size-4 shrink-0 text-success" aria-hidden />
- <span>{name ? `Added ${name}.` : "Added the computer."} It shows in your machines.</span>
+ <span>
+ {name ? `Added ${name}.` : "Added the computer."}{" "}
+ {team?.phase === "added"
+ ? "Your team can use it now."
+ : team?.phase === "failed"
+ ? `It isn't on your team yet: ${team.error ?? "something went wrong"}`
+ : "It shows in your machines."}
+ </span>
</div>
);
}
diff --git a/apps/cua-spaces-web/src/components/share-sheet.tsx b/apps/cua-spaces-web/src/components/share-sheet.tsx
index 4b815e098a..b71b2609dc 100644
--- a/apps/cua-spaces-web/src/components/share-sheet.tsx
+++ b/apps/cua-spaces-web/src/components/share-sheet.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { useShareSheet } from "@/bridge";
+import { teamName, useShareSheet, useTeamChoices } from "@/bridge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
@@ -12,15 +12,29 @@ import { cn } from "@/lib/utils";
* "Share": one line per person with a role menu, an email field and Done,
* as the SwiftUI app's `ShareSheetView`. Every word and step is the app
* core's (`share.view`); sharing asks for presence in the daemon before it
- * reaches the relay.
+ * reaches the relay. "Share with team" offers the account's teams that can
+ * take machines (owner or admin, Teams plan), the current team first: it
+ * shares with `team:<id>`, as typing it would.
*/
export default function ShareSheet() {
const { session, sharing } = useShareSheet();
+ const choices = useTeamChoices(Boolean(session?.input.signedIn && session.input.shareable));
if (!session || !sharing) return null;
const v = session.view;
const locked = v.busy || v.disabledReason !== null;
const roles = v.roles.map((r) => ({ value: r.id, label: r.label }));
const send = sharing.send.bind(sharing);
+ const shared = new Set(v.rows.map((r) => r.who));
+ const offered = choices.teams.filter((t) => !shared.has(`team:${t.id}`));
+ const shareWithTeam = async (id: string) => {
+ await send({ type: "set-who", who: `team:${id}` });
+ await send({ type: "submit" });
+ };
+ // `team:<id>` rows read as the team's name.
+ const label = (who: string) => {
+ const t = who.startsWith("team:") ? choices.all.find((x) => x.id === who.slice(5)) : undefined;
+ return t ? `${teamName(t)} (team)` : who;
+ };
return (
<Dialog open onOpenChange={(open) => !open && sharing.close()}>
<DialogPopup data-share-sheet className="w-[min(520px,calc(100vw-2rem))]">
@@ -56,6 +70,15 @@ export default function ShareSheet() {
{v.shareLabel}
</Button>
</form>
+ {offered.length > 0 && v.disabledReason === null ? (
+ <div className="mt-3 flex flex-wrap items-center gap-2" data-share-teams>
+ {offered.map((t) => (
+ <Button key={t.id} size="sm" variant="outline" disabled={v.busy} onClick={() => void shareWithTeam(t.id)} data-share-team={t.id}>
+ Share with {teamName(t)}
+ </Button>
+ ))}
+ </div>
+ ) : null}
{v.hint ? (
<p className="mt-1.5 text-xs text-muted-foreground" data-share-hint>
{v.hint}
@@ -74,7 +97,7 @@ export default function ShareSheet() {
className={cn("size-1.5 shrink-0 rounded-full", row.connected ? "bg-emerald-500" : "bg-muted-foreground/40")}
title={row.connected ? "Connected now" : undefined}
/>
- <span className="min-w-0 flex-1 truncate text-[13px]">{row.who}</span>
+ <span className="min-w-0 flex-1 truncate text-[13px]">{label(row.who)}</span>
{locked ? (
<span className="text-xs text-muted-foreground">{roles.find((r) => r.value === row.role)?.label ?? row.role}</span>
) : (
diff --git a/apps/cua-spaces/src-tauri/src/commands.rs b/apps/cua-spaces/src-tauri/src/commands.rs
index d889c82f30..b25f9cecc9 100644
--- a/apps/cua-spaces/src-tauri/src/commands.rs
+++ b/apps/cua-spaces/src-tauri/src/commands.rs
@@ -998,6 +998,12 @@ pub async fn devices_create_pairing_code(
state.0.devices()?.create_pairing_code(team).await
}
+/// The account's Teams, for "Add a machine" and "Share".
+#[tauri::command]
+pub async fn teams_list(state: State<'_, AppState>) -> CmdResult<crate::devices::TeamsListView> {
+ state.0.devices()?.teams().await
+}
+
/// The account's pairing codes, newest first (without the codes).
#[tauri::command]
pub async fn devices_pairing_codes(
diff --git a/apps/cua-spaces/src-tauri/src/devices.rs b/apps/cua-spaces/src-tauri/src/devices.rs
index 2a3fed34c3..eac1380a24 100644
--- a/apps/cua-spaces/src-tauri/src/devices.rs
+++ b/apps/cua-spaces/src-tauri/src/devices.rs
@@ -257,8 +257,11 @@ impl DevicesService {
}
/// Makes a one-time code (link, QR code, install commands) that adds
- /// another computer to the account, or to `team`, from this enrolled
- /// device. It expires after 30 minutes.
+ /// another computer to the account, from this enrolled device. It
+ /// expires after 30 minutes. With `team` (an organization id) the code
+ /// is the same: the relay's own teams are retired, and the machine
+ /// becomes a team machine once it joined (the web UI shares it with
+ /// `team:<id>`, through the Spaces API).
pub async fn create_pairing_code(
&self,
team: Option<String>,
@@ -266,13 +269,46 @@ impl DevicesService {
let (relay, token) = self.account_relay().await?;
let req = PairingCodeRequest {
name: None,
- team,
+ team: None,
ttl_secs: None,
};
- let code = relay.create_pairing_code(&token, &req).await.map_err(err)?;
+ let mut code = relay.create_pairing_code(&token, &req).await.map_err(err)?;
+ code.team = team.filter(|t| !t.trim().is_empty());
Ok(PairingCodeView::new(code, self.auth.relay_url()))
}
+ /// The account's Teams (the organizations of `GET /v1/me` on the Spaces
+ /// API), for "Add a machine" and "Share". This app keeps no current
+ /// team, so none is chosen.
+ pub async fn teams(&self) -> Result<TeamsListView, String> {
+ let token = self.tokens.access_token().await.map_err(err)?;
+ let me = cua_host::spaces_api::SpacesApiClient::current()
+ .map_err(err)?
+ .me(&token)
+ .await
+ .map_err(err)?;
+ Ok(TeamsListView {
+ teams: me
+ .orgs
+ .into_iter()
+ .map(|o| TeamChoiceView {
+ // Team machines decide what can be offered: the API's
+ // features when it lists them, else the plan.
+ plan: if o.has("team_machines") {
+ "teams".into()
+ } else {
+ o.plan
+ },
+ id: o.id,
+ alias: o.alias,
+ name: o.name,
+ role: o.role,
+ })
+ .collect(),
+ current_team_id: None,
+ })
+ }
+
/// The account's pairing codes, newest first (without the codes).
pub async fn pairing_codes(&self) -> Result<Vec<PairingCodeView>, String> {
let (relay, token) = self.account_relay().await?;
@@ -324,3 +360,22 @@ impl PresenceGate for OsPresence<'_> {
pub fn presence_needs_passphrase() -> bool {
!cfg!(target_os = "macos")
}
+
+/// One of the account's Teams (`teams.list`).
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TeamChoiceView {
+ pub id: String,
+ pub alias: String,
+ pub name: String,
+ pub role: String,
+ pub plan: String,
+}
+
+/// `teams.list`: the account's Teams and the current one.
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TeamsListView {
+ pub teams: Vec<TeamChoiceView>,
+ pub current_team_id: Option<String>,
+}
diff --git a/apps/cua-spaces/src-tauri/src/lib.rs b/apps/cua-spaces/src-tauri/src/lib.rs
index 9beb71206e..714dd5071a 100644
--- a/apps/cua-spaces/src-tauri/src/lib.rs
+++ b/apps/cua-spaces/src-tauri/src/lib.rs
@@ -514,6 +514,7 @@ pub fn run() {
commands::devices_confirm_machine,
commands::devices_create_pairing_code,
commands::devices_pairing_codes,
+ commands::teams_list,
commands::devices_revoke_pairing_code,
commands::devices_notify,
commands::space_shares,
diff --git a/docs/content/docs/cua-cli/reference/cli/host.mdx b/docs/content/docs/cua-cli/reference/cli/host.mdx
index 06034ea889..7f1956da78 100644
--- a/docs/content/docs/cua-cli/reference/cli/host.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/host.mdx
@@ -88,11 +88,12 @@ cua host pair [OPTIONS]
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-host-pair--team"></span>`--team` | string | | Add the machine for this team (its id). |
+| <span id="cua-host-pair--team"></span>`--team` | string | | Add the machine to this team (id, alias or name; owner or admin): waits until the machine joins, then makes it a team machine. |
| <span id="cua-host-pair--name"></span>`--name` | string | | Name the machine gets (default: its own host name). |
| <span id="cua-host-pair--expires"></span>`--expires` | integer | `30` | Minutes until the code expires (1 to 1440). |
| <span id="cua-host-pair--revoke"></span>`--revoke` | string | | Revoke an unused code by id (`pc_…`). |
| <span id="cua-host-pair--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production). |
+| <span id="cua-host-pair--no-wait"></span>`--no-wait` | boolean | `false` | With --team: print the code and exit instead of waiting; add the machine later with `cua team add-machine <team> relay:<id>`. |
| <span id="cua-host-pair--list"></span>`--list` | boolean | `false` | List your codes (used, unused, revoked, expired) instead. |
**Examples**
@@ -102,6 +103,9 @@ cua host pair
cua host pair --name build-box --expires 60
cua host pair --list
cua host pair --revoke pc_0123456789abcdef
+
+# Add the machine to a team: waits for it to join, then adds it
+cua host pair --team AIGIS
```
## `cua host config`
diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdx
index 0cf79be972..cc4d7b06b2 100644
--- a/docs/content/docs/cua-cli/reference/cli/index.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx
@@ -168,11 +168,11 @@ Enroll this device on the relay, approve, rename and revoke devices, and read th
### `cua team`
-Teams, their members, machines, device approvals and audit log. [Reference](/cua-cli/reference/cli/team).
+Teams (organizations), their members, machines and device approvals. [Reference](/cua-cli/reference/cli/team).
| Command | Description | Subcommands |
| --- | --- | --- |
-| <span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/team#cua-team) | Teams share machines with every member and their agents. | [`create`](/cua-cli/reference/cli/team#cua-team-create), [`ls`](/cua-cli/reference/cli/team#cua-team-ls), [`show`](/cua-cli/reference/cli/team#cua-team-show), [`invite`](/cua-cli/reference/cli/team#cua-team-invite), [`join`](/cua-cli/reference/cli/team#cua-team-join), [`leave`](/cua-cli/reference/cli/team#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/team#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/team#cua-team-set-role), [`devices`](/cua-cli/reference/cli/team#cua-team-devices), [`approve`](/cua-cli/reference/cli/team#cua-team-approve), [`deny`](/cua-cli/reference/cli/team#cua-team-deny), [`request`](/cua-cli/reference/cli/team#cua-team-request), [`add-machine`](/cua-cli/reference/cli/team#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/team#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/team#cua-team-audit), [`delete`](/cua-cli/reference/cli/team#cua-team-delete) |
+| <span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/team#cua-team) | Teams (organizations of your cua.ai account) share machines with every member and their agents. | [`create`](/cua-cli/reference/cli/team#cua-team-create), [`ls`](/cua-cli/reference/cli/team#cua-team-ls), [`show`](/cua-cli/reference/cli/team#cua-team-show), [`invite`](/cua-cli/reference/cli/team#cua-team-invite), [`join`](/cua-cli/reference/cli/team#cua-team-join), [`leave`](/cua-cli/reference/cli/team#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/team#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/team#cua-team-set-role), [`devices`](/cua-cli/reference/cli/team#cua-team-devices), [`approve`](/cua-cli/reference/cli/team#cua-team-approve), [`deny`](/cua-cli/reference/cli/team#cua-team-deny), [`request`](/cua-cli/reference/cli/team#cua-team-request), [`add-machine`](/cua-cli/reference/cli/team#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/team#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/team#cua-team-audit), [`delete`](/cua-cli/reference/cli/team#cua-team-delete) |
### `cua usage`
diff --git a/docs/content/docs/cua-cli/reference/cli/team.mdx b/docs/content/docs/cua-cli/reference/cli/team.mdx
index cd2d2e07e2..bdb5978f79 100644
--- a/docs/content/docs/cua-cli/reference/cli/team.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/team.mdx
@@ -1,6 +1,6 @@
---
title: "cua team"
-description: "Teams, their members, machines, device approvals and audit log."
+description: "Teams (organizations), their members, machines and device approvals."
---
{/*
@@ -13,10 +13,10 @@ description: "Teams, their members, machines, device approvals and audit log."
| Command | Description |
| --- | --- |
| [`cua team create`](#cua-team-create) | Create a team; you are its owner. |
-| [`cua team ls`](#cua-team-ls) | Your teams, and email invites waiting for you. |
-| [`cua team show`](#cua-team-show) | A team: members, machines, open invites and devices. |
-| [`cua team invite`](#cua-team-invite) | Invite someone by email, or make a link anyone can join with. |
-| [`cua team join`](#cua-team-join) | Join a team with an invite link or code, or (with --team) the email invite for your account's email. |
+| [`cua team ls`](#cua-team-ls) | Your teams. |
+| [`cua team show`](#cua-team-show) | A team: plan, members, machines, open invites and devices. |
+| [`cua team invite`](#cua-team-invite) | Invite someone by email: cua.ai emails them an invitation. |
+| [`cua team join`](#cua-team-join) | After accepting an emailed invitation: take the role it offered. |
| [`cua team leave`](#cua-team-leave) | Leave a team. |
| [`cua team remove-member`](#cua-team-remove-member) | Remove a member (owner or admin; admins cannot remove admins). |
| [`cua team set-role`](#cua-team-set-role) | Make a member an admin, or an admin a member (owner). |
@@ -26,14 +26,14 @@ description: "Teams, their members, machines, device approvals and audit log."
| [`cua team request`](#cua-team-request) | Ask the team's admins to approve this device. |
| [`cua team add-machine`](#cua-team-add-machine) | Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. |
| [`cua team remove-machine`](#cua-team-remove-machine) | Take a machine off the team. |
-| [`cua team audit`](#cua-team-audit) | The team's audit log: joins, approvals, machines opened, changes. |
-| [`cua team delete`](#cua-team-delete) | Delete a team (owner). |
+| [`cua team audit`](#cua-team-audit) | The team's audit log. |
+| [`cua team delete`](#cua-team-delete) | Delete a team (owner; cancel its subscription first). |
Every command also accepts the [global options](/cua-cli/reference/cli#global-options).
<span id="cua-team"></span>
-Teams share machines with every member and their agents. Owners and admins invite (email or link), approve member devices, add machines and read the audit log.
+Teams (organizations of your cua.ai account) share machines with every member and their agents. Owners and admins invite by email, approve member devices and add machines.
```text output
cua team [OPTIONS] <COMMAND>
@@ -46,12 +46,12 @@ cua team create AIGIS
cua team invite AIGIS [email protected]
cua team add-machine AIGIS local:build-box
cua team approve AIGIS dev_0123456789abcdef01234567
-cua team audit AIGIS
+cua team show AIGIS
```
## `cua team create`
-Create a team; you are its owner.
+Create a team; you are its owner. Buy Teams for it at app.cua.ai to add machines.
```text output
cua team create [OPTIONS] <NAME>
@@ -69,7 +69,7 @@ cua team create "AIGIS"
## `cua team ls`
-Your teams, and email invites waiting for you.
+Your teams.
```text output
cua team ls [OPTIONS]
@@ -86,7 +86,7 @@ cua team ls --json
## `cua team show`
-A team: members, machines, open invites and devices.
+A team: plan, members, machines, open invites and devices.
```text output
cua team show [OPTIONS] <TEAM>
@@ -94,7 +94,7 @@ cua team show [OPTIONS] <TEAM>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id (`team-…`) or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
**Examples**
@@ -104,51 +104,44 @@ cua team show AIGIS
## `cua team invite`
-Invite someone by email, or make a link anyone can join with.
+Invite someone by email: cua.ai emails them an invitation. Manage invites at app.cua.ai/team.
```text output
-cua team invite [OPTIONS] <TEAM> [EMAIL]
+cua team invite [OPTIONS] <TEAM> <EMAIL>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
-| `<EMAIL>` | string | optional | Their email (they join by signing in with it). |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<EMAIL>` | string | required | Their email. |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
| <span id="cua-team-invite--role"></span>`--role` | `member` \| `admin` | `member` | `member` or `admin` (only the owner invites admins). |
-| <span id="cua-team-invite--link"></span>`--link` | boolean | `false` | Make a link instead (up to 25 joins, 7 days). |
**Examples**
```bash test="cli-shape" id="ref-cua-team-invite"
cua team invite AIGIS [email protected]
-cua team invite AIGIS --link
cua team invite AIGIS [email protected] --role admin
```
## `cua team join`
-Join a team with an invite link or code, or (with --team) the email invite for your account's email.
+After accepting an emailed invitation: take the role it offered. Run `cua auth login` first so your session lists the team.
```text output
-cua team join [OPTIONS] [CODE]
+cua team join [OPTIONS] <TEAM>
```
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<CODE>` | string | optional | The invite link or code. |
-
-| Flag | Type | Default | Description |
-| --- | --- | --- | --- |
-| <span id="cua-team-join--team"></span>`--team` | string | | The team of an email invite. |
+| `<TEAM>` | string | required | Team id, alias or name. |
**Examples**
```bash test="cli-shape" id="ref-cua-team-join"
-cua team join https://relay.cua.ai/join/team/team-0a1b….xyz
-cua team join --team team-0a1b2c3d4e5f6a7b
+cua team join AIGIS
```
## `cua team leave`
@@ -161,7 +154,7 @@ cua team leave [OPTIONS] <TEAM>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
**Examples**
@@ -179,7 +172,7 @@ cua team remove-member [OPTIONS] <TEAM> <WHO>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
| `<WHO>` | string | required | Their email or account id. |
**Examples**
@@ -198,7 +191,7 @@ cua team set-role [OPTIONS] <TEAM> <WHO> <ROLE>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
| `<WHO>` | string | required | Their email or account id. |
| `<ROLE>` | `member` \| `admin` | required | `member` or `admin`. |
@@ -218,7 +211,7 @@ cua team devices [OPTIONS] <TEAM>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
**Examples**
@@ -236,7 +229,7 @@ cua team approve [OPTIONS] <TEAM> <DEVICE>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
| `<DEVICE>` | string | required | Device id (`cua team devices`). |
**Examples**
@@ -255,7 +248,7 @@ cua team deny [OPTIONS] <TEAM> <DEVICE>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
| `<DEVICE>` | string | required | Device id. |
**Examples**
@@ -274,7 +267,7 @@ cua team request [OPTIONS] <TEAM>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
**Examples**
@@ -284,7 +277,7 @@ cua team request AIGIS
## `cua team add-machine`
-Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. Macs, Linux and Windows machines all can.
+Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. Macs, Linux and Windows machines all can. Each Space is added on its own: adding a host does not add the Spaces it provides.
```text output
cua team add-machine [OPTIONS] <TEAM> <SPACE>
@@ -292,8 +285,8 @@ cua team add-machine [OPTIONS] <TEAM> <SPACE>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
-| `<SPACE>` | string | required | Space id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
+| `<SPACE>` | string | required | Space id or name (`relay:<id>` for a machine you host). |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
@@ -316,7 +309,7 @@ cua team remove-machine [OPTIONS] <TEAM> <MACHINE>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
| `<MACHINE>` | string | required | The machine (`relay:<id>` or its id, as `cua team show` lists it). |
**Examples**
@@ -327,7 +320,7 @@ cua team remove-machine AIGIS relay:0123abcd4567ef89
## `cua team audit`
-The team's audit log: joins, approvals, machines opened, changes.
+The team's audit log. Audit export is coming soon; for now see the account app (app.cua.ai).
```text output
cua team audit [OPTIONS] <TEAM>
@@ -335,21 +328,21 @@ cua team audit [OPTIONS] <TEAM>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-team-audit--limit"></span>`--limit` | integer | `50` | Newest events to show. |
+| <span id="cua-team-audit--limit"></span>`--limit` | integer | `50` | Newest events to show (when export arrives). |
**Examples**
```bash test="cli-shape" id="ref-cua-team-audit"
-cua team audit AIGIS --limit 50
+cua team audit AIGIS
```
## `cua team delete`
-Delete a team (owner). Its machines stay yours.
+Delete a team (owner; cancel its subscription first). Its machines stay yours.
```text output
cua team delete [OPTIONS] <TEAM>
@@ -357,7 +350,7 @@ cua team delete [OPTIONS] <TEAM>
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
-| `<TEAM>` | string | required | Team id or name. |
+| `<TEAM>` | string | required | Team id, alias or name. |
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
diff --git a/docs/content/docs/cua-cli/reference/index.mdx b/docs/content/docs/cua-cli/reference/index.mdx
index 7fcfea0186..a43f342c7d 100644
--- a/docs/content/docs/cua-cli/reference/index.mdx
+++ b/docs/content/docs/cua-cli/reference/index.mdx
@@ -32,7 +32,7 @@ description: "Every cua command and every cua MCP tool, generated from the CLI d
| [`cua cloud`](/cua-cli/reference/cli/cloud) | Your own AWS, Google Cloud or Modal account as a place for sandboxes and Spaces: connect, test, status, sweep. |
| [`cua host`](/cua-cli/reference/cli/host) | Set this machine up for unattended access. |
| [`cua devices`](/cua-cli/reference/cli/devices) | Enroll this device on the relay, approve, rename and revoke devices, and read the access log. |
-| [`cua team`](/cua-cli/reference/cli/team) | Teams, their members, machines, device approvals and audit log. |
+| [`cua team`](/cua-cli/reference/cli/team) | Teams (organizations), their members, machines and device approvals. |
| [`cua usage`](/cua-cli/reference/cli/usage) | Your hosted relay allowance this month: live sessions and relay hours. |
| [`cua teleport`](/cua-cli/reference/cli/teleport) | Move a desktop app session into a sandbox. |
| [`cua volume`](/cua-cli/reference/cli/volume) | Cua Volume: files, versions, grants, access requests and audit of the volume every Space and agent shares. |
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
index 75fecbc39f..c37d6f3b16 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
@@ -1088,9 +1088,12 @@ pub struct RelayAccount {
pub url: String,
pub tokens: Arc<dyn AccountTokens>,
pub device: Option<Arc<DeviceAuth>>,
+ pub spaces_api: Option<String>,
}
impl RelayAccount {
fn new(url: impl Into<String>, tokens: Arc<dyn AccountTokens>) -> Self;
+ fn with_spaces_api(self, url: impl Into<String>) -> Self;
+ fn spaces_api(&self) -> Result<SpacesApiClient>;
fn with_device(self, device: Arc<DeviceAuth>) -> Self;
async fn device_session(&self) -> Option<String>;
async fn client(&self) -> Result<RelayClient>;
@@ -1683,6 +1686,7 @@ impl Spaces {
async fn share_space(&self, space: &str, who: &str, role: ShareRole) -> Result<SpaceShares>;
async fn unshare_space(&self, space: &str, who: Option<&str>) -> Result<SpaceShares>;
async fn share_with_team(&self, space: &str, team: &str) -> Result<SpaceShares>;
+ async fn share_with_team_waiting(&self, space: &str, team: &str, waiting: &mut dyn FnMut(Duration) + Send) -> Result<SpaceShares>;
async fn unshare_from_team(&self, space: &str, team: &str) -> Result<SpaceShares>;
async fn relay_register(&self, space: &str) -> Result<RelayRegistration>;
async fn relay_unregister(&self, space: &str) -> Result<bool>;
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index 8436c07a84..2d53df88a0 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -100,11 +100,18 @@ pub enum HostCmd {
cua host pair
cua host pair --name build-box --expires 60
cua host pair --list
- cua host pair --revoke pc_0123456789abcdef")]
+ cua host pair --revoke pc_0123456789abcdef
+ # Add the machine to a team: waits for it to join, then adds it
+ cua host pair --team AIGIS")]
Pair {
- /// Add the machine for this team (its id).
+ /// Add the machine to this team (id, alias or name; owner or admin):
+ /// waits until the machine joins, then makes it a team machine.
#[arg(long)]
team: Option<String>,
+ /// With --team: print the code and exit instead of waiting; add the
+ /// machine later with `cua team add-machine <team> relay:<id>`.
+ #[arg(long, requires = "team")]
+ no_wait: bool,
/// Name the machine gets (default: its own host name).
#[arg(long)]
name: Option<String>,
@@ -611,12 +618,21 @@ pub async fn run_spaces_sdk(
SpacesCmd::Share {
space, who, role, ..
} => {
+ let who = team_who(&who).await?;
+ if who.starts_with("team:") && !json {
+ eprintln!(
+ "Adding {space} to the team… (right after a Teams checkout this can take up to a minute while the plan is set up)"
+ );
+ }
let s = spaces.space(space).await?;
print_shares(&s.share(who, Some(role)).await?, json, out);
}
SpacesCmd::Unshare { space, who, all } => {
let s = spaces.space(space).await?;
- let who = if all { None } else { who };
+ let who = match who {
+ Some(w) if !all => Some(team_who(&w).await?),
+ _ => None,
+ };
print_shares(&s.unshare(who).await?, json, out);
}
SpacesCmd::Shares { space } => {
@@ -1382,6 +1398,7 @@ pub async fn run_host(
}
HostCmd::Pair {
team,
+ no_wait,
name,
expires,
list,
@@ -1396,6 +1413,7 @@ pub async fn run_host(
device,
relay,
team,
+ no_wait,
name,
expires,
list,
@@ -1404,7 +1422,7 @@ pub async fn run_host(
out,
)
.await
- .map_err(host_err)?;
+ .map_err(crate::team_cmd::err)?;
}
HostCmd::Status => {
let s = host.status().await.map_err(host_err)?;
@@ -1557,6 +1575,23 @@ fn print_allow(allow: &[String], json: bool, out: &mut dyn Write) {
}
}
+/// `who` as it is shared with: a `team:<name>` becomes `team:<organization
+/// id>` (the Spaces API resolves names and aliases); anything else as is.
+async fn team_who(who: &str) -> Result<String, CuaError> {
+ match who.trim().strip_prefix("team:") {
+ Some(t)
+ if !cua_host::spaces_api::is_org_ref(t)
+ && !cua_host::spaces_api::is_legacy_team_id(t) =>
+ {
+ Ok(format!(
+ "team:{}",
+ crate::team_cmd::resolve_team(&crate::util::cua_home(), t).await?
+ ))
+ }
+ _ => Ok(who.trim().to_string()),
+ }
+}
+
/// `cua host pair`: mints (default), lists or revokes pairing codes as the
/// account from this enrolled device.
#[allow(clippy::too_many_arguments)]
@@ -1566,6 +1601,7 @@ async fn pair_codes(
device: Option<&DeviceAuth>,
relay: Option<String>,
team: Option<String>,
+ no_wait: bool,
name: Option<String>,
expires: u64,
list: bool,
@@ -1622,12 +1658,35 @@ async fn pair_codes(
"--expires is 1 to 1440 minutes".into(),
));
}
+ // A team is an organization of the Spaces API: the relay code carries
+ // no team (the relay's own teams are retired), and the machine becomes
+ // a team machine once it joins (below).
+ let api = cua_host::spaces_api::SpacesApiClient::current()?;
+ let org = match &team {
+ Some(t) => {
+ let org = api.resolve_org(&token, t).await?;
+ if !org.manages() {
+ return Err(cua_host::Error::PermissionDenied(format!(
+ "only an owner or admin of {} can add machines to it",
+ org.label()
+ )));
+ }
+ if !org.has("team_machines") {
+ eprintln!(
+ "Note: {} has no team machines on its plan yet (buy Teams at app.cua.ai); a plan bought a moment ago is waited for.",
+ org.label()
+ );
+ }
+ Some(org)
+ }
+ None => None,
+ };
let minted = client
.create_pairing_code(
&token,
&cua_host::PairingCodeRequest {
name,
- team,
+ team: None,
ttl_secs: Some(expires * 60),
},
)
@@ -1645,7 +1704,7 @@ async fn pair_codes(
out,
serde_json::json!({
"id": minted.id, "code": code, "url": link, "expires_at": minted.expires_at,
- "team": minted.team, "install": {"sh": sh, "powershell": ps},
+ "team": org.as_ref().map(|o| o.id.clone()), "install": {"sh": sh, "powershell": ps},
})
.to_string(),
);
@@ -1664,6 +1723,62 @@ async fn pair_codes(
line(out, l);
}
}
+ let Some(org) = org else {
+ return Ok(());
+ };
+ let later = format!("cua team add-machine {} relay:<machine id>", org.id);
+ if no_wait {
+ if !json {
+ line(
+ out,
+ format!("When it has joined, add it to {}: {later}", org.label()),
+ );
+ }
+ return Ok(());
+ }
+ if !json {
+ line(
+ out,
+ format!(
+ "Waiting for the machine to join, to add it to {} (Ctrl-C to stop; then: {later})…",
+ org.label()
+ ),
+ );
+ }
+ let mut said = false;
+ let machine = client
+ .add_paired_machine_to_team(
+ &api,
+ &token,
+ &minted.id,
+ &org.id,
+ minted.expires_at.max(1),
+ std::time::Duration::from_secs(3),
+ |_| {
+ if !said && !json {
+ eprintln!(
+ "{} (the team's plan is on its way)",
+ cua_host::spaces_api::FINISHING_SETUP
+ );
+ said = true;
+ }
+ },
+ )
+ .await?;
+ if json {
+ line(
+ out,
+ serde_json::json!({ "team": org.id, "machine": machine }).to_string(),
+ );
+ } else {
+ line(
+ out,
+ format!(
+ "relay:{machine} joined and is a machine of {}.",
+ org.label()
+ ),
+ );
+ }
Ok(())
}
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index 8b0298f20f..bc0bd92035 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -232,9 +232,9 @@ enum Command {
cua devices audit"
)]
Devices(devices_cmd::DevicesCmd),
- /// Teams share machines with every member and their agents. Owners
- /// and admins invite (email or link), approve member devices, add
- /// machines and read the audit log.
+ /// Teams (organizations of your cua.ai account) share machines with
+ /// every member and their agents. Owners and admins invite by email,
+ /// approve member devices and add machines.
#[command(
subcommand,
after_help = "Examples:
@@ -242,7 +242,7 @@ enum Command {
cua team invite AIGIS [email protected]
cua team add-machine AIGIS local:build-box
cua team approve AIGIS dev_0123456789abcdef01234567
- cua team audit AIGIS"
+ cua team show AIGIS"
)]
Team(team_cmd::TeamCmd),
/// Your relay allowance this month: live sessions, relay hours, and
@@ -1715,8 +1715,7 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
// Adding a machine is sharing the Space with the team: the same
// path as `cua spaces share <space> team:<id>` (attach, confirm).
Command::Team(team_cmd::TeamCmd::AddMachine { team, space, yes }) => {
- let auth = devices_cmd::device_auth(&host::relay_url(None, &util::cua_home()))?;
- let id = team_cmd::resolve_team(&auth, &team).await?;
+ let id = team_cmd::resolve_team(&util::cua_home(), &team).await?;
let share = Cli {
command: Command::Spaces(host::SpacesCmd::Share {
space,
@@ -2542,7 +2541,23 @@ fn cli_command(teams: bool) -> clap::Command {
}
cmd.mut_subcommand("team", |c| c.hide(true))
.mut_subcommand("host", |h| {
- h.mut_subcommand("pair", |p| p.mut_arg("team", |a| a.hide(true)))
+ h.mut_subcommand("pair", |p| {
+ // Drop the Teams example too.
+ let examples = p.get_after_help().map(|h| {
+ h.to_string()
+ .lines()
+ .filter(|l| !l.contains("team"))
+ .collect::<Vec<_>>()
+ .join("\n")
+ });
+ let p = p
+ .mut_arg("team", |a| a.hide(true))
+ .mut_arg("no_wait", |a| a.hide(true));
+ match examples {
+ Some(e) => p.after_help(e),
+ None => p,
+ }
+ })
})
}
diff --git a/libs/cua/crates/cua-cli/src/team_cmd.rs b/libs/cua/crates/cua-cli/src/team_cmd.rs
index 562db6d0bf..147b3d1fc7 100644
--- a/libs/cua/crates/cua-cli/src/team_cmd.rs
+++ b/libs/cua/crates/cua-cli/src/team_cmd.rs
@@ -1,29 +1,37 @@
-//! `cua team …`: teams on the relay. A team shares machines with every
-//! member (and their agents); owners and admins invite by email or link,
-//! remove members, add machines they own (Mac, Linux or Windows), approve each member
-//! device before it opens team machines, and read the team's audit log.
+//! `cua team …`: Teams. A team is an organization of your cua.ai account
+//! (the Spaces API, `https://api.cua.ai`); its id is the organization id
+//! `cua team ls` shows. A team shares machines with every member (and
+//! their agents); owners and admins invite by email, remove members, add
+//! machines they own (Mac, Linux or Windows) and approve each member
+//! device before it opens team machines.
//!
//! Adding a Space is `cua team add-machine <team> <space>`, the same as
//! `cua spaces share <space> team:<id>` (it attaches the Space to the relay
-//! first, and asks you to confirm); see `lib.rs`.
+//! first, and asks you to confirm); see `lib.rs`. The relay's old
+//! `team-…` teams are not used: a server without Teams says so.
use crate::util::{self, line};
use clap::Subcommand;
-use cua_host::{DeviceAuth, Team, TeamRole};
+use cua_host::AccountTokens;
+use cua_host::spaces_api::{
+ ApiDeviceApproval, ApiOrg, FINISHING_SETUP, SETUP_RETRY_WINDOW, SpacesApiClient,
+ is_teams_unavailable,
+};
use cua_sdk::CuaError;
use std::io::Write;
use std::path::Path;
#[derive(Subcommand, Debug, Clone)]
pub enum TeamCmd {
- /// Create a team; you are its owner.
+ /// Create a team; you are its owner. Buy Teams for it at app.cua.ai
+ /// to add machines.
#[command(after_help = "Examples:
cua team create \"AIGIS\"")]
Create {
/// Team name.
name: String,
},
- /// Your teams, and email invites waiting for you.
+ /// Your teams.
#[command(
visible_alias = "list",
after_help = "Examples:
@@ -31,56 +39,47 @@ pub enum TeamCmd {
cua team ls --json"
)]
Ls,
- /// A team: members, machines, open invites and devices.
+ /// A team: plan, members, machines, open invites and devices.
#[command(after_help = "Examples:
cua team show AIGIS")]
Show {
- /// Team id (`team-…`) or name.
+ /// Team id, alias or name.
team: String,
},
- /// Invite someone by email, or make a link anyone can join with.
+ /// Invite someone by email: cua.ai emails them an invitation. Manage
+ /// invites at app.cua.ai/team.
#[command(after_help = "Examples:
cua team invite AIGIS [email protected]
- cua team invite AIGIS --link
cua team invite AIGIS [email protected] --role admin")]
Invite {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
- /// Their email (they join by signing in with it).
- #[arg(required_unless_present = "link", conflicts_with = "link")]
- email: Option<String>,
- /// Make a link instead (up to 25 joins, 7 days).
- #[arg(long)]
- link: bool,
+ /// Their email.
+ email: String,
/// `member` or `admin` (only the owner invites admins).
#[arg(long, default_value = "member", value_parser = ["member", "admin"])]
role: String,
},
- /// Join a team with an invite link or code, or (with --team) the email
- /// invite for your account's email.
+ /// After accepting an emailed invitation: take the role it offered.
+ /// Run `cua auth login` first so your session lists the team.
#[command(after_help = "Examples:
- cua team join https://relay.cua.ai/join/team/team-0a1b….xyz
- cua team join --team team-0a1b2c3d4e5f6a7b")]
+ cua team join AIGIS")]
Join {
- /// The invite link or code.
- #[arg(required_unless_present = "team")]
- code: Option<String>,
- /// The team of an email invite.
- #[arg(long, conflicts_with = "code")]
- team: Option<String>,
+ /// Team id, alias or name.
+ team: String,
},
/// Leave a team.
#[command(after_help = "Examples:
cua team leave AIGIS")]
Leave {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
},
/// Remove a member (owner or admin; admins cannot remove admins).
#[command(after_help = "Examples:
cua team remove-member AIGIS [email protected]")]
RemoveMember {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
/// Their email or account id.
who: String,
@@ -89,7 +88,7 @@ pub enum TeamCmd {
#[command(after_help = "Examples:
cua team set-role AIGIS [email protected] admin")]
SetRole {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
/// Their email or account id.
who: String,
@@ -101,14 +100,14 @@ pub enum TeamCmd {
#[command(after_help = "Examples:
cua team devices AIGIS")]
Devices {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
},
/// Approve a member device so it can open team machines.
#[command(after_help = "Examples:
cua team approve AIGIS dev_0123456789abcdef01234567")]
Approve {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
/// Device id (`cua team devices`).
device: String,
@@ -117,7 +116,7 @@ pub enum TeamCmd {
#[command(after_help = "Examples:
cua team deny AIGIS dev_0123456789abcdef01234567")]
Deny {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
/// Device id.
device: String,
@@ -126,18 +125,20 @@ pub enum TeamCmd {
#[command(after_help = "Examples:
cua team request AIGIS")]
Request {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
},
/// Make a Space (or a machine you host) a team machine: every member
- /// and their agents see it and can open it. Macs, Linux and Windows machines all can.
+ /// and their agents see it and can open it. Macs, Linux and Windows
+ /// machines all can. Each Space is added on its own: adding a host does
+ /// not add the Spaces it provides.
#[command(after_help = "Examples:
cua team add-machine AIGIS local:build-box
cua team add-machine AIGIS relay:0123abcd4567ef89 --yes")]
AddMachine {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
- /// Space id or name.
+ /// Space id or name (`relay:<id>` for a machine you host).
space: String,
/// Confirm without a prompt.
#[arg(long)]
@@ -147,26 +148,28 @@ pub enum TeamCmd {
#[command(after_help = "Examples:
cua team remove-machine AIGIS relay:0123abcd4567ef89")]
RemoveMachine {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
/// The machine (`relay:<id>` or its id, as `cua team show` lists it).
machine: String,
},
- /// The team's audit log: joins, approvals, machines opened, changes.
+ /// The team's audit log. Audit export is coming soon; for now see the
+ /// account app (app.cua.ai).
#[command(after_help = "Examples:
- cua team audit AIGIS --limit 50")]
+ cua team audit AIGIS")]
Audit {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
- /// Newest events to show.
+ /// Newest events to show (when export arrives).
#[arg(long, default_value_t = 50)]
limit: usize,
},
- /// Delete a team (owner). Its machines stay yours.
+ /// Delete a team (owner; cancel its subscription first). Its machines
+ /// stay yours.
#[command(after_help = "Examples:
cua team delete AIGIS --yes")]
Delete {
- /// Team id or name.
+ /// Team id, alias or name.
team: String,
/// Do not ask for confirmation.
#[arg(long)]
@@ -180,6 +183,7 @@ impl TeamCmd {
match self {
TeamCmd::Show { team }
| TeamCmd::Invite { team, .. }
+ | TeamCmd::Join { team }
| TeamCmd::Leave { team }
| TeamCmd::RemoveMember { team, .. }
| TeamCmd::SetRole { team, .. }
@@ -191,314 +195,355 @@ impl TeamCmd {
| TeamCmd::RemoveMachine { team, .. }
| TeamCmd::Audit { team, .. }
| TeamCmd::Delete { team, .. } => Some(team),
- TeamCmd::Create { .. } | TeamCmd::Ls | TeamCmd::Join { .. } => None,
+ TeamCmd::Create { .. } | TeamCmd::Ls => None,
}
}
}
-fn err(e: cua_host::Error) -> CuaError {
+/// A Teams error as the CLI reports it: a server without Teams is
+/// `unsupported`, with the words the apps use too.
+pub fn err(e: cua_host::Error) -> CuaError {
+ if is_teams_unavailable(&e) {
+ return CuaError::Unsupported(e.to_string());
+ }
+ if cua_host::spaces_api::is_feature_required(&e) {
+ return CuaError::PermissionDenied(format!(
+ "this team's plan does not include that yet: finish the Teams checkout at app.cua.ai, then try again ({e})"
+ ));
+ }
crate::host::host_err(e)
}
-/// The team id `query` names: an id as is, else the one team of yours
-/// with that name (case-insensitive).
-pub async fn resolve_team(auth: &DeviceAuth, query: &str) -> Result<String, CuaError> {
- let q = query.trim();
- let q = q.strip_prefix("team:").unwrap_or(q);
- if q.starts_with("team-") {
- return Ok(q.to_string());
- }
- let list = auth.teams().await.map_err(err)?;
- let matches: Vec<_> = list
- .teams
- .iter()
- .filter(|t| t.name.eq_ignore_ascii_case(q))
- .collect();
- match matches.as_slice() {
- [t] => Ok(t.id.clone()),
- [] => Err(CuaError::NotFound(format!(
- "no team of yours is called {q:?} (`cua team ls`)"
- ))),
- _ => Err(CuaError::InvalidArgument(format!(
- "several of your teams are called {q:?}: use the team id (`cua team ls`)"
- ))),
+/// What a team command runs with: the Spaces API, the account token and
+/// (for `request`) this device's relay id.
+pub struct TeamCtx {
+ pub api: SpacesApiClient,
+ pub token: String,
+ pub device: Option<String>,
+}
+
+impl TeamCtx {
+ /// For the signed-in account (`cua auth login`) in this environment.
+ pub async fn current(home: &Path, with_device: bool) -> Result<Self, CuaError> {
+ let api = SpacesApiClient::current().map_err(err)?;
+ let token = crate::host::SessionTokens
+ .access_token()
+ .await
+ .map_err(err)?;
+ let device = if with_device {
+ let auth = crate::devices_cmd::device_auth(&crate::host::relay_url(None, home))?;
+ auth.device_id().map_err(err)?
+ } else {
+ None
+ };
+ Ok(Self { api, token, device })
}
}
-fn when(ts: u64) -> String {
- chrono::DateTime::<chrono::Utc>::from_timestamp(ts as i64, 0)
- .map(|d| d.format("%Y-%m-%d %H:%M UTC").to_string())
- .unwrap_or_else(|| "-".into())
+/// The organization id `query` (an id, alias or name) names.
+pub async fn resolve_team(home: &Path, query: &str) -> Result<String, CuaError> {
+ let ctx = TeamCtx::current(home, false).await?;
+ Ok(ctx
+ .api
+ .resolve_org(&ctx.token, query)
+ .await
+ .map_err(err)?
+ .id)
}
fn emit_json(out: &mut dyn Write, v: &impl serde::Serialize) {
line(out, serde_json::to_string(v).unwrap_or_default());
}
-fn print_team(t: &Team, out: &mut dyn Write) {
- line(
- out,
- format!("{} ({}), you are {}", t.name, t.id, t.role.as_str()),
- );
- line(out, format!("Members ({}):", t.members.len()));
- for m in &t.members {
- line(out, format!(" {} {}", m.label(), m.role.as_str()));
+fn print_devices(org: &ApiOrg, devices: &[ApiDeviceApproval], out: &mut dyn Write) {
+ if devices.is_empty() {
+ return;
}
- line(out, format!("Machines ({}):", t.machines.len()));
- if t.machines.is_empty() {
- line(
- out,
- " none yet: `cua team add-machine <team> <space>` (owner or admin)",
- );
+ line(out, "Devices:");
+ for d in devices {
+ line(out, format!(" {} {} {}", d.device_id, d.sub, d.state));
}
- for m in &t.machines {
+ if org.manages() && devices.iter().any(|d| d.state == "pending") {
line(
out,
- format!(
- " relay:{} {} (owner {}{})",
- m.id,
- if m.name.is_empty() { "-" } else { &m.name },
- m.owner,
- if m.online { ", online" } else { ", offline" }
- ),
+ format!("Approve one with `cua team approve {} <device>`.", org.id),
);
}
- if !t.invites.is_empty() {
- line(out, "Open invites:");
- for i in &t.invites {
- line(
- out,
- format!(
- " {} {} as {}, expires {}",
- i.id,
- i.email.as_deref().unwrap_or("link"),
- i.role.as_str(),
- when(i.expires_at)
- ),
- );
- }
- }
- print_devices(t, out);
- if let Some(state) = &t.this_device {
- line(out, format!("This device: {state}"));
- }
}
-fn print_devices(t: &Team, out: &mut dyn Write) {
- if t.devices.is_empty() {
- return;
- }
- line(out, "Devices:");
- for d in &t.devices {
- line(
- out,
- format!(
- " {} {} {}{}",
- d.device,
- d.email.as_deref().unwrap_or(&d.account),
- d.state,
- if d.name.is_empty() {
- String::new()
- } else {
- format!(" ({})", d.name)
- }
- ),
- );
- }
- if t.role.manages() && t.devices.iter().any(|d| d.state == "pending") {
- line(
- out,
- format!("Approve one with `cua team approve {} <device>`.", t.id),
- );
+/// The account id (`sub`) `who` (an email or account id) names in `org`.
+async fn member_sub(ctx: &TeamCtx, org: &str, who: &str) -> Result<String, CuaError> {
+ let who = who.trim();
+ let members = ctx.api.members(&ctx.token, org).await.map_err(err)?;
+ members
+ .iter()
+ .find(|m| m.sub == who || m.email.eq_ignore_ascii_case(who))
+ .map(|m| m.sub.clone())
+ .ok_or_else(|| CuaError::NotFound(format!("{who} is not a member of this team")))
+}
+
+/// `cua team audit`: export is not there yet; say where to look.
+fn audit_notice(json: bool, out: &mut dyn Write) -> i32 {
+ let msg = format!(
+ "Audit export is coming soon (CUA-1374); see {}",
+ cua_home::env::account_app_url().trim_start_matches("https://")
+ );
+ if json {
+ emit_json(out, &serde_json::json!({ "events": [], "note": msg }));
+ } else {
+ line(out, msg);
}
+ 0
}
-/// Runs `cmd` (all but `add-machine`, which goes through Spaces) for this
-/// device. `confirm` answers the delete prompt.
+/// Runs `cmd` (all but `add-machine`, which goes through Spaces).
+/// `confirm` answers the delete prompt.
pub async fn run_with(
cmd: TeamCmd,
- auth: &DeviceAuth,
+ ctx: &TeamCtx,
confirm: &dyn Fn(&str) -> bool,
json: bool,
out: &mut dyn Write,
) -> Result<i32, CuaError> {
- let team = match cmd.team_arg() {
- Some(q) if !matches!(cmd, TeamCmd::AddMachine { .. }) => Some(resolve_team(auth, q).await?),
+ let (api, token) = (&ctx.api, ctx.token.as_str());
+ if let TeamCmd::Audit { .. } = cmd {
+ return Ok(audit_notice(json, out));
+ }
+ let org = match cmd.team_arg() {
+ Some(q) if !matches!(cmd, TeamCmd::AddMachine { .. }) => {
+ Some(api.resolve_org(token, q).await.map_err(err)?)
+ }
_ => None,
};
- let id = || team.clone().unwrap_or_default();
+ let org = org.unwrap_or_default();
+ let id = org.id.as_str();
match cmd {
TeamCmd::Create { name } => {
- let t = auth.create_team(&name).await.map_err(err)?;
+ let t = api.create_org(token, &name).await.map_err(err)?;
if json {
emit_json(out, &t);
} else {
- line(out, format!("Created team {} ({}).", t.name, t.id));
+ line(out, format!("Created team {} ({}).", t.label(), t.id));
line(out, "Next:");
line(
out,
- format!(" cua team invite {} <email> (or --link)", t.id),
+ " cua auth login (your session lists the team after a new sign-in)",
);
+ line(
+ out,
+ " buy Teams for it at app.cua.ai (team machines and device approval need it)",
+ );
+ line(out, format!(" cua team invite {} <email>", t.id));
line(out, format!(" cua team add-machine {} <space>", t.id));
}
}
TeamCmd::Ls => {
- let l = auth.teams().await.map_err(err)?;
+ let me = api.me(token).await.map_err(err)?;
if json {
- emit_json(out, &l);
+ emit_json(out, &serde_json::json!({ "teams": me.orgs }));
return Ok(0);
}
- if l.teams.is_empty() {
+ if me.orgs.is_empty() {
line(
out,
- "You are in no team. Create one with `cua team create <name>`.",
+ "You are in no team. Create one with `cua team create <name>` (or at app.cua.ai).",
);
}
- for t in &l.teams {
+ for o in &me.orgs {
line(
out,
format!(
- "{} {} {} {} members, {} machines{}",
- t.id,
- t.name,
- t.role.as_str(),
- t.members.len(),
- t.machines.len(),
- match t.this_device.as_deref() {
- Some("approved") | None => String::new(),
- Some(s) => format!(", this device {s}"),
+ "{} {} {} {}{}",
+ o.id,
+ o.label(),
+ o.role,
+ if o.plan.is_empty() { "free" } else { &o.plan },
+ if o.has("team_machines") {
+ ""
+ } else {
+ " (no team machines: buy Teams at app.cua.ai)"
}
),
);
}
- for i in &l.invites {
+ }
+ TeamCmd::Show { .. } => {
+ let detail = api.org(token, id).await.map_err(err)?;
+ let members = api.members(token, id).await.map_err(err)?;
+ let machines = api.org_machines(token, id).await.map_err(err)?;
+ let invites = if org.manages() {
+ api.invites(token, id).await.unwrap_or_default()
+ } else {
+ Vec::new()
+ };
+ let devices = api.org_devices(token, id).await.unwrap_or_default();
+ if json {
+ emit_json(
+ out,
+ &serde_json::json!({
+ "team": detail, "members": members, "machines": machines,
+ "invites": invites, "devices": devices,
+ }),
+ );
+ return Ok(0);
+ }
+ line(
+ out,
+ format!(
+ "{} ({}), you are {}; plan {}, {} of {} seats",
+ org.label(),
+ org.id,
+ detail.role,
+ if detail.plan.is_empty() {
+ "free"
+ } else {
+ &detail.plan
+ },
+ detail.seats_used,
+ detail.seats_paid
+ ),
+ );
+ line(out, format!("Members ({}):", members.len()));
+ for m in &members {
line(
out,
format!(
- "Invited to {} ({}) as {}: `cua team join --team {}`",
- i.team_name,
- i.team,
- i.invite.role.as_str(),
- i.team
+ " {} {}",
+ if m.email.is_empty() { &m.sub } else { &m.email },
+ m.role
),
);
}
- }
- TeamCmd::Show { .. } => {
- let t = auth.team(&id()).await.map_err(err)?;
- if json {
- emit_json(out, &t);
- } else {
- print_team(&t, out);
+ line(out, format!("Machines ({}):", machines.len()));
+ if machines.is_empty() {
+ line(
+ out,
+ " none yet: `cua team add-machine <team> <space>` (owner or admin)",
+ );
}
+ for m in &machines {
+ line(
+ out,
+ format!(
+ " relay:{} {} {}",
+ m.machine_id,
+ if m.label.is_empty() { "-" } else { &m.label },
+ if m.platform.is_empty() {
+ "-"
+ } else {
+ &m.platform
+ }
+ ),
+ );
+ }
+ if !invites.is_empty() {
+ line(out, "Open invites:");
+ for i in &invites {
+ line(out, format!(" {} {}", i.id, i.email));
+ }
+ }
+ print_devices(&org, &devices, out);
}
- TeamCmd::Invite {
- email, link, role, ..
- } => {
- let role = TeamRole::parse(&role).map_err(err)?;
- let email = if link { None } else { email };
- let n = auth
- .invite_to_team(&id(), email.as_deref(), role)
+ TeamCmd::Invite { email, role, .. } => {
+ api.invite(token, id, email.trim(), &role)
.await
.map_err(err)?;
if json {
- emit_json(out, &n);
+ emit_json(
+ out,
+ &serde_json::json!({ "team": id, "email": email.trim(), "role": role }),
+ );
} else {
- match &n.invite.email {
- Some(e) => {
- line(
- out,
- format!(
- "Invited {e} as {}. Send them this link (it works only when they sign in as {e}), expires {}:",
- role.as_str(),
- when(n.invite.expires_at)
- ),
- );
- }
- None => line(
- out,
- format!(
- "Invite link ({} joins, as {}, expires {}). Anyone with it can join; admins then approve their device:",
- n.invite.uses_left,
- role.as_str(),
- when(n.invite.expires_at)
- ),
+ line(
+ out,
+ format!(
+ "Invited {} to {} as {role}: cua.ai emails them an invitation. They accept it, sign in again (`cua auth login`), and run `cua team join {}`.",
+ email.trim(),
+ org.label(),
+ org.id
),
- }
- line(out, format!(" {}", n.link));
- line(out, format!("They run: cua team join {}", n.link));
+ );
+ line(
+ out,
+ format!(
+ "See and revoke invites at {}/team.",
+ cua_home::env::account_app_url()
+ ),
+ );
}
}
- TeamCmd::Join { code, team } => {
- let t = auth
- .join_team(code.as_deref(), team.as_deref())
- .await
- .map_err(err)?;
+ TeamCmd::Join { .. } => {
+ let role = api.claim_invite(token, id).await.map_err(err)?;
if json {
- emit_json(out, &t);
+ emit_json(out, &serde_json::json!({ "team": id, "role": role }));
} else {
line(
out,
- format!("You joined {} ({}) as {}.", t.name, t.id, t.role.as_str()),
+ format!("You are in {} ({}) as {role}.", org.label(), org.id),
);
- match t.this_device.as_deref() {
- Some("approved") => line(out, "This device can open the team's machines."),
- Some(_) => line(
- out,
- "This device waits for a team admin's approval before it can open the team's machines.",
- ),
- None => line(
- out,
- format!(
- "Enroll this device (`cua devices enroll`), then ask for approval: `cua team request {}`.",
- t.id
- ),
+ line(
+ out,
+ format!(
+ "If the team approves devices, ask for this one: `cua team request {}`.",
+ org.id
),
- }
+ );
}
}
TeamCmd::Leave { .. } => {
- auth.leave_team(&id()).await.map_err(err)?;
+ api.leave_org(token, id).await.map_err(err)?;
if !json {
- line(out, format!("You left {}.", id()));
+ line(out, format!("You left {}.", org.label()));
}
}
TeamCmd::RemoveMember { who, .. } => {
- auth.remove_team_member(&id(), &who).await.map_err(err)?;
+ let sub = member_sub(ctx, id, &who).await?;
+ api.remove_member(token, id, &sub).await.map_err(err)?;
if !json {
line(
out,
- format!("Removed {who}: their open sessions on team machines ended."),
+ format!("Removed {who}: their open sessions on team machines end."),
);
}
}
TeamCmd::SetRole { who, role, .. } => {
- let role = TeamRole::parse(&role).map_err(err)?;
- let m = auth.set_team_role(&id(), &who, role).await.map_err(err)?;
+ let sub = member_sub(ctx, id, &who).await?;
+ api.set_member_role(token, id, &sub, &role)
+ .await
+ .map_err(err)?;
if json {
- emit_json(out, &m);
+ emit_json(out, &serde_json::json!({ "sub": sub, "role": role }));
} else {
- line(out, format!("{} is now {}.", m.label(), m.role.as_str()));
+ line(out, format!("{who} is now {role}."));
}
}
TeamCmd::Devices { .. } => {
- let t = auth.team(&id()).await.map_err(err)?;
+ let devices = api.org_devices(token, id).await.map_err(err)?;
if json {
- emit_json(out, &t.devices);
- } else if t.devices.is_empty() {
+ emit_json(out, &devices);
+ } else if devices.is_empty() {
line(out, "No member device has asked yet.");
} else {
- print_devices(&t, out);
+ print_devices(&org, &devices, out);
}
}
- TeamCmd::Approve { device, .. } => decide(auth, &id(), &device, true, json, out).await?,
- TeamCmd::Deny { device, .. } => decide(auth, &id(), &device, false, json, out).await?,
+ TeamCmd::Approve { device, .. } => decide(ctx, &org, &device, true, json, out).await?,
+ TeamCmd::Deny { device, .. } => decide(ctx, &org, &device, false, json, out).await?,
TeamCmd::Request { .. } => {
- let d = auth.request_team_device(&id()).await.map_err(err)?;
+ let device = ctx.device.clone().ok_or_else(|| {
+ CuaError::InvalidArgument(
+ "this computer is not an enrolled device: run `cua devices enroll` first"
+ .into(),
+ )
+ })?;
+ let d = api
+ .request_org_device(token, id, &device)
+ .await
+ .map_err(err)?;
if json {
emit_json(out, &d);
} else {
- line(out, format!("This device ({}): {}.", d.device, d.state));
+ line(out, format!("This device ({}): {}.", d.device_id, d.state));
}
}
TeamCmd::AddMachine { .. } => {
@@ -507,40 +552,31 @@ pub async fn run_with(
TeamCmd::RemoveMachine { machine, .. } => {
let m = machine.trim();
let m = m.strip_prefix("relay:").unwrap_or(m);
- let t = auth.remove_team_machine(&id(), m).await.map_err(err)?;
+ api.remove_org_machine(token, id, m).await.map_err(err)?;
if json {
- emit_json(out, &t);
+ emit_json(out, &serde_json::json!({ "team": id, "removed": m }));
} else {
line(
out,
- format!("relay:{m} is no longer a machine of {}.", t.name),
+ format!("relay:{m} is no longer a machine of {}.", org.label()),
);
}
}
- TeamCmd::Audit { limit, .. } => {
- let events = auth.team_audit(&id(), limit).await.map_err(err)?;
- if json {
- emit_json(out, &events);
- return Ok(0);
- }
- for e in &events {
- let mut parts = vec![when(e.ts), e.kind.clone(), e.actor.clone()];
- parts.extend(e.subject.clone());
- parts.extend(e.machine.as_ref().map(|m| format!("relay:{m}")));
- parts.extend(e.detail.clone());
- parts.extend(e.device.as_ref().map(|d| format!("from {d}")));
- line(out, parts.join(" "));
- }
- }
+ TeamCmd::Audit { .. } => unreachable!("answered above"),
TeamCmd::Delete { yes, .. } => {
- if !yes && !confirm(&format!("Delete team {}? Members lose its machines.", id())) {
+ if !yes
+ && !confirm(&format!(
+ "Delete team {}? Members lose its machines.",
+ org.label()
+ ))
+ {
return Err(CuaError::InvalidArgument(
"not deleted (pass --yes when not in a terminal)".into(),
));
}
- auth.delete_team(&id()).await.map_err(err)?;
+ api.delete_org(token, id).await.map_err(err)?;
if !json {
- line(out, format!("Deleted {}.", id()));
+ line(out, format!("Deleted {}.", org.label()));
}
}
}
@@ -548,15 +584,47 @@ pub async fn run_with(
}
async fn decide(
- auth: &DeviceAuth,
- team: &str,
+ ctx: &TeamCtx,
+ org: &ApiOrg,
device: &str,
approve: bool,
json: bool,
out: &mut dyn Write,
) -> Result<(), CuaError> {
- let d = auth
- .decide_team_device(team, device.trim(), approve)
+ let device = device.trim();
+ let requests = ctx
+ .api
+ .org_devices(&ctx.token, &org.id)
+ .await
+ .map_err(err)?;
+ let sub = requests
+ .iter()
+ .find(|d| d.device_id == device)
+ .map(|d| d.sub.clone())
+ .ok_or_else(|| {
+ CuaError::NotFound(format!(
+ "no member of {} asked for device {device} (`cua team devices {}`)",
+ org.label(),
+ org.id
+ ))
+ })?;
+ let mut said = false;
+ let d = ctx
+ .api
+ .finishing_setup(
+ &ctx.token,
+ SETUP_RETRY_WINDOW,
+ |_| {
+ if !said && !json {
+ eprintln!("{FINISHING_SETUP} (the team's plan is on its way)");
+ said = true;
+ }
+ },
+ || {
+ ctx.api
+ .decide_org_device(&ctx.token, &org.id, device, &sub, approve)
+ },
+ )
.await
.map_err(err)?;
if json {
@@ -566,12 +634,11 @@ async fn decide(
out,
format!(
"Approved {} ({}): it can open the team's machines.",
- d.device,
- d.email.as_deref().unwrap_or(&d.account)
+ d.device_id, d.sub
),
);
} else {
- line(out, format!("Declined {}.", d.device));
+ line(out, format!("Declined {}.", d.device_id));
}
Ok(())
}
@@ -583,10 +650,13 @@ pub async fn run(
json: bool,
out: &mut dyn Write,
) -> Result<i32, CuaError> {
- let auth = crate::devices_cmd::device_auth(&crate::host::relay_url(None, home))?;
+ if let TeamCmd::Audit { .. } = cmd {
+ return Ok(audit_notice(json, out));
+ }
+ let ctx = TeamCtx::current(home, matches!(cmd, TeamCmd::Request { .. })).await?;
run_with(
cmd,
- &auth,
+ &ctx,
&|q| util::interactive() && util::confirm(q, false),
json,
out,
@@ -597,133 +667,118 @@ pub async fn run(
#[cfg(test)]
mod tests {
use super::*;
- use cua_host::testing::FakeRelay;
- use cua_host::{MemoryKeySlot, StaticToken};
- use std::sync::Arc;
+ use cua_host::testing::FakeSpacesApi;
- async fn enrolled(relay: &FakeRelay, token: &str, account: &str) -> DeviceAuth {
- relay.fresh_sign_in(account);
- let auth = DeviceAuth::new(
- &relay.url,
- Arc::new(StaticToken(token.into())),
- Arc::new(MemoryKeySlot::default()),
- format!("{account} laptop"),
- )
- .unwrap()
- .with_machine_id(Some(format!("machine-of-{account}")));
- auth.enroll().await.unwrap();
- auth
+ fn ctx(api: &FakeSpacesApi, token: &str, device: Option<&str>) -> TeamCtx {
+ TeamCtx {
+ api: SpacesApiClient::new(&api.url).unwrap(),
+ token: token.into(),
+ device: device.map(str::to_string),
+ }
}
- async fn text(cmd: TeamCmd, auth: &DeviceAuth) -> Result<String, CuaError> {
+ async fn text(cmd: TeamCmd, ctx: &TeamCtx) -> Result<String, CuaError> {
let mut out = Vec::new();
- run_with(cmd, auth, &|_| true, false, &mut out).await?;
+ run_with(cmd, ctx, &|_| true, false, &mut out).await?;
Ok(String::from_utf8(out).unwrap())
}
#[tokio::test]
- async fn create_invite_join_approve_and_audit() {
- let relay = FakeRelay::start().await;
- relay.add_account("t-ada", "ada", Some("[email protected]"));
- relay.add_account("t-bob", "bob", Some("[email protected]"));
- relay.require_devices(true);
- let ada = enrolled(&relay, "t-ada", "ada").await;
- let bob = enrolled(&relay, "t-bob", "bob").await;
+ async fn teams_are_organizations_with_machines_and_approved_devices() {
+ let api = FakeSpacesApi::start().await;
+ api.add_account("t-ada", "ada", "[email protected]");
+ api.add_account("t-bob", "bob", "[email protected]");
+ let org = api.add_org(
+ "aigis",
+ "AIGIS",
+ "ada",
+ &["team_machines", "device_approval"],
+ );
+ api.add_member(&org, "bob", "member");
+ let ada = ctx(&api, "t-ada", Some("dev_ada"));
+ let bob = ctx(&api, "t-bob", Some("dev_bob"));
- let t = text(
- TeamCmd::Create {
- name: "AIGIS".into(),
- },
- &ada,
- )
- .await
- .unwrap();
- assert!(t.contains("Created team AIGIS (team-"), "{t}");
- // Teams resolve by name.
+ // Listed by organization id; resolved by name.
+ let t = text(TeamCmd::Ls, &bob).await.unwrap();
+ assert!(t.contains(&format!("{org} AIGIS member teams")), "{t}");
let t = text(
TeamCmd::Invite {
team: "aigis".into(),
- email: None,
- link: true,
+ email: "[email protected]".into(),
role: "member".into(),
},
&ada,
)
.await
.unwrap();
- let link = t
- .lines()
- .find_map(|l| l.trim().strip_prefix("They run: cua team join "))
- .expect("a join line")
- .to_string();
- assert!(link.contains("/join/team/"), "{link}");
+ assert!(t.contains("emails them an invitation"), "{t}");
+ // Bob asks for his device; he cannot approve it himself; Ada does.
let t = text(
- TeamCmd::Join {
- code: Some(link),
- team: None,
+ TeamCmd::Request {
+ team: "AIGIS".into(),
},
&bob,
)
.await
.unwrap();
- assert!(t.contains("You joined AIGIS"), "{t}");
- assert!(t.contains("waits for a team admin's approval"), "{t}");
-
- // A member cannot approve; the owner sees the device and approves.
- let bob_device = bob.device_id().unwrap().unwrap();
+ assert!(t.contains("dev_bob") && t.contains("pending"), "{t}");
let refused = text(
TeamCmd::Approve {
team: "AIGIS".into(),
- device: bob_device.clone(),
+ device: "dev_bob".into(),
},
&bob,
)
.await
.unwrap_err();
assert!(
- matches!(refused, CuaError::PermissionDenied(_)),
+ matches!(
+ refused,
+ CuaError::NotFound(_) | CuaError::PermissionDenied(_)
+ ),
"{refused:?}"
);
+ let t = text(TeamCmd::Devices { team: org.clone() }, &ada)
+ .await
+ .unwrap();
+ assert!(t.contains("dev_bob") && t.contains("pending"), "{t}");
let t = text(
- TeamCmd::Devices {
- team: "AIGIS".into(),
+ TeamCmd::Approve {
+ team: org.clone(),
+ device: "dev_bob".into(),
},
&ada,
)
.await
.unwrap();
- assert!(t.contains(&bob_device) && t.contains("pending"), "{t}");
- let t = text(
- TeamCmd::Approve {
+ assert!(t.contains("Approved dev_bob"), "{t}");
+ assert_eq!(
+ api.approvals(&org),
+ vec![("dev_bob".into(), "approved".into())]
+ );
+
+ // Machines: removing one the team does not have is not found.
+ let e = text(
+ TeamCmd::RemoveMachine {
team: "AIGIS".into(),
- device: bob_device.clone(),
+ machine: "relay:nope".into(),
},
&ada,
)
.await
- .unwrap();
- assert!(t.contains("Approved"), "{t}");
+ .unwrap_err();
+ assert!(matches!(e, CuaError::NotFound(_)), "{e:?}");
- let t = text(TeamCmd::Ls, &bob).await.unwrap();
- assert!(t.contains("AIGIS member"), "{t}");
let t = text(
- TeamCmd::Audit {
+ TeamCmd::Show {
team: "AIGIS".into(),
- limit: 50,
},
&ada,
)
.await
.unwrap();
- for k in [
- "team_created",
- "invite_created",
- "member_joined",
- "device_approved",
- ] {
- assert!(t.contains(k), "{k} in {t}");
- }
+ assert!(t.contains("AIGIS") && t.contains("[email protected]"), "{t}");
let e = text(
TeamCmd::Show {
team: "nope".into(),
@@ -733,5 +788,47 @@ mod tests {
.await
.unwrap_err();
assert!(matches!(e, CuaError::NotFound(_)), "{e:?}");
+ // The relay's old team ids are refused outright.
+ let e = text(
+ TeamCmd::Show {
+ team: "team-0a1b2c3d4e5f6a7b".into(),
+ },
+ &ada,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(e, CuaError::InvalidArgument(_)), "{e:?}");
+ }
+
+ #[tokio::test]
+ async fn audit_points_to_the_account_app() {
+ let api = FakeSpacesApi::start().await;
+ let t = text(
+ TeamCmd::Audit {
+ team: "AIGIS".into(),
+ limit: 50,
+ },
+ &ctx(&api, "t-nobody", None),
+ )
+ .await
+ .unwrap();
+ assert!(
+ t.starts_with("Audit export is coming soon (CUA-1374); see app."),
+ "{t}"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_server_without_teams_says_so() {
+ let api = FakeSpacesApi::start().await;
+ api.add_account("t-ada", "ada", "[email protected]");
+ api.without_teams();
+ let e = text(TeamCmd::Ls, &ctx(&api, "t-ada", None))
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(e, CuaError::Unsupported(ref m) if m.contains("Teams are not available on this server yet")),
+ "{e:?}"
+ );
}
}
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index ed59d8370c..4f40778075 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -45,7 +45,6 @@ pub mod service;
#[cfg(test)]
mod setup_tests;
pub mod spaces_api;
-pub mod team;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
#[cfg(test)]
@@ -72,10 +71,6 @@ pub use relay::{
RelayUsageTeam, StaticToken, relay_url_from_env,
};
pub use service::{RunnerKind, ServiceManager, ServiceSpec, ServiceState};
-pub use team::{
- NewTeamInvite, Team, TeamAuditEvent, TeamDevice, TeamInvite, TeamList, TeamMachine, TeamMember,
- TeamRole, team_code_from_link,
-};
/// The default display name of this device: the macOS Computer Name, else
/// the host name without a `.local` / `.localdomain` suffix.
diff --git a/libs/cua/crates/cua-host/src/pairing.rs b/libs/cua/crates/cua-host/src/pairing.rs
index 9618dab177..a0ca79ac84 100644
--- a/libs/cua/crates/cua-host/src/pairing.rs
+++ b/libs/cua/crates/cua-host/src/pairing.rs
@@ -264,6 +264,66 @@ impl RelayClient {
}
}
+impl RelayClient {
+ /// Waits (polling every `poll`) until the pairing code `code_id` adds a
+ /// machine, then makes that machine a machine of the team `org` on the
+ /// Spaces API (`POST /v1/orgs/{org}/machines`): pairing alone never puts
+ /// a machine in a team. A plan bought a moment ago is waited for (see
+ /// [`crate::spaces_api::SpacesApiClient::finishing_setup`]; `waiting`
+ /// is called meanwhile). Gives up when the code is revoked or expires,
+ /// or at `until` (Unix seconds). Returns the machine id.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn add_paired_machine_to_team(
+ &self,
+ api: &crate::spaces_api::SpacesApiClient,
+ token: &str,
+ code_id: &str,
+ org: &str,
+ until: u64,
+ poll: std::time::Duration,
+ waiting: impl FnMut(std::time::Duration),
+ ) -> Result<String> {
+ let now = || {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+ };
+ let (machine, name) = loop {
+ let codes = self.pairing_codes(token).await?;
+ let c = codes.into_iter().find(|c| c.id == code_id);
+ match c {
+ Some(c) if c.state == "used" && c.machine.is_some() => {
+ break (c.machine.unwrap_or_default(), c.name.unwrap_or_default());
+ }
+ Some(c) if c.state == "revoked" || c.state == "expired" => {
+ return Err(Error::InvalidArgument(format!(
+ "pairing code {code_id} was {} before a machine used it",
+ c.state
+ )));
+ }
+ None => {
+ return Err(Error::NotFound(format!("pairing code {code_id}")));
+ }
+ Some(_) if now() >= until => {
+ return Err(Error::InvalidArgument(format!(
+ "no machine used pairing code {code_id} in time"
+ )));
+ }
+ Some(_) => tokio::time::sleep(poll).await,
+ }
+ };
+ api.finishing_setup(
+ token,
+ crate::spaces_api::SETUP_RETRY_WINDOW,
+ waiting,
+ || api.add_org_machine(token, org, &machine, "", &name),
+ )
+ .await?;
+ Ok(machine)
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/libs/cua/crates/cua-host/src/spaces_api.rs b/libs/cua/crates/cua-host/src/spaces_api.rs
index 740e8dc84a..4b48032028 100644
--- a/libs/cua/crates/cua-host/src/spaces_api.rs
+++ b/libs/cua/crates/cua-host/src/spaces_api.rs
@@ -33,6 +33,137 @@ pub struct ApiOrg {
pub status: String,
#[serde(default)]
pub seats: i64,
+ /// Paid features the org has (`team_machines`, `space_sharing`,
+ /// `device_approval`, ...).
+ #[serde(default)]
+ pub features: Vec<String>,
+}
+
+impl ApiOrg {
+ /// The name to show: the display name, else the alias, else the id.
+ pub fn label(&self) -> &str {
+ [&self.name, &self.alias, &self.id]
+ .into_iter()
+ .find(|s| !s.is_empty())
+ .map(String::as_str)
+ .unwrap_or("")
+ }
+
+ /// Whether the org's plan includes `feature`.
+ pub fn has(&self, feature: &str) -> bool {
+ self.features.iter().any(|f| f == feature)
+ }
+
+ /// Whether the account may administer the org (add machines, approve
+ /// devices, invite).
+ pub fn manages(&self) -> bool {
+ matches!(self.role.as_str(), "owner" | "admin")
+ }
+}
+
+/// `GET /v1/orgs/{org}`: one org with its plan and seats.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiOrgDetail {
+ #[serde(default)]
+ pub id: String,
+ #[serde(default)]
+ pub alias: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub role: String,
+ #[serde(default)]
+ pub plan: String,
+ #[serde(default)]
+ pub status: String,
+ #[serde(default)]
+ pub features: Vec<String>,
+ #[serde(default)]
+ pub seats_paid: i64,
+ #[serde(default)]
+ pub seats_used: i64,
+}
+
+/// A machine bound to an org (`GET /v1/orgs/{org}/machines`): every
+/// member opens it from an approved device. `machine_id` is the relay
+/// record id (`relay:<machine_id>`).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiOrgMachine {
+ #[serde(default)]
+ pub machine_id: String,
+ #[serde(default)]
+ pub platform: String,
+ #[serde(default)]
+ pub label: String,
+ #[serde(default)]
+ pub added_by: String,
+ #[serde(default)]
+ pub added_at: String,
+}
+
+/// A member device's approval in an org (`GET /v1/orgs/{org}/devices`).
+/// `device_id` is the relay device id (`dev_…`).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiDeviceApproval {
+ #[serde(default)]
+ pub sub: String,
+ #[serde(default)]
+ pub device_id: String,
+ /// `pending`, `approved` or `denied`.
+ #[serde(default)]
+ pub state: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub decided_by: Option<String>,
+ #[serde(default)]
+ pub requested_at: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub decided_at: Option<String>,
+}
+
+/// `GET /v1/pairing-codes/{id}`.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ApiPairingState {
+ #[serde(default)]
+ pub id: String,
+ /// `pending`, `redeemed` or `expired`.
+ #[serde(default)]
+ pub state: String,
+ #[serde(default)]
+ pub device_id: String,
+ #[serde(default)]
+ pub expires_at: String,
+}
+
+/// What the clients say when the Spaces API has no Teams (org) routes, or
+/// cannot be reached. The clients never fall back to the relay's retired
+/// `team-…` teams.
+pub const TEAMS_NOT_AVAILABLE: &str =
+ "Teams are not available on this server yet. Try again later, or update Cua.";
+
+/// What a team operation says while it waits for a just-paid plan to
+/// reach the API (see [`SpacesApiClient::finishing_setup`]).
+pub const FINISHING_SETUP: &str = "Finishing setup…";
+
+/// How long a team operation keeps retrying a `402 feature_required` (the
+/// plan was just bought and its entitlements are on their way).
+pub const SETUP_RETRY_WINDOW: Duration = Duration::from_secs(60);
+
+/// Whether `e` is the API's `402 feature_required` (the org's plan lacks a
+/// feature, or a just-bought plan has not reached the API yet).
+pub fn is_feature_required(e: &Error) -> bool {
+ e.to_string().contains("HTTP 402 (feature_required")
+}
+
+/// Whether `e` says Teams are not available on this server (see
+/// [`TEAMS_NOT_AVAILABLE`]).
+pub fn is_teams_unavailable(e: &Error) -> bool {
+ e.to_string().starts_with(TEAMS_NOT_AVAILABLE)
+}
+
+/// Whether `e` is worth retrying: a just-paid plan (402 feature_required)
+/// or a dependency of the API that is down for a moment (503).
+fn is_retryable(e: &Error) -> bool {
+ is_feature_required(e) || e.to_string().contains("HTTP 503")
}
/// `GET /v1/me`.
@@ -108,6 +239,30 @@ pub struct TeamsSnapshot {
pub teams: Vec<TeamDetail>,
}
+/// A path segment (org ids, aliases, device and machine ids are plain, but
+/// never trust them into a URL as is).
+fn seg(s: &str) -> String {
+ url::form_urlencoded::byte_serialize(s.trim().as_bytes()).collect()
+}
+
+/// Whether `id` is a team id of the relay's retired teams
+/// (`team-<16 hex>`), which the clients no longer use.
+pub fn is_legacy_team_id(id: &str) -> bool {
+ id.strip_prefix("team-")
+ .is_some_and(|h| h.len() == 16 && h.chars().all(|c| c.is_ascii_hexdigit()))
+}
+
+/// Whether `id` can name an org (Team): its Keycloak id (a UUID) or its
+/// alias (lowercase letters, digits and dashes). Not a retired `team-…` id.
+pub fn is_org_ref(id: &str) -> bool {
+ !id.is_empty()
+ && id.len() <= 64
+ && !is_legacy_team_id(id)
+ && id
+ .chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
+}
+
/// A Spaces API client.
#[derive(Clone)]
pub struct SpacesApiClient {
@@ -115,6 +270,35 @@ pub struct SpacesApiClient {
http: reqwest::Client,
}
+/// The API's error code (`{"error":"org_not_found"}`), when it sent one.
+fn error_code(body: &str) -> Option<String> {
+ serde_json::from_str::<serde_json::Value>(body)
+ .ok()?
+ .get("error")?
+ .as_str()
+ .map(str::to_string)
+}
+
+/// The error of an org (Teams) route: [`http_error`], except that a route
+/// the server does not have (404 without one of the API's own codes, 410
+/// Gone, 501) means Teams are not available there, and `not_owner` gets
+/// the words the apps show.
+fn org_error(status: u16, body: &str) -> Error {
+ let code = error_code(body);
+ let unavailable = match status {
+ 410 | 501 => true,
+ 404 => !code.as_deref().is_some_and(|c| c.ends_with("_not_found")),
+ _ => false,
+ };
+ if unavailable {
+ return Error::Internal(format!("{TEAMS_NOT_AVAILABLE} (HTTP {status})"));
+ }
+ if status == 403 && code.as_deref() == Some("not_owner") {
+ return Error::PermissionDenied("Only the machine's owner can add it to a team.".into());
+ }
+ http_error(status, body)
+}
+
fn http_error(status: u16, body: &str) -> Error {
let detail = serde_json::from_str::<serde_json::Value>(body)
.ok()
@@ -134,7 +318,7 @@ fn http_error(status: u16, body: &str) -> Error {
);
match status {
401 => Error::Unauthenticated(msg),
- 403 => Error::PermissionDenied(msg),
+ 402 | 403 => Error::PermissionDenied(msg),
404 => Error::NotFound(msg),
409 => Error::Conflict(msg),
_ => Error::Internal(msg),
@@ -173,18 +357,46 @@ impl SpacesApiClient {
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)))?;
+ self.send_as(req, token, false).await
+ }
+
+ /// Sends an org (Teams) request: see [`org_error`]. An API that cannot
+ /// be reached at all also means Teams are not available.
+ async fn send_org<T: serde::de::DeserializeOwned>(
+ &self,
+ req: reqwest::RequestBuilder,
+ token: &str,
+ ) -> Result<T> {
+ self.send_as(req, token, true).await
+ }
+
+ async fn send_as<T: serde::de::DeserializeOwned>(
+ &self,
+ req: reqwest::RequestBuilder,
+ token: &str,
+ org: bool,
+ ) -> Result<T> {
+ let resp = req.bearer_auth(token).send().await.map_err(|e| {
+ if org {
+ Error::Internal(format!(
+ "{TEAMS_NOT_AVAILABLE} (the Spaces API at {} cannot be reached: {e})",
+ self.base
+ ))
+ } else {
+ 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));
+ return Err(if org {
+ org_error(status.as_u16(), &body)
+ } else {
+ http_error(status.as_u16(), &body)
+ });
}
serde_json::from_str(if body.trim().is_empty() {
"null"
@@ -199,9 +411,33 @@ impl SpacesApiClient {
.await
}
+ fn url(&self, path: &str) -> String {
+ format!("{}{path}", self.base)
+ }
+
+ async fn org_get<T: serde::de::DeserializeOwned>(&self, path: &str, token: &str) -> Result<T> {
+ self.send_org(self.http.get(self.url(path)), token).await
+ }
+
+ async fn org_post<T: serde::de::DeserializeOwned>(
+ &self,
+ path: &str,
+ token: &str,
+ body: serde_json::Value,
+ ) -> Result<T> {
+ self.send_org(self.http.post(self.url(path)).json(&body), token)
+ .await
+ }
+
+ async fn org_delete(&self, path: &str, token: &str) -> Result<()> {
+ self.send_org::<serde_json::Value>(self.http.delete(self.url(path)), token)
+ .await
+ .map(|_| ())
+ }
+
/// `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
+ self.org_get("/v1/me", token).await
}
/// `GET /v1/me/entitlements` (the raw answer).
@@ -217,7 +453,7 @@ impl SpacesApiClient {
members: Vec<ApiMember>,
}
Ok(self
- .get::<R>(&format!("/v1/orgs/{org}/members"), token)
+ .org_get::<R>(&format!("/v1/orgs/{}/members", seg(org)), token)
.await?
.members)
}
@@ -230,7 +466,7 @@ impl SpacesApiClient {
invites: Vec<ApiInvite>,
}
Ok(self
- .get::<R>(&format!("/v1/orgs/{org}/invites"), token)
+ .org_get::<R>(&format!("/v1/orgs/{}/invites", seg(org)), token)
.await?
.invites)
}
@@ -251,6 +487,277 @@ impl SpacesApiClient {
.await
}
+ /// The org (Team) `query` names, from `GET /v1/me`: its id, its alias,
+ /// or its display name (case-insensitive). The account's orgs come
+ /// from its token: one made a moment ago shows up after a new sign-in.
+ pub async fn resolve_org(&self, token: &str, query: &str) -> Result<ApiOrg> {
+ let q = query.trim();
+ let q = q.strip_prefix("team:").unwrap_or(q);
+ if is_legacy_team_id(q) {
+ return Err(Error::InvalidArgument(format!(
+ "{q} is a team id of the old Teams, which this version no longer uses: \
+ use the team's id from `cua team ls`"
+ )));
+ }
+ let me: ApiMe = self.org_get("/v1/me", token).await?;
+ if let Some(o) = me.orgs.iter().find(|o| o.id == q || o.alias == q) {
+ return Ok(o.clone());
+ }
+ let named: Vec<_> = me
+ .orgs
+ .iter()
+ .filter(|o| o.name.eq_ignore_ascii_case(q) || o.alias.eq_ignore_ascii_case(q))
+ .collect();
+ match named.as_slice() {
+ [o] => Ok((*o).clone()),
+ [] => Err(Error::NotFound(format!(
+ "no team of yours is called {q:?} (`cua team ls`; a team made or joined a \
+ moment ago shows up after `cua auth login`)"
+ ))),
+ _ => Err(Error::InvalidArgument(format!(
+ "several of your teams are called {q:?}: use the team id (`cua team ls`)"
+ ))),
+ }
+ }
+
+ /// `POST /v1/orgs`: makes a team; the account is its owner. The
+ /// account's token lists it after the next sign-in.
+ pub async fn create_org(&self, token: &str, name: &str) -> Result<ApiOrg> {
+ self.org_post("/v1/orgs", token, serde_json::json!({ "name": name }))
+ .await
+ }
+
+ /// `GET /v1/orgs/{org}`.
+ pub async fn org(&self, token: &str, org: &str) -> Result<ApiOrgDetail> {
+ self.org_get(&format!("/v1/orgs/{}", seg(org)), token).await
+ }
+
+ /// `DELETE /v1/orgs/{org}` (owner; only without a live subscription).
+ pub async fn delete_org(&self, token: &str, org: &str) -> Result<()> {
+ self.org_delete(&format!("/v1/orgs/{}", seg(org)), token)
+ .await
+ }
+
+ /// `POST /v1/orgs/{org}/leave`.
+ pub async fn leave_org(&self, token: &str, org: &str) -> Result<()> {
+ self.org_post::<serde_json::Value>(
+ &format!("/v1/orgs/{}/leave", seg(org)),
+ token,
+ serde_json::json!({}),
+ )
+ .await
+ .map(|_| ())
+ }
+
+ /// `POST /v1/orgs/{org}/invites` (owner or admin): Keycloak mails the
+ /// invitation.
+ pub async fn invite(&self, token: &str, org: &str, email: &str, role: &str) -> Result<()> {
+ self.org_post::<serde_json::Value>(
+ &format!("/v1/orgs/{}/invites", seg(org)),
+ token,
+ serde_json::json!({ "email": email, "role": role }),
+ )
+ .await
+ .map(|_| ())
+ }
+
+ /// `DELETE /v1/orgs/{org}/invites/{id}`.
+ pub async fn revoke_invite(&self, token: &str, org: &str, id: &str) -> Result<()> {
+ self.org_delete(&format!("/v1/orgs/{}/invites/{}", seg(org), seg(id)), token)
+ .await
+ }
+
+ /// `POST /v1/orgs/{org}/invites/claim`: after joining from the mailed
+ /// invitation, applies the role the invite promised. Returns the role.
+ pub async fn claim_invite(&self, token: &str, org: &str) -> Result<String> {
+ #[derive(Deserialize)]
+ struct R {
+ #[serde(default)]
+ role: String,
+ }
+ Ok(self
+ .org_post::<R>(
+ &format!("/v1/orgs/{}/invites/claim", seg(org)),
+ token,
+ serde_json::json!({}),
+ )
+ .await?
+ .role)
+ }
+
+ /// `PATCH /v1/orgs/{org}/members/{sub}` (owner): `admin` or `member`.
+ pub async fn set_member_role(
+ &self,
+ token: &str,
+ org: &str,
+ sub: &str,
+ role: &str,
+ ) -> Result<()> {
+ self.send_org::<serde_json::Value>(
+ self.http
+ .patch(self.url(&format!("/v1/orgs/{}/members/{}", seg(org), seg(sub))))
+ .json(&serde_json::json!({ "role": role })),
+ token,
+ )
+ .await
+ .map(|_| ())
+ }
+
+ /// `DELETE /v1/orgs/{org}/members/{sub}` (owner or admin).
+ pub async fn remove_member(&self, token: &str, org: &str, sub: &str) -> Result<()> {
+ self.org_delete(
+ &format!("/v1/orgs/{}/members/{}", seg(org), seg(sub)),
+ token,
+ )
+ .await
+ }
+
+ /// `GET /v1/orgs/{org}/machines`: the team's machines.
+ pub async fn org_machines(&self, token: &str, org: &str) -> Result<Vec<ApiOrgMachine>> {
+ #[derive(Deserialize)]
+ struct R {
+ #[serde(default)]
+ machines: Vec<ApiOrgMachine>,
+ }
+ Ok(self
+ .org_get::<R>(&format!("/v1/orgs/{}/machines", seg(org)), token)
+ .await?
+ .machines)
+ }
+
+ /// `POST /v1/orgs/{org}/machines` (owner or admin): makes the relay
+ /// machine (or Space) `machine_id` a team machine. Already a team
+ /// machine is not an error. A `402 feature_required` is returned as is;
+ /// [`Self::finishing_setup`] retries it after a checkout.
+ pub async fn add_org_machine(
+ &self,
+ token: &str,
+ org: &str,
+ machine_id: &str,
+ platform: &str,
+ label: &str,
+ ) -> Result<()> {
+ let label: String = label.chars().take(120).collect();
+ match self
+ .org_post::<serde_json::Value>(
+ &format!("/v1/orgs/{}/machines", seg(org)),
+ token,
+ serde_json::json!({ "machine_id": machine_id, "platform": platform, "label": label }),
+ )
+ .await
+ {
+ Ok(_) => Ok(()),
+ Err(Error::Conflict(m)) if m.contains("already_added") => Ok(()),
+ Err(e) => Err(e),
+ }
+ }
+
+ /// `DELETE /v1/orgs/{org}/machines/{id}` (owner or admin).
+ pub async fn remove_org_machine(&self, token: &str, org: &str, machine_id: &str) -> Result<()> {
+ self.org_delete(
+ &format!("/v1/orgs/{}/machines/{}", seg(org), seg(machine_id)),
+ token,
+ )
+ .await
+ }
+
+ /// `GET /v1/orgs/{org}/devices`: admins see every member device,
+ /// members their own.
+ pub async fn org_devices(&self, token: &str, org: &str) -> Result<Vec<ApiDeviceApproval>> {
+ #[derive(Deserialize)]
+ struct R {
+ #[serde(default)]
+ devices: Vec<ApiDeviceApproval>,
+ }
+ Ok(self
+ .org_get::<R>(&format!("/v1/orgs/{}/devices", seg(org)), token)
+ .await?
+ .devices)
+ }
+
+ /// `POST /v1/orgs/{org}/devices/request`: asks the team's admins to
+ /// approve the relay device `device_id` (this device).
+ pub async fn request_org_device(
+ &self,
+ token: &str,
+ org: &str,
+ device_id: &str,
+ ) -> Result<ApiDeviceApproval> {
+ self.org_post(
+ &format!("/v1/orgs/{}/devices/request", seg(org)),
+ token,
+ serde_json::json!({ "device_id": device_id }),
+ )
+ .await
+ }
+
+ /// `POST /v1/orgs/{org}/devices/{id}/approve|deny` (owner or admin):
+ /// `sub` is the member whose device it is.
+ pub async fn decide_org_device(
+ &self,
+ token: &str,
+ org: &str,
+ device_id: &str,
+ sub: &str,
+ approve: bool,
+ ) -> Result<ApiDeviceApproval> {
+ self.org_post(
+ &format!(
+ "/v1/orgs/{}/devices/{}/{}",
+ seg(org),
+ seg(device_id),
+ if approve { "approve" } else { "deny" }
+ ),
+ token,
+ serde_json::json!({ "sub": sub }),
+ )
+ .await
+ }
+
+ /// `GET /v1/pairing-codes/{id}`.
+ pub async fn pairing(&self, token: &str, id: &str) -> Result<ApiPairingState> {
+ self.get(&format!("/v1/pairing-codes/{}", seg(id)), token)
+ .await
+ }
+
+ /// Runs the team operation `op`, and while it answers `402
+ /// feature_required` (a plan bought a moment ago whose entitlements
+ /// have not reached the API) or a passing `503`, refreshes the
+ /// entitlements (`GET /v1/me/entitlements`) and retries with backoff
+ /// for up to `window`. `waiting` is called before each retry so the
+ /// caller can show [`FINISHING_SETUP`]. Any other answer, or the last
+ /// one after `window`, is returned.
+ pub async fn finishing_setup<T, F, Fut>(
+ &self,
+ token: &str,
+ window: Duration,
+ mut waiting: impl FnMut(Duration),
+ mut op: F,
+ ) -> Result<T>
+ where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = Result<T>>,
+ {
+ let start = std::time::Instant::now();
+ let mut pause = Duration::from_millis(500);
+ loop {
+ let res = op().await;
+ match &res {
+ Err(e) if is_retryable(e) => {
+ let spent = start.elapsed();
+ if spent >= window {
+ return res;
+ }
+ waiting(spent);
+ let _ = self.entitlements(token).await;
+ tokio::time::sleep(pause.min(window.saturating_sub(start.elapsed()))).await;
+ pause = (pause * 2).min(Duration::from_secs(8));
+ }
+ _ => return res,
+ }
+ }
+ }
+
/// 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.
@@ -421,6 +928,146 @@ mod tests {
assert!(SpacesApiClient::new("nonsense").is_err());
}
+ #[tokio::test]
+ async fn org_machines_and_devices_round_trip() {
+ let api = crate::testing::FakeSpacesApi::start().await;
+ api.add_account("ada", "sub-ada", "[email protected]");
+ api.add_account("bob", "sub-bob", "[email protected]");
+ let org = api.add_org(
+ "acme",
+ "Acme",
+ "sub-ada",
+ &["team_machines", "device_approval"],
+ );
+ api.add_member(&org, "sub-bob", "member");
+ let c = SpacesApiClient::new(&api.url).unwrap();
+
+ // Teams resolve by id, alias or name; the old team- ids are refused.
+ assert_eq!(c.resolve_org("ada", "Acme").await.unwrap().id, org);
+ assert_eq!(
+ c.resolve_org("ada", &format!("team:{org}"))
+ .await
+ .unwrap()
+ .alias,
+ "acme"
+ );
+ let e = c
+ .resolve_org("ada", "team-0123456789abcdef")
+ .await
+ .unwrap_err();
+ assert!(e.to_string().contains("old Teams"), "{e}");
+
+ c.add_org_machine("ada", &org, "m1", "linux", "box")
+ .await
+ .unwrap();
+ // Adding it again is not an error.
+ c.add_org_machine("ada", &org, "m1", "linux", "box")
+ .await
+ .unwrap();
+ assert_eq!(api.machines(&org), vec!["m1".to_string()]);
+ // A plain member cannot.
+ let e = c
+ .add_org_machine("bob", &org, "m2", "", "")
+ .await
+ .unwrap_err();
+ assert!(matches!(e, Error::PermissionDenied(_)), "{e}");
+ assert_eq!(c.org_machines("bob", &org).await.unwrap().len(), 1);
+
+ let a = c.request_org_device("bob", &org, "dev_b").await.unwrap();
+ assert_eq!(a.state, "pending");
+ let a = c
+ .decide_org_device("ada", &org, "dev_b", "sub-bob", true)
+ .await
+ .unwrap();
+ assert_eq!(a.state, "approved");
+ assert_eq!(
+ api.approvals(&org),
+ vec![("dev_b".into(), "approved".into())]
+ );
+
+ c.remove_org_machine("ada", &org, "m1").await.unwrap();
+ let e = c.remove_org_machine("ada", &org, "m1").await.unwrap_err();
+ assert!(matches!(e, Error::NotFound(_)), "{e}");
+ }
+
+ #[tokio::test]
+ async fn a_just_paid_plan_is_retried_until_it_arrives() {
+ let api = crate::testing::FakeSpacesApi::start().await;
+ api.add_account("ada", "sub-ada", "[email protected]");
+ let org = api.add_org("acme", "Acme", "sub-ada", &["team_machines"]);
+ api.feature_lag(2);
+ let c = SpacesApiClient::new(&api.url).unwrap();
+ let mut waits = 0;
+ c.finishing_setup(
+ "ada",
+ Duration::from_secs(10),
+ |_| waits += 1,
+ || c.add_org_machine("ada", &org, "m1", "linux", ""),
+ )
+ .await
+ .unwrap();
+ assert_eq!(waits, 2);
+ assert_eq!(api.entitlement_reads(), 2);
+ assert_eq!(api.machines(&org), vec!["m1".to_string()]);
+
+ // A plan that never arrives surfaces the 402 after the window.
+ let free = api.add_org("free", "Free", "sub-ada", &[]);
+ let e = c
+ .finishing_setup(
+ "ada",
+ Duration::from_millis(600),
+ |_| {},
+ || c.add_org_machine("ada", &free, "m1", "linux", ""),
+ )
+ .await
+ .unwrap_err();
+ assert!(is_feature_required(&e), "{e}");
+ }
+
+ #[tokio::test]
+ async fn a_server_without_teams_says_so() {
+ let api = crate::testing::FakeSpacesApi::start().await;
+ api.add_account("ada", "sub-ada", "[email protected]");
+ let org = api.add_org("acme", "Acme", "sub-ada", &["team_machines"]);
+ api.without_teams();
+ let c = SpacesApiClient::new(&api.url).unwrap();
+ let e = c
+ .add_org_machine("ada", &org, "m1", "", "")
+ .await
+ .unwrap_err();
+ assert!(is_teams_unavailable(&e), "{e}");
+ let e = c.resolve_org("ada", "acme").await.unwrap_err();
+ assert!(is_teams_unavailable(&e), "{e}");
+ // Unreachable is the same answer.
+ let c = SpacesApiClient::new("http://127.0.0.1:1").unwrap();
+ let e = c.org_machines("ada", "acme").await.unwrap_err();
+ assert!(is_teams_unavailable(&e), "{e}");
+ }
+
+ #[test]
+ fn org_errors_name_the_owner_rule_and_unknown_routes() {
+ let e = org_error(403, r#"{"error":"not_owner"}"#);
+ assert_eq!(
+ e.to_string(),
+ "Only the machine's owner can add it to a team."
+ );
+ assert!(is_teams_unavailable(&org_error(404, "404 page not found")));
+ assert!(!is_teams_unavailable(&org_error(
+ 404,
+ r#"{"error":"org_not_found"}"#
+ )));
+ assert!(is_feature_required(&org_error(
+ 402,
+ r#"{"error":"feature_required","detail":"team_machines"}"#
+ )));
+ assert!(!is_feature_required(&org_error(
+ 402,
+ r#"{"error":"machine_limit"}"#
+ )));
+ assert!(is_org_ref("acme") && is_org_ref("0f1e2d3c-0000-4000-8000-000000000001"));
+ assert!(!is_org_ref("team-0123456789abcdef") && !is_org_ref("Acme"));
+ }
+
#[test]
fn errors_carry_the_api_detail() {
let e = http_error(410, r#"{"error":"gone","detail":"retired"}"#);
diff --git a/libs/cua/crates/cua-host/src/team.rs b/libs/cua/crates/cua-host/src/team.rs
deleted file mode 100644
index bd50d90a6d..0000000000
--- a/libs/cua/crates/cua-host/src/team.rs
+++ /dev/null
@@ -1,567 +0,0 @@
-//! Teams on the relay: a named group of cua.ai accounts with roles
-//! (`owner`, `admin`, `member`) that shares machines with every member.
-//! Owners and admins invite (by email or link), remove members, add
-//! machines they own (Mac, Linux or Windows), approve member devices (a
-//! member device opens team machines only once approved) and read the
-//! team's audit log.
-//!
-//! [`RelayClient`] has the raw calls (account token, from an enrolled
-//! device's session); [`DeviceAuth`] wraps them with this device's session.
-
-use crate::Result;
-use crate::device::DeviceAuth;
-use crate::relay::RelayClient;
-use serde::{Deserialize, Serialize};
-use serde_json::json;
-
-/// A member's role.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum TeamRole {
- #[default]
- Member,
- Admin,
- Owner,
-}
-
-impl TeamRole {
- /// `owner` / `admin` / `member`.
- pub fn as_str(self) -> &'static str {
- match self {
- TeamRole::Owner => "owner",
- TeamRole::Admin => "admin",
- TeamRole::Member => "member",
- }
- }
-
- /// Parses `member` / `admin`.
- pub fn parse(s: &str) -> Result<TeamRole> {
- match s.trim().to_ascii_lowercase().as_str() {
- "member" => Ok(TeamRole::Member),
- "admin" => Ok(TeamRole::Admin),
- other => Err(crate::Error::InvalidArgument(format!(
- "team role {other:?}: use member or admin"
- ))),
- }
- }
-
- /// Owners and admins manage the team.
- pub fn manages(self) -> bool {
- matches!(self, TeamRole::Owner | TeamRole::Admin)
- }
-}
-
-/// One member.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct TeamMember {
- pub account: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub email: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub name: Option<String>,
- pub role: TeamRole,
- #[serde(default)]
- pub joined_at: u64,
-}
-
-impl TeamMember {
- /// Email when known, else the account id.
- pub fn label(&self) -> &str {
- self.email.as_deref().unwrap_or(&self.account)
- }
-}
-
-/// A team machine.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct TeamMachine {
- pub id: String,
- #[serde(default)]
- pub name: String,
- /// The owner's email (or account id).
- #[serde(default)]
- pub owner: String,
- #[serde(default)]
- pub online: bool,
-}
-
-/// An open invite (never its code).
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct TeamInvite {
- pub id: String,
- /// Only this email may use it; a link invite otherwise.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub email: Option<String>,
- pub role: TeamRole,
- #[serde(default)]
- pub expires_at: u64,
- #[serde(default)]
- pub uses_left: u32,
-}
-
-/// A member device and its approval: `pending`, `approved`, `denied`.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct TeamDevice {
- pub account: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub email: Option<String>,
- pub device: String,
- #[serde(default)]
- pub name: String,
- pub state: String,
- #[serde(default)]
- pub requested_at: u64,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub decided_by: Option<String>,
-}
-
-/// A team as one of its members sees it.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct Team {
- pub id: String,
- pub name: String,
- /// The caller's role.
- pub role: TeamRole,
- #[serde(default)]
- pub created_at: u64,
- #[serde(default)]
- pub members: Vec<TeamMember>,
- #[serde(default)]
- pub machines: Vec<TeamMachine>,
- /// Open invites (owner/admin view).
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub invites: Vec<TeamInvite>,
- /// Member devices (owner/admin: all; member: their own).
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub devices: Vec<TeamDevice>,
- /// This device's approval (`pending`, `approved`, `denied`), if known.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub this_device: Option<String>,
-}
-
-/// An email invite waiting for the caller.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct PendingTeamInvite {
- pub team: String,
- #[serde(default)]
- pub team_name: String,
- pub invite: TeamInvite,
-}
-
-/// `GET /v1/teams`.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct TeamList {
- #[serde(default)]
- pub teams: Vec<Team>,
- /// Email invites for the caller's verified email.
- #[serde(default)]
- pub invites: Vec<PendingTeamInvite>,
-}
-
-/// A new invite: its code and link are shown once.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct NewTeamInvite {
- pub invite: TeamInvite,
- pub code: String,
- pub link: String,
-}
-
-/// One team audit line.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct TeamAuditEvent {
- pub ts: u64,
- pub kind: String,
- #[serde(default)]
- pub actor: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub device: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub subject: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub machine: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub detail: Option<String>,
-}
-
-#[derive(Deserialize)]
-struct AuditList {
- #[serde(default)]
- events: Vec<TeamAuditEvent>,
-}
-
-/// The invite code in a pasted link (`…/join/team/<code>`) or the code
-/// itself.
-pub fn team_code_from_link(s: &str) -> String {
- let s = s.trim();
- s.rsplit_once("/join/team/")
- .map(|(_, c)| c)
- .unwrap_or(s)
- .trim_end_matches('/')
- .to_string()
-}
-
-fn seg(s: &str) -> String {
- url::form_urlencoded::byte_serialize(s.as_bytes())
- .collect::<String>()
- .replace('+', "%20")
-}
-
-impl RelayClient {
- /// Your teams and the email invites waiting for you.
- pub async fn teams(&self, token: &str) -> Result<TeamList> {
- self.send(self.http.get(self.url("/v1/teams")), token).await
- }
-
- /// One team you are in.
- pub async fn team(&self, token: &str, id: &str) -> Result<Team> {
- self.send(
- self.http.get(self.url(&format!("/v1/teams/{}", seg(id)))),
- token,
- )
- .await
- }
-
- /// Creates a team; you are its owner.
- pub async fn create_team(&self, token: &str, name: &str) -> Result<Team> {
- self.send(
- self.http
- .post(self.url("/v1/teams"))
- .json(&json!({ "name": name })),
- token,
- )
- .await
- }
-
- /// Deletes a team (owner).
- pub async fn delete_team(&self, token: &str, id: &str) -> Result<()> {
- let _: serde_json::Value = self
- .send(
- self.http
- .delete(self.url(&format!("/v1/teams/{}", seg(id)))),
- token,
- )
- .await?;
- Ok(())
- }
-
- /// Joins with an invite `code` (or link), or, with `team` and no code,
- /// the email invite for your verified email.
- pub async fn join_team(
- &self,
- token: &str,
- code: Option<&str>,
- team: Option<&str>,
- ) -> Result<Team> {
- self.send(
- self.http.post(self.url("/v1/teams/join")).json(&json!({
- "code": code.map(team_code_from_link),
- "team": team,
- })),
- token,
- )
- .await
- }
-
- /// Leaves a team.
- pub async fn leave_team(&self, token: &str, id: &str) -> Result<()> {
- let _: serde_json::Value = self
- .send(
- self.http
- .post(self.url(&format!("/v1/teams/{}/leave", seg(id))))
- .json(&json!({})),
- token,
- )
- .await?;
- Ok(())
- }
-
- /// Invites `email` (or, without one, makes a link) as `role`.
- pub async fn invite_to_team(
- &self,
- token: &str,
- id: &str,
- email: Option<&str>,
- role: TeamRole,
- ) -> Result<NewTeamInvite> {
- self.send(
- self.http
- .post(self.url(&format!("/v1/teams/{}/invites", seg(id))))
- .json(&json!({ "email": email, "role": role })),
- token,
- )
- .await
- }
-
- /// Revokes an open invite.
- pub async fn revoke_team_invite(&self, token: &str, id: &str, invite: &str) -> Result<()> {
- let _: serde_json::Value = self
- .send(
- self.http.delete(self.url(&format!(
- "/v1/teams/{}/invites/{}",
- seg(id),
- seg(invite)
- ))),
- token,
- )
- .await?;
- Ok(())
- }
-
- /// Makes a member an admin or a member (owner).
- pub async fn set_team_role(
- &self,
- token: &str,
- id: &str,
- who: &str,
- role: TeamRole,
- ) -> Result<TeamMember> {
- self.send(
- self.http
- .patch(self.url(&format!("/v1/teams/{}/members/{}", seg(id), seg(who))))
- .json(&json!({ "role": role })),
- token,
- )
- .await
- }
-
- /// Removes a member (email or account id).
- pub async fn remove_team_member(&self, token: &str, id: &str, who: &str) -> Result<()> {
- let _: serde_json::Value = self
- .send(
- self.http
- .delete(self.url(&format!("/v1/teams/{}/members/{}", seg(id), seg(who)))),
- token,
- )
- .await?;
- Ok(())
- }
-
- /// Asks the team's admins to approve this device.
- pub async fn request_team_device(&self, token: &str, id: &str) -> Result<TeamDevice> {
- self.send(
- self.http
- .post(self.url(&format!("/v1/teams/{}/devices/request", seg(id))))
- .json(&json!({})),
- token,
- )
- .await
- }
-
- /// Approves (or denies) a member device (owner/admin).
- pub async fn decide_team_device(
- &self,
- token: &str,
- id: &str,
- device: &str,
- approve: bool,
- ) -> Result<TeamDevice> {
- self.send(
- self.http
- .post(self.url(&format!(
- "/v1/teams/{}/devices/{}/{}",
- seg(id),
- seg(device),
- if approve { "approve" } else { "deny" }
- )))
- .json(&json!({})),
- token,
- )
- .await
- }
-
- /// Adds a relay machine you own to the team (owner/admin). `os` is
- /// what the Space runs, when known (`linux`, `macos`, `windows`).
- pub async fn add_team_machine(
- &self,
- token: &str,
- id: &str,
- machine: &str,
- os: Option<&str>,
- ) -> Result<Team> {
- self.send(
- self.http
- .post(self.url(&format!("/v1/teams/{}/machines", seg(id))))
- .json(&json!({ "machine": machine, "os": os })),
- token,
- )
- .await
- }
-
- /// Takes a machine off the team.
- pub async fn remove_team_machine(&self, token: &str, id: &str, machine: &str) -> Result<Team> {
- self.send(
- self.http
- .delete(self.url(&format!("/v1/teams/{}/machines/{}", seg(id), seg(machine)))),
- token,
- )
- .await
- }
-
- /// The team's audit log, newest last (owner/admin).
- pub async fn team_audit(
- &self,
- token: &str,
- id: &str,
- limit: usize,
- ) -> Result<Vec<TeamAuditEvent>> {
- let l: AuditList = self
- .send(
- self.http
- .get(self.url(&format!("/v1/teams/{}/audit?limit={limit}", seg(id)))),
- token,
- )
- .await?;
- Ok(l.events)
- }
-}
-
-/// Every team call from this enrolled device (its session, renewed once if
-/// the relay forgot it).
-macro_rules! with_device {
- ($self:ident, [$($v:ident),*], |$relay:ident, $token:ident| $call:expr) => {
- $self
- .with_session_retry(move |$relay: RelayClient, $token: String| {
- $(let $v = $v.clone();)*
- async move { $call }
- })
- .await
- };
-}
-
-impl DeviceAuth {
- /// Your teams and the email invites waiting for you.
- pub async fn teams(&self) -> Result<TeamList> {
- with_device!(self, [], |r, t| r.teams(&t).await)
- }
-
- /// One team.
- pub async fn team(&self, id: &str) -> Result<Team> {
- let id = id.to_owned();
- with_device!(self, [id], |r, t| r.team(&t, &id).await)
- }
-
- /// Creates a team.
- pub async fn create_team(&self, name: &str) -> Result<Team> {
- let name = name.to_owned();
- with_device!(self, [name], |r, t| r.create_team(&t, &name).await)
- }
-
- /// Deletes a team (owner).
- pub async fn delete_team(&self, id: &str) -> Result<()> {
- let id = id.to_owned();
- with_device!(self, [id], |r, t| r.delete_team(&t, &id).await)
- }
-
- /// Joins with a code or link, or the email invite of `team`.
- pub async fn join_team(&self, code: Option<&str>, team: Option<&str>) -> Result<Team> {
- let (code, team) = (code.map(str::to_owned), team.map(str::to_owned));
- with_device!(self, [code, team], |r, t| r
- .join_team(&t, code.as_deref(), team.as_deref())
- .await)
- }
-
- /// Leaves a team.
- pub async fn leave_team(&self, id: &str) -> Result<()> {
- let id = id.to_owned();
- with_device!(self, [id], |r, t| r.leave_team(&t, &id).await)
- }
-
- /// Invites by email, or makes a link without one.
- pub async fn invite_to_team(
- &self,
- id: &str,
- email: Option<&str>,
- role: TeamRole,
- ) -> Result<NewTeamInvite> {
- let (id, email) = (id.to_owned(), email.map(str::to_owned));
- with_device!(self, [id, email], |r, t| r
- .invite_to_team(&t, &id, email.as_deref(), role)
- .await)
- }
-
- /// Revokes an invite.
- pub async fn revoke_team_invite(&self, id: &str, invite: &str) -> Result<()> {
- let (id, invite) = (id.to_owned(), invite.to_owned());
- with_device!(self, [id, invite], |r, t| r
- .revoke_team_invite(&t, &id, &invite)
- .await)
- }
-
- /// Changes a member's role (owner).
- pub async fn set_team_role(&self, id: &str, who: &str, role: TeamRole) -> Result<TeamMember> {
- let (id, who) = (id.to_owned(), who.to_owned());
- with_device!(self, [id, who], |r, t| r
- .set_team_role(&t, &id, &who, role)
- .await)
- }
-
- /// Removes a member.
- pub async fn remove_team_member(&self, id: &str, who: &str) -> Result<()> {
- let (id, who) = (id.to_owned(), who.to_owned());
- with_device!(self, [id, who], |r, t| r
- .remove_team_member(&t, &id, &who)
- .await)
- }
-
- /// Asks for this device's approval.
- pub async fn request_team_device(&self, id: &str) -> Result<TeamDevice> {
- let id = id.to_owned();
- with_device!(self, [id], |r, t| r.request_team_device(&t, &id).await)
- }
-
- /// Approves or denies a member device.
- pub async fn decide_team_device(
- &self,
- id: &str,
- device: &str,
- approve: bool,
- ) -> Result<TeamDevice> {
- let (id, device) = (id.to_owned(), device.to_owned());
- with_device!(self, [id, device], |r, t| r
- .decide_team_device(&t, &id, &device, approve)
- .await)
- }
-
- /// Adds a relay machine you own (see [`RelayClient::add_team_machine`]).
- pub async fn add_team_machine(
- &self,
- id: &str,
- machine: &str,
- os: Option<&str>,
- ) -> Result<Team> {
- let (id, machine, os) = (id.to_owned(), machine.to_owned(), os.map(str::to_owned));
- with_device!(self, [id, machine, os], |r, t| r
- .add_team_machine(&t, &id, &machine, os.as_deref())
- .await)
- }
-
- /// Takes a machine off the team.
- pub async fn remove_team_machine(&self, id: &str, machine: &str) -> Result<Team> {
- let (id, machine) = (id.to_owned(), machine.to_owned());
- with_device!(self, [id, machine], |r, t| r
- .remove_team_machine(&t, &id, &machine)
- .await)
- }
-
- /// The team's audit log.
- pub async fn team_audit(&self, id: &str, limit: usize) -> Result<Vec<TeamAuditEvent>> {
- let id = id.to_owned();
- with_device!(self, [id], |r, t| r.team_audit(&t, &id, limit).await)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn links_and_roles() {
- assert_eq!(
- team_code_from_link(" https://relay.cua.ai/join/team/team-ab.cd_EF/ "),
- "team-ab.cd_EF"
- );
- assert_eq!(team_code_from_link("team-ab.cd"), "team-ab.cd");
- assert_eq!(TeamRole::parse("Admin").unwrap(), TeamRole::Admin);
- assert!(TeamRole::parse("owner").is_err());
- assert_eq!(seg("[email protected]"), "bob%2Bx%40ex.com");
- }
-}
diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rs
index fc478c4d10..d6e13703be 100644
--- a/libs/cua/crates/cua-host/src/testing.rs
+++ b/libs/cua/crates/cua-host/src/testing.rs
@@ -78,11 +78,6 @@ struct State_ {
/// machine id → `(path prefix, base URL)` its `/m/<id>/…` gRPC-Web
/// requests go to (the longest matching prefix wins).
tunnels: BTreeMap<String, Vec<(String, String)>>,
- /// Teams (a simplified model of the relay's: membership, machines,
- /// invite codes, device approvals and an audit of kinds).
- teams: BTreeMap<String, crate::team::Team>,
- /// invite code → (team, role, email)
- team_codes: BTreeMap<String, (String, crate::team::TeamRole, Option<String>)>,
/// What `GET /v1/usage` answers; none: 404, as a relay that does not
/// meter.
usage: Option<serde_json::Value>,
@@ -1102,20 +1097,6 @@ impl FakeRelay {
axum::routing::patch(device_rename).delete(device_revoke),
)
.route("/v1/audit", get(audit))
- .route("/v1/teams", get(team_list).post(team_create))
- .route("/v1/teams/join", post(team_join))
- .route("/v1/teams/{id}", get(team_get))
- .route("/v1/teams/{id}/invites", post(team_invite))
- .route("/v1/teams/{id}/machines", post(team_add_machine))
- .route(
- "/v1/teams/{id}/machines/{machine}",
- axum::routing::delete(team_remove_machine),
- )
- .route(
- "/v1/teams/{id}/devices/{device}/approve",
- post(team_approve),
- )
- .route("/v1/teams/{id}/audit", get(team_audit))
.route("/v1/usage", get(usage))
.route("/v1/pairing-codes", get(pairing_list).post(pairing_mint))
.route(
@@ -1296,328 +1277,587 @@ impl FakeRelay {
}
}
-// ---- teams (simplified) ----
+// ---- the Spaces API (Teams are Keycloak organizations) ----
+
+#[derive(Clone, Debug, Default)]
+struct FakeOrg {
+ id: String,
+ alias: String,
+ name: String,
+ features: Vec<String>,
+ /// sub → role
+ members: BTreeMap<String, String>,
+ /// (id, email, role)
+ invites: Vec<(String, String, String)>,
+ machines: Vec<crate::spaces_api::ApiOrgMachine>,
+ approvals: Vec<crate::spaces_api::ApiDeviceApproval>,
+}
+
+#[derive(Default)]
+struct ApiState {
+ /// token → (sub, email)
+ accounts: BTreeMap<String, (String, String)>,
+ orgs: BTreeMap<String, FakeOrg>,
+ /// `POST /v1/orgs/{org}/machines` answers `402 feature_required` this
+ /// many more times (a plan bought a moment ago).
+ feature_lag: usize,
+ entitlement_reads: usize,
+ /// Every org route answers 410, as a server without Teams.
+ gone: bool,
+}
+
+type A = Arc<Mutex<ApiState>>;
+
+/// An in-process fake of the Spaces API's Teams routes (`/v1/me`,
+/// `/v1/orgs/…`, `/v1/me/entitlements`): orgs with roles, machines and
+/// device approvals, the `402 feature_required` of a plan that has not
+/// arrived yet ([`FakeSpacesApi::feature_lag`]) and a server without
+/// Teams ([`FakeSpacesApi::without_teams`]).
+pub struct FakeSpacesApi {
+ /// `http://127.0.0.1:<port>`.
+ pub url: String,
+ state: A,
+}
+
+fn api_fail(status: StatusCode, code: &str, detail: &str) -> Response {
+ (
+ status,
+ Json(serde_json::json!({ "error": code, "detail": detail })),
+ )
+ .into_response()
+}
-type TeamResult = Result<(Identity, Option<String>), Response>;
+type ApiCaller = Result<(String, String), Response>;
#[allow(clippy::result_large_err)]
-fn team_caller(st: &State_, headers: &HeaderMap) -> TeamResult {
- let who = account_of(st, headers)?;
- st.gate(headers)?;
- let device = st.device_of(headers, &who);
- Ok((who, device))
+fn api_caller(st: &ApiState, h: &HeaderMap) -> ApiCaller {
+ let tok = h
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .unwrap_or("");
+ st.accounts
+ .get(tok)
+ .cloned()
+ .ok_or_else(|| api_fail(StatusCode::UNAUTHORIZED, "unauthorized", ""))
}
-fn team_for(team: &crate::team::Team, who: &Identity) -> crate::team::Team {
- let mut t = team.clone();
- if let Some(m) = t.members.iter().find(|m| m.account == who.id) {
- t.role = m.role;
+/// The org `key` (id or alias) and the caller's role in it, when at least
+/// `min`.
+#[allow(clippy::result_large_err)]
+fn api_org(st: &ApiState, key: &str, sub: &str, min: &str) -> Result<(String, String), Response> {
+ if st.gone {
+ return Err(api_fail(StatusCode::GONE, "gone", "retired"));
+ }
+ let rank = |r: &str| match r {
+ "owner" => 3,
+ "admin" => 2,
+ "member" => 1,
+ _ => 0,
+ };
+ let Some(o) = st.orgs.values().find(|o| o.id == key || o.alias == key) else {
+ return Err(api_fail(StatusCode::NOT_FOUND, "org_not_found", ""));
+ };
+ let Some(role) = o.members.get(sub) else {
+ return Err(api_fail(StatusCode::NOT_FOUND, "org_not_found", ""));
+ };
+ if rank(role) < rank(min) {
+ return Err(api_fail(
+ StatusCode::FORBIDDEN,
+ "forbidden",
+ &format!("needs the {min} role"),
+ ));
}
- if !t.role.manages() {
- t.invites.clear();
- t.devices.retain(|d| d.account == who.id);
+ Ok((o.id.clone(), role.clone()))
+}
+
+fn api_now() -> String {
+ now_secs().to_string()
+}
+
+macro_rules! tri {
+ ($e:expr) => {
+ match $e {
+ Ok(v) => v,
+ Err(r) => return r,
+ }
+ };
+}
+
+impl FakeSpacesApi {
+ /// Starts on an ephemeral loopback port.
+ pub async fn start() -> Self {
+ let state: A = Arc::default();
+ let app = Router::new()
+ .route("/v1/me", get(api_me))
+ .route("/v1/me/entitlements", get(api_entitlements))
+ .route("/v1/orgs", post(api_create_org))
+ .route("/v1/orgs/{org}", get(api_get_org).delete(api_delete_org))
+ .route("/v1/orgs/{org}/members", get(api_members))
+ .route(
+ "/v1/orgs/{org}/members/{sub}",
+ axum::routing::patch(api_set_role).delete(api_remove_member),
+ )
+ .route("/v1/orgs/{org}/leave", post(api_leave))
+ .route("/v1/orgs/{org}/invites", get(api_invites).post(api_invite))
+ .route(
+ "/v1/orgs/{org}/machines",
+ get(api_machines).post(api_add_machine),
+ )
+ .route(
+ "/v1/orgs/{org}/machines/{id}",
+ axum::routing::delete(api_remove_machine),
+ )
+ .route("/v1/orgs/{org}/devices", get(api_devices))
+ .route("/v1/orgs/{org}/devices/request", post(api_request_device))
+ .route(
+ "/v1/orgs/{org}/devices/{id}/{decision}",
+ post(api_decide_device),
+ )
+ .fallback(|| async { api_fail(StatusCode::GONE, "gone", "retired") })
+ .with_state(state.clone());
+ 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() });
+ Self {
+ url: format!("http://{addr}"),
+ state,
+ }
+ }
+
+ /// Accepts `token` as the account `sub`.
+ pub fn add_account(&self, token: &str, sub: &str, email: &str) {
+ self.state
+ .lock()
+ .unwrap()
+ .accounts
+ .insert(token.into(), (sub.into(), email.into()));
+ }
+
+ /// Adds an org with `features`, `owner` its owner; returns its id.
+ pub fn add_org(&self, alias: &str, name: &str, owner: &str, features: &[&str]) -> String {
+ let id = format!(
+ "{:08x}-0000-4000-8000-{:012x}",
+ rand::random::<u32>(),
+ rand::random::<u64>() & 0xffff_ffff_ffff
+ );
+ let mut members = BTreeMap::new();
+ members.insert(owner.to_string(), "owner".to_string());
+ self.state.lock().unwrap().orgs.insert(
+ id.clone(),
+ FakeOrg {
+ id: id.clone(),
+ alias: alias.into(),
+ name: name.into(),
+ features: features.iter().map(|f| f.to_string()).collect(),
+ members,
+ ..Default::default()
+ },
+ );
+ id
+ }
+
+ /// Makes `sub` a `role` of `org` (as accepting an invitation does).
+ pub fn add_member(&self, org: &str, sub: &str, role: &str) {
+ if let Some(o) = self.state.lock().unwrap().orgs.get_mut(org) {
+ o.members.insert(sub.into(), role.into());
+ }
+ }
+
+ /// The next `n` machine additions answer `402 feature_required`.
+ pub fn feature_lag(&self, n: usize) {
+ self.state.lock().unwrap().feature_lag = n;
+ }
+
+ /// Every org route answers 410 Gone, as a server without Teams.
+ pub fn without_teams(&self) {
+ self.state.lock().unwrap().gone = true;
+ }
+
+ /// How often `GET /v1/me/entitlements` was read.
+ pub fn entitlement_reads(&self) -> usize {
+ self.state.lock().unwrap().entitlement_reads
+ }
+
+ /// The machine ids bound to `org`.
+ pub fn machines(&self, org: &str) -> Vec<String> {
+ self.state
+ .lock()
+ .unwrap()
+ .orgs
+ .get(org)
+ .map(|o| o.machines.iter().map(|m| m.machine_id.clone()).collect())
+ .unwrap_or_default()
+ }
+
+ /// `(device_id, state)` of every approval request in `org`.
+ pub fn approvals(&self, org: &str) -> Vec<(String, String)> {
+ self.state
+ .lock()
+ .unwrap()
+ .orgs
+ .get(org)
+ .map(|o| {
+ o.approvals
+ .iter()
+ .map(|a| (a.device_id.clone(), a.state.clone()))
+ .collect()
+ })
+ .unwrap_or_default()
}
- t
}
-async fn team_list(State(s): State<S>, headers: HeaderMap) -> Response {
+async fn api_me(State(s): State<A>, h: HeaderMap) -> Response {
let st = s.lock().unwrap();
- let (who, _) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- let teams: Vec<_> = st
- .teams
+ let (sub, email) = tri!(api_caller(&st, &h));
+ if st.gone {
+ return api_fail(StatusCode::GONE, "gone", "retired");
+ }
+ let orgs: Vec<_> = st
+ .orgs
.values()
- .filter(|t| t.members.iter().any(|m| m.account == who.id))
- .map(|t| team_for(t, &who))
+ .filter_map(|o| {
+ let role = o.members.get(&sub)?;
+ Some(serde_json::json!({
+ "id": o.id, "alias": o.alias, "name": o.name, "role": role,
+ "plan": if o.features.is_empty() { "free" } else { "teams" },
+ "status": "active", "seats": 3, "features": o.features,
+ }))
+ })
.collect();
- Json(serde_json::json!({ "teams": teams, "invites": [] })).into_response()
+ Json(serde_json::json!({
+ "sub": sub, "email": email, "orgs": orgs,
+ "entitlements": {"sub": sub, "plan": "free", "status": "none", "warnings": []},
+ }))
+ .into_response()
}
-async fn team_create(
- State(s): State<S>,
- headers: HeaderMap,
- Json(body): Json<serde_json::Value>,
+async fn api_entitlements(State(s): State<A>, h: HeaderMap) -> Response {
+ let mut st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ st.entitlement_reads += 1;
+ Json(serde_json::json!({"sub": sub, "plan": "free"})).into_response()
+}
+
+async fn api_create_org(
+ State(s): State<A>,
+ h: HeaderMap,
+ Json(b): Json<serde_json::Value>,
) -> Response {
let mut st = s.lock().unwrap();
- let (who, device) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- let id = format!("team-{:016x}", rand::random::<u64>());
- let mut t = crate::team::Team {
- id: id.clone(),
- name: body["name"].as_str().unwrap_or_default().to_string(),
- role: crate::team::TeamRole::Owner,
- members: vec![crate::team::TeamMember {
- account: who.id.clone(),
- email: who.email.clone(),
- role: crate::team::TeamRole::Owner,
- ..Default::default()
- }],
- ..Default::default()
- };
- if let Some(d) = device {
- t.devices.push(crate::team::TeamDevice {
- account: who.id.clone(),
- device: d,
- state: "approved".into(),
- decided_by: Some("auto".into()),
- ..Default::default()
- });
- }
- st.audit.push((
+ let (sub, _) = tri!(api_caller(&st, &h));
+ if st.gone {
+ return api_fail(StatusCode::GONE, "gone", "retired");
+ }
+ let name = b["name"].as_str().unwrap_or("").trim().to_string();
+ if name.is_empty() {
+ return api_fail(StatusCode::UNPROCESSABLE_ENTITY, "bad_name", "");
+ }
+ let alias: String = name
+ .to_lowercase()
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
+ .collect();
+ let id = format!(
+ "{:08x}-0000-4000-8000-{:012x}",
+ rand::random::<u32>(),
+ rand::random::<u64>() & 0xffff_ffff_ffff
+ );
+ let mut members = BTreeMap::new();
+ members.insert(sub, "owner".to_string());
+ st.orgs.insert(
id.clone(),
- serde_json::json!({"kind": "team_created", "actor": who.id}),
- ));
- st.teams.insert(id, t.clone());
- (StatusCode::CREATED, Json(t)).into_response()
+ FakeOrg {
+ id: id.clone(),
+ alias: alias.clone(),
+ name: name.clone(),
+ members,
+ ..Default::default()
+ },
+ );
+ (
+ StatusCode::CREATED,
+ Json(serde_json::json!({"id": id, "alias": alias, "name": name, "role": "owner", "status": "active"})),
+ )
+ .into_response()
}
-async fn team_get(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+async fn api_get_org(State(s): State<A>, h: HeaderMap, Path(org): Path<String>) -> Response {
let st = s.lock().unwrap();
- let (who, _) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, role) = tri!(api_org(&st, &org, &sub, "member"));
+ let o = &st.orgs[&id];
+ Json(serde_json::json!({
+ "id": o.id, "alias": o.alias, "name": o.name, "role": role,
+ "plan": if o.features.is_empty() { "free" } else { "teams" }, "status": "active",
+ "features": o.features, "seats_paid": 3, "seats_used": o.members.len() + o.invites.len(),
+ }))
+ .into_response()
+}
+
+async fn api_delete_org(State(s): State<A>, h: HeaderMap, Path(org): Path<String>) -> Response {
+ let mut st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "owner"));
+ st.orgs.remove(&id);
+ StatusCode::NO_CONTENT.into_response()
+}
+
+async fn api_members(State(s): State<A>, h: HeaderMap, Path(org): Path<String>) -> Response {
+ let st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "member"));
+ let emails: BTreeMap<_, _> = st.accounts.values().cloned().collect();
+ let members: Vec<_> = st.orgs[&id]
+ .members
+ .iter()
+ .map(|(s, r)| serde_json::json!({"sub": s, "email": emails.get(s).cloned().unwrap_or_default(), "role": r}))
+ .collect();
+ Json(serde_json::json!({ "members": members })).into_response()
+}
+
+async fn api_set_role(
+ State(s): State<A>,
+ h: HeaderMap,
+ Path((org, target)): Path<(String, String)>,
+ Json(b): Json<serde_json::Value>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "owner"));
+ let role = b["role"].as_str().unwrap_or("").to_string();
+ let o = st.orgs.get_mut(&id).unwrap();
+ let Some(r) = o.members.get_mut(&target) else {
+ return api_fail(StatusCode::NOT_FOUND, "member_not_found", "");
};
- match st
- .teams
- .get(&id)
- .filter(|t| t.members.iter().any(|m| m.account == who.id))
+ *r = role.clone();
+ Json(serde_json::json!({"sub": target, "role": role})).into_response()
+}
+
+async fn api_remove_member(
+ State(s): State<A>,
+ h: HeaderMap,
+ Path((org, target)): Path<(String, String)>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "admin"));
+ if st
+ .orgs
+ .get_mut(&id)
+ .unwrap()
+ .members
+ .remove(&target)
+ .is_none()
{
- Some(t) => Json(team_for(t, &who)).into_response(),
- None => err(StatusCode::NOT_FOUND, "no such team"),
+ return api_fail(StatusCode::NOT_FOUND, "member_not_found", "");
}
+ StatusCode::NO_CONTENT.into_response()
}
-#[allow(clippy::result_large_err)]
-fn require_team_manager<'a>(
- st: &'a mut State_,
- id: &str,
- who: &Identity,
-) -> Result<&'a mut crate::team::Team, Response> {
- let t = st
- .teams
- .get_mut(id)
- .filter(|t| t.members.iter().any(|m| m.account == who.id))
- .ok_or_else(|| err(StatusCode::NOT_FOUND, "no such team"))?;
- let role = t
- .members
- .iter()
- .find(|m| m.account == who.id)
- .map(|m| m.role)
- .unwrap_or_default();
- if !role.manages() {
- return Err(err(
- StatusCode::FORBIDDEN,
- "only the team's owner or an admin can do this",
- ));
+async fn api_leave(State(s): State<A>, h: HeaderMap, Path(org): Path<String>) -> Response {
+ let mut st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, role) = tri!(api_org(&st, &org, &sub, "member"));
+ if role == "owner" {
+ return api_fail(
+ StatusCode::CONFLICT,
+ "owner_cannot_leave",
+ "delete the org instead",
+ );
}
- Ok(t)
+ st.orgs.get_mut(&id).unwrap().members.remove(&sub);
+ StatusCode::NO_CONTENT.into_response()
}
-async fn team_invite(
- State(s): State<S>,
- headers: HeaderMap,
- Path(id): Path<String>,
- Json(body): Json<serde_json::Value>,
+async fn api_invites(State(s): State<A>, h: HeaderMap, Path(org): Path<String>) -> Response {
+ let st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "admin"));
+ let invites: Vec<_> = st.orgs[&id]
+ .invites
+ .iter()
+ .map(|(i, e, _)| serde_json::json!({"id": i, "email": e}))
+ .collect();
+ Json(serde_json::json!({ "invites": invites })).into_response()
+}
+
+async fn api_invite(
+ State(s): State<A>,
+ h: HeaderMap,
+ Path(org): Path<String>,
+ Json(b): Json<serde_json::Value>,
) -> Response {
let mut st = s.lock().unwrap();
- let (who, _) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- let url = st.public_url.clone();
- let t = match require_team_manager(&mut st, &id, &who) {
- Ok(t) => t,
- Err(r) => return r,
- };
- let role: crate::team::TeamRole =
- serde_json::from_value(body["role"].clone()).unwrap_or_default();
- let email = body["email"].as_str().map(str::to_lowercase);
- let invite = crate::team::TeamInvite {
- id: format!("inv_{:08x}", rand::random::<u32>()),
- email: email.clone(),
- role,
- expires_at: now_secs() + 86_400,
- uses_left: if email.is_some() { 1 } else { 25 },
- };
- t.invites.push(invite.clone());
- let code = format!("{id}.{:016x}", rand::random::<u64>());
- st.team_codes
- .insert(code.clone(), (id.clone(), role, email));
- st.audit.push((
- id,
- serde_json::json!({"kind": "invite_created", "actor": who.id}),
- ));
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "admin"));
+ let email = b["email"].as_str().unwrap_or("").to_lowercase();
+ let role = b["role"].as_str().unwrap_or("member").to_string();
+ if !email.contains('@') {
+ return api_fail(StatusCode::UNPROCESSABLE_ENTITY, "bad_invite", "");
+ }
+ let n = format!("inv-{}", rand::random::<u32>());
+ st.orgs
+ .get_mut(&id)
+ .unwrap()
+ .invites
+ .push((n, email.clone(), role.clone()));
(
StatusCode::CREATED,
- Json(crate::team::NewTeamInvite {
- invite,
- link: format!("{url}/join/team/{code}"),
- code,
- }),
+ Json(serde_json::json!({"email": email, "role": role})),
)
.into_response()
}
-async fn team_join(
- State(s): State<S>,
- headers: HeaderMap,
- Json(body): Json<serde_json::Value>,
-) -> Response {
- let mut st = s.lock().unwrap();
- let (who, device) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- let code = body["code"].as_str().unwrap_or_default().to_string();
- let Some((id, role, email)) = st.team_codes.get(&code).cloned() else {
- return err(StatusCode::FORBIDDEN, "this invite is not valid");
- };
- if email.is_some() && email != who.email.as_ref().map(|e| e.to_lowercase()) {
- return err(StatusCode::FORBIDDEN, "this invite is for another email");
- }
- let Some(t) = st.teams.get_mut(&id) else {
- return err(StatusCode::NOT_FOUND, "no such team");
- };
- if !t.members.iter().any(|m| m.account == who.id) {
- t.members.push(crate::team::TeamMember {
- account: who.id.clone(),
- email: who.email.clone(),
- role,
- ..Default::default()
- });
- if let Some(d) = &device {
- t.devices.push(crate::team::TeamDevice {
- account: who.id.clone(),
- email: who.email.clone(),
- device: d.clone(),
- state: "pending".into(),
- ..Default::default()
- });
- }
- }
- let mut view = team_for(t, &who);
- view.this_device = device.map(|_| "pending".to_string());
- st.audit.push((
- id,
- serde_json::json!({"kind": "member_joined", "actor": who.id}),
- ));
- Json(view).into_response()
+async fn api_machines(State(s): State<A>, h: HeaderMap, Path(org): Path<String>) -> Response {
+ let st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "member"));
+ Json(serde_json::json!({ "machines": st.orgs[&id].machines })).into_response()
}
-async fn team_add_machine(
- State(s): State<S>,
- headers: HeaderMap,
- Path(id): Path<String>,
- Json(body): Json<serde_json::Value>,
+async fn api_add_machine(
+ State(s): State<A>,
+ h: HeaderMap,
+ Path(org): Path<String>,
+ Json(b): Json<serde_json::Value>,
) -> Response {
let mut st = s.lock().unwrap();
- let (who, _) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- let machine = body["machine"].as_str().unwrap_or_default().to_string();
- let Some(record) = st.machines.get(&machine).map(|r| r.machine.clone()) else {
- return err(StatusCode::NOT_FOUND, "no such machine");
- };
- if record.owner.id != who.id {
- return err(StatusCode::FORBIDDEN, "add a machine you own");
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "admin"));
+ let machine = b["machine_id"].as_str().unwrap_or("").to_string();
+ if machine.is_empty() {
+ return api_fail(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "bad_machine",
+ "machine_id is required",
+ );
}
- let t = match require_team_manager(&mut st, &id, &who) {
- Ok(t) => t,
- Err(r) => return r,
- };
- if !t.machines.iter().any(|m| m.id == machine) {
- t.machines.push(crate::team::TeamMachine {
- id: machine.clone(),
- name: record.name.clone(),
- owner: who.email.clone().unwrap_or(who.id.clone()),
- online: false,
- });
+ if st.feature_lag > 0 {
+ st.feature_lag -= 1;
+ return api_fail(
+ StatusCode::PAYMENT_REQUIRED,
+ "feature_required",
+ "team_machines",
+ );
}
- let view = team_for(t, &who);
- st.audit.push((
- id,
- serde_json::json!({"kind": "machine_added", "machine": machine}),
- ));
- Json(view).into_response()
+ let o = st.orgs.get_mut(&id).unwrap();
+ if !o.features.iter().any(|f| f == "team_machines") {
+ return api_fail(
+ StatusCode::PAYMENT_REQUIRED,
+ "feature_required",
+ "team_machines",
+ );
+ }
+ if o.machines.iter().any(|m| m.machine_id == machine) {
+ return api_fail(StatusCode::CONFLICT, "already_added", "");
+ }
+ o.machines.push(crate::spaces_api::ApiOrgMachine {
+ machine_id: machine.clone(),
+ platform: b["platform"].as_str().unwrap_or("").into(),
+ label: b["label"].as_str().unwrap_or("").into(),
+ added_by: sub,
+ added_at: api_now(),
+ });
+ (
+ StatusCode::CREATED,
+ Json(serde_json::json!({ "machine_id": machine })),
+ )
+ .into_response()
}
-async fn team_remove_machine(
- State(s): State<S>,
- headers: HeaderMap,
- Path((id, machine)): Path<(String, String)>,
+async fn api_remove_machine(
+ State(s): State<A>,
+ h: HeaderMap,
+ Path((org, machine)): Path<(String, String)>,
) -> Response {
let mut st = s.lock().unwrap();
- let (who, _) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- let t = match require_team_manager(&mut st, &id, &who) {
- Ok(t) => t,
- Err(r) => return r,
- };
- let before = t.machines.len();
- t.machines.retain(|m| m.id != machine);
- if t.machines.len() == before {
- return err(StatusCode::NOT_FOUND, "that machine is not in the team");
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "admin"));
+ let o = st.orgs.get_mut(&id).unwrap();
+ let before = o.machines.len();
+ o.machines.retain(|m| m.machine_id != machine);
+ if o.machines.len() == before {
+ return api_fail(StatusCode::NOT_FOUND, "machine_not_found", "");
}
- let view = team_for(t, &who);
- st.audit.push((
- id,
- serde_json::json!({"kind": "machine_removed", "machine": machine}),
- ));
- Json(view).into_response()
+ StatusCode::NO_CONTENT.into_response()
}
-async fn team_approve(
- State(s): State<S>,
- headers: HeaderMap,
- Path((id, device)): Path<(String, String)>,
+async fn api_devices(State(s): State<A>, h: HeaderMap, Path(org): Path<String>) -> Response {
+ let st = s.lock().unwrap();
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, role) = tri!(api_org(&st, &org, &sub, "member"));
+ let devices: Vec<_> = st.orgs[&id]
+ .approvals
+ .iter()
+ .filter(|a| role != "member" || a.sub == sub)
+ .collect();
+ Json(serde_json::json!({ "devices": devices })).into_response()
+}
+
+async fn api_request_device(
+ State(s): State<A>,
+ h: HeaderMap,
+ Path(org): Path<String>,
+ Json(b): Json<serde_json::Value>,
) -> Response {
let mut st = s.lock().unwrap();
- let (who, _) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- let t = match require_team_manager(&mut st, &id, &who) {
- Ok(t) => t,
- Err(r) => return r,
- };
- let Some(d) = t.devices.iter_mut().find(|d| d.device == device) else {
- return err(StatusCode::NOT_FOUND, "no request from that device");
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "member"));
+ let device = b["device_id"].as_str().unwrap_or("").to_string();
+ if device.is_empty() {
+ return api_fail(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "bad_device",
+ "device_id is required",
+ );
+ }
+ let o = st.orgs.get_mut(&id).unwrap();
+ o.approvals
+ .retain(|a| !(a.sub == sub && a.device_id == device));
+ let a = crate::spaces_api::ApiDeviceApproval {
+ sub,
+ device_id: device,
+ state: "pending".into(),
+ requested_at: api_now(),
+ ..Default::default()
};
- d.state = "approved".into();
- d.decided_by = who.email.clone();
- let d = d.clone();
- st.audit.push((
- id,
- serde_json::json!({"kind": "device_approved", "subject": device}),
- ));
- Json(d).into_response()
+ o.approvals.push(a.clone());
+ Json(a).into_response()
}
-async fn team_audit(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+async fn api_decide_device(
+ State(s): State<A>,
+ h: HeaderMap,
+ Path((org, device, decision)): Path<(String, String, String)>,
+ Json(b): Json<serde_json::Value>,
+) -> Response {
let mut st = s.lock().unwrap();
- let (who, _) = match team_caller(&st, &headers) {
- Ok(v) => v,
- Err(r) => return r,
- };
- if let Err(r) = require_team_manager(&mut st, &id, &who) {
- return r;
+ let (sub, _) = tri!(api_caller(&st, &h));
+ let (id, _) = tri!(api_org(&st, &org, &sub, "admin"));
+ let member = b["sub"].as_str().unwrap_or("").to_string();
+ if member.is_empty() {
+ return api_fail(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "bad_request",
+ "sub is required",
+ );
}
- let events: Vec<_> = st
- .audit
- .iter()
- .filter(|(k, _)| k == &id)
- .map(|(_, e)| {
- let mut e = e.clone();
- e["ts"] = now_secs().into();
- e
- })
- .collect();
- Json(serde_json::json!({ "events": events })).into_response()
+ let state = match decision.as_str() {
+ "approve" => "approved",
+ "deny" => "denied",
+ _ => return api_fail(StatusCode::NOT_FOUND, "gone", ""),
+ };
+ let o = st.orgs.get_mut(&id).unwrap();
+ let Some(a) = o
+ .approvals
+ .iter_mut()
+ .find(|a| a.sub == member && a.device_id == device)
+ else {
+ return api_fail(StatusCode::NOT_FOUND, "request_not_found", "");
+ };
+ a.state = state.into();
+ a.decided_by = Some(sub);
+ a.decided_at = Some(api_now());
+ Json(a.clone()).into_response()
}
diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rs
index a418ddb218..a1fe2dd1e5 100644
--- a/libs/cua/crates/cua-sdk/src/native/host.rs
+++ b/libs/cua/crates/cua-sdk/src/native/host.rs
@@ -980,6 +980,9 @@ impl Devices {
) -> Result<PairingCode> {
let auth = self.auth.clone();
let tokens = self.tokens.clone();
+ // `team` (an organization id) is only echoed back: the relay's own
+ // teams are retired, and the machine becomes a team machine once it
+ // joined, by sharing it with `team:<id>` (the Spaces API).
run(async move {
let session = auth.session().await?;
let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
@@ -990,11 +993,15 @@ impl Devices {
&token,
&cua_host::PairingCodeRequest {
name: None,
- team,
+ team: None,
ttl_secs,
},
)
.await?;
+ let code = cua_host::PairingCode {
+ team: team.filter(|t| !t.trim().is_empty()),
+ ..code
+ };
Ok(PairingCode::from_host(code, &relay))
})
.await
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json
index 8e9416873d..4791d52381 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json
@@ -209,11 +209,11 @@
"step": "a team is refused",
"view": {
"busy": false,
- "buttons": "Share off / Remove / Done",
+ "buttons": "Share on / Remove / Done",
"disabled": null,
"empty": "Only you",
"error": null,
- "field": "Email or account ID [team:design] Enter a team as team:<id>, as `cua team ls` shows it. as editor",
+ "field": "Email or account ID [team:design] - as editor",
"request": null,
"roles": "viewer=Can view, editor=Can edit",
"rows": [],
diff --git a/libs/cua/crates/cua-spaces-app-core/src/share.rs b/libs/cua/crates/cua-spaces-app-core/src/share.rs
index 3d15455c4f..58e926ea85 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/share.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/share.rs
@@ -203,13 +203,20 @@ fn validate_who_with(who: &str, teams: bool) -> Result<String, String> {
}
if let Some(team) = w.strip_prefix("team:") {
// A team (`team:<id>` as `cua team ls` or the Teams page shows it):
- // every member gets the Space, from a device an admin approved.
- let ok = team.starts_with("team-")
+ // an organization's id or alias. Every member gets the Space, from
+ // a device an admin approved. The relay's old `team-<16 hex>` ids
+ // are refused.
+ let legacy = team
+ .strip_prefix("team-")
+ .is_some_and(|h| h.len() == 16 && h.chars().all(|c| c.is_ascii_hexdigit()));
+ let ok = !team.is_empty()
&& team.len() <= 64
&& team
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
- return if ok {
+ return if legacy {
+ Err("That team ID is from the old Teams. Use the team ID `cua team ls` shows.".into())
+ } else if ok {
Ok(format!("team:{team}"))
} else {
Err("Enter a team as team:<id>, as `cua team ls` shows it.".into())
@@ -451,14 +458,25 @@ mod tests {
fn teams_are_shared_with_unless_turned_off() {
// On (the default): a team id, always for full use.
assert_eq!(
- validate_who_with("team:design", true).unwrap_err(),
+ validate_who_with("team:Design Team", true).unwrap_err(),
"Enter a team as team:<id>, as `cua team ls` shows it."
);
+ // An organization, by id or alias.
assert_eq!(
- validate_who_with(" team:team-0a1b ", true).unwrap(),
- "team:team-0a1b"
+ validate_who_with(" team:0f1e2d3c-0000-4000-8000-000000000001 ", true).unwrap(),
+ "team:0f1e2d3c-0000-4000-8000-000000000001"
);
- assert_eq!(role_for("team:team-0a1b", "viewer"), "editor");
+ assert_eq!(
+ validate_who_with("team:design", true).unwrap(),
+ "team:design"
+ );
+ // Not the old relay team ids.
+ assert!(
+ validate_who_with("team:team-0a1b2c3d4e5f6a7b", true)
+ .unwrap_err()
+ .contains("old Teams")
+ );
+ assert_eq!(role_for("team:design", "viewer"), "editor");
// Off (CUA_EXPERIMENTAL_TEAMS=0): refused, whatever the id.
for who in ["team:team-0a1b", "team:design", "org:acme"] {
assert_eq!(
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 5d5d20787a..781809ef6f 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -2870,6 +2870,7 @@ mod teams_tests {
plan: "teams".into(),
status: "active".into(),
seats: 3,
+ features: vec!["team_machines".into()],
},
members: vec![ApiMember {
sub: "u1".into(),
diff --git a/libs/cua/crates/cua-spaces/src/relay.rs b/libs/cua/crates/cua-spaces/src/relay.rs
index 1a2b987ca3..f0d2c3a1ee 100644
--- a/libs/cua/crates/cua-spaces/src/relay.rs
+++ b/libs/cua/crates/cua-spaces/src/relay.rs
@@ -28,6 +28,9 @@ pub struct RelayAccount {
pub tokens: Arc<dyn AccountTokens>,
/// This client device (its session rides on every relay call).
pub device: Option<Arc<DeviceAuth>>,
+ /// The Spaces API Teams go through (`None`: the environment's,
+ /// [`cua_host::spaces_api::SpacesApiClient::current`]).
+ pub spaces_api: Option<String>,
}
impl RelayAccount {
@@ -37,6 +40,22 @@ impl RelayAccount {
url: url.into(),
tokens,
device: None,
+ spaces_api: None,
+ }
+ }
+
+ /// Teams (organizations) go through the Spaces API at `url` instead of
+ /// the environment's.
+ pub fn with_spaces_api(mut self, url: impl Into<String>) -> Self {
+ self.spaces_api = Some(url.into());
+ self
+ }
+
+ /// The Spaces API client Teams go through.
+ pub fn spaces_api(&self) -> cua_host::Result<cua_host::spaces_api::SpacesApiClient> {
+ match &self.spaces_api {
+ Some(u) => cua_host::spaces_api::SpacesApiClient::new(u),
+ None => cua_host::spaces_api::SpacesApiClient::current(),
}
}
diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rs
index ea53575ada..dcb8b8e8db 100644
--- a/libs/cua/crates/cua-spaces/src/share.rs
+++ b/libs/cua/crates/cua-spaces/src/share.rs
@@ -175,6 +175,26 @@ pub fn normalize_who(who: &str) -> Result<String> {
Ok(w.to_string())
}
+/// A Teams error as the user reads it: a team that is not theirs, a plan
+/// that lacks team machines, a server without Teams.
+fn team_err(e: cua_host::Error) -> Error {
+ use cua_host::spaces_api::is_feature_required;
+ match e {
+ cua_host::Error::NotFound(m) if m.contains("org_not_found") => Error::NotFound(
+ "that team (you are not in it, or it does not exist; a team joined a moment ago shows up after you sign in again)".into(),
+ ),
+ e if is_feature_required(&e) => Error::Relay(cua_host::Error::PermissionDenied(
+ "this team's plan does not include team machines (yet): finish the Teams checkout at app.cua.ai, then try again".into(),
+ )),
+ cua_host::Error::PermissionDenied(m) if m.contains("machine_limit") => {
+ Error::Relay(cua_host::Error::PermissionDenied(
+ "the team has as many machines as its seats allow: add seats at app.cua.ai".into(),
+ ))
+ }
+ other => Error::Relay(other),
+ }
+}
+
/// The team a `team:<id>` invitee names (`None` for anything else).
/// Sharing with a team makes the Space a team machine: every member (and
/// their agents) sees it and opens it as an editor from a device a team
@@ -193,12 +213,13 @@ fn team_of_with(who: &str, teams: bool) -> Option<Result<String>> {
cua_home::experimental::TEAMS_UNAVAILABLE
))));
}
- let ok = id.starts_with("team-")
- && id.len() <= 64
- && id
- .chars()
- .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
- Some(if ok {
+ // A team is an organization: its id (a UUID) or alias. The relay's
+ // old `team-…` ids are refused, never sent anywhere.
+ Some(if cua_host::spaces_api::is_legacy_team_id(id) {
+ Err(Error::invalid(format!(
+ "{who:?} is a team of the old Teams, which this version no longer uses: use team:<id> as `cua team ls` shows it"
+ )))
+ } else if cua_host::spaces_api::is_org_ref(id) {
Ok(id.to_string())
} else {
Err(Error::invalid(format!(
@@ -409,24 +430,23 @@ impl Spaces {
let client = relay.client().await?;
let m = client.machine(&token, machine).await?;
let mut shares = entries(&m);
- // Teams it is a machine of (best effort: a relay without teams, or
- // a device not enrolled, lists none; none while Teams are off).
- let teams = if cua_home::experimental::teams_enabled() {
- client.teams(&token).await.ok()
- } else {
- None
- };
- if let Some(list) = teams {
- shares.extend(
- list.teams
- .iter()
- .filter(|t| t.machines.iter().any(|tm| tm.id == machine))
- .map(|t| ShareEntry {
- who: format!("team:{}", t.id),
+ // Teams it is a machine of (best effort: a server without Teams,
+ // or Teams turned off, lists none).
+ if cua_home::experimental::teams_enabled()
+ && let Ok(api) = relay.spaces_api()
+ && let Ok(me) = api.me(&token).await
+ {
+ for org in me.orgs.iter().filter(|o| o.has("team_machines")) {
+ if let Ok(ms) = api.org_machines(&token, &org.id).await
+ && ms.iter().any(|m| m.machine_id == machine)
+ {
+ shares.push(ShareEntry {
+ who: format!("team:{}", org.id),
role: ShareRole::Editor,
connected: false,
- }),
- );
+ });
+ }
+ }
}
Ok(SpaceShares {
space: space.to_string(),
@@ -572,41 +592,75 @@ impl Spaces {
})
}
- /// Makes `space` a machine of `team`: every member (and their agents)
- /// lists it and opens it as an editor, from a device a team admin
- /// approved. Only a team owner or admin who owns the Space can. Macs, Linux and
- /// Windows machines can all be team machines.
+ /// Makes `space` a machine of `team` (an organization of the Spaces
+ /// API, by id or alias): every member (and their agents) lists it and
+ /// opens it as an editor, from a device a team admin approved. Only a
+ /// team owner or admin who owns the Space can. Macs, Linux and Windows
+ /// machines can all be team machines. A Space of a host is its own
+ /// relay record: sharing the host does not share its Spaces.
+ ///
+ /// Right after the team's plan was bought, the API may still answer
+ /// `402 feature_required`: this retries for up to a minute
+ /// ([`cua_host::spaces_api::SpacesApiClient::finishing_setup`]).
pub async fn share_with_team(&self, space: &str, team: &str) -> Result<SpaceShares> {
+ self.share_with_team_waiting(space, team, &mut |_| {}).await
+ }
+
+ /// [`Self::share_with_team`], calling `waiting` while a just-paid plan
+ /// is on its way (show "Finishing setup…").
+ pub async fn share_with_team_waiting(
+ &self,
+ space: &str,
+ team: &str,
+ waiting: &mut (dyn FnMut(std::time::Duration) + Send),
+ ) -> Result<SpaceShares> {
let id = self.resolve(space)?;
let canonical = id.to_string();
+ let relay = self.relay()?;
+ let api = relay.spaces_api()?;
+ let token = relay.tokens.access_token().await?;
+ let org = api.resolve_org(&token, team).await.map_err(team_err)?;
+ if !org.manages() {
+ return Err(Error::Relay(cua_host::Error::PermissionDenied(format!(
+ "only an owner or admin of {} can add machines to it",
+ org.label()
+ ))));
+ }
// What the Space runs, as this device knows it (a relay machine's
// own record speaks for itself on the relay).
- let os = self
- .list()?
- .into_iter()
- .find(|i| i.id == canonical)
- .map(|i| i.os)
- .filter(|o| !o.is_empty());
+ let listed = self.list()?.into_iter().find(|i| i.id == canonical);
+ let os = listed
+ .as_ref()
+ .map(|i| i.os.clone())
+ .filter(|o| !o.is_empty())
+ .unwrap_or_default();
+ let label = listed.map(|i| i.name).unwrap_or_default();
self.confirm_share(format!(
- "Let every member of team {team} use {canonical} (see and control it)"
+ "Let every member of team {} use {canonical} (see and control it)",
+ org.label()
))
.await?;
let machine = self.ensure_shared_machine(&canonical).await?;
- let relay = self.relay()?;
let token = relay.tokens.access_token().await?;
- relay
- .client()
- .await?
- .add_team_machine(&token, team, &machine, os.as_deref())
- .await
- .map_err(|e| match e {
- cua_host::Error::NotFound(m) if m.contains("no such team") => Error::NotFound(
- format!("team {team} (you are not in it, or it does not exist)"),
- ),
- other => Error::Relay(other),
- })?;
- self.audit_share("share", &canonical, &format!("team:{team} editor"));
- self.shares_of(&canonical, &machine).await
+ api.finishing_setup(
+ &token,
+ cua_host::spaces_api::SETUP_RETRY_WINDOW,
+ waiting,
+ || api.add_org_machine(&token, &org.id, &machine, &os, &label),
+ )
+ .await
+ .map_err(team_err)?;
+ self.audit_share("share", &canonical, &format!("team:{} editor", org.id));
+ let mut shares = self.shares_of(&canonical, &machine).await?;
+ let who = format!("team:{}", org.id);
+ if !shares.shares.iter().any(|s| s.who == who) {
+ shares.shares.push(ShareEntry {
+ who,
+ role: ShareRole::Editor,
+ connected: false,
+ });
+ }
+ Ok(shares)
}
/// Takes `space` off `team`.
@@ -617,14 +671,19 @@ impl Spaces {
return Err(Error::NotFound(format!("{canonical} is not shared")));
};
let relay = self.relay()?;
+ let api = relay.spaces_api()?;
let token = relay.tokens.access_token().await?;
- relay
- .client()
- .await?
- .remove_team_machine(&token, team, &machine)
- .await?;
- self.audit_share("unshare", &canonical, &format!("team:{team}"));
- self.shares_of(&canonical, &machine).await
+ let org = api.resolve_org(&token, team).await.map_err(team_err)?;
+ match api.remove_org_machine(&token, &org.id, &machine).await {
+ Ok(()) => {}
+ Err(cua_host::Error::NotFound(m)) if m.contains("machine_not_found") => {}
+ Err(e) => return Err(team_err(e)),
+ }
+ self.audit_share("unshare", &canonical, &format!("team:{}", org.id));
+ let mut shares = self.shares_of(&canonical, &machine).await?;
+ let who = format!("team:{}", org.id);
+ shares.shares.retain(|s| s.who != who);
+ Ok(shares)
}
/// Detaches `space`'s driver from the relay and removes its machine.
@@ -818,11 +877,23 @@ mod tests {
);
}
assert!(normalize_who("team:design").is_err());
+ // A team is an organization, by id or alias.
+ let org = "0f1e2d3c-0000-4000-8000-000000000001";
assert_eq!(
- team_of_with("team:team-0a1b", true).unwrap().unwrap(),
- "team-0a1b"
+ team_of_with(&format!("team:{org}"), true).unwrap().unwrap(),
+ org
);
- assert!(team_of_with("team:design", true).unwrap().is_err());
+ assert_eq!(
+ team_of_with("team:design", true).unwrap().unwrap(),
+ "design"
+ );
+ assert!(team_of_with("team:Design Team", true).unwrap().is_err());
+ // The old relay team ids are refused.
+ let e = team_of_with("team:team-0a1b2c3d4e5f6a7b", true)
+ .unwrap()
+ .unwrap_err()
+ .to_string();
+ assert!(e.contains("old Teams"), "{e}");
assert!(team_of_with("[email protected]", true).is_none());
assert!(team_of_with("[email protected]", false).is_none());
// With Teams off, a team is refused whatever its id.
diff --git a/libs/cua/crates/cua-spaces/tests/share.rs b/libs/cua/crates/cua-spaces/tests/share.rs
index 0b1b81655c..2819318209 100644
--- a/libs/cua/crates/cua-spaces/tests/share.rs
+++ b/libs/cua/crates/cua-spaces/tests/share.rs
@@ -201,9 +201,9 @@ async fn sharing_a_space_attaches_it_and_moves_people_between_roles() {
"machine removed"
);
- // Teams are not relay principals.
+ // Not a team (an organization id or alias), and never sent anywhere.
let e = spaces
- .share_space(&info.id, "team:design", ShareRole::Viewer)
+ .share_space(&info.id, "team:Design Team", ShareRole::Viewer)
.await
.unwrap_err();
assert_eq!(e.tag(), "invalid_argument");
@@ -686,28 +686,29 @@ async fn only_the_owner_removes_a_relay_record() {
assert!(relay.machine(gone).is_none());
}
-/// `team:<id>` makes a Space a team machine (attaching it first, with the
-/// user's confirmation and the Space's OS on its relay record); a Mac
-/// can be one too (Macs, Linux and Windows machines all can); `unshare team:<id>`
-/// takes it off.
+/// `team:<org>` makes a Space a team machine of the organization on the
+/// Spaces API (attaching it first, with the user's confirmation and the
+/// Space's OS); a Mac can be one too; `unshare team:<org>` takes it off. A
+/// plan bought a moment ago (402 feature_required) is waited for.
#[tokio::test]
async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {
// Teams are on by default; pin them on regardless of the environment.
cua_home::experimental::set_teams_enabled(Some(true));
let relay = FakeRelay::start().await;
relay.add_account("ada-token", "ada", Some("[email protected]"));
+ let api = cua_host::testing::FakeSpacesApi::start().await;
+ api.add_account("ada-token", "ada", "[email protected]");
+ let team = api.add_org("aigis", "AIGIS", "ada", &["team_machines"]);
let home = tempfile::tempdir().unwrap();
let consent = yes();
let spaces = Spaces::builder()
.home(home.path())
- .relay(RelayAccount::new(
- &relay.url,
- Arc::new(StaticToken("ada-token".into())),
- ))
+ .relay(
+ RelayAccount::new(&relay.url, Arc::new(StaticToken("ada-token".into())))
+ .with_spaces_api(&api.url),
+ )
.share_consent(consent.clone())
.build();
- let client = cua_host::RelayClient::new(&relay.url).unwrap();
- let team = client.create_team("ada-token", "AIGIS").await.unwrap();
let linux = MockServer::start(MockAuth::default()).await;
linux.state.advertise(&["relay_attach"]);
@@ -734,8 +735,10 @@ async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {
panic!("never attached");
}
});
+ // The plan was just bought: the first answer is 402, then it arrives.
+ api.feature_lag(1);
let shares = spaces
- .share_space(&info.id, &format!("team:{}", team.id), ShareRole::Viewer)
+ .share_space(&info.id, "team:aigis", ShareRole::Viewer)
.await
.unwrap();
let attached = online.await.unwrap();
@@ -745,14 +748,15 @@ async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {
.lock()
.unwrap()
.iter()
- .any(|r| r.contains(&format!("every member of team {}", team.id))),
+ .any(|r| r.contains("every member of team AIGIS")),
"the user confirmed"
);
- // A team gets full use, whatever role was asked for.
+ // A team gets full use, whatever role was asked for; it is named by
+ // its organization id.
assert_eq!(
shares.shares,
vec![cua_spaces::share::ShareEntry {
- who: format!("team:{}", team.id),
+ who: format!("team:{team}"),
role: ShareRole::Editor,
connected: false,
}]
@@ -762,23 +766,16 @@ async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {
m.meta.get("cua.space.os").map(String::as_str),
Some("linux")
);
- let t = client.team("ada-token", &team.id).await.unwrap();
- assert_eq!(t.machines[0].id, attached.machine_id);
+ assert_eq!(api.machines(&team), vec![attached.machine_id.clone()]);
+ assert!(api.entitlement_reads() >= 1, "entitlements refreshed");
// Off the team again.
let shares = spaces
- .unshare_space(&info.id, Some(&format!("team:{}", team.id)))
+ .unshare_space(&info.id, Some(&format!("team:{team}")))
.await
.unwrap();
assert!(shares.shares.is_empty(), "{shares:?}");
- assert!(
- client
- .team("ada-token", &team.id)
- .await
- .unwrap()
- .machines
- .is_empty()
- );
+ assert!(api.machines(&team).is_empty());
// A Mac can be a team machine like any other.
let mac = MockServer::start(MockAuth::default()).await;
@@ -807,22 +804,24 @@ async fn sharing_with_a_team_adds_a_team_machine_including_a_mac() {
}
});
spaces
- .share_space(
- &mac_info.id,
- &format!("team:{}", team.id),
- ShareRole::Editor,
- )
+ .share_space(&mac_info.id, &format!("team:{team}"), ShareRole::Editor)
.await
.unwrap();
let mac_attached = mac_online.await.unwrap();
- let t = client.team("ada-token", &team.id).await.unwrap();
- assert_eq!(t.machines.len(), 1);
- assert_eq!(t.machines[0].id, mac_attached.machine_id);
+ assert_eq!(api.machines(&team), vec![mac_attached.machine_id]);
- // Not a team id.
+ // The old relay team ids are refused before anything is sent.
let e = spaces
- .share_space(&info.id, "team:design", ShareRole::Editor)
+ .share_space(&info.id, "team:team-0a1b2c3d4e5f6a7b", ShareRole::Editor)
.await
.unwrap_err();
assert_eq!(e.tag(), "invalid_argument", "{e}");
+
+ // A server without Teams says so; nothing falls back to the relay.
+ api.without_teams();
+ let e = spaces
+ .share_space(&info.id, "team:aigis", ShareRole::Editor)
+ .await
+ .unwrap_err();
+ assert!(e.to_string().contains("Teams are not available"), "{e}");
}
diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.json
index 5a801a70e2..18ebed3023 100644
--- a/scripts/docs-generators/cli-specs/cua.json
+++ b/scripts/docs-generators/cli-specs/cua.json
@@ -9491,10 +9491,21 @@
},
{
"abstract": "Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. Codes work once and expire (30 minutes by default). Run from an enrolled device",
- "after_help": "Examples:\n cua host pair\n cua host pair --name build-box --expires 60\n cua host pair --list\n cua host pair --revoke pc_0123456789abcdef",
+ "after_help": "Examples:\n cua host pair\n cua host pair --name build-box --expires 60\n cua host pair --list\n cua host pair --revoke pc_0123456789abcdef\n # Add the machine to a team: waits for it to join, then adds it\n cua host pair --team AIGIS",
"aliases": [],
"arguments": [],
"flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "With --team: print the code and exit instead of waiting; add the machine later with `cua team add-machine <team> relay:<id>`",
+ "hidden": false,
+ "name": "no-wait",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ },
{
"aliases": [],
"default_value": false,
@@ -9515,7 +9526,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Add the machine for this team (its id)",
+ "help": "Add the machine to this team (id, alias or name; owner or admin): waits until the machine joins, then makes it a team machine",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -11270,8 +11281,8 @@
"usage": "cua devices [OPTIONS] <COMMAND>"
},
{
- "abstract": "Teams share machines with every member and their agents. Owners and admins invite (email or link), approve member devices, add machines and read the audit log",
- "after_help": "Examples:\n cua team create AIGIS\n cua team invite AIGIS [email protected]\n cua team add-machine AIGIS local:build-box\n cua team approve AIGIS dev_0123456789abcdef01234567\n cua team audit AIGIS",
+ "abstract": "Teams (organizations of your cua.ai account) share machines with every member and their agents. Owners and admins invite by email, approve member devices and add machines",
+ "after_help": "Examples:\n cua team create AIGIS\n cua team invite AIGIS [email protected]\n cua team add-machine AIGIS local:build-box\n cua team approve AIGIS dev_0123456789abcdef01234567\n cua team show AIGIS",
"aliases": [],
"arguments": [],
"flags": [],
@@ -11282,7 +11293,7 @@
"subcommand_optional": false,
"subcommands": [
{
- "abstract": "Create a team; you are its owner",
+ "abstract": "Create a team; you are its owner. Buy Teams for it at app.cua.ai to add machines",
"after_help": "Examples:\n cua team create \"AIGIS\"",
"aliases": [],
"arguments": [
@@ -11307,7 +11318,7 @@
"usage": "cua team create [OPTIONS] <NAME>"
},
{
- "abstract": "Your teams, and email invites waiting for you",
+ "abstract": "Your teams",
"after_help": "Examples:\n cua team ls\n cua team ls --json",
"aliases": [
"list"
@@ -11323,13 +11334,13 @@
"usage": "cua team ls [OPTIONS]"
},
{
- "abstract": "A team: members, machines, open invites and devices",
+ "abstract": "A team: plan, members, machines, open invites and devices",
"after_help": "Examples:\n cua team show AIGIS",
"aliases": [],
"arguments": [
{
"default_value": null,
- "help": "Team id (`team-…`) or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11348,13 +11359,13 @@
"usage": "cua team show [OPTIONS] <TEAM>"
},
{
- "abstract": "Invite someone by email, or make a link anyone can join with",
- "after_help": "Examples:\n cua team invite AIGIS [email protected]\n cua team invite AIGIS --link\n cua team invite AIGIS [email protected] --role admin",
+ "abstract": "Invite someone by email: cua.ai emails them an invitation. Manage invites at app.cua.ai/team",
+ "after_help": "Examples:\n cua team invite AIGIS [email protected]\n cua team invite AIGIS [email protected] --role admin",
"aliases": [],
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11364,28 +11375,16 @@
},
{
"default_value": null,
- "help": "Their email (they join by signing in with it)",
+ "help": "Their email",
"hidden": false,
- "is_optional": true,
+ "is_optional": false,
"name": "EMAIL",
"possible_values": [],
"repeatable": false,
"type": "string"
}
],
- "flags": [
- {
- "aliases": [],
- "default_value": false,
- "env": null,
- "help": "Make a link instead (up to 25 joins, 7 days)",
- "hidden": false,
- "name": "link",
- "repeatable": false,
- "short_name": null,
- "takes_value": false
- }
- ],
+ "flags": [],
"hidden": false,
"hidden_aliases": [],
"name": "invite",
@@ -11412,19 +11411,19 @@
],
"subcommand_optional": false,
"subcommands": [],
- "usage": "cua team invite [OPTIONS] <TEAM> [EMAIL]"
+ "usage": "cua team invite [OPTIONS] <TEAM> <EMAIL>"
},
{
- "abstract": "Join a team with an invite link or code, or (with --team) the email invite for your account's email",
- "after_help": "Examples:\n cua team join https://relay.cua.ai/join/team/team-0a1b….xyz\n cua team join --team team-0a1b2c3d4e5f6a7b",
+ "abstract": "After accepting an emailed invitation: take the role it offered. Run `cua auth login` first so your session lists the team",
+ "after_help": "Examples:\n cua team join AIGIS",
"aliases": [],
"arguments": [
{
"default_value": null,
- "help": "The invite link or code",
+ "help": "Team id, alias or name",
"hidden": false,
- "is_optional": true,
- "name": "CODE",
+ "is_optional": false,
+ "name": "TEAM",
"possible_values": [],
"repeatable": false,
"type": "string"
@@ -11434,27 +11433,10 @@
"hidden": false,
"hidden_aliases": [],
"name": "join",
- "options": [
- {
- "aliases": [],
- "default_value": null,
- "env": null,
- "help": "The team of an email invite",
- "hidden": false,
- "is_optional": true,
- "multiple_values": false,
- "name": "team",
- "possible_values": [],
- "repeatable": false,
- "short_name": null,
- "takes_value": true,
- "type": "string",
- "value_name": "TEAM"
- }
- ],
+ "options": [],
"subcommand_optional": false,
"subcommands": [],
- "usage": "cua team join [OPTIONS] [CODE]"
+ "usage": "cua team join [OPTIONS] <TEAM>"
},
{
"abstract": "Leave a team",
@@ -11463,7 +11445,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11488,7 +11470,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11523,7 +11505,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11571,7 +11553,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11596,7 +11578,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11631,7 +11613,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11666,7 +11648,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11685,13 +11667,13 @@
"usage": "cua team request [OPTIONS] <TEAM>"
},
{
- "abstract": "Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. Macs, Linux and Windows machines all can",
+ "abstract": "Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. Macs, Linux and Windows machines all can. Each Space is added on its own: adding a host does not add the Spaces it provides",
"after_help": "Examples:\n cua team add-machine AIGIS local:build-box\n cua team add-machine AIGIS relay:0123abcd4567ef89 --yes",
"aliases": [],
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11701,7 +11683,7 @@
},
{
"default_value": null,
- "help": "Space id or name",
+ "help": "Space id or name (`relay:<id>` for a machine you host)",
"hidden": false,
"is_optional": false,
"name": "SPACE",
@@ -11738,7 +11720,7 @@
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11767,13 +11749,13 @@
"usage": "cua team remove-machine [OPTIONS] <TEAM> <MACHINE>"
},
{
- "abstract": "The team's audit log: joins, approvals, machines opened, changes",
- "after_help": "Examples:\n cua team audit AIGIS --limit 50",
+ "abstract": "The team's audit log. Audit export is coming soon; for now see the account app (app.cua.ai)",
+ "after_help": "Examples:\n cua team audit AIGIS",
"aliases": [],
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
@@ -11791,7 +11773,7 @@
"aliases": [],
"default_value": "50",
"env": null,
- "help": "Newest events to show",
+ "help": "Newest events to show (when export arrives)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -11809,13 +11791,13 @@
"usage": "cua team audit [OPTIONS] <TEAM>"
},
{
- "abstract": "Delete a team (owner). Its machines stay yours",
+ "abstract": "Delete a team (owner; cancel its subscription first). Its machines stay yours",
"after_help": "Examples:\n cua team delete AIGIS --yes",
"aliases": [],
"arguments": [
{
"default_value": null,
- "help": "Team id or name",
+ "help": "Team id, alias or name",
"hidden": false,
"is_optional": false,
"name": "TEAM",
diff --git a/scripts/docs-generators/cua-cli.ts b/scripts/docs-generators/cua-cli.ts
index 096a16d7ef..2b04bd26ba 100644
--- a/scripts/docs-generators/cua-cli.ts
+++ b/scripts/docs-generators/cua-cli.ts
@@ -121,7 +121,7 @@ export const CLI_GROUPS: CliGroup[] = [
{ slug: 'cloud', title: 'cua cloud', summary: 'Your own AWS, Google Cloud or Modal account as a place for sandboxes and Spaces: connect, test, status, sweep', commands: ['cloud'] },
{ slug: 'host', title: 'cua host', summary: 'Set this machine up for unattended access', commands: ['host'] },
{ slug: 'devices', title: 'cua devices', summary: 'Enroll this device on the relay, approve, rename and revoke devices, and read the access log', commands: ['devices'] },
- { slug: 'team', title: 'cua team', summary: 'Teams, their members, machines, device approvals and audit log', commands: ['team'] },
+ { slug: 'team', title: 'cua team', summary: 'Teams (organizations), their members, machines and device approvals', commands: ['team'] },
{ slug: 'usage', title: 'cua usage', summary: 'Your hosted relay allowance this month: live sessions and relay hours', commands: ['usage'] },
{ slug: 'teleport', title: 'cua teleport', summary: 'Move a desktop app session into a sandbox', commands: ['teleport'] },
{ slug: 'volume', title: 'cua volume', summary: 'Cua Volume: files, versions, grants, access requests and audit of the volume every Space and agent shares', commands: ['volume'] },