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.

Spaces: plan-limit refusals in plain words, with Upgrade and a usage meter (#5556)

Francesco Bonacci6ab2ca10f930
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
index e1a645edae..0590a693db 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
@@ -1222,6 +1222,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_spaces_ffi_fn_func_app_plan_limit_notice": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_spaces_ffi_fn_func_app_power_button": {
args: [FfiType.RustBuffer],
ret: FfiType.RustBuffer,
@@ -2962,6 +2967,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_spaces_ffi_checksum_func_app_plan_limit_notice": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_spaces_ffi_checksum_func_app_power_button": {
args: [],
ret: FfiType.UInt16,
@@ -4230,6 +4240,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_fn_func_app_picker_sensitive_options(state: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_picker_status(state: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_picker_window_grid(windows: Uint8Array, query: Uint8Array, selected: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_plan_limit_notice(error: Uint8Array, accountApp: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_power_button(space: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_presence_name(name: Uint8Array, email: Uint8Array, username: Uint8Array, osFullName: Uint8Array, osUser: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_presence_principal_id(email: Uint8Array, subject: Uint8Array, username: Uint8Array, osUser: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -4578,6 +4589,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_checksum_func_app_picker_sensitive_options(): number;
uniffi_cua_spaces_ffi_checksum_func_app_picker_status(): number;
uniffi_cua_spaces_ffi_checksum_func_app_picker_window_grid(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_plan_limit_notice(): number;
uniffi_cua_spaces_ffi_checksum_func_app_power_button(): number;
uniffi_cua_spaces_ffi_checksum_func_app_presence_name(): number;
uniffi_cua_spaces_ffi_checksum_func_app_presence_principal_id(): number;
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
index 36e0873522..3b134d8641 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
@@ -3488,6 +3488,28 @@ export function appPickerWindowGrid(windows: Array<AppOpenWindow>, query: string
));
}
+/**
+ * The relay refusing a new session over the plan's cap, from the error's
+ * text: the sentence and Upgrade. None for any other error.
+ */
+export function appPlanLimitNotice(error: string, accountApp: string): AppRelayAllowanceNotice | undefined {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterOptionalTypeAppRelayAllowanceNotice.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_plan_limit_notice(
+ FfiConverterString.lower(error, nativeModule().rustbuffer_alloc),
+ FfiConverterString.lower(accountApp, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
/**
* The power button next to Delete, for a Space that turns off and on.
*/
@@ -32223,7 +32245,7 @@ const FfiConverterTypeAppRefreshReport = (() => {
export type AppRelayAllowanceNotice = {
/**
- * "You've used your free relay allowance for this month. ..."
+ * On Free: "You're using 2 of 2 live sessions on the free plan. ..."
*/
text: string,
/**
@@ -62753,6 +62775,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_picker_window_grid() !== 8477) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_picker_window_grid");
}
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_plan_limit_notice() !== 24944) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_plan_limit_notice");
+ }
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_power_button() !== 25513) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_power_button");
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index c8435d1792..cbe33dce10 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -999,6 +999,7 @@ public final class AppModel {
sendCreate(.cancelDone(id: pendingId))
throw error
} catch {
+ devices.noteRefusal(LiveSpacesBackend.words(error))
sendCreate(.fail(id: pendingId, error: LiveSpacesBackend.words(error),
errorVariant: (error as? CuaError).flatMap { Mirror(reflecting: $0).children.first?.label } ?? ""))
throw error
@@ -1107,6 +1108,7 @@ public final class AppModel {
sendCreate(.powerDone(id: space.id))
await refresh()
} catch {
+ devices.noteRefusal(LiveSpacesBackend.words(error))
sendCreate(.powerFail(id: space.id, error: LiveSpacesBackend.words(error)))
}
}
@@ -1119,6 +1121,7 @@ public final class AppModel {
}
public func show(error: String) {
+ devices.noteRefusal(error)
banner = error
bannerIsError = true
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
index 3f1543f1e7..0d06210513 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
@@ -364,6 +364,9 @@ public final class DevicesModel {
let defaults: UserDefaults
static let relayNoticeDismissedKey = "cua.relayAllowance.dismissed"
public private(set) var relayNoticeDismissed: String?
+ /// The relay just refused a new session over the plan's cap: the sentence
+ /// with Upgrade, shown until dismissed or a session starts.
+ public private(set) var refusal: AppRelayAllowanceNotice?
public init(devices: DevicesRunning?, presence: PresenceChecking = LivePresence(),
defaults: UserDefaults = .standard) {
@@ -494,6 +497,7 @@ public final class DevicesModel {
/// At 80% of the relay hours (`warn`) it is a prompt, so it waits while a
/// live session is going; past the allowance (`limit`) it always shows.
public var relayNotice: AppRelayAllowanceNotice? {
+ if let refusal { return refusal }
guard let notice = relayUsageView?.notice, notice.dismissKey != relayNoticeDismissed else { return nil }
if notice.level == "warn", (relayUsage?.liveSessions ?? 0) > 0 { return nil }
return notice
@@ -505,7 +509,19 @@ public final class DevicesModel {
telemetry?.record(appTelemetryFeature(feature: feature))
}
+ /// Keeps an error's text when it is the relay refusing a session over
+ /// the plan's cap (the core's `appPlanLimitNotice`); any other error is
+ /// not a refusal and leaves the notice alone.
+ public func noteRefusal(_ error: String) {
+ guard let notice = appPlanLimitNotice(error: error, accountApp: appAccountAppUrl()) else { return }
+ refusal = notice
+ }
+
public func dismissRelayNotice() {
+ if refusal != nil {
+ refusal = nil
+ return
+ }
guard let key = relayUsageView?.notice?.dismissKey else { return }
recordUpsell("upsell_meter_dismiss")
relayNoticeDismissed = key
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
index aabdfbe768..4c3bbfc980 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
@@ -264,21 +264,35 @@ struct RelayUsageTests {
let (m, defaults) = model(fixture)
await m.readRelayUsage()
let notice = try #require(m.relayNotice)
- #expect(notice.text == "You've reached the free plan's remote limit for this month. Your Spaces keep working. Pro gives you more.")
+ #expect(notice.text == "You're using 2 of 2 live sessions and 20.4 of 20 remote hours on the free plan. Your Spaces keep working. Pro gives you 5 live sessions and 200 remote hours.")
#expect(notice.upgrade == "Upgrade")
#expect(notice.upgradeUrl == "https://app.cua.ai/buy/pro?from=app_meter")
#expect(notice.level == "limit")
m.dismissRelayNotice()
#expect(m.relayNotice == nil)
- #expect(defaults.string(forKey: DevicesModel.relayNoticeDismissedKey) == "2026-10:hours")
+ #expect(defaults.string(forKey: DevicesModel.relayNoticeDismissedKey) == "2026-10:hours,sessions")
// Kept across launches; another reason shows it again.
let again = DevicesModel(devices: fixture, presence: FixturePresence(), defaults: defaults)
again.signedIn = true
await again.readRelayUsage()
#expect(again.relayNotice == nil)
- fixture.usage?.reasons = ["sessions", "hours"]
+ fixture.usage?.liveSessions = 1
+ fixture.usage?.reasons = ["hours"]
await again.readRelayUsage()
- #expect(again.relayNotice?.dismissKey == "2026-10:hours,sessions")
+ #expect(again.relayNotice?.dismissKey == "2026-10:hours")
+ }
+
+ @Test func aRefusedSessionShowsTheSentenceWithUpgradeUntilDismissed() async throws {
+ let (m, _) = model(FixtureDevices())
+ m.noteRefusal("timed out")
+ #expect(m.relayNotice == nil)
+ m.noteRefusal("relay: You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams.")
+ let notice = try #require(m.relayNotice)
+ #expect(notice.text == "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams.")
+ #expect(notice.upgrade == "Upgrade")
+ #expect(notice.upgradeUrl?.hasSuffix("/buy/teams?from=plan_limit") == true)
+ m.dismissRelayNotice()
+ #expect(m.relayNotice == nil)
}
@Test func atEightyPercentOfHoursAFreePlanGetsAHeadsUpThatWaitsForLiveSessions() async throws {
diff --git a/apps/cua-spaces-web/src/__tests__/upsell.test.tsx b/apps/cua-spaces-web/src/__tests__/upsell.test.tsx
index 221bfcc3d9..c0108fbfeb 100644
--- a/apps/cua-spaces-web/src/__tests__/upsell.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/upsell.test.tsx
@@ -76,6 +76,31 @@ describe.skipIf(!wasmBuilt)("in-app Pro and Teams prompts (real routes, wasm cor
await waitFor(() => expect(features(tracked)).toContain("upsell_plan_card_click"));
});
+ it("Settings shows the usage meter: Pro at 5 of 5 live sessions says so, with Upgrade to Teams", async () => {
+ const opened: string[] = [];
+ const { router } = await mountApp("/settings", host(idle({ plan: "pro", liveSessions: 5, liveSessionsLimit: 5, hoursUsed: 12, hoursLimit: 200 }), opened));
+ await router.load();
+ const sessions = await waitFor(() => {
+ const el = document.querySelector('[data-usage-meter="Live sessions"]');
+ expect(el).toBeTruthy();
+ return el as HTMLElement;
+ });
+ expect(sessions.getAttribute("aria-valuenow")).toBe("5");
+ expect(sessions.getAttribute("aria-valuemax")).toBe("5");
+ expect(sessions.hasAttribute("data-full")).toBe(true);
+ const hours = document.querySelector('[data-usage-meter="Remote hours"]')!;
+ expect(hours.getAttribute("aria-valuenow")).toBe("12");
+ expect(hours.hasAttribute("data-full")).toBe(false);
+ const notice = await waitFor(() => {
+ const el = document.querySelector("[data-relay-allowance]");
+ expect(el).toBeTruthy();
+ return el as HTMLElement;
+ });
+ expect(notice.textContent).toContain("You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams.");
+ fireEvent.click(notice.querySelector("[data-relay-upgrade]")!);
+ await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/teams?from=app_meter"]));
+ });
+
it("Settings shows Pro's plan card with Manage plan and Teams", async () => {
const { router } = await mountApp("/settings", host(idle({ plan: "pro", liveSessionsLimit: 5, hoursLimit: 200 })));
await router.load();
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.tsx
index f33aab5040..59111ca1c1 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/relay-usage.test.tsx
+++ b/apps/cua-spaces-web/src/bridge/__tests__/relay-usage.test.tsx
@@ -60,7 +60,7 @@ describe("relay.usage", () => {
const past = relayUsageView(core, { ...demoRelayUsage(), hoursUsed: 20.24, softLimitReached: true, reasons: ["hours"], team: { id: "acme", seats: 3 } })!;
expect(past.line).toBe("Live sessions 1 of 2 · Remote hours 20.2 of 20 this month · Team pool, 3 seats");
expect(past.notice).toEqual({
- text: "You've reached the free plan's remote limit for this month. Your Spaces keep working. Pro gives you more.",
+ text: "You're using 20.2 of 20 remote hours on the free plan. Your Spaces keep working. Pro gives you 5 live sessions and 200 remote hours.",
upgrade: "Upgrade",
upgradeUrl: "https://app.cua.ai/buy/pro?from=app_meter",
dismiss: "Dismiss",
@@ -70,7 +70,7 @@ describe("relay.usage", () => {
expect(relayUsageView(noCore, demoRelayUsage())).toBeNull();
});
- it("reads once for every screen, again every 5 minutes, and drops it when signed out", async () => {
+ it("reads once for every screen, again every minute, and drops it when signed out", async () => {
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
const demo = createDemoAdapter({ latencyMs: 0 });
const call = vi.fn(demo.call);
diff --git a/apps/cua-spaces-web/src/bridge/derive.ts b/apps/cua-spaces-web/src/bridge/derive.ts
index f70926c1eb..3e4c745e07 100644
--- a/apps/cua-spaces-web/src/bridge/derive.ts
+++ b/apps/cua-spaces-web/src/bridge/derive.ts
@@ -33,7 +33,7 @@ import type {
VaultView,
} from "./contracts/keyvault";
import type { CreateAction, CreatesState, PendingCreate, Space, SpaceOs, SpaceRow, SpaceStatus } from "./contracts/spaces";
-import type { RelayUsage, RelayUsageView } from "./ops/relay-usage";
+import type { RelayAllowanceNotice, RelayUsage, RelayUsageView } from "./ops/relay-usage";
import type { SessionSnapshot, SettingsSnapshot } from "./protocol";
import { notSharingOf, realLimits } from "./sharing";
import { hostOs, type HostOs } from "./host-os";
@@ -764,3 +764,10 @@ export function orderRuns<T extends SpaceAgentRun>(core: CoreClient, runs: T[]):
export function relayUsageView(core: CoreClient, usage: RelayUsage, accountApp: string | null = null): RelayUsageView | null {
return core.tryCall<RelayUsageView | null>("relayUsage.view", accountApp ? { usage, accountApp } : { usage }) ?? null;
}
+
+/** A refused new session (the relay's plan limit) as the sentence with
+ * Upgrade, from an error's text (the core's `relayUsage.planLimit`); null
+ * for any other error, or without the core. */
+export function planLimitNotice(core: CoreClient, error: string, accountApp: string | null = null): RelayAllowanceNotice | null {
+ return core.tryCall<RelayAllowanceNotice | null>("relayUsage.planLimit", accountApp ? { error, accountApp } : { error }) ?? null;
+}
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index 82d984283a..54f3ccefb1 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -137,6 +137,7 @@ export {
export {
useRelayUsage,
useRelayUsageView,
+ usePlanLimitNotice,
RELAY_USAGE_FOCUS_MS,
RELAY_USAGE_POLL_MS,
type PlanCard,
diff --git a/apps/cua-spaces-web/src/bridge/relay-usage.ts b/apps/cua-spaces-web/src/bridge/relay-usage.ts
index e7570fbd22..7c0b08e6c0 100644
--- a/apps/cua-spaces-web/src/bridge/relay-usage.ts
+++ b/apps/cua-spaces-web/src/bridge/relay-usage.ts
@@ -3,7 +3,7 @@
/**
* 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
+ * it: at once, every minute, 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. The words
* are the app core's (`relayUsage.view`).
@@ -12,13 +12,13 @@
import { useContext, useMemo, useSyncExternalStore } from "react";
import { isUnsupported, type DataAdapter } from "./adapter";
import { BridgeContext } from "./BridgeProvider";
-import { relayUsageView } from "./derive";
+import { planLimitNotice, relayUsageView } from "./derive";
import { useSettings } from "./hooks";
-import type { RelayUsage, RelayUsageView } from "./ops/relay-usage";
+import type { RelayAllowanceNotice, RelayUsage, RelayUsageView } from "./ops/relay-usage";
export type { PlanCard, PlanLink, RelayAllowanceNotice, RelayUsage, RelayUsageView } from "./ops/relay-usage";
-export const RELAY_USAGE_POLL_MS = 5 * 60_000;
+export const RELAY_USAGE_POLL_MS = 60_000;
/** A focus reads again only when the last read is older than this. */
export const RELAY_USAGE_FOCUS_MS = 60_000;
@@ -135,3 +135,11 @@ export function useRelayUsageView(): RelayUsageView | null {
const accountApp = useSettings().data?.accountUrl ?? null;
return useMemo(() => (usage && core ? relayUsageView(core, usage, accountApp) : null), [usage, core, accountApp]);
}
+
+/** The plan-limit refusal in an error's text, as the core's sentence with
+ * its Upgrade link; null for any other error (or without the core). */
+export function usePlanLimitNotice(): (error: string) => RelayAllowanceNotice | null {
+ const core = useContext(BridgeContext)?.core;
+ const accountApp = useSettings().data?.accountUrl ?? null;
+ return useMemo(() => (error: string) => (core ? planLimitNotice(core, error, accountApp) : null), [core, accountApp]);
+}
diff --git a/apps/cua-spaces-web/src/components/shell/plan-limit-toast-action.test.tsx b/apps/cua-spaces-web/src/components/shell/plan-limit-toast-action.test.tsx
new file mode 100644
index 0000000000..b411eeee3d
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/shell/plan-limit-toast-action.test.tsx
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createDemoAdapter } from "@/bridge/adapters/demo";
+import { BridgeProvider, type CoreClient, type DataAdapter } from "@/bridge";
+import { noCore } from "@/bridge/__tests__/testCore";
+import { ToastProvider, toastError, toastManager } from "@/components/ui/toast";
+
+import { PlanLimitToastAction } from "./plan-limit-toast-action";
+
+afterEach(() => {
+ act(() => toastManager.close());
+ cleanup();
+});
+
+const SENTENCE = "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams.";
+
+/** A core that answers only `relayUsage.planLimit`, as the real one does. */
+const core: CoreClient = {
+ ...noCore,
+ status: "ready",
+ call: () => undefined as never,
+ tryCall: <T,>(method: string, args?: Record<string, unknown>) =>
+ (method === "relayUsage.planLimit" && String(args?.error).includes("live sessions on Pro")
+ ? { text: SENTENCE, upgrade: "Upgrade", upgradeUrl: "https://app.cua.ai/buy/teams?from=plan_limit", dismiss: "Dismiss", dismissKey: "refused:Sessions", level: "limit" }
+ : null) as T,
+};
+
+function mount() {
+ const demo = createDemoAdapter({ latencyMs: 0 });
+ 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);
+ },
+ };
+ render(
+ <BridgeProvider adapter={adapter} core={core}>
+ <ToastProvider>
+ <PlanLimitToastAction />
+ </ToastProvider>
+ </BridgeProvider>,
+ );
+ return opened;
+}
+
+describe("PlanLimitToastAction", () => {
+ it("a refused session shows the plain sentence with an Upgrade that opens the plan's page", async () => {
+ const opened = mount();
+ await act(() => new Promise((r) => setTimeout(r, 10)));
+ act(() => toastError("Couldn't open the Space")(new Error(SENTENCE)));
+ expect(screen.getAllByText(SENTENCE).length).toBeGreaterThan(0);
+ const button = document.querySelector("[data-toast-action]") as HTMLElement;
+ expect(button.textContent).toBe("Upgrade");
+ fireEvent.click(button);
+ await act(() => new Promise((r) => setTimeout(r, 10)));
+ expect(opened).toEqual(["https://app.cua.ai/buy/teams?from=plan_limit"]);
+ });
+
+ it("any other failure has no Upgrade", async () => {
+ mount();
+ await act(() => new Promise((r) => setTimeout(r, 10)));
+ act(() => toastError("Couldn't open the Space")(new Error("timed out")));
+ expect(document.querySelector("[data-toast-action]")).toBeNull();
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/shell/plan-limit-toast-action.tsx b/apps/cua-spaces-web/src/components/shell/plan-limit-toast-action.tsx
new file mode 100644
index 0000000000..fc53150672
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/shell/plan-limit-toast-action.tsx
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { useEffect } from "react";
+
+import { usePlanLimitNotice, useSession } from "@/bridge";
+import { setErrorAction } from "@/components/ui/toast";
+
+/**
+ * Puts Upgrade on the toast of a failed action when the failure is the
+ * relay refusing a new live session over the plan's cap ("You're using 5 of
+ * 5 live sessions on Pro. Close one or upgrade to Teams."). The sentence is
+ * the error's own; the button opens the plan's page on the account app.
+ * Renders nothing.
+ */
+export function PlanLimitToastAction() {
+ const noticeFor = usePlanLimitNotice();
+ const { openExternal } = useSession();
+ useEffect(() => {
+ setErrorAction((text) => {
+ const notice = noticeFor(text);
+ const url = notice?.upgradeUrl;
+ if (!notice || !url) return null;
+ return { label: notice.upgrade, onClick: () => void openExternal(url).catch(() => {}) };
+ });
+ return () => setErrorAction(null);
+ }, [noticeFor, openExternal]);
+ return null;
+}
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.tsx
index 8e20193a29..f5ceba5934 100644
--- 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.tsx
@@ -61,7 +61,7 @@ describe.skipIf(!wasmBuilt)("<RelayAllowanceNotice>", () => {
const { view, opened } = host(reached);
view();
const notice = await screen.findByRole("status");
- expect(notice.textContent).toContain("You've reached the free plan's remote limit for this month. Your Spaces keep working.");
+ expect(notice.textContent).toContain("You're using 20.2 of 20 remote hours on the free plan. Your Spaces keep working.");
fireEvent.click(screen.getByRole("button", { name: "Upgrade" }));
await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/pro?from=app_meter"]));
});
diff --git a/apps/cua-spaces-web/src/components/ui/toast.tsx b/apps/cua-spaces-web/src/components/ui/toast.tsx
index 3fcb3b4882..bc2916fd5d 100644
--- a/apps/cua-spaces-web/src/components/ui/toast.tsx
+++ b/apps/cua-spaces-web/src/components/ui/toast.tsx
@@ -20,6 +20,20 @@ export const TOAST_MS = 5000;
*/
export const ERROR_TOAST_MS = 15000;
+/** A button on a toast (an error's Upgrade). */
+export interface ToastAction {
+ label: string;
+ onClick: () => void;
+}
+
+let errorAction: ((text: string) => ToastAction | null) | null = null;
+
+/** Offers an action on a failed action's toast, from the error's text (the
+ * plan-limit refusal's Upgrade). Set by the shell, which has the core. */
+export function setErrorAction(fn: ((text: string) => ToastAction | null) | null) {
+ errorAction = fn;
+}
+
/** The open toasts of each group (`toast`'s `group`). */
const groups = new Map<string, Set<string>>();
@@ -28,7 +42,7 @@ const groups = new Map<string, Set<string>>();
* create that worked closes the failure of the try before it. `fromCua` marks
* one of Cua's own notifications: it shows the Cua key instead of the info icon.
*/
-export function toast(title: string, options: { description?: string; type?: ToastType; group?: string; fromCua?: boolean } = {}) {
+export function toast(title: string, options: { description?: string; type?: ToastType; group?: string; fromCua?: boolean; action?: ToastAction } = {}) {
const type = options.type ?? "info";
const group = options.group;
if (group) {
@@ -38,7 +52,7 @@ export function toast(title: string, options: { description?: string; type?: Toa
// Base UI's own timer pauses while the window is unfocused and resumes on
// focus, which a webview in a native window may never report (an
// "Opening…" toast stayed 10+ min). A plain timer closes it either way.
- const id = toastManager.add({ title, description: options.description, type, timeout: 0, data: { fromCua: options.fromCua === true } });
+ const id = toastManager.add({ title, description: options.description, type, timeout: 0, data: { fromCua: options.fromCua === true, action: options.action } });
if (group) groups.set(group, new Set([id]));
setTimeout(() => {
toastManager.close(id);
@@ -48,8 +62,10 @@ export function toast(title: string, options: { description?: string; type?: Toa
}
/** A failed action: `title` says what didn't happen, the error says why. */
-export const toastError = (title: string, group?: string) => (e: unknown) =>
- toast(title, { description: e instanceof Error ? e.message : String(e), type: "error", group });
+export const toastError = (title: string, group?: string) => (e: unknown) => {
+ const description = e instanceof Error ? e.message : String(e);
+ toast(title, { description, type: "error", group, action: errorAction?.(description) ?? undefined });
+};
const ICONS = { info: InfoIcon, success: CircleCheckIcon, error: CircleAlertIcon } as const;
@@ -85,6 +101,16 @@ function ToastList() {
<Toast.Content className="min-w-0 flex-1">
<Toast.Title className="text-[13px] font-medium" />
<Toast.Description className="text-xs text-muted-foreground" />
+ {(t.data as { action?: ToastAction } | undefined)?.action ? (
+ <button
+ type="button"
+ data-toast-action=""
+ className="mt-2 rounded-md border px-2 py-1 text-xs font-medium hover:bg-accent"
+ onClick={() => (t.data as { action: ToastAction }).action.onClick()}
+ >
+ {(t.data as { action: ToastAction }).action.label}
+ </button>
+ ) : null}
</Toast.Content>
<Toast.Close aria-label="Dismiss" className="rounded-md p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
<XIcon className="size-3.5" />
diff --git a/apps/cua-spaces-web/src/routes/__root.tsx b/apps/cua-spaces-web/src/routes/__root.tsx
index eac025e405..6dc60ca5fa 100644
--- a/apps/cua-spaces-web/src/routes/__root.tsx
+++ b/apps/cua-spaces-web/src/routes/__root.tsx
@@ -11,6 +11,7 @@ import { NewSpace } from "@/components/new-space";
import { CommandPalette } from "@/components/shell/command-palette";
import { DevicesBanner } from "@/components/shell/devices-banner";
import { Sidebar } from "@/components/shell/sidebar";
+import { PlanLimitToastAction } from "@/components/shell/plan-limit-toast-action";
import { RelayAllowanceNotice } from "@/components/shell/relay-allowance-notice";
import { ShareRemovalNotice } from "@/components/shell/share-removal-notice";
import { SpacesNotice } from "@/components/shell/spaces-notice";
@@ -77,6 +78,7 @@ function RootLayout() {
<Outlet />
</main>
</div>
+ <PlanLimitToastAction />
<CommandPalette />
<ChecklistTracker />
<NewSpace />
diff --git a/apps/cua-spaces-web/src/routes/settings/index.tsx b/apps/cua-spaces-web/src/routes/settings/index.tsx
index 3fbb1abb4a..1d40a8171b 100644
--- a/apps/cua-spaces-web/src/routes/settings/index.tsx
+++ b/apps/cua-spaces-web/src/routes/settings/index.tsx
@@ -9,6 +9,7 @@ import {
useExperiments,
useLoginItem,
useMachines,
+ useRelayUsage,
useRelayUsageView,
useTrackPlanClick,
useSession,
@@ -189,9 +190,30 @@ function GlobalShortcutRow({ shortcut }: { shortcut: GlobalShortcut | null | und
);
}
+/** One bar of the usage meter: `used` of `limit` (no bar without a limit). */
+function UsageMeter({ label, used, limit }: { label: string; used: number; limit: number | null }) {
+ if (!limit || limit <= 0) return null;
+ const share = Math.min(1, used / limit);
+ return (
+ <div
+ role="meter"
+ aria-label={label}
+ aria-valuemin={0}
+ aria-valuemax={limit}
+ aria-valuenow={Math.min(used, limit)}
+ data-usage-meter={label}
+ data-full={used >= limit ? "" : undefined}
+ className="h-1.5 w-full overflow-hidden rounded-full bg-muted"
+ >
+ <div className={used >= limit ? "h-full bg-destructive" : "h-full bg-brand-strong"} style={{ width: `${Math.round(share * 100)}%` }} />
+ </div>
+ );
+}
+
/** The plan and remote use this month (the core's words), where the host reads it. */
function RelayUsageRow() {
const view = useRelayUsageView();
+ const usage = useRelayUsage();
const { openExternal } = useSession();
const trackClick = useTrackPlanClick();
if (!view) return null;
@@ -204,6 +226,12 @@ function RelayUsageRow() {
<>
<div data-relay-usage="">
<SettingsRow label={view.label} description={view.line} control={<span className="text-[13px] text-muted-foreground">{view.plan}</span>} />
+ {usage ? (
+ <div className="flex flex-col gap-2 px-4 pb-3">
+ <UsageMeter label="Live sessions" used={usage.liveSessions} limit={usage.liveSessionsLimit} />
+ <UsageMeter label="Remote hours" used={usage.hoursUsed} limit={usage.hoursLimit} />
+ </div>
+ ) : null}
</div>
<div data-plan-card={card.plan} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
diff --git a/docs/content/docs/cua-sdk/reference/typescript/spaces.mdx b/docs/content/docs/cua-sdk/reference/typescript/spaces.mdx
index 73a76030e2..5a00cfeab7 100644
--- a/docs/content/docs/cua-sdk/reference/typescript/spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/typescript/spaces.mdx
@@ -271,31 +271,6 @@ A membership rule was broken. The message says which number.
- `Error`
-#### Constructors
-
-##### Constructor
-
-```ts
-new GroupChatError(code, message): GroupChatError;
-```
-
-###### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `code` | [`GroupChatErrorCode`](#groupchaterrorcode) |
-| `message` | `string` |
-
-###### Returns
-
-[`GroupChatError`](#groupchaterror)
-
-###### Overrides
-
-```ts
-Error.constructor
-```
-
#### Properties
| Property | Modifier | Type |
@@ -659,6 +634,36 @@ workingBots(chatID): string[];
***
+### PlanLimitError
+
+The relay refused a new live session because the account's plan is at its
+cap (HTTP 429, `x-cua-relay-error: plan_limit_sessions|plan_limit_hours`).
+Live sessions are never cut and retrying gets the same answer: close one,
+or send the person to [PlanLimitError.upgradeUrl](#property-upgradeurl).
+
+`message` is the plain sentence, such as "You're using 5 of 5 live sessions
+on Pro. Close one or upgrade to Teams."
+
+#### Extends
+
+- [`SpacesError`](#spaceserror)
+
+#### Properties
+
+| Property | Modifier | Type | Description | Inherited from |
+| ------ | ------ | ------ | ------ | ------ |
+| <a id="property-code-1"></a> `code` | `readonly` | [`SpacesErrorCode`](#spaceserrorcode) | - | [`SpacesError`](#spaceserror).[`code`](#property-code-2) |
+| <a id="property-detail"></a> `detail` | `readonly` | `string` \| `undefined` | - | [`SpacesError`](#spaceserror).[`detail`](#property-detail-1) |
+| <a id="property-kind"></a> `kind` | `readonly` | [`PlanLimitKind`](#planlimitkind) | - | - |
+| <a id="property-limit"></a> `limit` | `readonly` | `number` | - | - |
+| <a id="property-plan"></a> `plan` | `readonly` | `string` | `free`, `pro` or `teams`; any other plan keeps its own name. | - |
+| <a id="property-status"></a> `status` | `readonly` | `number` \| `undefined` | - | [`SpacesError`](#spaceserror).[`status`](#property-status-1) |
+| <a id="property-target"></a> `target` | `readonly` | `string` \| `undefined` | - | [`SpacesError`](#spaceserror).[`target`](#property-target-1) |
+| <a id="property-upgradeurl"></a> `upgradeUrl` | `readonly` | `string` \| `undefined` | Where to add room, or undefined when the error carried no link. | - |
+| <a id="property-used"></a> `used` | `readonly` | `number` | - | - |
+
+#### Methods
+
### PresenceRoster
Who is in a Space's presence and where their cursors are. Pure state.
@@ -1291,44 +1296,18 @@ update(routine): void;
- `Error`
-#### Constructors
-
-##### Constructor
-
-```ts
-new SpacesError(
- code,
- message,
- options?
-): SpacesError;
-```
-
-###### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `code` | [`SpacesErrorCode`](#spaceserrorcode) |
-| `message` | `string` |
-| `options` | [`SpacesErrorOptions`](#spaceserroroptions) |
-
-###### Returns
-
-[`SpacesError`](#spaceserror)
-
-###### Overrides
+#### Extended by
-```ts
-Error.constructor
-```
+- [`PlanLimitError`](#planlimiterror)
#### Properties
| Property | Modifier | Type |
| ------ | ------ | ------ |
-| <a id="property-code-1"></a> `code` | `readonly` | [`SpacesErrorCode`](#spaceserrorcode) |
-| <a id="property-detail"></a> `detail` | `readonly` | `string` \| `undefined` |
-| <a id="property-status"></a> `status` | `readonly` | `number` \| `undefined` |
-| <a id="property-target"></a> `target` | `readonly` | `string` \| `undefined` |
+| <a id="property-code-2"></a> `code` | `readonly` | [`SpacesErrorCode`](#spaceserrorcode) |
+| <a id="property-detail-1"></a> `detail` | `readonly` | `string` \| `undefined` |
+| <a id="property-status-1"></a> `status` | `readonly` | `number` \| `undefined` |
+| <a id="property-target-1"></a> `target` | `readonly` | `string` \| `undefined` |
#### Methods
@@ -1689,7 +1668,7 @@ SDK will not invent one that silently does nothing.
| Property | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-derived"></a> `derived` | `boolean` | `true` when this event was inferred from unstructured terminal output rather than reported by the agent runtime. Always check it before treating an event as authoritative. | - | `ThreadEventBase.derived` |
-| <a id="property-kind"></a> `kind` | `"approval_request"` | - | `ThreadEventBase.kind` | - |
+| <a id="property-kind-1"></a> `kind` | `"approval_request"` | - | `ThreadEventBase.kind` | - |
| <a id="property-observedat"></a> `observedAt` | `string` | Wall clock at the moment the SDK observed it, not when the agent produced it. | - | `ThreadEventBase.observedAt` |
| <a id="property-options"></a> `options` | `string`[] | Choices parsed from the prompt, when they were parseable. | - | - |
| <a id="property-prompt"></a> `prompt` | `string` | - | - | - |
@@ -1721,7 +1700,7 @@ One shape's art: an SVG path (absolute M, L, C, Z; nonzero fill) and its hot spo
| Property | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-derived-1"></a> `derived` | `boolean` | `true` when this event was inferred from unstructured terminal output rather than reported by the agent runtime. Always check it before treating an event as authoritative. | - | `ThreadEventBase.derived` |
-| <a id="property-kind-1"></a> `kind` | `"error"` | - | `ThreadEventBase.kind` | - |
+| <a id="property-kind-2"></a> `kind` | `"error"` | - | `ThreadEventBase.kind` | - |
| <a id="property-message"></a> `message` | `string` | - | - | - |
| <a id="property-observedat-1"></a> `observedAt` | `string` | Wall clock at the moment the SDK observed it, not when the agent produced it. | - | `ThreadEventBase.observedAt` |
| <a id="property-seq-1"></a> `seq` | `number` | Monotonic within a thread, assigned by the SDK. | - | `ThreadEventBase.seq` |
@@ -1755,7 +1734,7 @@ A file the agent appears to have produced, by absolute path inside the Space.
| Property | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-derived-2"></a> `derived` | `boolean` | `true` when this event was inferred from unstructured terminal output rather than reported by the agent runtime. Always check it before treating an event as authoritative. | - | `ThreadEventBase.derived` |
-| <a id="property-kind-2"></a> `kind` | `"file"` | - | `ThreadEventBase.kind` | - |
+| <a id="property-kind-3"></a> `kind` | `"file"` | - | `ThreadEventBase.kind` | - |
| <a id="property-observedat-2"></a> `observedAt` | `string` | Wall clock at the moment the SDK observed it, not when the agent produced it. | - | `ThreadEventBase.observedAt` |
| <a id="property-path"></a> `path` | `string` | - | - | - |
| <a id="property-seq-2"></a> `seq` | `number` | Monotonic within a thread, assigned by the SDK. | - | `ThreadEventBase.seq` |
@@ -1898,7 +1877,7 @@ An image the agent produced. `data` is base64; `path` is set instead when the
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-data"></a> `data?` | `string` | - | - | - |
| <a id="property-derived-3"></a> `derived` | `boolean` | `true` when this event was inferred from unstructured terminal output rather than reported by the agent runtime. Always check it before treating an event as authoritative. | - | `ThreadEventBase.derived` |
-| <a id="property-kind-3"></a> `kind` | `"image"` | - | `ThreadEventBase.kind` | - |
+| <a id="property-kind-4"></a> `kind` | `"image"` | - | `ThreadEventBase.kind` | - |
| <a id="property-mimetype"></a> `mimeType` | `string` | - | - | - |
| <a id="property-observedat-3"></a> `observedAt` | `string` | Wall clock at the moment the SDK observed it, not when the agent produced it. | - | `ThreadEventBase.observedAt` |
| <a id="property-path-1"></a> `path?` | `string` | - | - | - |
@@ -1917,7 +1896,7 @@ An image the agent produced. `data` is base64; `path` is set instead when the
| Property | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-derived-4"></a> `derived` | `boolean` | `true` when this event was inferred from unstructured terminal output rather than reported by the agent runtime. Always check it before treating an event as authoritative. | - | `ThreadEventBase.derived` |
-| <a id="property-kind-4"></a> `kind` | `"link"` | - | `ThreadEventBase.kind` | - |
+| <a id="property-kind-5"></a> `kind` | `"link"` | - | `ThreadEventBase.kind` | - |
| <a id="property-observedat-4"></a> `observedAt` | `string` | Wall clock at the moment the SDK observed it, not when the agent produced it. | - | `ThreadEventBase.observedAt` |
| <a id="property-seq-4"></a> `seq` | `number` | Monotonic within a thread, assigned by the SDK. | - | `ThreadEventBase.seq` |
| <a id="property-url"></a> `url` | `string` | - | - | - |
@@ -2055,9 +2034,9 @@ save(json): void;
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-cause"></a> `cause?` | `unknown` | - |
-| <a id="property-detail-1"></a> `detail?` | `string` | Free-form, already-redacted detail shown in the message. |
-| <a id="property-status-1"></a> `status?` | `number` | HTTP status, when code is 'http'. |
-| <a id="property-target-1"></a> `target?` | `string` | Request target, for triage. Never carries credentials. |
+| <a id="property-detail-2"></a> `detail?` | `string` | Free-form, already-redacted detail shown in the message. |
+| <a id="property-status-2"></a> `status?` | `number` | HTTP status, when code is 'http'. |
+| <a id="property-target-2"></a> `target?` | `string` | Request target, for triage. Never carries credentials. |
***
@@ -2086,7 +2065,7 @@ save(json): void;
| Property | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-derived-5"></a> `derived` | `boolean` | `true` when this event was inferred from unstructured terminal output rather than reported by the agent runtime. Always check it before treating an event as authoritative. | - | `ThreadEventBase.derived` |
-| <a id="property-kind-5"></a> `kind` | `"state"` | - | `ThreadEventBase.kind` | - |
+| <a id="property-kind-6"></a> `kind` | `"state"` | - | `ThreadEventBase.kind` | - |
| <a id="property-observedat-5"></a> `observedAt` | `string` | Wall clock at the moment the SDK observed it, not when the agent produced it. | - | `ThreadEventBase.observedAt` |
| <a id="property-reason-1"></a> `reason` | `string` | The ladder's reason for this status. | - | - |
| <a id="property-seq-5"></a> `seq` | `number` | Monotonic within a thread, assigned by the SDK. | - | `ThreadEventBase.seq` |
@@ -2105,7 +2084,7 @@ save(json): void;
| Property | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-derived-6"></a> `derived` | `boolean` | `true` when this event was inferred from unstructured terminal output rather than reported by the agent runtime. Always check it before treating an event as authoritative. | - | `ThreadEventBase.derived` |
-| <a id="property-kind-6"></a> `kind` | `"text"` | - | `ThreadEventBase.kind` | - |
+| <a id="property-kind-7"></a> `kind` | `"text"` | - | `ThreadEventBase.kind` | - |
| <a id="property-observedat-6"></a> `observedAt` | `string` | Wall clock at the moment the SDK observed it, not when the agent produced it. | - | `ThreadEventBase.observedAt` |
| <a id="property-seq-6"></a> `seq` | `number` | Monotonic within a thread, assigned by the SDK. | - | `ThreadEventBase.seq` |
| <a id="property-text-1"></a> `text` | `string` | - | - | - |
@@ -2124,7 +2103,7 @@ Everything the SDK knows about a run's current moment.
| <a id="property-desktopwindow"></a> `desktopWindow` | `string` \| `null` | The agent's terminal window on the Space desktop, when it was found. `null` means "not found", which is not the same as "does not exist". |
| <a id="property-reason-2"></a> `reason` | `string` | Why the ladder landed there, in words. Always populated. |
| <a id="property-runid-1"></a> `runId` | `string` | - |
-| <a id="property-status-2"></a> `status` | [`AgentStatus`](#agentstatus) | - |
+| <a id="property-status-3"></a> `status` | [`AgentStatus`](#agentstatus) | - |
| <a id="property-transcript"></a> `transcript` | `string` | The raw transcript tail exactly as the Space reported it. Always present, because every derived event above is an interpretation of this. |
***
@@ -2252,6 +2231,16 @@ Who said a line: the human, a Bot, or the group itself (joins, leaves, refusals)
***
+### PlanLimitKind
+
+```ts
+type PlanLimitKind = "sessions" | "hours";
+```
+
+Which plan cap the relay refused.
+
+***
+
### RoutineFiring
```ts
@@ -2319,7 +2308,8 @@ type SpacesErrorCode =
| "capability_missing"
| "host_capability_missing"
| "spacesd_not_available"
- | "teleport_refused";
+ | "teleport_refused"
+ | "plan_limit";
```
Stable, matchable error codes. Adding a code is a minor release; removing or
@@ -3008,6 +2998,44 @@ The first slot strictly after `reference`, in local time; `undefined` for an inv
***
+### parsePlanLimit()
+
+```ts
+function parsePlanLimit(text):
+ | {
+ kind: PlanLimitKind;
+ limit: number;
+ message: string;
+ plan: string;
+ upgradeUrl?: string;
+ used: number;
+}
+ | undefined;
+```
+
+Reads the relay's plan-limit sentence (and the `Upgrade: <url>` the CLI and
+SDK append) back out of an error's text. Undefined for any other text.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `text` | `string` |
+
+#### Returns
+
+ \| \{
+ `kind`: [`PlanLimitKind`](#planlimitkind);
+ `limit`: `number`;
+ `message`: `string`;
+ `plan`: `string`;
+ `upgradeUrl?`: `string`;
+ `used`: `number`;
+\}
+ \| `undefined`
+
+***
+
### parseRoutines()
```ts
diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lock
index cb1cf195b8..f4c04ba40f 100644
--- a/examples/streaming/rust/Cargo.lock
+++ b/examples/streaming/rust/Cargo.lock
@@ -1515,6 +1515,7 @@ dependencies = [
"cua-auth",
"cua-create-failure",
"cua-daemon",
+ "cua-home",
"cua-host",
"cua-image",
"cua-proto",
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index 81de94cc75..44f1ffe9d3 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -2478,6 +2478,7 @@ dependencies = [
"cua-auth",
"cua-create-failure",
"cua-daemon",
+ "cua-home",
"cua-host",
"cua-image",
"cua-proto",
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index 3aa1bdd822..f8df1a3dcf 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -1033,6 +1033,15 @@ fn host_error(e: cua_host::Error, m: String) -> CuaError {
E::PermissionDenied(_) => CuaError::PermissionDenied(m),
E::NotFound(_) => CuaError::NotFound(m),
E::Relay(_) | E::Download(_) => CuaError::Http(m),
+ // The plain sentence, then where to upgrade.
+ E::PlanLimit(_) => {
+ let url = cua_home::plan_limit::PlanLimit::parse(&m)
+ .map(|l| l.upgrade_url(&cua_home::env::account_app_url()));
+ CuaError::Http(match url {
+ Some(url) => format!("{m} Upgrade: {url}"),
+ None => m,
+ })
+ }
E::Service(_) => CuaError::Runtime(m),
E::Io(_) | E::Internal(_) => CuaError::Internal(m),
}
diff --git a/libs/cua/crates/cua-cli/src/usage_cmd.rs b/libs/cua/crates/cua-cli/src/usage_cmd.rs
index f85afe7267..1ab4e458f0 100644
--- a/libs/cua/crates/cua-cli/src/usage_cmd.rs
+++ b/libs/cua/crates/cua-cli/src/usage_cmd.rs
@@ -95,16 +95,61 @@ fn print(u: &RelayUsage, out: &mut dyn Write) {
),
);
}
- if u.soft_limit_reached {
- let upgrade = u
- .upgrade_url
- .as_deref()
- .map(|url| format!(" Upgrade: {url}"))
- .unwrap_or_default();
+ let plan = cua_home::plan_limit::PlanLimit {
+ kind: cua_home::plan_limit::Kind::Sessions,
+ plan: match u.plan.as_str() {
+ "team" => "teams".into(),
+ p => p.to_owned(),
+ },
+ used: 0.0,
+ limit: 0.0,
+ };
+ let caps = [
+ u.live_sessions_limit
+ .filter(|l| u.live_sessions >= *l)
+ .map(|l| {
+ (
+ cua_home::plan_limit::Kind::Sessions,
+ f64::from(u.live_sessions),
+ f64::from(l),
+ )
+ }),
+ u.hours_limit
+ .filter(|l| u.hours_used >= *l)
+ .map(|l| (cua_home::plan_limit::Kind::Hours, u.hours_used, l)),
+ ];
+ let upgrade = |fallback: String| {
+ let url = u.upgrade_url.clone().unwrap_or(fallback);
+ format!(" Upgrade: {url}")
+ };
+ let mut said = false;
+ for (kind, used, limit) in caps.into_iter().flatten() {
+ let p = cua_home::plan_limit::PlanLimit {
+ kind,
+ used,
+ limit,
+ ..plan.clone()
+ };
+ let account_app = cua_home::env::account_app_url();
+ line(
+ out,
+ format!("{}{}", p.sentence(), upgrade(p.upgrade_url(&account_app))),
+ );
+ said = true;
+ }
+ if u.soft_limit_reached || said {
+ let upgrade = if said {
+ String::new()
+ } else {
+ u.upgrade_url
+ .as_deref()
+ .map(|url| format!(" Upgrade: {url}"))
+ .unwrap_or_default()
+ };
line(
out,
format!(
- "You've reached your plan's remote limit for this month. Your Spaces keep working.{upgrade}"
+ "Your Spaces keep working. New live sessions wait until there is room.{upgrade}"
),
);
}
@@ -174,11 +219,43 @@ mod tests {
"{t}"
);
assert!(
- t.contains("You've reached your plan's remote limit for this month. Your Spaces keep working. Upgrade: https://cua.ai/pricing"),
+ t.contains("You've used 21 of 20 remote hours this month on the free plan. Upgrade to Pro for more. Upgrade: https://cua.ai/pricing"),
"{t}"
);
+ assert!(t.contains("Your Spaces keep working."), "{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);
}
+
+ #[tokio::test]
+ async fn pro_at_five_of_five_says_so_with_the_teams_upgrade() {
+ let relay = FakeRelay::start().await;
+ relay.add_account("acct", "user-1", None);
+ relay.set_usage(Some(serde_json::json!({
+ "metered": true, "period": "2026-10", "plan": "pro",
+ "live_sessions": 5, "live_sessions_limit": 5, "hours_used": 12, "hours_limit": 200,
+ "my_hours_used": 12, "soft_limit_reached": false, "reasons": [],
+ "upgrade_url": "https://app.cua.ai/buy/teams"
+ })));
+ let t = text(&relay, false).await;
+ assert!(
+ t.contains("You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams. Upgrade: https://app.cua.ai/buy/teams"),
+ "{t}"
+ );
+ assert!(!t.contains("remote hours this month on"), "{t}");
+ }
+
+ #[test]
+ fn a_refused_session_error_carries_the_sentence_and_the_upgrade_link() {
+ let e = crate::host::host_err(cua_host::Error::PlanLimit(
+ "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams.".into(),
+ ));
+ let m = e.to_string();
+ assert!(
+ m.contains("You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams. Upgrade: https://"),
+ "{m}"
+ );
+ assert!(m.contains("/buy/teams?from=plan_limit"), "{m}");
+ }
}
diff --git a/libs/cua/crates/cua-home/src/lib.rs b/libs/cua/crates/cua-home/src/lib.rs
index 1101d8f134..bec19f1ecd 100644
--- a/libs/cua/crates/cua-home/src/lib.rs
+++ b/libs/cua/crates/cua-home/src/lib.rs
@@ -27,6 +27,7 @@ use std::path::{Path, PathBuf};
pub mod env;
pub mod experimental;
+pub mod plan_limit;
/// Environment variable that marks a test process.
pub const CUA_TEST_ENV: &str = "CUA_TEST";
diff --git a/libs/cua/crates/cua-home/src/plan_limit.rs b/libs/cua/crates/cua-home/src/plan_limit.rs
new file mode 100644
index 0000000000..9a255f67df
--- /dev/null
+++ b/libs/cua/crates/cua-home/src/plan_limit.rs
@@ -0,0 +1,238 @@
+//! The relay's plan-limit refusal, in plain words, for every client.
+//!
+//! The relay answers a NEW live session over the plan's cap with HTTP 429
+//! and `x-cua-relay-error: plan_limit_sessions` (or `plan_limit_hours`),
+//! plus `x-cua-relay-plan`, `x-cua-relay-used` and `x-cua-relay-limit`.
+//! Live sessions are never cut. The host client turns those headers into
+//! one sentence ([`PlanLimit::sentence`]); the apps read the same sentence
+//! back ([`PlanLimit::parse`]) to show it with an Upgrade button. No
+//! dependencies, so the wasm build can use it.
+
+/// The header that names the refusal.
+pub const ERROR_HEADER: &str = "x-cua-relay-error";
+/// The plan the account is on (`free`, `pro`, `team`).
+pub const PLAN_HEADER: &str = "x-cua-relay-plan";
+/// What is used now.
+pub const USED_HEADER: &str = "x-cua-relay-used";
+/// What the plan allows.
+pub const LIMIT_HEADER: &str = "x-cua-relay-limit";
+
+/// Which cap was hit.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Kind {
+ /// Live sessions at once.
+ Sessions,
+ /// Remote hours this month.
+ Hours,
+}
+
+/// A refused new session.
+#[derive(Debug, Clone, PartialEq)]
+pub struct PlanLimit {
+ /// The cap.
+ pub kind: Kind,
+ /// `free`, `pro` or `teams`; other plans keep their own name.
+ pub plan: String,
+ /// Used now.
+ pub used: f64,
+ /// Allowed.
+ pub limit: f64,
+}
+
+fn number(n: f64) -> String {
+ let tenths = (n * 10.0).round() / 10.0;
+ if tenths.fract() == 0.0 {
+ format!("{tenths:.0}")
+ } else {
+ format!("{tenths:.1}")
+ }
+}
+
+fn kind_of_plan(plan: &str) -> String {
+ match plan.trim().to_ascii_lowercase().as_str() {
+ "team" => "teams".into(),
+ p => p.to_owned(),
+ }
+}
+
+/// "the free plan", "Pro", "Teams".
+fn plan_name(plan: &str) -> String {
+ match plan {
+ "free" => "the free plan".into(),
+ "" => "your plan".into(),
+ p => {
+ let mut c = p.chars();
+ c.next()
+ .map(|f| format!("{}{}", f.to_uppercase(), c.as_str()))
+ .unwrap_or_default()
+ }
+ }
+}
+
+fn from_name(name: &str) -> String {
+ match name {
+ "the free plan" => "free".into(),
+ "your plan" => String::new(),
+ n => n.to_ascii_lowercase(),
+ }
+}
+
+impl PlanLimit {
+ /// From the relay's headers; none when `error` is not a plan limit or
+ /// the numbers are missing.
+ pub fn from_headers(
+ error: Option<&str>,
+ plan: Option<&str>,
+ used: Option<&str>,
+ limit: Option<&str>,
+ ) -> Option<Self> {
+ let kind = match error?.trim() {
+ "plan_limit_sessions" => Kind::Sessions,
+ "plan_limit_hours" => Kind::Hours,
+ _ => return None,
+ };
+ Some(Self {
+ kind,
+ plan: kind_of_plan(plan.unwrap_or_default()),
+ used: used?.trim().parse().ok()?,
+ limit: limit?.trim().parse().ok()?,
+ })
+ }
+
+ fn next_step(&self) -> &'static str {
+ match (self.kind, self.plan.as_str()) {
+ (Kind::Sessions, "free") => "Close one or upgrade to Pro.",
+ (Kind::Sessions, "pro") => "Close one or upgrade to Teams.",
+ (Kind::Sessions, "teams") => "Close one or add seats.",
+ (Kind::Sessions, _) => "Close one or upgrade your plan.",
+ (Kind::Hours, "free") => "Upgrade to Pro for more.",
+ (Kind::Hours, "pro") => "Upgrade to Teams for more.",
+ (Kind::Hours, "teams") => "Add seats for more.",
+ (Kind::Hours, _) => "Upgrade your plan for more.",
+ }
+ }
+
+ /// "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams."
+ pub fn sentence(&self) -> String {
+ let plan = plan_name(&self.plan);
+ let (used, limit) = (number(self.used), number(self.limit));
+ match self.kind {
+ Kind::Sessions => format!(
+ "You're using {used} of {limit} live sessions on {plan}. {}",
+ self.next_step()
+ ),
+ Kind::Hours => format!(
+ "You've used {used} of {limit} remote hours this month on {plan}. {}",
+ self.next_step()
+ ),
+ }
+ }
+
+ /// Reads [`PlanLimit::sentence`] back out of an error's text (which may
+ /// wrap it). None for any other text.
+ pub fn parse(text: &str) -> Option<Self> {
+ for (marker, kind, tail) in [
+ ("You're using ", Kind::Sessions, " live sessions on "),
+ ("You've used ", Kind::Hours, " remote hours this month on "),
+ ] {
+ let Some(i) = text.find(marker) else { continue };
+ let rest = &text[i + marker.len()..];
+ let Some((counts, after)) = rest.split_once(tail) else {
+ continue;
+ };
+ let Some((used, limit)) = counts.split_once(" of ") else {
+ continue;
+ };
+ let Some((name, _)) = after.split_once(". ") else {
+ continue;
+ };
+ let (Ok(used), Ok(limit)) = (used.parse(), limit.parse()) else {
+ continue;
+ };
+ return Some(Self {
+ kind,
+ plan: from_name(name),
+ used,
+ limit,
+ });
+ }
+ None
+ }
+
+ /// The account-app page that adds room: Free to Pro, Pro to Teams, a
+ /// team to its billing page; `?from=plan_limit` for the purchase funnel.
+ pub fn upgrade_url(&self, account_app: &str) -> String {
+ let base = account_app.trim_end_matches('/');
+ match self.plan.as_str() {
+ "free" => format!("{base}/buy/pro?from=plan_limit"),
+ "pro" => format!("{base}/buy/teams?from=plan_limit"),
+ _ => format!("{base}/billing"),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn h(e: &str, plan: &str, used: &str, limit: &str) -> Option<PlanLimit> {
+ PlanLimit::from_headers(Some(e), Some(plan), Some(used), Some(limit))
+ }
+
+ #[test]
+ fn pro_sessions_in_plain_words() {
+ let l = h("plan_limit_sessions", "pro", "5", "5").unwrap();
+ assert_eq!(
+ l.sentence(),
+ "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams."
+ );
+ assert_eq!(
+ l.upgrade_url("https://app.cua.ai/"),
+ "https://app.cua.ai/buy/teams?from=plan_limit"
+ );
+ }
+
+ #[test]
+ fn free_and_hours() {
+ let l = h("plan_limit_sessions", "free", "2", "2").unwrap();
+ assert_eq!(
+ l.sentence(),
+ "You're using 2 of 2 live sessions on the free plan. Close one or upgrade to Pro."
+ );
+ let l = h("plan_limit_hours", "free", "20.04", "20").unwrap();
+ assert_eq!(
+ l.sentence(),
+ "You've used 20 of 20 remote hours this month on the free plan. Upgrade to Pro for more."
+ );
+ let l = h("plan_limit_hours", "pro", "200", "200").unwrap();
+ assert_eq!(
+ l.sentence(),
+ "You've used 200 of 200 remote hours this month on Pro. Upgrade to Teams for more."
+ );
+ }
+
+ #[test]
+ fn the_sentence_reads_back_even_when_wrapped() {
+ for l in [
+ h("plan_limit_sessions", "pro", "5", "5").unwrap(),
+ h("plan_limit_sessions", "free", "2", "2").unwrap(),
+ h("plan_limit_hours", "team", "400", "400").unwrap(),
+ h("plan_limit_hours", "pro", "12.5", "200").unwrap(),
+ ] {
+ assert_eq!(PlanLimit::parse(&l.sentence()), Some(l.clone()));
+ let wrapped = format!("relay: HTTP 429: {}", l.sentence());
+ assert_eq!(PlanLimit::parse(&wrapped), Some(l));
+ }
+ assert_eq!(PlanLimit::parse("no machine image is configured"), None);
+ }
+
+ #[test]
+ fn other_refusals_are_not_plan_limits() {
+ assert!(h("rate_limited", "pro", "5", "5").is_none());
+ assert!(
+ PlanLimit::from_headers(Some("plan_limit_sessions"), Some("pro"), None, Some("5"))
+ .is_none()
+ );
+ assert!(PlanLimit::from_headers(None, None, None, None).is_none());
+ }
+}
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index 70394af081..aa9aea8f6e 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -137,6 +137,11 @@ pub enum Error {
/// Relay unreachable or failed.
#[error("relay: {0}")]
Relay(String),
+ /// The relay refused a new live session over the plan's cap (HTTP 429,
+ /// `x-cua-relay-error: plan_limit_*`). The text is the plain sentence
+ /// ([`cua_home::plan_limit::PlanLimit::sentence`]); never retried.
+ #[error("{0}")]
+ PlanLimit(String),
/// Driver download failed.
#[error("download: {0}")]
Download(String),
@@ -162,6 +167,7 @@ impl Error {
Error::PermissionDenied(m) if m.starts_with("relay: ") => Some(403),
Error::NotFound(m) if m.starts_with("relay: ") => Some(404),
Error::Conflict(m) if m.starts_with("relay: ") => Some(409),
+ Error::PlanLimit(_) => Some(429),
Error::Relay(m) | Error::Download(m) => status_in(m),
_ => None,
}
diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rs
index 04632de9cd..3303438de5 100644
--- a/libs/cua/crates/cua-host/src/relay.rs
+++ b/libs/cua/crates/cua-host/src/relay.rs
@@ -432,6 +432,9 @@ pub struct RelayUsage {
pub soft_limit_reached: bool,
/// What is past it: `sessions` and/or `hours`.
pub reasons: Vec<String>,
+ /// Free plan only: `free_limit_sessions` and/or `free_limit_relay_hours`
+ /// when at or over that allowance (CUA-1745). Older relays send none.
+ pub warnings: Vec<String>,
/// Where to get more.
#[serde(skip_serializing_if = "Option::is_none")]
pub upgrade_url: Option<String>,
@@ -555,11 +558,17 @@ impl RelayClient {
.await
.map_err(|e| (Error::Relay(format!("{}: {e}", self.base)), e.is_connect()))?;
let status = resp.status();
+ let limit = plan_limit(resp.headers());
let body = resp
.text()
.await
.map_err(|e| (Error::Relay(e.to_string()), false))?;
if !status.is_success() {
+ // A plan limit is a decision, not a hiccup: sending it again
+ // gets the same answer.
+ if let (429, Some(l)) = (status.as_u16(), limit) {
+ return Err((Error::PlanLimit(l.sentence()), false));
+ }
let retry = matches!(status.as_u16(), 429 | 502 | 503);
return Err((http_error(status.as_u16(), &body), retry));
}
@@ -880,6 +889,18 @@ impl RelayClient {
}
}
+/// The plan-limit refusal the relay's headers describe, if it is one.
+fn plan_limit(h: &reqwest::header::HeaderMap) -> Option<cua_home::plan_limit::PlanLimit> {
+ use cua_home::plan_limit as pl;
+ let get = |k: &str| h.get(k).and_then(|v| v.to_str().ok());
+ pl::PlanLimit::from_headers(
+ get(pl::ERROR_HEADER),
+ get(pl::PLAN_HEADER),
+ get(pl::USED_HEADER),
+ get(pl::LIMIT_HEADER),
+ )
+}
+
fn http_error(status: u16, body: &str) -> Error {
let message = serde_json::from_str::<serde_json::Value>(body)
.ok()
@@ -1014,4 +1035,43 @@ mod tests {
let bare: RelayUsage = serde_json::from_str("{}").unwrap();
assert!(!bare.metered && bare.live_sessions_limit.is_none());
}
+
+ #[tokio::test]
+ async fn a_plan_limit_refusal_is_one_plain_sentence_and_is_not_retried() {
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let hits = Arc::new(AtomicUsize::new(0));
+ let counter = hits.clone();
+ let app = axum::Router::new().route(
+ "/v1/machines",
+ axum::routing::get(move || {
+ counter.fetch_add(1, Ordering::SeqCst);
+ async {
+ (
+ axum::http::StatusCode::TOO_MANY_REQUESTS,
+ [
+ ("x-cua-relay-error", "plan_limit_sessions"),
+ ("x-cua-relay-plan", "pro"),
+ ("x-cua-relay-used", "5"),
+ ("x-cua-relay-limit", "5"),
+ ],
+ "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams: https://x",
+ )
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let client = RelayClient::new(&format!("http://{addr}")).unwrap();
+ let e = client.machines("tok").await.unwrap_err();
+ assert!(matches!(e, Error::PlanLimit(_)), "{e:?}");
+ assert_eq!(
+ e.to_string(),
+ "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams."
+ );
+ assert_eq!(e.http_status(), Some(429));
+ assert!(!e.is_transient());
+ assert_eq!(hits.load(Ordering::SeqCst), 1);
+ }
}
diff --git a/libs/cua/crates/cua-sdk/Cargo.toml b/libs/cua/crates/cua-sdk/Cargo.toml
index cbb7be49fc..c38c178650 100644
--- a/libs/cua/crates/cua-sdk/Cargo.toml
+++ b/libs/cua/crates/cua-sdk/Cargo.toml
@@ -66,6 +66,7 @@ cua-sandbox-core.workspace = true
async-trait.workspace = true
cua-host = { workspace = true, optional = true }
cua-daemon = { workspace = true, features = ["client"] }
+cua-home.workspace = true
cua-spaces = { path = "../cua-spaces", optional = true }
pbjson-types = { workspace = true, optional = true }
tokio = { workspace = true }
diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rs
index 68074e7a95..1becb63a47 100644
--- a/libs/cua/crates/cua-sdk/src/native/host.rs
+++ b/libs/cua/crates/cua-sdk/src/native/host.rs
@@ -17,6 +17,16 @@ impl From<cua_host::Error> for CuaError {
E::PermissionDenied(_) => CuaError::PermissionDenied(m),
E::NotFound(_) => CuaError::NotFound(m),
E::Relay(_) | E::Download(_) => CuaError::Http(m),
+ // The plain sentence, then where to upgrade, as the CLI says it;
+ // the Python and TypeScript SDKs read both back as `PlanLimitError`.
+ E::PlanLimit(_) => {
+ let url = cua_home::plan_limit::PlanLimit::parse(&m)
+ .map(|l| l.upgrade_url(&cua_home::env::account_app_url()));
+ CuaError::Http(match url {
+ Some(url) => format!("{m} Upgrade: {url}"),
+ None => m,
+ })
+ }
E::Service(_) => CuaError::Runtime(m),
E::Io(_) | E::Internal(_) => CuaError::Internal(m),
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index e6f4e2e544..69a578f169 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -293,6 +293,7 @@ pub const METHODS: &[&str] = &[
"experiments.choose",
"wizard.placementOptions",
"relayUsage.view",
+ "relayUsage.planLimit",
"resources.view",
"resources.thisMac",
"resources.space",
@@ -495,6 +496,13 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
_ => relay_usage::view(&usage),
})
}
+ // An error's text that is the relay refusing a new session over the
+ // plan's cap: the sentence and Upgrade (null for any other error).
+ "relayUsage.planLimit" => {
+ let error: String = a.get("error")?;
+ let app = a.get::<Option<String>>("accountApp")?.unwrap_or_default();
+ out(relay_usage::plan_limit_notice(&error, &app))
+ }
// Processor, memory and disk: the rows, bars and warning the apps
// draw from the runtime's snapshot (`Spaces.resources`).
// `nowMs` is the shell's clock: the core has none (wasm).
diff --git a/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rs b/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rs
index 98f53dba28..ba1e52fe59 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/relay_usage.rs
@@ -98,7 +98,7 @@ pub struct RelayUsage {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelayAllowanceNotice {
- /// "You've used your free relay allowance for this month. ..."
+ /// On Free: "You're using 2 of 2 live sessions on the free plan. ..."
pub text: String,
/// [`UPGRADE`].
pub upgrade: String,
@@ -241,7 +241,87 @@ pub fn dismiss_key(u: &RelayUsage) -> String {
format!("{}:{}", u.period, reasons.join(","))
}
-/// The notice's sentence.
+/// Folds the relay's Free-limit `warnings` (at or over an allowance) into
+/// the "reached" flag and `reasons` the apps already draw from, so a Free
+/// person sees the prompt at 2 of 2 live sessions, not only past it.
+pub fn with_warnings(
+ reached: bool,
+ mut reasons: Vec<String>,
+ warnings: &[String],
+) -> (bool, Vec<String>) {
+ let mut reached = reached;
+ for (warning, reason) in [
+ ("free_limit_sessions", "sessions"),
+ ("free_limit_relay_hours", "hours"),
+ ] {
+ if warnings.iter().any(|w| w == warning) {
+ reached = true;
+ if !reasons.iter().any(|r| r == reason) {
+ reasons.push(reason.to_owned());
+ }
+ }
+ }
+ (reached, reasons)
+}
+
+/// What the relay says when it refuses a new session over the cap
+/// ([`cua_home::plan_limit`]), for each cap this account is at: "You're
+/// using 5 of 5 live sessions on Pro. Close one or upgrade to Teams." Empty
+/// when no cap with a known limit is reached.
+fn plan_limit_sentences(u: &RelayUsage) -> String {
+ use cua_home::plan_limit::{Kind, PlanLimit};
+ let plan = plan_kind(&u.plan).to_owned();
+ let mut said = Vec::new();
+ if let Some(l) = u.live_sessions_limit.filter(|l| u.live_sessions >= *l) {
+ said.push(PlanLimit {
+ kind: Kind::Sessions,
+ plan: plan.clone(),
+ used: f64::from(u.live_sessions),
+ limit: f64::from(l),
+ });
+ }
+ if let Some(l) = u.hours_limit.filter(|l| u.hours_used >= *l) {
+ said.push(PlanLimit {
+ kind: Kind::Hours,
+ plan,
+ used: u.hours_used,
+ limit: l,
+ });
+ }
+ said.iter()
+ .map(PlanLimit::sentence)
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+/// The usage with the caps it is at counted as reached: a plan at 5 of 5
+/// live sessions has its next session refused, so the apps say so before
+/// that happens, on every plan (Free's relay warning does the same).
+fn at_cap(u: &RelayUsage) -> RelayUsage {
+ let mut u = u.clone();
+ for (hit, reason) in [
+ (
+ u.live_sessions_limit
+ .is_some_and(|l| l > 0 && u.live_sessions >= l),
+ "sessions",
+ ),
+ (
+ u.hours_limit.is_some_and(|l| l > 0.0 && u.hours_used >= l),
+ "hours",
+ ),
+ ] {
+ if hit {
+ u.soft_limit_reached = true;
+ if !u.reasons.iter().any(|r| r == reason) {
+ u.reasons.push(reason.to_owned());
+ }
+ }
+ }
+ u
+}
+
+/// The notice's sentence. On Free it says what is used and what Pro gives
+/// (the numbers on cua.ai/pricing); nothing is blocked.
pub fn notice_text(u: &RelayUsage) -> String {
if warns(u) {
return format!(
@@ -250,7 +330,36 @@ pub fn notice_text(u: &RelayUsage) -> String {
hours(u.hours_limit.unwrap_or_default()),
);
}
- match plan_kind(&u.plan) {
+ let kind = plan_kind(&u.plan);
+ if kind == "free" {
+ let mut parts = Vec::new();
+ if let (true, Some(limit)) = (
+ u.reasons.iter().any(|r| r == "sessions"),
+ u.live_sessions_limit,
+ ) {
+ parts.push(format!("{} of {limit} live sessions", u.live_sessions));
+ }
+ if let (true, Some(limit)) = (u.reasons.iter().any(|r| r == "hours"), u.hours_limit) {
+ parts.push(format!(
+ "{} of {} remote hours",
+ hours(u.hours_used),
+ hours(limit)
+ ));
+ }
+ if !parts.is_empty() {
+ return format!(
+ "You're using {} on the free plan. Your Spaces keep working. Pro gives you {PRO_SESSIONS} live sessions and {PRO_HOURS} remote hours.",
+ parts.join(" and ")
+ );
+ }
+ }
+ if kind != "free" {
+ let said = plan_limit_sentences(u);
+ if !said.is_empty() {
+ return said;
+ }
+ }
+ match kind {
"free" => "You've reached the free plan's remote limit for this month. Your Spaces keep working. Pro gives you more.".into(),
"pro" => "You've reached your plan's remote limit for this month. Your Spaces keep working. Teams pools remote hours across seats.".into(),
_ => "You've reached your team's remote limit for this month. Your Spaces keep working. Add seats for more.".into(),
@@ -348,6 +457,27 @@ pub fn plan_card(u: &RelayUsage, account_app: &str) -> PlanCard {
}
}
+/// A refused new session as the shells show it: the plain sentence with an
+/// Upgrade button, from the text of the error ([`cua_home::plan_limit`]).
+/// None for any other error. Never dismissed for good: the refusal is an
+/// answer to something the person just did.
+pub fn plan_limit_notice(error: &str, account_app: &str) -> Option<RelayAllowanceNotice> {
+ let limit = cua_home::plan_limit::PlanLimit::parse(error)?;
+ let account_app = if account_app.starts_with("https://") {
+ account_app.to_owned()
+ } else {
+ cua_home::env::account_app_url()
+ };
+ Some(RelayAllowanceNotice {
+ text: limit.sentence(),
+ upgrade: UPGRADE.into(),
+ upgrade_url: Some(limit.upgrade_url(&account_app)),
+ dismiss: DISMISS.into(),
+ dismiss_key: format!("refused:{:?}", limit.kind),
+ level: "limit".into(),
+ })
+}
+
/// The row, the notice and the plan card; none when the relay meters
/// nothing (the apps show nothing about it). Upgrade opens the plan's page
/// on the account app ([`upgrade_target`]).
@@ -360,6 +490,7 @@ pub fn view_for(u: &RelayUsage, account_app: &str) -> Option<RelayUsageView> {
if !u.metered {
return None;
}
+ let u = &at_cap(u);
let team = u
.team
.as_ref()
@@ -445,7 +576,7 @@ mod tests {
let n = v.notice.unwrap();
assert_eq!(
n.text,
- "You've reached the free plan's remote limit for this month. Your Spaces keep working. Pro gives you more."
+ "You're using 1 of 2 live sessions and 20.2 of 20 remote hours on the free plan. Your Spaces keep working. Pro gives you 5 live sessions and 200 remote hours."
);
assert_eq!(n.upgrade, "Upgrade");
assert_eq!(n.level, "limit");
@@ -464,7 +595,10 @@ mod tests {
.unwrap()
.notice
.unwrap();
- assert!(n.text.starts_with("You've reached your"), "{}", n.text);
+ assert_eq!(
+ n.text,
+ "You've used 20.2 of 20 remote hours this month on Pro. Upgrade to Teams for more."
+ );
assert_eq!(
n.upgrade_url.as_deref(),
Some("https://app.cua.ai/buy/teams?from=app_meter")
@@ -638,6 +772,101 @@ mod tests {
assert!(team.secondary.is_none());
}
+ #[test]
+ fn a_free_user_at_the_limit_is_asked_before_going_over() {
+ // The relay's warnings fire at 2 of 2 live sessions, before anything is over.
+ let (reached, reasons) = with_warnings(false, vec![], &["free_limit_sessions".into()]);
+ assert!(reached);
+ let u = RelayUsage {
+ live_sessions: 2,
+ soft_limit_reached: reached,
+ reasons,
+ ..free()
+ };
+ let n = view_for(&u, "https://app.cua.ai").unwrap().notice.unwrap();
+ assert_eq!(
+ n.text,
+ "You're using 2 of 2 live sessions on the free plan. Your Spaces keep working. Pro gives you 5 live sessions and 200 remote hours."
+ );
+ assert_eq!(n.upgrade, "Upgrade");
+ assert_eq!(
+ n.upgrade_url.as_deref(),
+ Some("https://app.cua.ai/buy/pro?from=app_meter")
+ );
+ // Nothing to say without a warning or an overage; known reasons are not doubled.
+ assert_eq!(with_warnings(false, vec![], &[]), (false, vec![]));
+ assert_eq!(
+ with_warnings(
+ true,
+ vec!["hours".into()],
+ &["free_limit_relay_hours".into()]
+ ),
+ (true, vec!["hours".to_owned()])
+ );
+ }
+
+ #[test]
+ fn pro_at_five_of_five_says_so_and_offers_teams() {
+ let u = RelayUsage {
+ plan: "pro".into(),
+ live_sessions: PRO_SESSIONS,
+ live_sessions_limit: Some(PRO_SESSIONS),
+ hours_used: 12.0,
+ hours_limit: Some(f64::from(PRO_HOURS)),
+ ..free()
+ };
+ let v = view_for(&u, "https://app.cua.ai").unwrap();
+ assert_eq!(
+ v.line,
+ "Live sessions 5 of 5 \u{b7} Remote hours 12 of 200 this month"
+ );
+ let n = v.notice.unwrap();
+ assert_eq!(
+ n.text,
+ "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams."
+ );
+ assert_eq!((n.upgrade.as_str(), n.level.as_str()), ("Upgrade", "limit"));
+ assert_eq!(
+ n.upgrade_url.as_deref(),
+ Some("https://app.cua.ai/buy/teams?from=app_meter")
+ );
+ // Room left: no notice.
+ let room = RelayUsage {
+ live_sessions: 4,
+ ..u
+ };
+ assert!(
+ view_for(&room, "https://app.cua.ai")
+ .unwrap()
+ .notice
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn a_refused_session_becomes_the_sentence_with_upgrade() {
+ let raw = "relay: You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams.";
+ let n = plan_limit_notice(raw, "https://app.cua.ai").unwrap();
+ assert_eq!(
+ n.text,
+ "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams."
+ );
+ assert_eq!(n.upgrade, "Upgrade");
+ assert_eq!(
+ n.upgrade_url.as_deref(),
+ Some("https://app.cua.ai/buy/teams?from=plan_limit")
+ );
+ let hours = "You've used 20 of 20 remote hours this month on the free plan. Upgrade to Pro for more.";
+ assert_eq!(
+ plan_limit_notice(hours, "https://app.cua.ai")
+ .unwrap()
+ .upgrade_url
+ .as_deref(),
+ Some("https://app.cua.ai/buy/pro?from=plan_limit")
+ );
+ assert_eq!(plan_limit_notice("timed out", "https://app.cua.ai"), None);
+ }
+
#[test]
fn no_limits_and_unmetered() {
let u = RelayUsage {
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 2838915bac..8485f3afc3 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -1939,6 +1939,8 @@ pub async fn app_relay_usage(
}
fn relay_usage(u: cua_host::RelayUsage) -> AppRelayUsage {
+ let (soft_limit_reached, reasons) =
+ core::relay_usage::with_warnings(u.soft_limit_reached, u.reasons, &u.warnings);
core::relay_usage::checked(core::relay_usage::RelayUsage {
metered: u.metered,
period: u.period,
@@ -1952,8 +1954,8 @@ fn relay_usage(u: cua_host::RelayUsage) -> AppRelayUsage {
hours_used: u.hours_used,
hours_limit: u.hours_limit,
my_hours_used: u.my_hours_used,
- soft_limit_reached: u.soft_limit_reached,
- reasons: u.reasons,
+ soft_limit_reached,
+ reasons,
upgrade_url: u.upgrade_url,
})
}
@@ -2021,6 +2023,16 @@ pub fn app_relay_usage_view(usage: AppRelayUsage) -> Option<AppRelayUsageView> {
core::relay_usage::view(&usage)
}
+/// The relay refusing a new session over the plan's cap, from the error's
+/// text: the sentence and Upgrade. None for any other error.
+#[uniffi::export]
+pub fn app_plan_limit_notice(
+ error: String,
+ account_app: String,
+) -> Option<AppRelayAllowanceNotice> {
+ core::relay_usage::plan_limit_notice(&error, &account_app)
+}
+
/// An SDK record as the app core's (the same JSON, the same names).
fn core_of<T: serde::Serialize, U: serde::de::DeserializeOwned + Default>(v: &T) -> U {
serde_json::to_value(v)
@@ -3002,7 +3014,8 @@ mod relay_usage_tests {
notice.upgrade_url.as_deref(),
Some("https://app.cua.ai/buy/pro?from=app_meter")
);
- assert_eq!(notice.dismiss_key, "2026-10:hours");
+ // Free at 2 of 2 live sessions is at the sessions limit too (CUA-1745).
+ assert_eq!(notice.dismiss_key, "2026-10:hours,sessions");
let plain = relay_usage(cua_host::RelayUsage {
upgrade_url: Some("http://cua.ai/pricing".into()),
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index 4caff2f139..27a7fdb438 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -9672,7 +9672,7 @@ pub struct AppRelayUsage {
pub type AppRelayAllowanceNotice = core::relay_usage::RelayAllowanceNotice;
#[uniffi::remote(Record)]
pub struct AppRelayAllowanceNotice {
- /// "You've used your free relay allowance for this month. ..."
+ /// On Free: "You're using 2 of 2 live sessions on the free plan. ..."
pub text: String,
/// [`UPGRADE`].
pub upgrade: String,
diff --git a/libs/cua/python/src/cua/__init__.py b/libs/cua/python/src/cua/__init__.py
index de4694343a..9073d3779c 100644
--- a/libs/cua/python/src/cua/__init__.py
+++ b/libs/cua/python/src/cua/__init__.py
@@ -94,6 +94,53 @@ _CuaError.doc_url = property( # type: ignore[attr-defined]
lambda self: _error_doc_url(type(self).__name__)
)
+# ── Plan limits ────────────────────────────────────────────────────────────
+# The relay refuses a new live session over the plan's cap (HTTP 429). The
+# SDK raises `CuaError.Http` with the plain sentence; `error.plan_limit`
+# reads it as a `PlanLimitError` (None for any other error).
+from ._plan_limit import parse_plan_limit as _parse_plan_limit # noqa: E402
+
+
+class PlanLimitError(_CuaError.Http): # type: ignore[name-defined,misc]
+ """The relay refused a new live session because the plan is at its cap.
+
+ ``str(error)`` is the plain sentence. Live sessions are never cut, and
+ retrying gets the same answer: close one, or send the person to
+ ``upgrade_url``.
+ """
+
+ code = "plan_limit"
+ status = 429
+
+ def __init__(self, message, *, kind, plan, used, limit, upgrade_url=None):
+ super().__init__(message)
+ self.kind = kind # "sessions" or "hours"
+ self.plan = plan # "free", "pro", "teams", or the relay's own name
+ self.used = used
+ self.limit = limit
+ self.upgrade_url = upgrade_url
+
+ def __repr__(self):
+ return "PlanLimitError({})".format(repr(str(self)))
+
+ @classmethod
+ def from_error(cls, error):
+ """The refusal an error carries, else None."""
+ found = _parse_plan_limit(str(error))
+ if found is None:
+ return None
+ return cls(
+ found.message,
+ kind=found.kind,
+ plan=found.plan,
+ used=found.used,
+ limit=found.limit,
+ upgrade_url=found.upgrade_url,
+ )
+
+
+_CuaError.Http.plan_limit = property(PlanLimitError.from_error) # type: ignore[attr-defined]
+
# `Sandbox` is resolved lazily (see __getattr__): the cua-sandbox facade when
# it is installed, else the native handle type.
del Sandbox # type: ignore[name-defined] # noqa: F821
diff --git a/libs/cua/python/src/cua/_plan_limit.py b/libs/cua/python/src/cua/_plan_limit.py
new file mode 100644
index 0000000000..cd96a9420d
--- /dev/null
+++ b/libs/cua/python/src/cua/_plan_limit.py
@@ -0,0 +1,58 @@
+"""Reads the relay's plan-limit refusal back out of an error's text.
+
+The relay answers a new live session over the plan's cap with HTTP 429. The
+SDK turns it into one plain sentence, such as "You're using 5 of 5 live
+sessions on Pro. Close one or upgrade to Teams.", and appends
+"Upgrade: <url>". This module holds no native code, so it loads anywhere.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import NamedTuple, Optional
+
+_FORMS = (
+ ("You're using ", "sessions", " live sessions on "),
+ ("You've used ", "hours", " remote hours this month on "),
+)
+_COUNTS = re.compile(r"^(\d+(?:\.\d+)?) of (\d+(?:\.\d+)?)$")
+_UPGRADE = re.compile(r"\sUpgrade: (https?://\S+)\s*$")
+
+
+class PlanLimitDetails(NamedTuple):
+ kind: str
+ plan: str
+ used: float
+ limit: float
+ upgrade_url: Optional[str]
+ message: str
+
+
+def parse_plan_limit(text: str) -> Optional[PlanLimitDetails]:
+ """The details when `text` is a plan-limit refusal, else None."""
+ for marker, kind, tail in _FORMS:
+ start = text.find(marker)
+ if start < 0:
+ continue
+ rest = text[start + len(marker):]
+ mid = rest.find(tail)
+ if mid < 0:
+ continue
+ counts = _COUNTS.match(rest[:mid])
+ after = rest[mid + len(tail):]
+ dot = after.find(". ")
+ if not counts or dot < 0:
+ continue
+ name = after[:dot].strip().lower()
+ plan = "free" if name == "the free plan" else "" if name == "your plan" else name
+ upgrade = _UPGRADE.search(text)
+ body = (text[: upgrade.start()] if upgrade else text)[start:].strip()
+ return PlanLimitDetails(
+ kind=kind,
+ plan=plan,
+ used=float(counts.group(1)),
+ limit=float(counts.group(2)),
+ upgrade_url=upgrade.group(1) if upgrade else None,
+ message=body,
+ )
+ return None
diff --git a/libs/cua/python/tests/test_plan_limit.py b/libs/cua/python/tests/test_plan_limit.py
new file mode 100644
index 0000000000..05567a98f5
--- /dev/null
+++ b/libs/cua/python/tests/test_plan_limit.py
@@ -0,0 +1,31 @@
+"""The relay's plan-limit refusal reads back as a typed `PlanLimitError`."""
+
+import cua
+
+SENTENCE = "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams."
+
+
+def test_a_sessions_refusal_carries_its_numbers_and_the_upgrade_link():
+ error = cua.CuaError.Http(f"{SENTENCE} Upgrade: https://app.cua.ai/buy/teams?from=plan_limit")
+ refusal = error.plan_limit
+ assert isinstance(refusal, cua.PlanLimitError)
+ assert isinstance(refusal, cua.CuaError.Http)
+ assert str(refusal) == SENTENCE
+ assert refusal.code == "plan_limit"
+ assert (refusal.kind, refusal.plan, refusal.used, refusal.limit) == ("sessions", "pro", 5, 5)
+ assert refusal.upgrade_url == "https://app.cua.ai/buy/teams?from=plan_limit"
+ assert refusal.status == 429
+
+
+def test_remote_hours_on_the_free_plan_without_a_link():
+ text = "You've used 20.5 of 20 remote hours this month on the free plan. Upgrade to Pro for more."
+ refusal = cua.PlanLimitError.from_error(cua.CuaError.Http("relay: " + text))
+ assert refusal is not None
+ assert str(refusal) == text
+ assert (refusal.kind, refusal.plan, refusal.used, refusal.limit) == ("hours", "free", 20.5, 20)
+ assert refusal.upgrade_url is None
+
+
+def test_any_other_error_is_not_a_plan_limit():
+ assert cua.CuaError.Http("http 500").plan_limit is None
+ assert cua.PlanLimitError.from_error(cua.CuaError.NotFound("x")) is None
diff --git a/libs/cua/typescript/src/spaces/errors.ts b/libs/cua/typescript/src/spaces/errors.ts
index 5863dcbc91..7d19b84e45 100644
--- a/libs/cua/typescript/src/spaces/errors.ts
+++ b/libs/cua/typescript/src/spaces/errors.ts
@@ -47,7 +47,9 @@ export type SpacesErrorCode =
/** The Space has no cua-spacesd. */
| 'spacesd_not_available'
/** The teleport consent gate refused (or the approver declined). */
- | 'teleport_refused';
+ | 'teleport_refused'
+ /** The relay refused a new live session because the plan's cap is reached. */
+ | 'plan_limit';
export interface SpacesErrorOptions {
cause?: unknown;
@@ -71,6 +73,7 @@ export class SpacesError extends Error {
readonly target: string | undefined;
readonly detail: string | undefined;
+ /** @internal */
constructor(code: SpacesErrorCode, message: string, options: SpacesErrorOptions = {}) {
super(message, options.cause === undefined ? undefined : { cause: options.cause });
this.name = 'SpacesError';
@@ -94,6 +97,82 @@ export class SpacesError extends Error {
}
}
+/** Which plan cap the relay refused. */
+export type PlanLimitKind = 'sessions' | 'hours';
+
+/**
+ * The relay refused a new live session because the account's plan is at its
+ * cap (HTTP 429, `x-cua-relay-error: plan_limit_sessions|plan_limit_hours`).
+ * Live sessions are never cut and retrying gets the same answer: close one,
+ * or send the person to {@link PlanLimitError.upgradeUrl}.
+ *
+ * `message` is the plain sentence, such as "You're using 5 of 5 live sessions
+ * on Pro. Close one or upgrade to Teams."
+ */
+export class PlanLimitError extends SpacesError {
+ readonly kind: PlanLimitKind;
+ /** `free`, `pro` or `teams`; any other plan keeps its own name. */
+ readonly plan: string;
+ readonly used: number;
+ readonly limit: number;
+ /** Where to add room, or undefined when the error carried no link. */
+ readonly upgradeUrl: string | undefined;
+
+ /** @internal */
+ constructor(
+ fields: { kind: PlanLimitKind; plan: string; used: number; limit: number; upgradeUrl?: string | undefined },
+ message: string,
+ options: SpacesErrorOptions = {},
+ ) {
+ super('plan_limit', message, { ...options, status: 429 });
+ this.name = 'PlanLimitError';
+ this.kind = fields.kind;
+ this.plan = fields.plan;
+ this.used = fields.used;
+ this.limit = fields.limit;
+ this.upgradeUrl = fields.upgradeUrl;
+ }
+}
+
+const PLAN_LIMIT_FORMS: ReadonlyArray<readonly [string, PlanLimitKind, string]> = [
+ ["You're using ", 'sessions', ' live sessions on '],
+ ["You've used ", 'hours', ' remote hours this month on '],
+];
+
+/**
+ * Reads the relay's plan-limit sentence (and the `Upgrade: <url>` the CLI and
+ * SDK append) back out of an error's text. Undefined for any other text.
+ */
+export function parsePlanLimit(
+ text: string,
+): { kind: PlanLimitKind; plan: string; used: number; limit: number; upgradeUrl?: string | undefined; message: string } | undefined {
+ for (const [marker, kind, tail] of PLAN_LIMIT_FORMS) {
+ const start = text.indexOf(marker);
+ if (start < 0) continue;
+ const rest = text.slice(start + marker.length);
+ const mid = rest.indexOf(tail);
+ if (mid < 0) continue;
+ const counts = /^(\d+(?:\.\d+)?) of (\d+(?:\.\d+)?)$/.exec(rest.slice(0, mid));
+ const after = rest.slice(mid + tail.length);
+ const dot = after.indexOf('. ');
+ if (!counts || dot < 0) continue;
+ const name = after.slice(0, dot).trim().toLowerCase();
+ const plan = name === 'the free plan' ? 'free' : name === 'your plan' ? '' : name;
+ // The sentence ends at its last full stop before any " Upgrade: <url>".
+ const upgrade = /\sUpgrade: (https?:\/\/\S+)\s*$/.exec(text);
+ const body = (upgrade ? text.slice(0, upgrade.index) : text).slice(start).trim();
+ return {
+ kind,
+ plan,
+ used: Number(counts[1]),
+ limit: Number(counts[2]),
+ upgradeUrl: upgrade?.[1],
+ message: body,
+ };
+ }
+ return undefined;
+}
+
/** Narrowing helper for consumers: `if (isSpacesError(e, 'verification')) …` */
export function isSpacesError(value: unknown, code?: SpacesErrorCode): value is SpacesError {
return value instanceof SpacesError && (code === undefined || value.code === code);
@@ -137,6 +216,11 @@ export function toSpacesError(error: unknown): SpacesError {
const tag = (error as { tag?: unknown } | null)?.tag;
const code = typeof tag === 'string' ? CUA_TAGS[tag] : undefined;
const message = error instanceof Error ? error.message : String(error);
+ const refusal = tag === 'Http' ? parsePlanLimit(message) : undefined;
+ if (refusal) {
+ const { message: sentence, ...fields } = refusal;
+ return new PlanLimitError(fields, sentence, { cause: error });
+ }
return new SpacesError(code ?? 'protocol', message, { cause: error });
}
diff --git a/libs/cua/typescript/src/spaces/groups.ts b/libs/cua/typescript/src/spaces/groups.ts
index 33123b67bc..56f7e9f9cd 100644
--- a/libs/cua/typescript/src/spaces/groups.ts
+++ b/libs/cua/typescript/src/spaces/groups.ts
@@ -27,6 +27,7 @@ export type GroupChatErrorCode = "tooFewBots" | "tooManyBots" | "full" | "atFloo
/** A membership rule was broken. The message says which number. */
export class GroupChatError extends Error {
+ /** @internal */
constructor(
readonly code: GroupChatErrorCode,
message: string,
diff --git a/libs/cua/typescript/src/spaces/index.ts b/libs/cua/typescript/src/spaces/index.ts
index e9161d40fc..489ffbce25 100644
--- a/libs/cua/typescript/src/spaces/index.ts
+++ b/libs/cua/typescript/src/spaces/index.ts
@@ -80,8 +80,8 @@ export type {
VideoFrame,
} from "../native/index.js"
-export { SpacesError, isSpacesError, excerpt, toSpacesError, wrapErrors } from "./errors.js"
-export type { SpacesErrorCode, SpacesErrorOptions } from "./errors.js"
+export { SpacesError, PlanLimitError, isSpacesError, excerpt, parsePlanLimit, toSpacesError, wrapErrors } from "./errors.js"
+export type { PlanLimitKind, SpacesErrorCode, SpacesErrorOptions } from "./errors.js"
export { TranscriptAdapter, detectApproval } from "./events.js"
export type {
AgentStatus,
diff --git a/libs/cua/typescript/test/spaces-unit.test.mjs b/libs/cua/typescript/test/spaces-unit.test.mjs
index 91e10a3318..6dea9d353a 100644
--- a/libs/cua/typescript/test/spaces-unit.test.mjs
+++ b/libs/cua/typescript/test/spaces-unit.test.mjs
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os"
import { join } from "node:path"
import { test } from "node:test"
-import { isSpacesError, toSpacesError, SpacesError } from "../dist/spaces/errors.js"
+import { isSpacesError, toSpacesError, parsePlanLimit, PlanLimitError, SpacesError } from "../dist/spaces/errors.js"
import { TranscriptAdapter, detectApproval } from "../dist/spaces/events.js"
import { SpaceTurnLock, Thread, validatePlacement, startThread } from "../dist/spaces/thread.js"
import { HostPresentation, cuaHome, readControlEndpoint } from "../dist/spaces/host.js"
@@ -567,3 +567,40 @@ test("the control file lives under CUA_HOME, like the Rust core", async () => {
else process.env.CUA_HOME = saved
}
})
+
+// -- plan limit --------------------------------------------------------------
+
+test("the relay's plan-limit refusal is a PlanLimitError with its numbers and the upgrade link", () => {
+ const sentence = "You're using 5 of 5 live sessions on Pro. Close one or upgrade to Teams."
+ const native = Object.assign(new Error(`${sentence} Upgrade: https://app.cua.ai/buy/teams?from=plan_limit`), { tag: "Http" })
+ const error = toSpacesError(native)
+ assert.ok(error instanceof PlanLimitError)
+ assert.ok(isSpacesError(error, "plan_limit"))
+ assert.equal(error.message, sentence)
+ assert.equal(error.kind, "sessions")
+ assert.equal(error.plan, "pro")
+ assert.equal(error.used, 5)
+ assert.equal(error.limit, 5)
+ assert.equal(error.status, 429)
+ assert.equal(error.upgradeUrl, "https://app.cua.ai/buy/teams?from=plan_limit")
+ assert.equal(error.cause, native)
+})
+
+test("remote hours on the free plan, with no link", () => {
+ const p = parsePlanLimit("relay: You've used 20.5 of 20 remote hours this month on the free plan. Upgrade to Pro for more.")
+ assert.deepEqual(p, {
+ kind: "hours",
+ plan: "free",
+ used: 20.5,
+ limit: 20,
+ upgradeUrl: undefined,
+ message: "You've used 20.5 of 20 remote hours this month on the free plan. Upgrade to Pro for more.",
+ })
+})
+
+test("other errors are not plan limits", () => {
+ assert.equal(parsePlanLimit("timed out"), undefined)
+ const e = toSpacesError(Object.assign(new Error("http 500"), { tag: "Http" }))
+ assert.ok(!(e instanceof PlanLimitError))
+ assert.equal(e.code, "http")
+})
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 929b5a1715..1aec782885 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -26494,7 +26494,7 @@ public func FfiConverterTypeAppRefreshReport_lower(_ value: AppRefreshReport) ->
public struct AppRelayAllowanceNotice: Equatable, Hashable {
/**
- * "You've used your free relay allowance for this month. ..."
+ * On Free: "You're using 2 of 2 live sessions on the free plan. ..."
*/
public var text: String
/**
@@ -26526,7 +26526,7 @@ public struct AppRelayAllowanceNotice: Equatable, Hashable {
// declare one manually.
public init(
/**
- * "You've used your free relay allowance for this month. ..."
+ * On Free: "You're using 2 of 2 live sessions on the free plan. ..."
*/text: String,
/**
* [`UPGRADE`].
@@ -68671,6 +68671,18 @@ public func appPickerWindowGrid(windows: [AppOpenWindow], query: String, selecte
)
})
}
+/**
+ * The relay refusing a new session over the plan's cap, from the error's
+ * text: the sentence and Upgrade. None for any other error.
+ */
+public func appPlanLimitNotice(error: String, accountApp: String) -> AppRelayAllowanceNotice? {
+ return try! FfiConverterOptionTypeAppRelayAllowanceNotice.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_plan_limit_notice(
+ FfiConverterString.lower(error),
+ FfiConverterString.lower(accountApp),$0
+ )
+})
+}
/**
* The power button next to Delete, for a Space that turns off and on.
*/
@@ -70775,6 +70787,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_picker_window_grid() != 8477) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_app_plan_limit_notice() != 24944) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_app_power_button() != 25513) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
index a7d87a5ade..7d3979b0d9 100644
--- a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
+++ b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
@@ -1512,6 +1512,11 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_picker_status(RustBuffer state, Rus
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_picker_window_grid(RustBuffer windows, RustBuffer query, RustBuffer selected, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_PLAN_LIMIT_NOTICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_PLAN_LIMIT_NOTICE
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_plan_limit_notice(RustBuffer error, RustBuffer account_app, RustCallStatus *_Nonnull out_status
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_POWER_BUTTON
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_POWER_BUTTON
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_power_button(RustBuffer space, RustCallStatus *_Nonnull out_status
@@ -3475,6 +3480,12 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_picker_status(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_PICKER_WINDOW_GRID
uint16_t uniffi_cua_spaces_ffi_checksum_func_app_picker_window_grid(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_PLAN_LIMIT_NOTICE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_PLAN_LIMIT_NOTICE
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_plan_limit_notice(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_POWER_BUTTON
diff --git a/scripts/docs-generators/typescript-sdk.ts b/scripts/docs-generators/typescript-sdk.ts
index 2845c0f50f..55a77025ab 100644
--- a/scripts/docs-generators/typescript-sdk.ts
+++ b/scripts/docs-generators/typescript-sdk.ts
@@ -164,6 +164,26 @@ function routeFor(file: string): string | undefined {
return page === 'index' ? ROUTE : `${ROUTE}/${page}`;
}
+/**
+ * Drop class members that are only inherited (typedoc repeats the base
+ * class's methods under every subclass), which keeps pages in the page budget.
+ * Members that override or extend are kept.
+ */
+export function dropInheritedMembers(markdown: string): string {
+ const parts = markdown.split(/^(?=#{1,6} )/m);
+ const out: string[] = [];
+ for (let i = 0; i < parts.length; i++) {
+ const part = parts[i];
+ if (/^##### /.test(part)) {
+ let body = part;
+ while (i + 1 < parts.length && /^#{6} /.test(parts[i + 1])) body += parts[++i];
+ if (/^###### Inherited from/m.test(body) && !/^###### Overrides/m.test(body)) continue;
+ out.push(body);
+ } else out.push(part);
+ }
+ return out.join('');
+}
+
/**
* Post-pass over one typedoc Markdown file: drop the H1 (the page title comes
* from frontmatter), rewrite `.md` links to site routes, and normalise
@@ -180,6 +200,7 @@ export function postProcess(markdown: string, file: string): string {
// typedoc escapes `_` inside words; harmless, but keep identifiers readable.
out = out.replace(/([A-Za-z0-9])\\_(?=[A-Za-z0-9])/g, '$1_');
out = dropTableColumn(out, 'Defined in');
+ out = dropInheritedMembers(out);
return (
out
.replace(/[ \t]+$/gm, '')
diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lock
index 27dc4d1d4f..1655a9eddb 100644
--- a/tests/e2e/cua-sdk/rust/Cargo.lock
+++ b/tests/e2e/cua-sdk/rust/Cargo.lock
@@ -1515,6 +1515,7 @@ dependencies = [
"cua-auth",
"cua-create-failure",
"cua-daemon",
+ "cua-home",
"cua-host",
"cua-image",
"cua-proto",