Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces): relay allowance usage and upgrade notice in the app and CLI (CUA-1360) (#5002)
Francesco Bonaccic9a607993875
diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.tsindex e6e97858de..d2bcf66491 100644--- a/apps/cua-spaces-desktop/src/bridge/index.ts+++ b/apps/cua-spaces-desktop/src/bridge/index.ts@@ -23,6 +23,7 @@ import { hostStatus, machinesMethods } from "./machines";import { ELECTRON_METHODS, METHODS } from "./methods";import { notificationsMethods } from "./notifications";import { onboardingMethods } from "./onboarding";+import { relayUsageMethods } from "./relay-usage";import { sessionMethods, sessionState } from "./session";import { settingsMethods } from "./settings";import { sharingMethods } from "./sharing";@@ -62,6 +63,7 @@ export const AREAS = [startupMethods,streamMethods,onboardingMethods,+ relayUsageMethods,];export interface Bridge {diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 0b6bcfafbc..6ae66d2541 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -41,8 +41,9 @@ export const METHODS = ["startup.get", "startup.act",] as const;-/** A live desktop's media ticket for the page's WebCodecs player, and the- * first run's state (the SwiftUI app draws its first run natively). */-export const ELECTRON_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream"] as const;+/** A live desktop's media ticket for the page's WebCodecs player, the+ * first run's state (the SwiftUI app draws its first run natively), and the+ * account's relay allowance. */+export const ELECTRON_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream", "relay.usage"] as const;export type Method = (typeof METHODS)[number] | (typeof ELECTRON_METHODS)[number];diff --git a/apps/cua-spaces-desktop/src/bridge/relay-usage.ts b/apps/cua-spaces-desktop/src/bridge/relay-usage.tsnew file mode 100644index 0000000000..10aa0acc59--- /dev/null+++ b/apps/cua-spaces-desktop/src/bridge/relay-usage.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The account's relay allowance this month (`relay.usage`; `cua usage`):+// the relay's `GET /v1/usage` with the account's token, as the page's+// camelCase `RelayUsage` (the web bridge's ops/relay-usage.ts). Null when+// signed out, or from a relay that meters nothing (404). Only this host+// reads it; the SwiftUI app does not yet.+import type { BridgeContext } from "./context";+import { Failure, type Handlers } from "./host";++export const DEFAULT_RELAY_URL = "https://relay.cua.ai";++/** The relay the session's devices use, else `CUA_RELAY_URL`, else relay.cua.ai. Null: not one the token may go to (plain http off this machine). */+export function relayUrl(ctx: BridgeContext): string | null {+ let fromSession: string | undefined;+ try {+ fromSession = ctx.model.devices?.devices()?.relayUrl();+ } catch {+ fromSession = undefined;+ }+ const raw = (fromSession?.trim() || ctx.env.CUA_RELAY_URL?.trim() || DEFAULT_RELAY_URL).replace(/\/+$/, "");+ try {+ const url = new URL(raw.replace(/^wss:/, "https:").replace(/^ws:/, "http:"));+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) return null;+ return url.toString().replace(/\/+$/, "");+ } catch {+ return null;+ }+}++const num = (v: unknown, fallback = 0) => (typeof v === "number" && Number.isFinite(v) ? v : fallback);+const maybeNum = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);+const str = (v: unknown) => (typeof v === "string" ? v : "");++/** The relay's snake_case answer as the page's `RelayUsage`; missing fields take their defaults. */+export function relayUsage(raw: unknown) {+ const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;+ const team = r.team && typeof r.team === "object" ? (r.team as Record<string, unknown>) : null;+ return {+ metered: r.metered === true,+ period: str(r.period),+ plan: str(r.plan),+ team: team ? { id: str(team.id), seats: num(team.seats) } : null,+ liveSessions: num(r.live_sessions),+ liveSessionsLimit: maybeNum(r.live_sessions_limit),+ hoursUsed: num(r.hours_used),+ hoursLimit: maybeNum(r.hours_limit),+ myHoursUsed: num(r.my_hours_used),+ softLimitReached: r.soft_limit_reached === true,+ reasons: Array.isArray(r.reasons) ? r.reasons.filter((x): x is string => typeof x === "string") : [],+ upgradeUrl: typeof r.upgrade_url === "string" && /^https:\/\//.test(r.upgrade_url) ? r.upgrade_url : null,+ };+}++export function relayUsageMethods(ctx: BridgeContext, fetchImpl: typeof fetch = (...a) => fetch(...a)): Handlers {+ return {+ "relay.usage": async () => {+ const { model } = ctx;+ // Before the session is up, or signed out: nothing to read.+ if (!model.servicesIn || !model.identity || !model.account) return null;+ const token = await model.account.accessToken(false);+ const base = relayUrl(ctx);+ if (!token || !base) return null;+ const resp = await fetchImpl(`${base}/v1/usage`, {+ headers: { authorization: `Bearer ${token}` },+ signal: AbortSignal.timeout(15_000),+ });+ if (resp.status === 404) return null;+ if (!resp.ok) throw Failure.failed(`The relay could not say your usage (HTTP ${resp.status})`);+ return relayUsage(await resp.json());+ },+ };+}diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.tsindex cae3908201..71a153949a 100644--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts@@ -170,8 +170,8 @@ describe.skipIf(!built)("the bridge on the app core", () => {for (const [method, args] of cases) problems.push(...shapeProblems(method, await call(method, args)));expect(problems).toEqual([]);// Every ported method has its case (or is checked below).- // (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts.)- const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);+ // (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts.)+ const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);const ported = bridge.registry.methods.filter((m) => !NOT_YET.includes(m) && !elsewhere.has(m));expect(ported.filter((m) => !cases.some(([c]) => c === m))).toEqual([]);});@@ -180,7 +180,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {const info = (await call("app.info")) as { platform: string; host: string; version: string; methods: string[] };expect(info).toMatchObject({ platform: "macos", host: "electron", version: "1.2.3" });expect(info.methods[0]).toBe("app.info");- expect(info.methods.at(-1)).toBe("spaces.openStream");+ expect(info.methods.at(-1)).toBe("relay.usage");});it("answers New Space's options while starting and once ready", () => {@@ -476,7 +476,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {"clouds.connect": { target: { provider: "aws", region: "us-west-2" }, makeDefault: false },};// This machine, Devices, Settings and the rest: host-bridge.test.ts reads them with their arguments.- const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", ...VAULT_OPS, ...(HOST_OPS as OpName[])]);+ const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", ...VAULT_OPS, ...(HOST_OPS as OpName[])]);const problems: string[] = [];const checked: string[] = [];for (const op of OPERATIONS) {diff --git a/apps/cua-spaces-desktop/test/relay-usage.test.ts b/apps/cua-spaces-desktop/test/relay-usage.test.tsnew file mode 100644index 0000000000..b7ffaebac0--- /dev/null+++ b/apps/cua-spaces-desktop/test/relay-usage.test.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// `relay.usage`: the relay's `GET /v1/usage` with the account's token, as the+// page's camelCase shape, checked against the web contract.+import { describe, expect, it, vi } from "vitest";+import { OP_SHAPES, SHAPE_DEFS } from "../../cua-spaces-web/src/bridge/contracts/shapes";+import { validate } from "../../cua-spaces-web/src/bridge/contracts/schema";+import type { BridgeContext } from "../src/bridge/context";+import { relayUrl, relayUsageMethods } from "../src/bridge/relay-usage";++const RELAY = {+ metered: true, period: "2026-10", plan: "free", team: { id: "acme", seats: 2 },+ live_sessions: 1, live_sessions_limit: 2, hours_used: 20.4, hours_limit: 20, my_hours_used: 3.4,+ soft_limit_reached: true, reasons: ["hours"], upgrade_url: "https://cua.ai/pricing",+};++function context(o: { signedIn?: boolean; relay?: string; env?: NodeJS.ProcessEnv } = {}) {+ const accessToken = vi.fn(async () => (o.signedIn === false ? null : "acct-token"));+ const ctx = {+ model: {+ servicesIn: true,+ identity: o.signedIn === false ? null : "[email protected]",+ account: { accessToken },+ devices: { devices: () => (o.relay ? { relayUrl: () => o.relay } : null) },+ },+ env: o.env ?? {},+ } as unknown as BridgeContext;+ return { ctx, accessToken };+}++const answer = (status: number, body: unknown = null) =>+ vi.fn(async () => new Response(body === null ? null : JSON.stringify(body), { status })) as unknown as typeof fetch & ReturnType<typeof vi.fn>;++describe("relay.usage", () => {+ it("reads the allowance from the session's relay with the account's token", async () => {+ const { ctx } = context({ relay: "https://relay.example/" });+ const fetch = answer(200, RELAY);+ const usage = await relayUsageMethods(ctx, fetch)["relay.usage"]!({}, {});+ expect(fetch).toHaveBeenCalledWith("https://relay.example/v1/usage", expect.objectContaining({ headers: { authorization: "Bearer acct-token" } }));+ expect(usage).toEqual({+ metered: true, period: "2026-10", plan: "free", team: { id: "acme", seats: 2 },+ liveSessions: 1, liveSessionsLimit: 2, hoursUsed: 20.4, hoursLimit: 20, myHoursUsed: 3.4,+ softLimitReached: true, reasons: ["hours"], upgradeUrl: "https://cua.ai/pricing",+ });+ expect(validate(OP_SHAPES["relay.usage"], usage, SHAPE_DEFS)).toEqual([]);+ // An older relay's answer with fields missing takes the defaults.+ const bare = await relayUsageMethods(ctx, answer(200, { metered: true }))["relay.usage"]!({}, {});+ expect(validate(OP_SHAPES["relay.usage"], bare, SHAPE_DEFS)).toEqual([]);+ });++ it("is null signed out and from a relay that meters nothing; fails on other errors", async () => {+ const out = context({ signedIn: false });+ const fetch = answer(200, RELAY);+ expect(await relayUsageMethods(out.ctx, fetch)["relay.usage"]!({}, {})).toBeNull();+ expect(fetch).not.toHaveBeenCalled();+ const { ctx } = context();+ expect(await relayUsageMethods(ctx, answer(404))["relay.usage"]!({}, {})).toBeNull();+ await expect(relayUsageMethods(ctx, answer(500))["relay.usage"]!({}, {})).rejects.toMatchObject({ code: "failed" });+ });++ it("resolves the relay as the CLI does, and sends the token over https only (or to this machine)", () => {+ expect(relayUrl(context().ctx)).toBe("https://relay.cua.ai");+ expect(relayUrl(context({ env: { CUA_RELAY_URL: " https://r.example/ " } }).ctx)).toBe("https://r.example");+ expect(relayUrl(context({ relay: "http://127.0.0.1:8080", env: { CUA_RELAY_URL: "https://r.example" } }).ctx)).toBe("http://127.0.0.1:8080");+ expect(relayUrl(context({ env: { CUA_RELAY_URL: "http://relay.example" } }).ctx)).toBeNull();+ });+});diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.mdindex b82ad51476..da45e269ea 100644--- a/apps/cua-spaces-web/src/bridge/README.md+++ b/apps/cua-spaces-web/src/bridge/README.md@@ -125,11 +125,13 @@ request is `invoke("cua:bridge", { id, method, args })` and resolves to thesame envelope, and the host's events arrive on `cua:event` as`{ event, payload }`. The preload refuses every other channel. OnlyElectron answers `ELECTRON_HOST_METHODS`: `spaces.openStream` (it draws a-Space's video in the page) and `onboarding.get` / `onboarding.complete`+Space's video in the page), `onboarding.get` / `onboarding.complete`(its first run is this page's `routes/onboarding`, with Done's "Launch atlogin"; the SwiftUI app's is native, so there `session.get` reads it as-done). Electron reads drag regions from the CSS, so the adapter sends none-there.+done), and `relay.usage` (the account's relay allowance this month,+`ops/relay-usage.ts`, for Settings' Relay usage row and the notice above+every page once it is used up; other hosts show neither). Electron reads+drag regions from the CSS, so the adapter sends none there.### SwiftUI WKWebView: `webkit-protocol.ts`diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex a399c60879..c429a05b2a 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -86,6 +86,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"volume.reveal": { path: "/Users/ada/Cua Volume/public" },"agents.setupDriver": { agents: ["codex"] },"spaces.openStream": { spaceId: SPACE, tier: "tile" },+ "relay.usage": {},"about.get": {},"about.set": { channel: "beta" },"about.checkNow": {},diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 6d246e4488..45c1cea425 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -13,6 +13,7 @@ import { AGENT_KEYS_ARGS } from "../ops/agent-keys";import { KEYVAULT_MANAGE_ARGS } from "../ops/keyvault-manage";import { KEYVAULT_SETUP_ARGS } from "../ops/keyvault-setup";import { STREAM_ARGS } from "../ops/stream";+import { RELAY_USAGE_ARGS } from "../ops/relay-usage";import type { HostWindow } from "../detect";import { ELECTRON_BRIDGE_CHANNEL } from "../electron-channels";import { OPERATIONS, type OpArgs, type OpName } from "../protocol";@@ -112,6 +113,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"startup.get": {},"startup.act": { action: "allowAccess" },...STREAM_ARGS,+ ...RELAY_USAGE_ARGS,};const unsupportedOn = (op: OpName, host: "webkit" | "tauri") =>diff --git a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.tsindex e5fff8b4b3..3acd37a0bd 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts@@ -270,6 +270,13 @@ describe("electron adapter", () => {expect(invoke).toHaveBeenCalledWith(ELECTRON_BRIDGE_CHANNEL, expect.objectContaining({ method: "spaces.openStream", args: { spaceId: "local:a", tier: "tile" } }));});+ it("asks the shell for the relay allowance (the SwiftUI app does not read it yet)", async () => {+ const usage = { metered: true, period: "2026-10", plan: "free", team: null, liveSessions: 1, liveSessionsLimit: 2, hoursUsed: 6.5, hoursLimit: 20, myHoursUsed: 6.5, softLimitReached: false, reasons: [], upgradeUrl: null };+ const { win, invoke } = electronHost(bridged(() => ({ ok: true, result: usage })));+ expect(await createElectronAdapter(win).call("relay.usage", {})).toEqual(usage);+ expect(invoke).toHaveBeenCalledWith(ELECTRON_BRIDGE_CHANNEL, expect.objectContaining({ method: "relay.usage" }));+ });+it("reads the first run from the shell and finishes it there (the SwiftUI app's is native)", async () => {const sent: [string, unknown][] = [];let completed = false;diff --git a/apps/cua-spaces-web/src/bridge/__tests__/relay-usage.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/relay-usage.test.tsxnew file mode 100644index 0000000000..33d6b20861--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/__tests__/relay-usage.test.tsx@@ -0,0 +1,129 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { act, cleanup, render } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createDemoAdapter } from "../adapters/demo";+import { demoRelayUsage } from "../adapters/demo/relay-usage";+import { createWebkitAdapter } from "../adapters/webkit";+import { BridgeProvider, isUnsupported, relayUsageLine, useRelayUsage, type DataAdapter, type RelayUsage } from "..";+import type { HostWindow } from "../detect";+import { RELAY_USAGE_POLL_MS } from "../relay-usage";+import { noCore } from "./testCore";++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++function Probe({ seen }: { seen: { usage?: RelayUsage | null } }) {+ seen.usage = useRelayUsage();+ return null;+}++describe("relay.usage", () => {+ it("the demo host answers a free plan partway through the month, and null signed out", async () => {+ expect(await createDemoAdapter({ latencyMs: 0 }).call("relay.usage", {})).toEqual(demoRelayUsage());+ expect(await createDemoAdapter({ latencyMs: 0, signedIn: false }).call("relay.usage", {})).toBeNull();+ });++ it("the SwiftUI host does not answer it, and the page shows nothing", async () => {+ const postMessage = vi.fn();+ const win = { webkit: { messageHandlers: { cua: { postMessage } } }, addEventListener: () => {}, removeEventListener: () => {} } as unknown as HostWindow;+ const adapter = createWebkitAdapter(win);+ expect(isUnsupported(await adapter.call("relay.usage", {}).catch((e: unknown) => e))).toBe(true);+ expect(postMessage).not.toHaveBeenCalled();++ const seen: { usage?: RelayUsage | null } = {};+ render(+ <BridgeProvider adapter={adapter} core={noCore}>+ <Probe seen={seen} />+ </BridgeProvider>,+ );+ await act(() => new Promise((r) => setTimeout(r, 10)));+ expect(seen.usage).toBeNull();+ });++ it("reads once for every screen, again every 5 minutes, and drops it when signed out", async () => {+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });+ const demo = createDemoAdapter({ latencyMs: 0 });+ const call = vi.fn(demo.call);+ const adapter: DataAdapter = { ...demo, call };+ const seen: { usage?: RelayUsage | null } = {};+ render(+ <BridgeProvider adapter={adapter} core={noCore}>+ <Probe seen={seen} />+ <Probe seen={{}} />+ </BridgeProvider>,+ );+ await act(() => new Promise((r) => setTimeout(r, 10)));+ const reads = () => call.mock.calls.filter(([op]) => op === "relay.usage").length;+ expect(reads()).toBe(1);+ expect(seen.usage).toMatchObject({ plan: "free", liveSessions: 1 });+ expect(relayUsageLine(seen.usage!)).toBe("Live sessions 1 of 2 · Relay hours 6.5 of 20 this month");++ await act(() => vi.advanceTimersByTimeAsync(RELAY_USAGE_POLL_MS - 100));+ expect(reads()).toBe(1);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(200);+ await new Promise((r) => setTimeout(r, 10));+ });+ expect(reads()).toBe(2);++ await act(async () => {+ await demo.call("session.signOut", {});+ await new Promise((r) => setTimeout(r, 10));+ });+ expect(seen.usage).toBeNull();+ });++ it("an account change drops an answer still in flight and reads for the new account", async () => {+ const demo = createDemoAdapter({ latencyMs: 0 });+ const listeners = new Set<(e: { type: string }) => void>();+ let release: (v: RelayUsage | null) => void = () => {};+ let n = 0;+ const call = vi.fn((op: string, args: unknown) => {+ if (op !== "relay.usage") return demo.call(op as never, args as never);+ n += 1;+ // The first read hangs until released; later ones answer at once.+ if (n === 1) return new Promise<RelayUsage | null>((r) => (release = r));+ return Promise.resolve({ ...demoRelayUsage(), plan: "pro" });+ });+ const adapter = {+ ...demo,+ call,+ subscribe: (l: (e: { type: string }) => void) => {+ listeners.add(l);+ return () => listeners.delete(l);+ },+ } as unknown as DataAdapter;+ const seen: { usage?: RelayUsage | null } = {};+ render(+ <BridgeProvider adapter={adapter} core={noCore}>+ <Probe seen={seen} />+ </BridgeProvider>,+ );+ await act(() => new Promise((r) => setTimeout(r, 10)));+ await act(async () => {+ for (const l of listeners) l({ type: "session.changed" });+ release({ ...demoRelayUsage(), plan: "free" });+ await new Promise((r) => setTimeout(r, 10));+ });+ expect(n).toBe(2);+ expect(seen.usage).toMatchObject({ plan: "pro" });+ });++ it("a relay that meters nothing reads as nothing to show", async () => {+ const demo = createDemoAdapter({ latencyMs: 0 });+ demo.state.relayUsage = { ...demoRelayUsage(), metered: false };+ const seen: { usage?: RelayUsage | null } = {};+ render(+ <BridgeProvider adapter={demo} core={noCore}>+ <Probe seen={seen} />+ </BridgeProvider>,+ );+ await act(() => new Promise((r) => setTimeout(r, 10)));+ expect(seen.usage).toBeNull();+ });+});diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex b3e304a5fa..8254e79b16 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -44,6 +44,7 @@ import { demoVolumeHandlers, demoVolumeState, type DemoVolumeState } from "./demimport { demoHostSetupHandlers, demoHostSetupState, type DemoHostSetupState } from "./demo/host-setup";import { demoSpaceDetailHandlers, demoSpaceDetailState, type DemoSpaceDetailState } from "./demo/space-detail";import { demoTelemetryHandlers, demoTelemetryState, type DemoTelemetryState } from "./demo/telemetry";+import { demoRelayUsageHandlers, demoRelayUsageState, type DemoRelayUsageState } from "./demo/relay-usage";import { demoStartupHandlers, demoStartupState, type DemoStartupState } from "./demo/startup";import { demoMachine, MAC_DEMO_PLATFORM, type DemoPlatform } from "./demo/platform";@@ -114,6 +115,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { replatform: options.platform ?? MAC_DEMO_PLATFORM,volume: demoVolumeState(now(), options.onboarded !== false, options.platform),...demoTelemetryState(),+ ...demoRelayUsageState(),...demoSpaceDetailState(),...demoHostSetupState(now(), options.onboarded === false),...demoStartupState(Boolean(options.keychain)),@@ -433,6 +435,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...demoVolumeHandlers({ state: state.volume, now, wait, step, emit, platform: state.platform }),...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })) }),...demoTelemetryHandlers(ctx),+ ...demoRelayUsageHandlers(ctx),...demoSpaceDetailHandlers(ctx),...demoHostSetupHandlers(ctx),...demoKeyvaultSetupHandlers(ctx),@@ -459,7 +462,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re};}-export interface DemoState extends DemoTelemetryState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {+export interface DemoState extends DemoTelemetryState, DemoRelayUsageState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {rows: SpaceRow[];items: KvItem[];keyvaultLocked: boolean;diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/relay-usage.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/relay-usage.tsnew file mode 100644index 0000000000..ffa2450f3d--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/relay-usage.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/** The demo host's relay allowance: a free plan partway through the month+ * (`relayUsage` in its state; tests set it past the allowance). */++import type { RelayUsage } from "../../ops/relay-usage";+import type { DemoContext, DemoHandlers } from "./context";++export interface DemoRelayUsageState {+ relayUsage: RelayUsage | null;+}++export const demoRelayUsage = (): RelayUsage => ({+ metered: true,+ period: "2026-10",+ plan: "free",+ team: null,+ liveSessions: 1,+ liveSessionsLimit: 2,+ hoursUsed: 6.5,+ hoursLimit: 20,+ myHoursUsed: 6.5,+ softLimitReached: false,+ reasons: [],+ upgradeUrl: "https://cua.ai/pricing",+});++export const demoRelayUsageState = (): DemoRelayUsageState => ({ relayUsage: demoRelayUsage() });++export function demoRelayUsageHandlers({ state }: DemoContext): DemoHandlers<"relay.usage"> {+ return {+ // Signed out: no account, no allowance.+ "relay.usage": () => (state.identity && state.relayUsage ? { ...state.relayUsage, reasons: [...state.relayUsage.reasons] } : null),+ };+}diff --git a/apps/cua-spaces-web/src/bridge/adapters/electron.ts b/apps/cua-spaces-web/src/bridge/adapters/electron.tsindex fadde66ae7..b1a45d61aa 100644--- a/apps/cua-spaces-web/src/bridge/adapters/electron.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/electron.ts@@ -5,8 +5,9 @@* The Electron shell: a native host like the SwiftUI app. Its main process* answers the SwiftUI host's methods (`../webkit-protocol.ts`) from the same* Rust library, so this is the webkit adapter over the preload's- * `window.cuaDesktop` (`../transport.ts`), plus the one thing only Electron- * answers: a Space's media ticket for the page's video (`spaces.openStream`).+ * `window.cuaDesktop` (`../transport.ts`), plus what only Electron answers+ * (`ELECTRON_HOST_METHODS`): a Space's media ticket for the page's video+ * (`spaces.openStream`), its first run and the relay allowance.*/import type { DataAdapter } from "../adapter";diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex 18f75b9e6f..6f2bf8025b 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -55,6 +55,7 @@ import {import { tauriHostSetupOps } from "../ops/host-setup";import { TAURI_SPACE_DETAIL_UNSUPPORTED, tauriSpaceDetailOps } from "../ops/space-detail";import { STREAM_OPERATIONS } from "../ops/stream";+import { RELAY_USAGE_OPERATIONS } from "../ops/relay-usage";import { tauriTelemetryOps } from "../ops/telemetry";import { tauriStartupOps } from "../ops/startup";@@ -85,6 +86,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [...TAURI_SETTINGS_UNSUPPORTED,...TAURI_SPACE_DETAIL_UNSUPPORTED,...STREAM_OPERATIONS,+ ...RELAY_USAGE_OPERATIONS,];/** `persistent_agent_list`'s snake_case agents, as `PersistentAgent`s (as `src/native/persistent.ts` maps them). */diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex b345b6bc38..024f5d4f06 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -54,6 +54,7 @@ import { webkitKeyvaultSetupOps } from "../ops/keyvault-setup";import { webkitSettingsOps } from "../ops/settings";import { startupFromHost, webkitStartupOps } from "../ops/startup";import { unsupportedStreamOps, type StreamTicket } from "../ops/stream";+import { unsupportedRelayUsageOps, type RelayUsage } from "../ops/relay-usage";import type { SpaceRow } from "../contracts/spaces";import {isWebkitResponse,@@ -574,6 +575,8 @@ export function createWebkitAdapter(...(electron? { "spaces.openStream": (target: OpArgs<"spaces.openStream">) => request<StreamTicket>("spaces.openStream", { ...target }) }: unsupportedStreamOps("webkit")),+ // The relay allowance: Electron reads it; the Mac app not yet.+ ...(electron ? { "relay.usage": () => request<RelayUsage | null>("relay.usage") } : unsupportedRelayUsageOps("webkit")),};const onEvent = (detail: WebkitEventDetail) => {diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex a09d6955b2..3695ceaa6d 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -3860,6 +3860,91 @@"notifications.markAllRead": {"type": "null"},+ "relay.usage": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "metered": {+ "type": "boolean"+ },+ "period": {+ "type": "string"+ },+ "plan": {+ "type": "string"+ },+ "team": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "seats": {+ "type": "number"+ }+ },+ "required": [+ "id",+ "seats"+ ]+ },+ "liveSessions": {+ "type": "number"+ },+ "liveSessionsLimit": {+ "type": [+ "number",+ "null"+ ]+ },+ "hoursUsed": {+ "type": "number"+ },+ "hoursLimit": {+ "type": [+ "number",+ "null"+ ]+ },+ "myHoursUsed": {+ "type": "number"+ },+ "softLimitReached": {+ "type": "boolean"+ },+ "reasons": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "upgradeUrl": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "metered",+ "period",+ "plan",+ "team",+ "liveSessions",+ "liveSessionsLimit",+ "hoursUsed",+ "hoursLimit",+ "myHoursUsed",+ "softLimitReached",+ "reasons",+ "upgradeUrl"+ ]+ },"session.completeOnboarding": {"type": "null"},diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 1c9a516917..6b5f2d4fa0 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -58,6 +58,7 @@ import type { CatalogEntry, ConsentItem, KvDomainCount, KvInventory, OpenWindow,import type { AgentSetupOutcome, DriveGrantInput, DriveMountInput, DriveRequestInput, Experiments, VolumeOverview } from "./volume";import type { AgentKeysReport } from "../ops/agent-keys";import type { SentFileInfo, SpaceThumbnail, SpaceUsage, SpaceWindows } from "../ops/space-detail";+import type { RelayUsage } from "../ops/relay-usage";import type { StartupState } from "../ops/startup";import type { StreamTicket } from "../ops/stream";import type { HostSettings, HostSignIn, OpName, SessionSnapshot, SettingsSnapshot, SettingsValues } from "../protocol";@@ -686,6 +687,22 @@ export const OP_SHAPES: Record<OpName, Schema> = {"agents.setupDriver": list(obj<AgentSetupOutcome>()({ agents: strings, target: str, item: str, change: str, detail: str })),"spaces.openStream": obj<StreamTicket>()({ wsUrl: str, expiresAt: nullable(str) }),+ "relay.usage": nullable(+ obj<RelayUsage>()({+ metered: bool,+ period: str,+ plan: str,+ team: nullable(object({ id: str, seats: num })),+ liveSessions: num,+ liveSessionsLimit: nullable(num),+ hoursUsed: num,+ hoursLimit: nullable(num),+ myHoursUsed: num,+ softLimitReached: bool,+ reasons: strings,+ upgradeUrl: nullable(str),+ }),+ ),"about.get": AboutShape,"about.set": AboutShape,diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 5a637526be..2ad76ce533 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -38,6 +38,7 @@ import type { HostMethod, WebkitMethod } from "./webkit-protocol";import { HOST_SETUP_COVERAGE } from "./ops/host-setup";import { SPACE_DETAIL_COVERAGE } from "./ops/space-detail";import { STREAM_COVERAGE } from "./ops/stream";+import { RELAY_USAGE_COVERAGE } from "./ops/relay-usage";import { TELEMETRY_COVERAGE } from "./ops/telemetry";import { STARTUP_COVERAGE } from "./ops/startup";@@ -152,6 +153,7 @@ export const HOST_COVERAGE = {...HOST_SETUP_COVERAGE,...STARTUP_COVERAGE,...STREAM_COVERAGE,+ ...RELAY_USAGE_COVERAGE,} as const satisfies Record<OpName, OpCoverage>;/**diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex 52b37cd705..604fb5d1ce 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -112,3 +112,4 @@ export {type ChecklistState,type ChecklistStep,} from "./checklist";+export { formatHours, relayUsageLine, useRelayUsage, RELAY_USAGE_FOCUS_MS, RELAY_USAGE_POLL_MS, type RelayUsage } from "./relay-usage";diff --git a/apps/cua-spaces-web/src/bridge/ops/relay-usage.ts b/apps/cua-spaces-web/src/bridge/ops/relay-usage.tsnew file mode 100644index 0000000000..c670d29d9c--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/ops/relay-usage.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The account's relay allowance this month (`cua usage`). A live session is+ * a connection to one of your remote machines through the hosted relay;+ * relay hours are the time with at least one. Nothing stops at the limit:+ * past it, the page says so and offers the upgrade.+ *+ * | Operation | Electron | SwiftUI | Tauri |+ * |---|---|---|---|+ * | `relay.usage` | the host method `relay.usage`: the relay's `GET /v1/usage` with the account's token (`src/bridge/relay-usage.ts`) | unsupported | unsupported |+ *+ * Null: signed out, or a relay that meters nothing. Where unsupported, the+ * page shows nothing about it.+ */++import { UnsupportedOperationError, type BridgeMode } from "../adapter";+import type { OpCoverage } from "../coverage";++/** `cua_host::RelayUsage`, camelCase. */+export interface RelayUsage {+ metered: boolean;+ /** The month counted (`2026-10`). */+ period: string;+ /** `free`, `pro`, `team`, ... */+ plan: string;+ /** The team whose allowance is pooled. */+ team: { id: string; seats: number } | null;+ liveSessions: number;+ /** Null: no limit. */+ liveSessionsLimit: number | null;+ /** The team's, when pooled. */+ hoursUsed: number;+ hoursLimit: number | null;+ myHoursUsed: number;+ softLimitReached: boolean;+ /** What is past the allowance: `sessions` and/or `hours`. */+ reasons: string[];+ upgradeUrl: string | null;+}++export interface RelayUsageOps {+ "relay.usage": { args: Record<string, never>; result: RelayUsage | null };+}++export const RELAY_USAGE_OPERATIONS = ["relay.usage"] as const satisfies readonly (keyof RelayUsageOps)[];++export const RELAY_USAGE_COVERAGE = {+ "relay.usage": {+ webkit: { methods: [] },+ electron: { methods: ["relay.usage"] },+ tauri: [],+ unsupported: {+ webkit: "the Mac app does not read the relay allowance yet",+ tauri: "the Tauri app does not read the relay allowance",+ },+ },+} as const satisfies Record<keyof RelayUsageOps, OpCoverage>;++/** Hosts that do not read the allowance. */+export function unsupportedRelayUsageOps(mode: BridgeMode) {+ return {+ "relay.usage": (): Promise<RelayUsage | null> => Promise.reject(new UnsupportedOperationError(mode, "relay.usage")),+ };+}++/** Arguments that take it down its usual path (coverage tests). */+export const RELAY_USAGE_ARGS = { "relay.usage": {} };diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex 11ae989baf..6952660d87 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -43,6 +43,7 @@ import { SETTINGS_OPERATIONS, type SettingsOperations } from "./ops/settings";import type { HostSetupOps } from "./ops/host-setup";import type { SpaceDetailOps } from "./ops/space-detail";import { STREAM_OPERATIONS, type StreamOps } from "./ops/stream";+import { RELAY_USAGE_OPERATIONS, type RelayUsageOps } from "./ops/relay-usage";import type { TelemetryOps } from "./ops/telemetry";import { STARTUP_EVENTS, STARTUP_OPERATIONS, type StartupHostEvent, type StartupOps } from "./ops/startup";@@ -159,7 +160,8 @@ export interface HostOperationsSpaceDetailOps,HostSetupOps,StartupOps,- StreamOps {+ StreamOps,+ RelayUsageOps {"spaces.list": { args: Record<string, never>; result: SpaceRow[] };/** `os`: the plan's OS, for a host that draws its own pending row (the SwiftUI app's notch). */"spaces.create": { args: { config: SpaceCreateConfig; pendingId: string; os?: SpaceOs }; result: SpaceRow };@@ -259,6 +261,7 @@ export const OPERATIONS = [...KEYVAULT_MANAGE_OPERATIONS,...VOLUME_OPERATIONS,...STREAM_OPERATIONS,+ ...RELAY_USAGE_OPERATIONS,...SETTINGS_OPERATIONS,...NOTIFICATIONS_OPERATIONS,"telemetry.track",diff --git a/apps/cua-spaces-web/src/bridge/relay-usage.ts b/apps/cua-spaces-web/src/bridge/relay-usage.tsnew file mode 100644index 0000000000..84dbc36193--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/relay-usage.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The account's relay allowance (`relay.usage`), read while a screen shows+ * it: at once, every 5 minutes, and when the app comes to the front (at+ * most once a minute). A host without the operation, signed out, or a relay+ * that meters nothing reads as null, and the page shows nothing.+ */++import { useContext, useSyncExternalStore } from "react";+import { isUnsupported, type DataAdapter } from "./adapter";+import { BridgeContext } from "./BridgeProvider";+import type { RelayUsage } from "./ops/relay-usage";++export type { RelayUsage } from "./ops/relay-usage";++export const RELAY_USAGE_POLL_MS = 5 * 60_000;+/** A focus reads again only when the last read is older than this. */+export const RELAY_USAGE_FOCUS_MS = 60_000;++class RelayUsageStore {+ usage: RelayUsage | null = null;+ private unsupported = false;+ private readAt = 0;+ private reading = false;+ /** Bumped on every account change: an older read's answer is dropped. */+ private generation = 0;+ /** An account change came while a read was out: read again after it. */+ private again = false;+ private listeners = new Set<() => void>();+ private stop: (() => void) | null = null;++ constructor(private readonly adapter: DataAdapter) {}++ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ if (this.listeners.size === 1) this.start();+ return () => {+ this.listeners.delete(listener);+ if (this.listeners.size === 0) {+ this.stop?.();+ this.stop = null;+ }+ };+ };++ snapshot = (): RelayUsage | null => this.usage;++ async read(): Promise<void> {+ if (this.unsupported) return;+ if (this.reading) return;+ this.reading = true;+ this.readAt = Date.now();+ const generation = this.generation;+ try {+ const usage = await this.adapter.call("relay.usage", {});+ if (generation === this.generation) this.set(usage);+ } catch (e) {+ // Unsupported: never again. Anything else keeps the last answer.+ if (isUnsupported(e)) {+ this.unsupported = true;+ this.set(null);+ }+ } finally {+ this.reading = false;+ if (this.again) {+ this.again = false;+ void this.read();+ }+ }+ }++ /** The account changed (signed in, out, or another one): forget the+ * last answer, then read for the current account. */+ private accountChanged() {+ this.generation += 1;+ this.set(null);+ if (this.reading) this.again = true;+ else void this.read();+ }++ private set(usage: RelayUsage | null) {+ this.usage = usage?.metered ? usage : null;+ for (const l of [...this.listeners]) l();+ }++ private start() {+ void this.read();+ const timer = setInterval(() => void this.read(), RELAY_USAGE_POLL_MS);+ const onFocus = () => {+ if (Date.now() - this.readAt >= RELAY_USAGE_FOCUS_MS) void this.read();+ };+ const win = typeof window !== "undefined" ? window : null;+ win?.addEventListener("focus", onFocus);+ const unsubscribe = this.adapter.subscribe((e) => {+ if (e.type === "session.signedOut" || e.type === "session.signedIn" || e.type === "session.changed") {+ this.accountChanged();+ }+ });+ this.stop = () => {+ clearInterval(timer);+ win?.removeEventListener("focus", onFocus);+ unsubscribe();+ };+ }+}++const stores = new WeakMap<DataAdapter, RelayUsageStore>();++function storeFor(adapter: DataAdapter): RelayUsageStore {+ let s = stores.get(adapter);+ if (!s) stores.set(adapter, (s = new RelayUsageStore(adapter)));+ return s;+}++const none = () => () => {};+const nothing = () => null;++/** The relay allowance this month, or null (nothing to show). */+export function useRelayUsage(): RelayUsage | null {+ const adapter = useContext(BridgeContext)?.adapter ?? null;+ const store = adapter ? storeFor(adapter) : null;+ return useSyncExternalStore(store?.subscribe ?? none, store?.snapshot ?? nothing, nothing);+}++/** `20` or `6.5`. */+export function formatHours(h: number): string {+ const tenths = Math.round(h * 10) / 10;+ return Number.isInteger(tenths) ? String(tenths) : tenths.toFixed(1);+}++/** "Live sessions 1 of 2 · Relay hours 6.5 of 20 this month". */+export function relayUsageLine(u: RelayUsage): string {+ const of = (used: string, limit: string | null) => (limit === null ? used : `${used} of ${limit}`);+ const sessions = of(String(u.liveSessions), u.liveSessionsLimit === null ? null : String(u.liveSessionsLimit));+ const hours = of(formatHours(u.hoursUsed), u.hoursLimit === null ? null : formatHours(u.hoursLimit));+ return `Live sessions ${sessions} · Relay hours ${hours} this month`;+}+diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 96f03e7800..706454da56 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -147,8 +147,9 @@ export type WebkitMethod = (typeof WEBKIT_METHODS)[number];* page (WebCodecs), so the page asks it for a media ticket* (`ops/stream.ts`), and its first run is this page's (`onboarding.get`,* `onboarding.complete`); the Mac app draws video and its first run- * natively. */-export const ELECTRON_HOST_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream"] as const;+ * natively. It also reads the account's relay allowance+ * (`relay.usage`, `ops/relay-usage.ts`). */+export const ELECTRON_HOST_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream", "relay.usage"] as const;/** `onboarding.get` and `onboarding.complete`'s answer: whether the first run finished, and as what. */export interface WkOnboarding {diff --git a/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.test.tsx b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.test.tsxnew file mode 100644index 0000000000..6a1c74ce21--- /dev/null+++ b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.test.tsx@@ -0,0 +1,74 @@+// 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 { createDemoAdapter } from "@/bridge/adapters/demo";+import { demoRelayUsage } from "@/bridge/adapters/demo/relay-usage";+import { noCore } from "@/bridge/__tests__/testCore";+import { BridgeProvider, type DataAdapter, type RelayUsage } from "@/bridge";++import { RelayAllowanceNotice } from "./relay-allowance-notice";++afterEach(() => {+ cleanup();+ localStorage.clear();+});++const reached: RelayUsage = { ...demoRelayUsage(), hoursUsed: 20.2, softLimitReached: true, reasons: ["hours"] };++/** The demo host answering `usage`, recording the links it opens. */+function host(usage: RelayUsage | null) {+ const demo = createDemoAdapter({ latencyMs: 0 });+ demo.state.relayUsage = usage;+ const opened: string[] = [];+ const adapter: DataAdapter = {+ ...demo,+ call: (op, args) => {+ if (op === "session.openExternal") opened.push((args as { url: string }).url);+ return demo.call(op, args);+ },+ };+ const view = () =>+ render(+ <BridgeProvider adapter={adapter} core={noCore}>+ <RelayAllowanceNotice />+ </BridgeProvider>,+ );+ return { demo, opened, view };+}++describe("<RelayAllowanceNotice>", () => {+ it("shows nothing within the allowance", async () => {+ const { view } = host(demoRelayUsage());+ view();+ await act(() => new Promise((r) => setTimeout(r, 10)));+ expect(document.querySelector("[data-relay-allowance]")).toBeNull();+ });++ it("past the allowance: says the Spaces keep working, and Upgrade opens the plan's page", async () => {+ const { view, opened } = host(reached);+ view();+ const notice = await screen.findByRole("status");+ expect(notice.textContent).toContain("You've used your free relay allowance for this month. Your Spaces keep working.");+ fireEvent.click(screen.getByRole("button", { name: "Upgrade" }));+ await waitFor(() => expect(opened).toEqual(["https://cua.ai/pricing"]));+ });++ it("dismissed, it stays hidden for that month and reason, and shows again for another", async () => {+ const first = host(reached);+ first.view();+ fireEvent.click(await screen.findByRole("button", { name: "Dismiss" }));+ expect(document.querySelector("[data-relay-allowance]")).toBeNull();+ cleanup();++ host(reached).view();+ await act(() => new Promise((r) => setTimeout(r, 10)));+ expect(document.querySelector("[data-relay-allowance]")).toBeNull();+ cleanup();++ host({ ...reached, reasons: ["sessions", "hours"] }).view();+ expect(await screen.findByRole("status")).toBeTruthy();+ });+});diff --git a/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsxnew file mode 100644index 0000000000..8ace587f39--- /dev/null+++ b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx@@ -0,0 +1,57 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { XIcon } from "lucide-react";+import { useState } from "react";++import { useRelayUsage, useSession, type RelayUsage } from "@/bridge";+import { Button } from "@/components/ui/button";++const DISMISSED_KEY = "cua.relayAllowance.dismissed";++/** One dismissal per month and reason: a new month, or another limit reached, shows it again. */+const dismissKey = (u: RelayUsage) => `${u.period}:${[...u.reasons].sort().join(",")}`;++function readDismissed(): string | null {+ try {+ return globalThis.localStorage?.getItem(DISMISSED_KEY) ?? null;+ } catch {+ return null;+ }+}++/**+ * The relay allowance for the month is used up: one line above every page+ * with Upgrade, until dismissed. Nothing stops at the limit, so it only+ * says so.+ */+export function RelayAllowanceNotice() {+ const usage = useRelayUsage();+ const { openExternal } = useSession();+ const [dismissed, setDismissed] = useState(readDismissed);+ if (!usage?.softLimitReached || dismissed === dismissKey(usage)) return null;+ const dismiss = () => {+ const key = dismissKey(usage);+ try {+ globalThis.localStorage?.setItem(DISMISSED_KEY, key);+ } catch {+ // Not kept: it shows again next launch.+ }+ setDismissed(key);+ };+ return (+ <div role="status" data-relay-allowance="" className="flex shrink-0 items-center gap-3 border-b px-4 py-2 text-xs text-muted-foreground">+ <span className="min-w-0 flex-1">+ You've used your {usage.plan === "free" ? "free " : ""}relay allowance for this month. Your Spaces keep working. Upgrade for more.+ </span>+ {usage.upgradeUrl ? (+ <Button size="sm" variant="outline" data-relay-upgrade="" onClick={() => void openExternal(usage.upgradeUrl!).catch(() => {})}>+ Upgrade+ </Button>+ ) : null}+ <Button size="icon-sm" variant="ghost" aria-label="Dismiss" data-relay-dismiss="" onClick={dismiss}>+ <XIcon className="size-3.5" />+ </Button>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/routes/__root.tsx b/apps/cua-spaces-web/src/routes/__root.tsxindex 44d632e7ae..e16dc88119 100644--- a/apps/cua-spaces-web/src/routes/__root.tsx+++ b/apps/cua-spaces-web/src/routes/__root.tsx@@ -10,6 +10,7 @@ import { ChecklistTracker } from "@/components/getting-started";import { NewSpace } from "@/components/new-space";import { CommandPalette } from "@/components/shell/command-palette";import { Sidebar } from "@/components/shell/sidebar";+import { RelayAllowanceNotice } from "@/components/shell/relay-allowance-notice";import { SpacesNotice } from "@/components/shell/spaces-notice";import { SpaceSheets } from "@/components/space-sheets";import { TopBar } from "@/components/shell/top-bar";@@ -64,6 +65,7 @@ function RootLayout() {<div className="flex min-w-0 flex-1 flex-col bg-background"><TopBar /><SpacesNotice />+ <RelayAllowanceNotice /><main className="min-h-0 flex-1"><Outlet /></main>diff --git a/apps/cua-spaces-web/src/routes/settings/index.tsx b/apps/cua-spaces-web/src/routes/settings/index.tsxindex ab6354c8ef..c86049cf96 100644--- a/apps/cua-spaces-web/src/routes/settings/index.tsx+++ b/apps/cua-spaces-web/src/routes/settings/index.tsx@@ -8,7 +8,9 @@ import {useBridge,useExperiments,useLoginItem,+ relayUsageLine,useMachines,+ useRelayUsage,useSession,useSettings,useStorageSettings,@@ -123,7 +125,12 @@ function CoreGeneralPage({ page }: { page: CorePage }) {return (<>- {account ? <SettingsGroup title={account.title}>{rows(account)}</SettingsGroup> : null}+ {account ? (+ <SettingsGroup title={account.title}>+ {rows(account)}+ <RelayUsageRow />+ </SettingsGroup>+ ) : null}<SettingsGroup title={general?.title ?? "General"}><LaunchAtLoginRows />@@ -157,6 +164,19 @@ function CoreGeneralPage({ page }: { page: CorePage }) {);}+/** The relay allowance this month, where the host reads it (Electron). */+function RelayUsageRow() {+ const usage = useRelayUsage();+ if (!usage) return null;+ const team = usage.team ? ` · Team pool, ${usage.team.seats} ${usage.team.seats === 1 ? "seat" : "seats"}` : "";+ const plan = usage.plan ? `${usage.plan[0]!.toUpperCase()}${usage.plan.slice(1)} plan` : "";+ return (+ <div data-relay-usage="">+ <SettingsRow label="Relay usage" description={relayUsageLine(usage) + team} control={<span className="text-[13px] text-muted-foreground">{plan}</span>} />+ </div>+ );+}+/** Without the core: the settings every host has, drawn by hand. */function FallbackSettingsPage() {const { data: settings, updateSetting } = useSettings();@@ -238,6 +258,7 @@ function FallbackSettingsPage() {)}/>+ <RelayUsageRow /></SettingsGroup><SettingsGroup title="Privacy">diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdxindex 2c7a940309..f0cb424ce1 100644--- a/docs/content/docs/cua-cli/reference/cli/index.mdx+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx@@ -174,6 +174,14 @@ Create a team, invite members, share machines with them, approve their devices a| --- | --- | --- || <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) |+### `cua usage`++Your hosted relay allowance this month: live sessions and relay hours. [Reference](/cua-cli/reference/cli/usage).++| Command | Description | Subcommands |+| --- | --- | --- |+| [`cua usage`](/cua-cli/reference/cli/usage#cua-usage) | Your relay allowance this month: live sessions, relay hours, and your plan. | |+### `cua teleport`Move a desktop app session into a sandbox. [Reference](/cua-cli/reference/cli/teleport).diff --git a/docs/content/docs/cua-cli/reference/cli/meta.json b/docs/content/docs/cua-cli/reference/cli/meta.jsonindex 7c356af392..5644330938 100644--- a/docs/content/docs/cua-cli/reference/cli/meta.json+++ b/docs/content/docs/cua-cli/reference/cli/meta.json@@ -20,6 +20,7 @@"host","devices","team",+ "usage","teleport","volume","keyvault",diff --git a/docs/content/docs/cua-cli/reference/cli/usage.mdx b/docs/content/docs/cua-cli/reference/cli/usage.mdxnew file mode 100644index 0000000000..b990c85e75--- /dev/null+++ b/docs/content/docs/cua-cli/reference/cli/usage.mdx@@ -0,0 +1,46 @@+---+title: "cua usage"+description: "Your hosted relay allowance this month: live sessions and relay hours."+---++{/*+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY+ Generated by: pnpm --dir docs docs:generate:cua-cli+ Source: cua dump-docs --type cli+ Version: 0.4.1+*/}++Every command also accepts the [global options](/cua-cli/reference/cli#global-options).++<span id="cua-usage"></span>++Your relay allowance this month: live sessions, relay hours, and your plan. Spaces on your own network use none of it.++```text output+cua usage [OPTIONS]+```++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| <span id="cua-usage--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |++**Examples**++```bash test="cli-shape" id="ref-cua-usage"+cua usage+cua usage --json+```++## Exit codes++| Code | Meaning |+| --- | --- |+| `0` | Success. |+| `1` | Failure, or `cua do` reported an error. |+| `2` | Invalid argument, or an ambiguous sandbox name (qualify it: `local:NAME`, `cloud:NAME`). |+| `3` | Not found: sandbox, window, skill or image (or an image not published yet). |+| `4` | Not supported, or not configured (for example no Fleet credentials). |+| `5` | No cua-spacesd answered, or a transport failure. |+| `6` | Unauthenticated or permission denied (by Cua, Fleet or your cloud account). |+| `7` | Not enough free disk space (see `cua cache`). |+| `130` | Cancelled (Ctrl-C during a create): what it made was removed. |diff --git a/docs/content/docs/cua-cli/reference/index.mdx b/docs/content/docs/cua-cli/reference/index.mdxindex 8d6126a963..7b4c1535d4 100644--- a/docs/content/docs/cua-cli/reference/index.mdx+++ b/docs/content/docs/cua-cli/reference/index.mdx@@ -33,6 +33,7 @@ description: "Every cua command and every cua MCP tool, generated from the CLI d| [`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) | Create a team, invite members, share machines with them, approve their devices and read the team audit log. |+| [`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. || [`cua keyvault`](/cua-cli/reference/cli/keyvault) | Set up, unlock and lock the Cua Keyvault, with the OS key store or a passphrase. |diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex 3d932f8a6a..c1b2c147d1 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -57,6 +57,7 @@ mod telemetry_cmd;pub mod teleport;pub mod teleport_session;mod trajectory;+mod usage_cmd;pub mod util;use clap::{ArgAction, CommandFactory, FromArgMatches, Parser, Subcommand};@@ -244,6 +245,16 @@ enum Command {cua team audit AIGIS")]Team(team_cmd::TeamCmd),+ /// Your relay allowance this month: live sessions, relay hours, and+ /// your plan. Spaces on your own network use none of it.+ #[command(after_help = "Examples:+ cua usage+ cua usage --json")]+ Usage {+ /// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).+ #[arg(long)]+ relay: Option<String>,+ },/// Move a desktop app session (tabs, profile, sign-in) into a sandbox.#[command(subcommand)]Teleport(teleport::TeleportCmd),@@ -1698,6 +1709,9 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {Command::Team(cmd) => {return team_cmd::run(cmd, &util::cua_home(), json, out).await;}+ Command::Usage { relay } => {+ return usage_cmd::run(relay, &util::cua_home(), json, out).await;+ }// A machine that provides Spaces over its direct address: kept in// this cua home's registry, which the daemon reads too.Command::Spaces(cmd @ host::SpacesCmd::Add { host: true, .. }) => {@@ -2086,6 +2100,7 @@ async fn run_sdk(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {| Command::Cloud(_)| Command::Devices(_)| Command::Team(_)+ | Command::Usage { .. }| Command::Fleet(_)| Command::Teleport(_)| Command::Cache(_)diff --git a/libs/cua/crates/cua-cli/src/usage_cmd.rs b/libs/cua/crates/cua-cli/src/usage_cmd.rsnew file mode 100644index 0000000000..5801a389a2--- /dev/null+++ b/libs/cua/crates/cua-cli/src/usage_cmd.rs@@ -0,0 +1,176 @@+//! `cua usage`: your relay allowance this month. A live session is a+//! connection to one of your remote machines through the hosted relay+//! (viewing, a terminal, an agent); relay hours are the time with at least+//! one. Spaces reached on your own network use no allowance, and nothing+//! stops at the limit: the relay only says it was reached.++use crate::util::line;+use cua_host::{AccountTokens, RelayClient, RelayUsage};+use cua_sdk::CuaError;+use std::io::Write;+use std::path::Path;++/// `cua usage` as the signed-in account, on `relay` (default: as `cua devices`).+pub async fn run(+ relay: Option<String>,+ home: &Path,+ json: bool,+ out: &mut dyn Write,+) -> Result<i32, CuaError> {+ let client =+ RelayClient::new(&crate::host::relay_url(relay, home)).map_err(crate::host::host_err)?;+ run_with(&client, &crate::host::SessionTokens, json, out).await+}++/// Reads the allowance from `client` with `tokens` and prints it.+pub async fn run_with(+ client: &RelayClient,+ tokens: &dyn AccountTokens,+ json: bool,+ out: &mut dyn Write,+) -> Result<i32, CuaError> {+ let err = crate::host::host_err;+ let token = tokens.access_token().await.map_err(err)?;+ let usage = client.usage(&token).await.map_err(err)?;+ if json {+ let value = match &usage {+ Some(u) => serde_json::to_value(u).unwrap_or_default(),+ None => serde_json::json!({ "metered": false }),+ };+ line(out, value.to_string());+ return Ok(0);+ }+ match usage {+ Some(u) if u.metered => print(&u, out),+ _ => line(out, "No relay allowance applies to your account."),+ }+ Ok(0)+}++fn print(u: &RelayUsage, out: &mut dyn Write) {+ let of = |used: String, limit: Option<String>| match limit {+ Some(l) => format!("{used} of {l}"),+ None => format!("{used} (no limit)"),+ };+ line(+ out,+ format!(+ "Plan: {}{}",+ if u.plan.is_empty() { "-" } else { &u.plan },+ if u.period.is_empty() {+ String::new()+ } else {+ format!(" ({})", u.period)+ }+ ),+ );+ line(+ out,+ format!(+ "Live sessions: {}",+ of(+ u.live_sessions.to_string(),+ u.live_sessions_limit.map(|l| l.to_string())+ )+ ),+ );+ line(+ out,+ format!(+ "Relay hours: {} this month",+ of(hours(u.hours_used), u.hours_limit.map(hours))+ ),+ );+ if let Some(team) = &u.team {+ line(+ out,+ format!(+ "Team pool: {}, {} seat{} (your hours: {})",+ team.id,+ team.seats,+ if team.seats == 1 { "" } else { "s" },+ hours(u.my_hours_used)+ ),+ );+ }+ if u.soft_limit_reached {+ let upgrade = u+ .upgrade_url+ .as_deref()+ .map(|url| format!(" Upgrade: {url}"))+ .unwrap_or_default();+ line(+ out,+ format!("You've reached your relay allowance. Your Spaces keep working.{upgrade}"),+ );+ }+}++/// `20` or `3.4`.+fn hours(h: f64) -> String {+ let tenths = (h * 10.0).round() / 10.0;+ if tenths.fract() == 0.0 {+ format!("{tenths:.0}")+ } else {+ format!("{tenths:.1}")+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use cua_host::StaticToken;+ use cua_host::testing::FakeRelay;++ async fn text(relay: &FakeRelay, json: bool) -> String {+ let client = RelayClient::new(&relay.url).unwrap();+ let mut out = Vec::new();+ run_with(&client, &StaticToken("acct".into()), json, &mut out)+ .await+ .unwrap();+ String::from_utf8(out).unwrap()+ }++ #[tokio::test]+ async fn prints_the_allowance_and_the_upgrade_past_it() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", None);+ assert_eq!(+ text(&relay, false).await.trim(),+ "No relay allowance applies to your account."+ );+ assert_eq!(text(&relay, true).await.trim(), r#"{"metered":false}"#);++ let mut usage = serde_json::json!({+ "metered": true, "period": "2026-10", "plan": "free",+ "live_sessions": 1, "live_sessions_limit": 2, "hours_used": 6.5, "hours_limit": 20,+ "my_hours_used": 6.5, "soft_limit_reached": false, "reasons": [],+ "upgrade_url": "https://cua.ai/pricing"+ });+ relay.set_usage(Some(usage.clone()));+ let t = text(&relay, false).await;+ assert!(t.contains("Plan: free (2026-10)"), "{t}");+ assert!(t.contains("Live sessions: 1 of 2"), "{t}");+ assert!(t.contains("Relay hours: 6.5 of 20 this month"), "{t}");+ assert!(!t.contains("Team pool") && !t.contains("reached"), "{t}");++ usage["team"] = serde_json::json!({ "id": "acme", "seats": 3 });+ usage["hours_used"] = serde_json::json!(21);+ usage["soft_limit_reached"] = serde_json::json!(true);+ usage["reasons"] = serde_json::json!(["hours"]);+ relay.set_usage(Some(usage));+ let t = text(&relay, false).await;+ assert!(t.contains("Relay hours: 21 of 20 this month"), "{t}");+ assert!(+ t.contains("Team pool: acme, 3 seats (your hours: 6.5)"),+ "{t}"+ );+ assert!(+ t.contains("You've reached your relay allowance. Your Spaces keep working. Upgrade: https://cua.ai/pricing"),+ "{t}"+ );+ let v: serde_json::Value = serde_json::from_str(&text(&relay, true).await).unwrap();+ assert_eq!(v["soft_limit_reached"], true);+ assert_eq!(v["team"]["seats"], 3);+ }+}diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex 05cc747274..f17e19e688 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -62,8 +62,8 @@ pub use provided::{};pub use relay::{AccountTokens, AuditEvent, ConnectedClient, DEFAULT_RELAY_URL, DeviceListing, DeviceState,- DeviceView, Enrollment, Identity, Machine, MachinePatch, NoAccount, RelayClient, StaticToken,- relay_url_from_env,+ DeviceView, Enrollment, Identity, Machine, MachinePatch, NoAccount, RelayClient, RelayUsage,+ RelayUsageTeam, StaticToken, relay_url_from_env,};pub use service::{RunnerKind, ServiceManager, ServiceSpec, ServiceState};pub use team::{diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rsindex 6fe0b0b9e4..8f2dacede7 100644--- a/libs/cua/crates/cua-host/src/relay.rs+++ b/libs/cua/crates/cua-host/src/relay.rs@@ -19,6 +19,7 @@//! PATCH /v1/devices/{id} enrolled device -> DeviceView//! DELETE /v1/devices/{id} enrolled device -> DeviceView//! GET /v1/audit account -> {events}+//! GET /v1/usage account -> RelayUsage//! ```//!//! Account calls other than registering a machine carry the client@@ -381,6 +382,52 @@ pub struct AuditEvent {pub detail: Option<String>,}+/// The account's relay allowance this month (`GET /v1/usage`). A live+/// session is a connection to one remote machine through the relay; relay+/// hours are the time with at least one. Past the allowance nothing stops:+/// the relay only says so (`soft_limit_reached`). Every field has a+/// default, so older and newer relays both parse.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct RelayUsage {+ /// The relay meters this account (false: no allowance applies).+ pub metered: bool,+ /// The month counted (`2026-10`).+ pub period: String,+ /// `free`, `pro`, `team`, ...+ pub plan: String,+ /// The team whose allowance is pooled, if any.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team: Option<RelayUsageTeam>,+ /// Live sessions now.+ pub live_sessions: u32,+ /// Live sessions allowed at once (none: no limit).+ pub live_sessions_limit: Option<u32>,+ /// Relay hours used this month (the team's, when pooled).+ pub hours_used: f64,+ /// Relay hours allowed this month (none: no limit).+ pub hours_limit: Option<f64>,+ /// This account's own relay hours this month.+ pub my_hours_used: f64,+ /// Past the allowance (sessions keep working).+ pub soft_limit_reached: bool,+ /// What is past it: `sessions` and/or `hours`.+ pub reasons: Vec<String>,+ /// Where to get more.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub upgrade_url: Option<String>,+}++/// The team behind a pooled allowance.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(default)]+pub struct RelayUsageTeam {+ /// Team id.+ pub id: String,+ /// Seats sharing the allowance.+ pub seats: u32,+}+#[derive(Deserialize)]struct DeviceReply {device: DeviceView,@@ -683,6 +730,19 @@ impl RelayClient {Ok(list.events)}+ /// The account's relay allowance this month; `None` from a relay that+ /// does not meter (no `/v1/usage`).+ pub async fn usage(&self, account_token: &str) -> Result<Option<RelayUsage>> {+ match self+ .send(self.http.get(self.url("/v1/usage")), account_token)+ .await+ {+ Ok(usage) => Ok(Some(usage)),+ Err(Error::NotFound(_)) => Ok(None),+ Err(e) => Err(e),+ }+ }+/// Machines the account owns or that are shared with it.pub async fn machines(&self, account_token: &str) -> Result<Vec<Machine>> {let list: MachineList = self@@ -867,4 +927,20 @@ mod tests {let bare: Machine = serde_json::from_str(r#"{"id":"abcd1234"}"#).unwrap();assert!(!bare.online);}++ #[test]+ fn usage_parses_with_missing_and_unknown_fields() {+ let u: RelayUsage = serde_json::from_str(+ r#"{"metered":true,"period":"2026-10","plan":"free","team":{"id":"acme","seats":2},+ "live_sessions":1,"live_sessions_limit":2,"hours_used":3.4,"hours_limit":20,+ "my_hours_used":3.4,"soft_limit_reached":true,"reasons":["hours"],+ "upgrade_url":"https://cua.ai/pricing","later":1}"#,+ )+ .unwrap();+ assert_eq!(u.team.as_ref().unwrap().seats, 2);+ assert_eq!(u.hours_limit, Some(20.0));+ assert_eq!(u.reasons, ["hours"]);+ let bare: RelayUsage = serde_json::from_str("{}").unwrap();+ assert!(!bare.metered && bare.live_sessions_limit.is_none());+ }}diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rsindex f6c747d38d..141a11538c 100644--- a/libs/cua/crates/cua-host/src/testing.rs+++ b/libs/cua/crates/cua-host/src/testing.rs@@ -83,6 +83,9 @@ struct State_ {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>,}impl State_ {@@ -766,6 +769,18 @@ async fn audit(State(s): State<S>, headers: HeaderMap) -> Response {Json(serde_json::json!({ "events": events })).into_response()}+async fn usage(State(s): State<S>, headers: HeaderMap) -> Response {+ let st = s.lock().unwrap();+ let Some(usage) = st.usage.clone() else {+ return err(StatusCode::NOT_FOUND, "not found");+ };+ match caller(&st, &headers) {+ Some(Caller::Account(_)) => Json(usage).into_response(),+ Some(Caller::Machine(_)) => err(StatusCode::FORBIDDEN, "account token required"),+ None => err(StatusCode::UNAUTHORIZED, "account token required"),+ }+}+async fn proxied(State(s): State<S>,method: axum::http::Method,@@ -959,6 +974,7 @@ impl FakeRelay {post(team_approve),).route("/v1/teams/{id}/audit", get(team_audit))+ .route("/v1/usage", get(usage)).fallback(proxied).with_state(state.clone());let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))@@ -1116,6 +1132,12 @@ impl FakeRelay {.push((prefix.to_string(), target.to_string()));}+ /// Answers `GET /v1/usage` with `usage` (the relay's JSON) for every+ /// account; none: 404, as a relay that does not meter.+ pub fn set_usage(&self, usage: Option<serde_json::Value>) {+ self.state.lock().unwrap().usage = usage;+ }+/// The current machine token of `id`.pub fn machine_token(&self, id: &str) -> Option<String> {self.statediff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex 8c99b0a574..8161e7270d 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -277,6 +277,42 @@ async fn direct_setup_serves_with_a_local_token_and_stop_stops_the_service() {assert!(!host.paths().dir.exists());}+#[tokio::test]+async fn relay_usage_is_none_where_the_relay_does_not_meter() {+ let relay = FakeRelay::start().await;+ relay.add_account("owner", "user-1", None);+ let f = fixture();+ let status = f+ .host()+ .setup(f.relay_opts(&relay.url), &StaticToken("owner".into()))+ .await+ .unwrap();+ let client = RelayClient::new(&relay.url).unwrap();+ assert_eq!(client.usage("owner").await.unwrap(), None);++ relay.set_usage(Some(serde_json::json!({+ "metered": true, "period": "2026-10", "plan": "free",+ "live_sessions": 2, "live_sessions_limit": 2, "hours_used": 20.5, "hours_limit": 20,+ "my_hours_used": 20.5, "soft_limit_reached": true, "reasons": ["sessions", "hours"],+ "upgrade_url": "https://cua.ai/pricing"+ })));+ let usage = client.usage("owner").await.unwrap().unwrap();+ assert!(usage.soft_limit_reached);+ assert_eq!(usage.live_sessions_limit, Some(2));+ assert_eq!(usage.reasons, ["sessions", "hours"]);+ assert!(usage.team.is_none());+ // Only people have an allowance: a machine token is refused.+ let machine_token = relay.machine_token(&status.machine_id.unwrap()).unwrap();+ assert!(matches!(+ client.usage(&machine_token).await.unwrap_err(),+ Error::PermissionDenied(_)+ ));+ assert!(matches!(+ client.usage("wrong").await.unwrap_err(),+ Error::Unauthenticated(_)+ ));+}+#[tokio::test]async fn relay_directory_lists_owned_and_shared_machines() {let relay = FakeRelay::start().await;diff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.inindex d74ffd2128..84483f1e08 100644--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in@@ -201,6 +201,7 @@"trajectory.serve","trajectory.stop","trajectory.view",+ "usage","viewer","volume.approve","volume.audit",diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex b2e7aa1af3..3e87d0a642 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -11714,6 +11714,37 @@],"usage": "cua team [OPTIONS] <COMMAND>"},+ {+ "abstract": "Your relay allowance this month: live sessions, relay hours, and your plan. Spaces on your own network use none of it",+ "after_help": "Examples:\n cua usage\n cua usage --json",+ "aliases": [],+ "arguments": [],+ "flags": [],+ "hidden": false,+ "hidden_aliases": [],+ "name": "usage",+ "options": [+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "relay",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "RELAY"+ }+ ],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua usage [OPTIONS]"+ },{"abstract": "Move a desktop app session (tabs, profile, sign-in) into a sandbox","aliases": [],diff --git a/scripts/docs-generators/cua-cli.ts b/scripts/docs-generators/cua-cli.tsindex 1662456757..571bbf7d81 100644--- a/scripts/docs-generators/cua-cli.ts+++ b/scripts/docs-generators/cua-cli.ts@@ -122,6 +122,7 @@ export const CLI_GROUPS: CliGroup[] = [{ 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: 'Create a team, invite members, share machines with them, approve their devices and read the team audit log', 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'] },{ slug: 'keyvault', title: 'cua keyvault', summary: 'Set up, unlock and lock the Cua Keyvault, with the OS key store or a passphrase', commands: ['keyvault'] },