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: in-app Pro and Teams prompts at value moments (#5325)

Francesco Bonaccidd84e77aa5ea
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
index 4ad3ffacdb..3f1543f1e7 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
@@ -235,6 +235,9 @@ public final class FixtureDevices: DevicesRunning, @unchecked Sendable {
var u = free
switch name {
case "none": return nil
+ case "warn":
+ u.hoursUsed = 16.5
+ u.myHoursUsed = 16.5
case "reached":
u.liveSessions = 2
u.hoursUsed = 20.4
@@ -487,13 +490,24 @@ public final class DevicesModel {
/// The notice above the main window, until dismissed for this month and
/// these reasons.
+ ///
+ /// 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? {
guard let notice = relayUsageView?.notice, notice.dismissKey != relayNoticeDismissed else { return nil }
+ if notice.level == "warn", (relayUsage?.liveSessions ?? 0) > 0 { return nil }
return notice
}
+ /// One usage event for a Pro or Teams surface (`upsell_<surface>_<action>`,
+ /// fixed names in the app core's telemetry schema).
+ public func recordUpsell(_ feature: String) {
+ telemetry?.record(appTelemetryFeature(feature: feature))
+ }
+
public func dismissRelayNotice() {
guard let key = relayUsageView?.notice?.dismissKey else { return }
+ recordUpsell("upsell_meter_dismiss")
relayNoticeDismissed = key
defaults.set(key, forKey: Self.relayNoticeDismissedKey)
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swift
index 60a2d3efec..2d6db9d3b1 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/DevicesViews.swift
@@ -410,7 +410,10 @@ struct RelayAllowanceBanner: View {
Text(notice.text).lineLimit(2).foregroundStyle(.secondary).help(notice.text)
Spacer(minLength: 8)
if let url = notice.upgradeUrl.flatMap(URL.init(string:)) {
- Button(notice.upgrade) { openURL(url) }
+ Button(notice.upgrade) {
+ devices.recordUpsell("upsell_meter_click")
+ openURL(url)
+ }
.controlSize(.small)
.accessibilityIdentifier("relay-upgrade")
}
@@ -430,13 +433,18 @@ struct RelayAllowanceBanner: View {
.background(.bar)
.overlay(alignment: .bottom) { Divider() }
.accessibilityIdentifier("relay-allowance")
+ .onAppear { devices.recordUpsell("upsell_meter_shown") }
}
}
}
-/// Settings → Account: the relay allowance this month, where it applies.
+/// Settings → Account: the plan and the relay allowance this month, where
+/// it applies. The plan card is always there, never a prompt: Free offers
+/// Pro and a team; each button opens its checkout on the account app.
struct RelayUsageRow: View {
let view: AppRelayUsageView
+ var onPlanLink: () -> Void = {}
+ @Environment(\.openURL) private var openURL
var body: some View {
LabeledContent {
@@ -446,5 +454,25 @@ struct RelayUsageRow: View {
Text(view.line)
}
.accessibilityIdentifier("settings-relay-usage")
+ LabeledContent {
+ HStack {
+ if let link = view.planCard.secondary { planButton(link, id: "plan-secondary") }
+ if let link = view.planCard.primary { planButton(link, id: "plan-primary") }
+ }
+ } label: {
+ Text(view.planCard.label)
+ Text(view.planCard.detail)
+ }
+ .accessibilityIdentifier("settings-plan-card")
+ }
+
+ private func planButton(_ link: AppPlanLink, id: String) -> some View {
+ Button(link.label) {
+ guard let url = URL(string: link.url) else { return }
+ onPlanLink()
+ openURL(url)
+ }
+ .controlSize(.small)
+ .accessibilityIdentifier(id)
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SettingsView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SettingsView.swift
index ff48a75606..7abb4ddbe3 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SettingsView.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SettingsView.swift
@@ -21,7 +21,7 @@ struct SettingsView: View {
Section {
ForEach(section.rows, id: \.id) { row($0, in: section.id) }
if section.id == "account", let usage = model.devices.relayUsageView {
- RelayUsageRow(view: usage)
+ RelayUsageRow(view: usage) { model.devices.recordUpsell("upsell_plan_card_click") }
}
} header: {
HStack {
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
index 355dbf5e8f..c85905488b 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift
@@ -264,9 +264,10 @@ struct RelayUsageTests {
let (m, defaults) = model(fixture)
await m.readRelayUsage()
let notice = try #require(m.relayNotice)
- #expect(notice.text == "You've used your free relay allowance for this month. Your Spaces keep working. Upgrade for more.")
+ #expect(notice.text == "You've used your free relay allowance for this month. Your Spaces keep working. Pro gives you more.")
#expect(notice.upgrade == "Upgrade")
- #expect(notice.upgradeUrl == "https://cua.ai/pricing")
+ #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")
@@ -280,6 +281,33 @@ struct RelayUsageTests {
#expect(again.relayNotice?.dismissKey == "2026-10:hours,sessions")
}
+ @Test func atEightyPercentOfHoursAFreePlanGetsAHeadsUpThatWaitsForLiveSessions() async throws {
+ let fixture = FixtureDevices()
+ fixture.usage = FixtureDevices.usage("warn")
+ let (m, _) = model(fixture)
+ await m.readRelayUsage()
+ // The fixture has a session going: the prompt waits.
+ #expect(m.relayNotice == nil)
+ fixture.usage?.liveSessions = 0
+ await m.readRelayUsage()
+ let notice = try #require(m.relayNotice)
+ #expect(notice.level == "warn")
+ #expect(notice.text == "You've used 16.5 of 20 relay hours this month. Nothing stops at the limit. Pro gives you 200 hours and 5 live sessions.")
+ #expect(notice.upgradeUrl == "https://app.cua.ai/buy/pro?from=app_meter")
+ #expect(notice.dismissKey == "2026-10:warn")
+ }
+
+ @Test func theFreePlanCardOffersProAndATeam() async throws {
+ let (m, _) = model(FixtureDevices())
+ await m.readRelayUsage()
+ let card = try #require(m.relayUsageView?.planCard)
+ #expect(card.label == "Free plan")
+ #expect(card.primary?.label == "Get Pro")
+ #expect(card.primary?.url == "https://app.cua.ai/buy/pro?from=app_plan_card")
+ #expect(card.secondary?.label == "Start a team")
+ #expect(card.secondary?.url == "https://app.cua.ai/buy/teams?from=app_plan_card")
+ }
+
@Test func signedOutUnmeteredAndFailedReads() async {
let fixture = FixtureDevices()
let (m, _) = model(fixture)
diff --git a/apps/cua-spaces-web/src/__tests__/app-harness.tsx b/apps/cua-spaces-web/src/__tests__/app-harness.tsx
index b9f3cb0d88..1a30793094 100644
--- a/apps/cua-spaces-web/src/__tests__/app-harness.tsx
+++ b/apps/cua-spaces-web/src/__tests__/app-harness.tsx
@@ -8,7 +8,7 @@
import { createMemoryHistory, createRouter, RouterProvider } from "@tanstack/react-router";
import { render } from "@testing-library/react";
-import { beforeEach } from "vitest";
+import { afterEach, beforeEach } from "vitest";
import type { DataAdapter } from "@/bridge/adapter";
import type { HostEvent } from "@/bridge/protocol";
import { createDemoAdapter } from "@/bridge/adapters/demo";
@@ -49,6 +49,18 @@ export interface TestHost {
intercept?: (op: string, args: unknown) => unknown;
}
+/** The routers mounted by the running test: a navigation the app started (a
+ * create that finishes sends the person to the new Space) may still be
+ * loading when the test ends, and a router that settles after jsdom is gone
+ * throws `window is not defined`. Each test waits for them to go idle first. */
+const mounted: Array<{ state: { isLoading: boolean } }> = [];
+
+afterEach(async () => {
+ const routers = mounted.splice(0);
+ const deadline = Date.now() + 3000;
+ while (routers.some((r) => r.state.isLoading) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 5));
+});
+
export async function mountApp(path: string, host: TestHost = { failsCreates: true, listsGhost: true }) {
const demo = createDemoAdapter({ latencyMs: 1, stepMs: 4 });
// The page's listeners, so a test can push what the host would (`emit`).
@@ -77,6 +89,7 @@ export async function mountApp(path: string, host: TestHost = { failsCreates: tr
}) as DataAdapter["call"],
};
const router = createRouter({ routeTree, history: createMemoryHistory({ initialEntries: [path] }) });
+ mounted.push(router);
const hooks = {} as { spaces: SpacesHook; machines: ReturnType<typeof useMachines>; core: ReturnType<typeof useBridge>["core"] };
function Probe() {
hooks.spaces = useSpaces();
diff --git a/apps/cua-spaces-web/src/__tests__/upsell.test.tsx b/apps/cua-spaces-web/src/__tests__/upsell.test.tsx
new file mode 100644
index 0000000000..8ee2743c33
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/upsell.test.tsx
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The in-app Pro and Teams prompts, on the real routes and the wasm core:
+// the plan card in Settings and the plan under the account name (always
+// there), the second-machine prompt on Machines, and the share prompt. The
+// rules (one prompt every 3 days, never during a live session, closable) are
+// the core's `upsell`.
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, it } from "vitest";
+
+import { createDemoAdapter } from "@/bridge/adapters/demo";
+import { demoRelayUsage } from "@/bridge/adapters/demo/relay-usage";
+import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";
+import type { MachineRow } from "@/bridge/contracts/host";
+import { BridgeProvider, resetUpsellMemory, type CoreClient, type DataAdapter, type RelayUsage } from "@/bridge";
+import { UpsellPrompt } from "@/components/upsell-prompt";
+import { mountApp, stubBrowserApis, type TestHost } from "./app-harness";
+
+afterEach(() => {
+ cleanup();
+ localStorage.clear();
+ resetUpsellMemory();
+});
+stubBrowserApis();
+
+const idle = (over: Partial<RelayUsage> = {}) => ({ ...demoRelayUsage(), liveSessions: 0, ...over });
+
+function host(usage: RelayUsage, opened: string[] = [], tracked: unknown[] = [], runs = false): TestHost {
+ return {
+ failsCreates: false,
+ listsGhost: false,
+ answer: (op, out) => {
+ if (op === "relay.usage") return usage;
+ // The demo host has an agent run going; these tests start with none.
+ if (op === "agents.runs" && !runs) return [];
+ if (op === "machines.list") {
+ return [...(out as MachineRow[]), { id: "studio", name: "Studio", via: "relay", online: true, os: "", detail: "", limits: [] }];
+ }
+ return out;
+ },
+ intercept: (op, args) => {
+ if (op === "session.openExternal") {
+ opened.push((args as { url: string }).url);
+ return null;
+ }
+ if (op === "telemetry.track") {
+ tracked.push(...(args as { signals: unknown[] }).signals);
+ return null;
+ }
+ return undefined;
+ },
+ };
+}
+
+const features = (tracked: unknown[]) => tracked.map((s) => (s as { feature?: string }).feature).filter(Boolean);
+
+describe.skipIf(!wasmBuilt)("in-app Pro and Teams prompts (real routes, wasm core)", () => {
+ it("Settings always shows the plan card: Free offers Pro and a team, each to its checkout", async () => {
+ const opened: string[] = [];
+ const tracked: unknown[] = [];
+ const { router } = await mountApp("/settings", host(idle({ liveSessions: 1 }), opened, tracked));
+ await router.load();
+ const card = await waitFor(() => {
+ const el = document.querySelector("[data-plan-card]");
+ expect(el).toBeTruthy();
+ return el as HTMLElement;
+ });
+ expect(card.getAttribute("data-plan-card")).toBe("free");
+ expect(card.textContent).toContain("Free plan");
+ expect(card.textContent).toContain("2 live sessions and 20 relay hours a month");
+ fireEvent.click(card.querySelector("[data-plan-primary]")!);
+ fireEvent.click(card.querySelector("[data-plan-secondary]")!);
+ await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/pro?from=app_plan_card", "https://app.cua.ai/buy/teams?from=app_plan_card"]));
+ await waitFor(() => expect(features(tracked)).toContain("upsell_plan_card_click"));
+ });
+
+ 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();
+ const card = await waitFor(() => {
+ const el = document.querySelector("[data-plan-card=pro]");
+ expect(el).toBeTruthy();
+ return el as HTMLElement;
+ });
+ expect(card.textContent).toContain("Pro plan");
+ expect(card.querySelector("[data-plan-primary]")?.textContent).toBe("Manage plan");
+ expect(card.querySelector("[data-plan-secondary]")?.textContent).toBe("See Teams");
+ });
+
+ it("the account name carries the plan; on Free it opens Pro's checkout", async () => {
+ const opened: string[] = [];
+ const tracked: unknown[] = [];
+ const { router } = await mountApp("/spaces", host(idle(), opened, tracked));
+ await router.load();
+ const plan = await waitFor(() => {
+ const el = document.querySelector("[data-account-plan]");
+ expect(el).toBeTruthy();
+ return el as HTMLElement;
+ });
+ expect(plan.textContent).toBe("Free plan · Upgrade");
+ fireEvent.click(plan);
+ await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/pro?from=app_account_menu"]));
+ await waitFor(() => expect(features(tracked)).toContain("upsell_account_menu_click"));
+ });
+
+ it("a second machine over the relay: one line with Get Pro, shown once, closable", async () => {
+ const opened: string[] = [];
+ const tracked: unknown[] = [];
+ const { router } = await mountApp("/machines", host(idle(), opened, tracked));
+ await router.load();
+ const prompt = await waitFor(() => {
+ const el = document.querySelector("[data-upsell=machine]");
+ expect(el).toBeTruthy();
+ return el as HTMLElement;
+ });
+ expect(prompt.textContent).toContain("Two machines now. Free includes 2 live sessions and 20 relay hours a month. Pro makes it 5 and 200, for $18 a month.");
+ await waitFor(() => expect(features(tracked)).toContain("upsell_machine_shown"));
+ fireEvent.click(document.querySelector("[data-upsell=machine] [data-upsell-cta]")!);
+ await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/pro?from=app_machine"]));
+ fireEvent.click(document.querySelector("[data-upsell=machine] [data-upsell-dismiss]")!);
+ expect(document.querySelector("[data-upsell=machine]")).toBeNull();
+ await waitFor(() => expect(features(tracked)).toEqual(expect.arrayContaining(["upsell_machine_click", "upsell_machine_dismiss"])));
+ cleanup();
+ // Closed: it does not come back on the next visit.
+ const again = await mountApp("/machines", host(idle()));
+ await again.router.load();
+ await act(() => new Promise((r) => setTimeout(r, 50)));
+ expect(document.querySelector("[data-upsell=machine]")).toBeNull();
+ });
+
+ it("never during a live session", async () => {
+ const { router } = await mountApp("/machines", host(idle({ liveSessions: 1 })));
+ await router.load();
+ await waitFor(() => expect(document.querySelector("[data-machine-row], [aria-label=Machines]")).toBeTruthy());
+ await act(() => new Promise((r) => setTimeout(r, 50)));
+ expect(document.querySelector("[data-upsell]")).toBeNull();
+ });
+
+ it("never during an agent run", async () => {
+ const { router } = await mountApp("/machines", host(idle(), [], [], true));
+ await router.load();
+ await waitFor(() => expect(document.querySelector("[aria-label=Machines]")).toBeTruthy());
+ await act(() => new Promise((r) => setTimeout(r, 80)));
+ expect(document.querySelector("[data-upsell]")).toBeNull();
+ });
+
+ it("not on Pro: a second machine has nothing to sell", async () => {
+ const { router } = await mountApp("/machines", host(idle({ plan: "pro" })));
+ await router.load();
+ await act(() => new Promise((r) => setTimeout(r, 50)));
+ expect(document.querySelector("[data-upsell]")).toBeNull();
+ });
+});
+
+describe.skipIf(!wasmBuilt)("<UpsellPrompt surface=share>", () => {
+ let core: CoreClient;
+ beforeAll(async () => {
+ core = await testCore();
+ });
+
+ function view(usage: RelayUsage, active = true, opened: string[] = []) {
+ const demo = createDemoAdapter({ latencyMs: 0 });
+ demo.state.relayUsage = usage;
+ const adapter: DataAdapter = {
+ ...demo,
+ call: (op, args) => {
+ if (op === "session.openExternal") {
+ opened.push((args as { url: string }).url);
+ return Promise.resolve(null) as never;
+ }
+ return demo.call(op, args);
+ },
+ };
+ return render(
+ <BridgeProvider adapter={adapter} core={core}>
+ <UpsellPrompt surface="share" active={active} />
+ </BridgeProvider>,
+ );
+ }
+
+ it("after sharing with a person: Teams, with its checkout", async () => {
+ const opened: string[] = [];
+ view(idle(), true, opened);
+ const note = await screen.findByRole("note");
+ expect(note.textContent).toContain("Sharing with people you work with? Teams adds team-owned machines, roles and device approval, from $30 a seat.");
+ fireEvent.click(screen.getByRole("button", { name: "See Teams" }));
+ await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/teams?from=app_share"]));
+ });
+
+ it("not before anything was shared, and not for a team already on Teams", async () => {
+ view(idle(), false);
+ await act(() => new Promise((r) => setTimeout(r, 30)));
+ expect(document.querySelector("[data-upsell]")).toBeNull();
+ cleanup();
+ view(idle({ plan: "team" }));
+ await act(() => new Promise((r) => setTimeout(r, 30)));
+ expect(document.querySelector("[data-upsell]")).toBeNull();
+ });
+});
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 e660748da3..cd555112cd 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
@@ -55,15 +55,17 @@ describe("relay.usage", () => {
it.skipIf(!wasmBuilt)("the row and the notice are the core's words", async () => {
const core = await testCore();
const free = relayUsageView(core, demoRelayUsage())!;
- expect(free).toEqual({ label: "Relay usage", line: "Live sessions 1 of 2 · Relay hours 6.5 of 20 this month", plan: "Free plan", notice: null });
+ expect(free).toMatchObject({ label: "Relay usage", line: "Live sessions 1 of 2 · Relay hours 6.5 of 20 this month", plan: "Free plan", notice: null });
+ expect(free.planCard).toMatchObject({ plan: "free", label: "Free plan", primary: { label: "Get Pro", url: "https://app.cua.ai/buy/pro?from=app_plan_card" }, secondary: { label: "Start a team", url: "https://app.cua.ai/buy/teams?from=app_plan_card" } });
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 · Relay hours 20.2 of 20 this month · Team pool, 3 seats");
expect(past.notice).toEqual({
- text: "You've used your free relay allowance for this month. Your Spaces keep working. Upgrade for more.",
+ text: "You've used your free relay allowance for this month. Your Spaces keep working. Pro gives you more.",
upgrade: "Upgrade",
- upgradeUrl: "https://cua.ai/pricing",
+ upgradeUrl: "https://app.cua.ai/buy/pro?from=app_meter",
dismiss: "Dismiss",
dismissKey: "2026-10:hours",
+ level: "limit",
});
expect(relayUsageView(noCore, demoRelayUsage())).toBeNull();
});
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index e81cec3736..14781e430f 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -50,7 +50,7 @@ import { demoVolumeHandlers, demoVolumeState, type DemoVolumeState } from "./dem
import { demoHostSetupHandlers, demoHostSetupState, type DemoHostSetupState } from "./demo/host-setup";
import { demoSpaceDetailHandlers, demoSpaceDetailState, type DemoSpaceDetailState } from "./demo/space-detail";
import { demoTelemetryHandlers, demoTelemetryState, type DemoTelemetryState } from "./demo/telemetry";
-import { demoRelayUsageHandlers, demoRelayUsageState, type DemoRelayUsageState } from "./demo/relay-usage";
+import { demoRelayUsageHandlers, demoRelayUsageNamed, demoRelayUsageState, type DemoRelayUsageState } from "./demo/relay-usage";
import { demoStartupHandlers, demoStartupState, type DemoStartupState } from "./demo/startup";
import { demoMachine, MAC_DEMO_PLATFORM, type DemoPlatform } from "./demo/platform";
@@ -74,6 +74,9 @@ export interface DemoOptions {
macHost?: boolean;
/** This device is not enrolled on the relay yet (the enroll bar above every page). */
unenrolled?: boolean;
+ /** The relay allowance: `idle` (free, no live session, so prompts can show),
+ * `warn` (80% of the hours), `limit` (used up), `pro` or `teams`. */
+ usage?: "idle" | "warn" | "limit" | "pro" | "teams";
/** The machine the demo runs on: a Mac on Apple silicon unless set (the
* Electron shell passes its own system and architecture). */
platform?: DemoPlatform;
@@ -99,6 +102,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {
keychain: flags.has("keychain"),
macHost: flags.has("mac-host"),
unenrolled: flags.has("unenrolled"),
+ usage: (["idle", "warn", "limit", "pro", "teams"] as const).find((u) => flags.has(`usage-${u}`)),
...(flags.has("update-ready")
? { update: { status: "downloaded" as const, version: "0.9.3", percent: 100, notesUrl: DEMO_NOTES } }
: flags.has("update-downloading")
@@ -148,7 +152,8 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
onboarding: { completed: options.onboarded !== false, mode: options.onboarded === false ? null : "client" },
creates: new Map(),
agents: demoPersistentAgents(now()),
- runs: demoRunRecords(now()),
+ // A named allowance is for showing the prompts, which wait for no agent run.
+ runs: options.usage ? [] : demoRunRecords(now()),
agentSetup: demoAgentSetup(),
platform: options.platform ?? MAC_DEMO_PLATFORM,
paired: [],
@@ -156,6 +161,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
volume: demoVolumeState(now(), options.onboarded !== false, options.platform),
...demoTelemetryState(),
...demoRelayUsageState(),
+ ...(options.usage ? { relayUsage: demoRelayUsageNamed(options.usage) } : {}),
...demoSpaceDetailState(),
...demoHostSetupState(now(), options.onboarded === false),
...demoStartupState(Boolean(options.keychain)),
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/relay-usage.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/relay-usage.ts
index ffa2450f3d..352e336863 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/relay-usage.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/relay-usage.ts
@@ -34,3 +34,20 @@ export function demoRelayUsageHandlers({ state }: DemoContext): DemoHandlers<"re
"relay.usage": () => (state.identity && state.relayUsage ? { ...state.relayUsage, reasons: [...state.relayUsage.reasons] } : null),
};
}
+
+/** The allowance for `?demo=usage-<name>` (see `DemoOptions.usage`). */
+export function demoRelayUsageNamed(name: "idle" | "warn" | "limit" | "pro" | "teams"): RelayUsage {
+ const free = demoRelayUsage();
+ switch (name) {
+ case "idle":
+ return { ...free, liveSessions: 0 };
+ case "warn":
+ return { ...free, liveSessions: 0, hoursUsed: 16.5, myHoursUsed: 16.5 };
+ case "limit":
+ return { ...free, hoursUsed: 20.4, myHoursUsed: 20.4, softLimitReached: true, reasons: ["hours"] };
+ case "pro":
+ return { ...free, plan: "pro", liveSessions: 0, liveSessionsLimit: 5, hoursUsed: 38, myHoursUsed: 38, hoursLimit: 200 };
+ case "teams":
+ return { ...free, plan: "team", team: { id: "acme", seats: 3 }, liveSessions: 0, liveSessionsLimit: 15, hoursUsed: 120, myHoursUsed: 41, hoursLimit: 600 };
+ }
+}
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index 8e77f79dc8..cac7851b4c 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -135,7 +135,19 @@ export {
useRelayUsageView,
RELAY_USAGE_FOCUS_MS,
RELAY_USAGE_POLL_MS,
+ type PlanCard,
+ type PlanLink,
type RelayAllowanceNotice,
type RelayUsage,
type RelayUsageView,
} from "./relay-usage";
+export {
+ resetUpsellMemory,
+ useQuiet,
+ useTrackPlanClick,
+ useUpsellGate,
+ useUpsellPrompt,
+ type UpsellGate,
+ type UpsellPrompt,
+ type UpsellSurface,
+} from "./upsell";
diff --git a/apps/cua-spaces-web/src/bridge/ops/relay-usage.ts b/apps/cua-spaces-web/src/bridge/ops/relay-usage.ts
index 2e6b67365b..9cfc3113e7 100644
--- a/apps/cua-spaces-web/src/bridge/ops/relay-usage.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/relay-usage.ts
@@ -55,6 +55,27 @@ export interface RelayAllowanceNotice {
dismiss: string;
/** A dismissal holds for this month and these reasons. */
dismissKey: string;
+ /** `warn`: 80% of the relay hours (a prompt, held back during a live
+ * session or an agent run). `limit`: the allowance is used (always shown). */
+ level: "warn" | "limit";
+}
+
+/** `relay_usage::PlanLink`: a button that opens a page on the account app. */
+export interface PlanLink {
+ label: string;
+ url: string;
+}
+
+/** `relay_usage::PlanCard`: Settings' plan card, always there. */
+export interface PlanCard {
+ plan: "free" | "pro" | "teams" | string;
+ /** "Free plan". */
+ label: string;
+ detail: string;
+ /** "Get Pro". */
+ primary: PlanLink | null;
+ /** "Start a team". */
+ secondary: PlanLink | null;
}
/** `relay_usage::RelayUsageView`: Settings' row and the notice. */
@@ -66,6 +87,7 @@ export interface RelayUsageView {
/** "Free plan". */
plan: string;
notice: RelayAllowanceNotice | null;
+ planCard: PlanCard;
}
export interface RelayUsageOps {
diff --git a/apps/cua-spaces-web/src/bridge/relay-usage.ts b/apps/cua-spaces-web/src/bridge/relay-usage.ts
index 43d8de0053..e7570fbd22 100644
--- a/apps/cua-spaces-web/src/bridge/relay-usage.ts
+++ b/apps/cua-spaces-web/src/bridge/relay-usage.ts
@@ -16,7 +16,7 @@ import { relayUsageView } from "./derive";
import { useSettings } from "./hooks";
import type { RelayUsage, RelayUsageView } from "./ops/relay-usage";
-export 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;
/** A focus reads again only when the last read is older than this. */
diff --git a/apps/cua-spaces-web/src/bridge/upsell.ts b/apps/cua-spaces-web/src/bridge/upsell.ts
new file mode 100644
index 0000000000..07626a4cab
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/upsell.ts
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The in-app Pro and Teams prompts. The words, the plan each one fits and
+ * the rules (one prompt every 3 days, not during a live session or an agent
+ * run, a closed prompt stays closed for 30 days) are the app core's
+ * (`upsell.prompt`, `upsell.allows`, `cua-spaces-app-core/src/upsell.rs`);
+ * this keeps what the page remembers and draws nothing.
+ *
+ * Usage events: `cua_spaces_feature_used` `upsell_<surface>_<action>`
+ * (`telemetry.upsell`): `meter`, `share` and `machine` shown, click or
+ * dismiss; `plan_card` and `account_menu` click.
+ */
+
+import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from "react";
+
+import { BridgeContext } from "./BridgeProvider";
+import { useAgents, useSettings } from "./hooks";
+import type { RelayUsage } from "./ops/relay-usage";
+import { useRelayUsage } from "./relay-usage";
+
+export type UpsellSurface = "meter" | "share" | "machine";
+export type UpsellAction = "shown" | "click" | "dismiss";
+
+/** `upsell::UpsellPrompt`. */
+export interface UpsellPrompt {
+ surface: UpsellSurface;
+ text: string;
+ cta: { label: string; url: string };
+ /** "Not now". */
+ dismiss: string;
+}
+
+/** `upsell::UpsellState`. */
+interface UpsellState {
+ nowMs: number;
+ lastPromptMs: number | null;
+ dismissedMs: number | null;
+ quiet: boolean;
+}
+
+const LAST_KEY = "cua.upsell.lastPromptAt";
+const dismissedKey = (s: UpsellSurface) => `cua.upsell.dismissed.${s}`;
+
+const listeners = new Set<() => void>();
+
+/** How long a shown prompt stays through remounts (a page redrawing, a
+ * sheet reopened) before the rules apply to it again. */
+const HOLD_MS = 10 * 60_000;
+/** Prompts on screen now, by surface: until when. */
+const holds = new Map<UpsellSurface, number>();
+const isHeld = (surface: UpsellSurface) => (holds.get(surface) ?? 0) > Date.now();
+
+function readMs(key: string): number | null {
+ try {
+ const v = Number(globalThis.localStorage?.getItem(key));
+ return Number.isFinite(v) && v > 0 ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+function writeMs(key: string, ms: number): void {
+ try {
+ globalThis.localStorage?.setItem(key, String(ms));
+ } catch {
+ // Not kept: the rules read it as never shown.
+ }
+ for (const l of [...listeners]) l();
+}
+
+/** Forget what was shown and closed (tests). */
+export function resetUpsellMemory(): void {
+ try {
+ holds.clear();
+ for (const k of [LAST_KEY, dismissedKey("meter"), dismissedKey("share"), dismissedKey("machine")]) globalThis.localStorage?.removeItem(k);
+ } catch {
+ // Nothing kept.
+ }
+ for (const l of [...listeners]) l();
+}
+
+const subscribe = (l: () => void) => {
+ listeners.add(l);
+ return () => void listeners.delete(l);
+};
+
+/** A live session (a relay connection) or an agent run is going. */
+export function useQuiet(): boolean {
+ const usage = useRelayUsage();
+ const agents = useAgents();
+ return (usage?.liveSessions ?? 0) > 0 || (agents.data?.runs ?? []).some((r) => r.status === "running");
+}
+
+function useTrack(): (surface: UpsellSurface | "plan_card" | "account_menu", action: UpsellAction) => void {
+ const ctx = useContext(BridgeContext);
+ return useCallback(
+ (surface, action) => {
+ const store = ctx?.store;
+ if (!store) return;
+ const signals = ctx.core.tryCall<unknown[]>("telemetry.upsell", { surface, action });
+ if (signals?.length) void store.telemetry.track(signals);
+ },
+ [ctx],
+ );
+}
+
+/** One click on an always-visible plan link (the plan card, the account menu). */
+export function useTrackPlanClick(): (surface: "plan_card" | "account_menu") => void {
+ const track = useTrack();
+ return useCallback((surface) => track(surface, "click"), [track]);
+}
+
+export interface UpsellGate {
+ /** Draw the prompt now. */
+ show: boolean;
+ click(): void;
+ dismiss(): void;
+}
+
+/**
+ * Whether the `surface` prompt may show, and its events. `candidate`: the
+ * moment is here (a notice exists, a share just worked). `gated`: it is a
+ * prompt, so the rules apply; the `limit` notice is the status and is not.
+ * Once shown it stays until closed or until a live session or an agent run
+ * starts. Without the core nothing shows.
+ */
+export function useUpsellGate(surface: UpsellSurface, candidate: boolean, gated = true): UpsellGate {
+ const ctx = useContext(BridgeContext);
+ const core = ctx?.core;
+ const quiet = useQuiet();
+ const track = useTrack();
+ const memory = useSyncExternalStore(subscribe, () => `${readMs(LAST_KEY)}:${readMs(dismissedKey(surface))}`, () => "");
+ const [held, setHeld] = useState(() => isHeld(surface));
+ const [closed, setClosed] = useState(false);
+ const tracked = useRef(false);
+
+ const allowed =
+ !gated ||
+ (core?.tryCall<boolean>("upsell.allows", {
+ state: { nowMs: Date.now(), lastPromptMs: readMs(LAST_KEY), dismissedMs: readMs(dismissedKey(surface)), quiet } satisfies UpsellState,
+ }) ?? false);
+
+ useEffect(() => {
+ if (held || closed || !candidate || !allowed) return;
+ holds.set(surface, Date.now() + HOLD_MS);
+ setHeld(true);
+ if (gated) writeMs(LAST_KEY, Date.now());
+ if (!tracked.current) {
+ tracked.current = true;
+ track(surface, "shown");
+ }
+ // `memory` re-reads the rules when another prompt was shown.
+ }, [held, closed, candidate, allowed, gated, surface, track, memory]);
+
+ const show = held && !closed && candidate && !(gated && quiet);
+ return {
+ show,
+ click: () => track(surface, "click"),
+ dismiss: () => {
+ track(surface, "dismiss");
+ holds.delete(surface);
+ // The meter holds its own dismissal per month and level (`dismissKey`).
+ if (surface !== "meter") writeMs(dismissedKey(surface), Date.now());
+ setClosed(true);
+ },
+ };
+}
+
+/** The `share` or `machine` prompt's words, when its moment fits the plan. */
+export function useUpsellPrompt(surface: "share" | "machine", usage: RelayUsage | null): UpsellPrompt | null {
+ const core = useContext(BridgeContext)?.core;
+ const accountApp = useSettings().data?.accountUrl ?? null;
+ if (!core || !usage) return null;
+ return (
+ core.tryCall<UpsellPrompt | null>("upsell.prompt", {
+ surface,
+ usage,
+ ...(accountApp ? { accountApp } : {}),
+ state: { nowMs: Date.now(), lastPromptMs: null, dismissedMs: null, quiet: false },
+ }) ?? null
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/share-sheet.tsx b/apps/cua-spaces-web/src/components/share-sheet.tsx
index b71b2609dc..6bbfdb83a5 100644
--- a/apps/cua-spaces-web/src/components/share-sheet.tsx
+++ b/apps/cua-spaces-web/src/components/share-sheet.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
+import { UpsellPrompt } from "@/components/upsell-prompt";
import { cn } from "@/lib/utils";
/**
@@ -116,6 +117,7 @@ export default function ShareSheet() {
))
)}
</ul>
+ <UpsellPrompt surface="share" active={v.rows.some((r) => !r.who.startsWith("team:"))} className="mt-3" />
{v.error ? (
<p className="mt-2 text-[13px] text-destructive" data-share-error>
{v.error}
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 2f9a891eb9..2d4922aec1 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
@@ -7,13 +7,14 @@ import { afterEach, beforeAll, describe, expect, it } from "vitest";
import { createDemoAdapter } from "@/bridge/adapters/demo";
import { demoRelayUsage } from "@/bridge/adapters/demo/relay-usage";
import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";
-import { BridgeProvider, type CoreClient, type DataAdapter, type RelayUsage } from "@/bridge";
+import { BridgeProvider, resetUpsellMemory, type CoreClient, type DataAdapter, type RelayUsage } from "@/bridge";
import { RelayAllowanceNotice } from "./relay-allowance-notice";
afterEach(() => {
cleanup();
localStorage.clear();
+ resetUpsellMemory();
});
let core: CoreClient;
@@ -21,6 +22,7 @@ beforeAll(async () => {
core = await testCore();
});
+const warning: RelayUsage = { ...demoRelayUsage(), hoursUsed: 16.5, liveSessions: 0 };
const reached: RelayUsage = { ...demoRelayUsage(), hoursUsed: 20.2, softLimitReached: true, reasons: ["hours"] };
/** The demo host answering `usage`, recording the links it opens. */
@@ -61,22 +63,55 @@ describe.skipIf(!wasmBuilt)("<RelayAllowanceNotice>", () => {
const notice = await screen.findByRole("status");
expect(notice.textContent).toContain("You've used your free relay allowance for this month. Your Spaces keep working.");
fireEvent.click(screen.getByRole("button", { name: "Upgrade" }));
- await waitFor(() => expect(opened).toEqual(["https://cua.ai/pricing"]));
+ await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/pro?from=app_meter"]));
});
- it("with no page from the relay, Upgrade opens the host's account app billing page", async () => {
+ it("Upgrade opens the host's account app: Free to Pro, Pro to Teams", async () => {
const staging = host({ ...reached, upgradeUrl: null }, "https://app.staging.cua.ai");
staging.view();
await waitFor(() => {
fireEvent.click(screen.getByRole("button", { name: "Upgrade" }));
- expect(staging.opened).toContain("https://app.staging.cua.ai/billing");
+ expect(staging.opened).toContain("https://app.staging.cua.ai/buy/pro?from=app_meter");
});
cleanup();
- // A host that names none: the production account app.
- const prod = host({ ...reached, upgradeUrl: null });
- prod.view();
+ localStorage.clear();
+ const pro = host({ ...reached, plan: "pro", upgradeUrl: null });
+ pro.view();
fireEvent.click(await screen.findByRole("button", { name: "Upgrade" }));
- await waitFor(() => expect(prod.opened).toEqual(["https://app.cua.ai/billing"]));
+ await waitFor(() => expect(pro.opened).toEqual(["https://app.cua.ai/buy/teams?from=app_meter"]));
+ });
+
+ it("at 80% of the hours: a heads-up that says nothing stops, with Pro's checkout", async () => {
+ const { view, opened } = host(warning);
+ view();
+ const notice = await screen.findByRole("status");
+ expect(notice.getAttribute("data-relay-allowance")).toBe("warn");
+ expect(notice.textContent).toContain("You've used 16.5 of 20 relay hours this month. Nothing stops at the limit.");
+ fireEvent.click(screen.getByRole("button", { name: "Upgrade" }));
+ await waitFor(() => expect(opened).toEqual(["https://app.cua.ai/buy/pro?from=app_meter"]));
+ });
+
+ it("the heads-up waits while a live session is going, but the limit notice does not", async () => {
+ const busy = host({ ...warning, liveSessions: 1 });
+ busy.view();
+ await act(() => new Promise((r) => setTimeout(r, 20)));
+ expect(document.querySelector("[data-relay-allowance]")).toBeNull();
+ cleanup();
+ host({ ...reached, liveSessions: 1 }).view();
+ expect(await screen.findByRole("status")).toBeTruthy();
+ });
+
+ it("the heads-up shows once: one prompt every three days, and a closed one stays closed", async () => {
+ host(warning).view();
+ fireEvent.click(await screen.findByRole("button", { name: "Dismiss" }));
+ cleanup();
+ host(warning).view();
+ await act(() => new Promise((r) => setTimeout(r, 20)));
+ expect(document.querySelector("[data-relay-allowance]")).toBeNull();
+ cleanup();
+ // The limit notice has its own dismissal and is not held back by the heads-up's.
+ host(reached).view();
+ expect(await screen.findByRole("status")).toBeTruthy();
});
it("dismissed, it stays hidden for that month and reason, and shows again for another", async () => {
diff --git a/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx
index f229f6c77f..8733a36248 100644
--- a/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx
+++ b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx
@@ -4,7 +4,7 @@
import { XIcon } from "lucide-react";
import { useSyncExternalStore } from "react";
-import { useRelayUsageView, useSession } from "@/bridge";
+import { useRelayUsageView, useSession, useUpsellGate } from "@/bridge";
import { Button } from "@/components/ui/button";
const DISMISSED_KEY = "cua.relayAllowance.dismissed";
@@ -35,16 +35,22 @@ export function useRelayAllowanceShowing(): boolean {
}
/**
- * The relay allowance for the month is used up: one line above every page
- * with Upgrade, until dismissed (for that month and reason: the core's
- * `dismissKey`). Nothing stops at the limit, so it only says so.
+ * The relay allowance for the month: one line above every page with
+ * Upgrade, until dismissed (for that month and reason: the core's
+ * `dismissKey`). At 80% of the hours it is a heads-up (`warn`: a prompt, held
+ * back while a live session or an agent run is going); past the allowance it
+ * is the status (`limit`) and always shows. Nothing stops at the limit, so it
+ * only says so. Free leads to Pro, Pro to Teams.
*/
export function RelayAllowanceNotice() {
const notice = useRelayUsageView()?.notice;
const { openExternal } = useSession();
const dismissed = useSyncExternalStore(subscribe, readDismissed, () => null);
- if (!notice || dismissed === notice.dismissKey) return null;
+ const hidden = !notice || dismissed === notice.dismissKey;
+ const gate = useUpsellGate("meter", !hidden, notice?.level === "warn");
+ if (!notice || hidden || !gate.show) return null;
const dismiss = () => {
+ gate.dismiss();
try {
globalThis.localStorage?.setItem(DISMISSED_KEY, notice.dismissKey);
} catch {
@@ -54,10 +60,18 @@ export function RelayAllowanceNotice() {
};
const upgradeUrl = notice.upgradeUrl;
return (
- <div role="status" data-relay-allowance="" className="flex shrink-0 items-center gap-3 border-b px-4 py-2 text-xs text-muted-foreground">
+ <div role="status" data-relay-allowance={notice.level} className="flex shrink-0 items-center gap-3 border-b px-4 py-2 text-xs text-muted-foreground">
<span className="min-w-0 flex-1">{notice.text}</span>
{upgradeUrl ? (
- <Button size="sm" variant="outline" data-relay-upgrade="" onClick={() => void openExternal(upgradeUrl).catch(() => {})}>
+ <Button
+ size="sm"
+ variant="outline"
+ data-relay-upgrade=""
+ onClick={() => {
+ gate.click();
+ void openExternal(upgradeUrl).catch(() => {});
+ }}
+ >
{notice.upgrade}
</Button>
) : null}
diff --git a/apps/cua-spaces-web/src/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
index 7241ef7600..524588e7b8 100644
--- a/apps/cua-spaces-web/src/components/shell/sidebar.tsx
+++ b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
@@ -6,7 +6,7 @@ import { useRef, type PointerEvent } from "react";
import { LogOutIcon } from "lucide-react";
-import { signInCodeText, useBridge, useMachines, useNotifications, useSession, useSpaces } from "@/bridge";
+import { signInCodeText, useBridge, useMachines, useNotifications, useRelayUsageView, useSession, useSpaces, useTrackPlanClick } from "@/bridge";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
import { Tooltip } from "@/components/ui/tooltip";
@@ -79,6 +79,8 @@ export function Sidebar() {
export function AccountFooter() {
const { mode, core } = useBridge();
const { data: session, signIn, signOut, cancelSignIn, openExternal } = useSession();
+ const plan = useRelayUsageView()?.planCard;
+ const trackPlanClick = useTrackPlanClick();
if (!session) return <div className="mt-auto h-12 border-t" />;
const identity = session.signedIn ? (session.identity ?? "Signed in") : null;
@@ -103,7 +105,23 @@ export function AccountFooter() {
</div>
<div className="min-w-0 flex-1 leading-tight">
<div className="truncate text-xs font-medium">{identity}</div>
- <div className="truncate text-2xs text-muted-foreground">Cua account</div>
+ {plan?.primary ? (
+ // The current plan, always visible; on Free it opens Pro's checkout.
+ <button
+ type="button"
+ data-account-plan={plan.plan}
+ className="block max-w-full truncate text-left text-2xs text-muted-foreground hover:text-foreground"
+ onClick={() => {
+ trackPlanClick("account_menu");
+ void openExternal(plan.primary!.url.replace("from=app_plan_card", "from=app_account_menu")).catch(() => {});
+ }}
+ >
+ {plan.label}
+ {plan.plan === "free" ? " · Upgrade" : ""}
+ </button>
+ ) : (
+ <div className="truncate text-2xs text-muted-foreground">Cua account</div>
+ )}
</div>
{session.fleet.authMode === "user" ? (
<Tooltip content="Sign out" side="top">
diff --git a/apps/cua-spaces-web/src/components/upsell-prompt.tsx b/apps/cua-spaces-web/src/components/upsell-prompt.tsx
new file mode 100644
index 0000000000..c44bf955c8
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/upsell-prompt.tsx
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { XIcon } from "lucide-react";
+
+import { useRelayUsage, useSession, useUpsellGate, useUpsellPrompt } from "@/bridge";
+import { Button } from "@/components/ui/button";
+
+/**
+ * A Pro or Teams prompt at the moment it fits (`share`: a Space was just
+ * shared with someone; `machine`: a second machine is reached over the
+ * relay). One quiet line with one button and a close; it never blocks
+ * anything. The words, the plan it fits and the rules (one prompt every 3
+ * days, not during a live session or an agent run) are the app core's
+ * (`bridge/upsell.ts`).
+ */
+export function UpsellPrompt({ surface, active, className }: { surface: "share" | "machine"; active: boolean; className?: string }) {
+ const usage = useRelayUsage();
+ const prompt = useUpsellPrompt(surface, usage);
+ const gate = useUpsellGate(surface, active && prompt !== null);
+ const { openExternal } = useSession();
+ if (!prompt || !gate.show) return null;
+ return (
+ <div role="note" data-upsell={surface} className={`flex items-start gap-3 rounded-lg border bg-card px-3.5 py-2.5 text-xs ${className ?? ""}`}>
+ <p className="min-w-0 flex-1 leading-relaxed text-muted-foreground">{prompt.text}</p>
+ <Button
+ size="sm"
+ variant="outline"
+ data-upsell-cta=""
+ onClick={() => {
+ gate.click();
+ void openExternal(prompt.cta.url).catch(() => {});
+ }}
+ >
+ {prompt.cta.label}
+ </Button>
+ <Button size="icon-sm" variant="ghost" aria-label={prompt.dismiss} data-upsell-dismiss="" onClick={gate.dismiss}>
+ <XIcon className="size-3.5" />
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/cua-spaces-web/src/routes/machines/index.tsx b/apps/cua-spaces-web/src/routes/machines/index.tsx
index 4ba7880ef8..30cd340901 100644
--- a/apps/cua-spaces-web/src/routes/machines/index.tsx
+++ b/apps/cua-spaces-web/src/routes/machines/index.tsx
@@ -7,6 +7,7 @@ import { useEffect, useState, type ReactNode } from "react";
import { useBridge, useExperiments, useMachines, useSpaces, type Machine, type Space, type SpaceDetailView } from "@/bridge";
import { spaceDetail } from "@/bridge/space-detail";
+import { UpsellPrompt } from "@/components/upsell-prompt";
import { AddMachineDialog } from "@/components/add-machine-dialog";
import { JoinWithCodeDialog } from "@/components/join-with-code-dialog";
import { ThisMachine } from "@/components/this-machine";
@@ -125,6 +126,7 @@ function MachinesPage() {
Only this machine so far. Add another to run Spaces on it from here.
</p>
) : null}
+ <UpsellPrompt surface="machine" active={machines.length >= 2 && machines.some((m) => m.via === "relay")} className="mt-3" />
</div>
{selected ? (
<MachineDetail
diff --git a/apps/cua-spaces-web/src/routes/settings/index.tsx b/apps/cua-spaces-web/src/routes/settings/index.tsx
index 4ad5eeb086..36f5711d9a 100644
--- a/apps/cua-spaces-web/src/routes/settings/index.tsx
+++ b/apps/cua-spaces-web/src/routes/settings/index.tsx
@@ -10,6 +10,7 @@ import {
useLoginItem,
useMachines,
useRelayUsageView,
+ useTrackPlanClick,
useSession,
useSettings,
useStorageSettings,
@@ -185,14 +186,39 @@ function GlobalShortcutRow({ shortcut }: { shortcut: GlobalShortcut | null | und
);
}
-/** The relay allowance this month (the core's words), where the host reads it. */
+/** The plan and the relay allowance this month (the core's words), where the host reads it. */
function RelayUsageRow() {
const view = useRelayUsageView();
+ const { openExternal } = useSession();
+ const trackClick = useTrackPlanClick();
if (!view) return null;
+ const { planCard: card } = view;
+ const open = (url: string) => {
+ trackClick("plan_card");
+ void openExternal(url).catch(() => {});
+ };
return (
- <div data-relay-usage="">
- <SettingsRow label={view.label} description={view.line} control={<span className="text-[13px] text-muted-foreground">{view.plan}</span>} />
- </div>
+ <>
+ <div data-relay-usage="">
+ <SettingsRow label={view.label} description={view.line} control={<span className="text-[13px] text-muted-foreground">{view.plan}</span>} />
+ </div>
+ <div data-plan-card={card.plan} className="flex items-center gap-3 px-4 py-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] font-medium">{card.label}</div>
+ <div className="mt-0.5 text-xs text-muted-foreground">{card.detail}</div>
+ </div>
+ {card.secondary ? (
+ <Button size="sm" variant="ghost" data-plan-secondary="" onClick={() => open(card.secondary!.url)}>
+ {card.secondary.label}
+ </Button>
+ ) : null}
+ {card.primary ? (
+ <Button size="sm" variant={card.plan === "free" ? "default" : "outline"} data-plan-primary="" onClick={() => open(card.primary!.url)}>
+ {card.primary.label}
+ </Button>
+ ) : null}
+ </div>
+ </>
);
}
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index 2c7a05211e..eb1771971e 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -142,4 +142,4 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b
291 items, 385 methods. The [Types](/cua-sdk/reference/types) page lists them.
-The Cua Spaces app export adds 779 items and 38 methods.
+The Cua Spaces app export adds 781 items and 38 methods.
diff --git a/docs/content/docs/cua-sdk/reference/spaces/account-app-core.mdx b/docs/content/docs/cua-sdk/reference/spaces/account-app-core.mdx
index a0302c0907..adf8dc5bd0 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/account-app-core.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/account-app-core.mdx
@@ -60,6 +60,7 @@ Returned by [`app_billing_status`](#app_billing_status).
| `upgrade_url` / `upgradeUrl` | `Option<String>` | | What Upgrade opens; none: no Upgrade button. |
| `dismiss` | `String` | | `DISMISS`. |
| `dismiss_key` / `dismissKey` | `String` | | What a dismissal remembers: the month and the reasons. A new month, or another limit reached, shows the notice again. |
+| `level` | `String` | | `warn` (80% of the relay hours) or `limit` (the allowance is used). A `warn` is a prompt: the shells hold it back while a live session or an agent run is going (`crate.upsell`). A `limit` is only the status, so it always shows. |
## `AppRelayUsage` record
@@ -96,7 +97,8 @@ Returned by [`app_relay_usage_view`](#app_relay_usage_view).
| `label` | `String` | | `ROW_LABEL`. |
| `line` | `String` | | "Live sessions 1 of 2 · Relay hours 6.5 of 20 this month", then the team pool when there is one. |
| `plan` | `String` | | "Free plan" (empty when the relay names none). |
-| `notice` | [`Option<AppRelayAllowanceNotice>`](#apprelayallowancenotice-record) | | Past the allowance. |
+| `notice` | [`Option<AppRelayAllowanceNotice>`](#apprelayallowancenotice-record) | | At 80% of the relay hours, or past the allowance. |
+| `plan_card` / `planCard` | [`AppPlanCard`](/cua-sdk/reference/spaces/app-core#appplancard-record) | | Settings' plan card. |
## `AppTeamInput` record
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
index e1812a0bd3..31717dd898 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
@@ -43,6 +43,23 @@ pub fn cua_spaces_register()
</Tab>
</Tabs>
+## `AppPlanCard` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `plan` | `String` | | `free`, `pro` or `teams`. |
+| `label` | `String` | | "Free plan". |
+| `detail` | `String` | | What the plan includes, in one sentence. |
+| `primary` | [`Option<AppPlanLink>`](#appplanlink-record) | | The main button ("Get Pro"); none when there is nothing to buy. |
+| `secondary` | [`Option<AppPlanLink>`](#appplanlink-record) | | The other one ("Start a team"). |
+
+## `AppPlanLink` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `label` | `String` | | "Get Pro". |
+| `url` | `String` | | https, on the account app. |
+
## `AppResourceEdit` record
| Field | Type | Default | Description |
@@ -123,11 +140,11 @@ pub fn app_account_app_url() -> String
## All items
-626 items, across this page and its subpages, grouped by page (each item's section is on its page). Methods are listed on their object.
+628 items, across this page and its subpages, grouped by page (each item's section is on its page). Methods are listed on their object.
**[About, updates and launch](/cua-sdk/reference/spaces/app-core/about)**: `app_about_after_launch`, `app_about_allowed_channels`, `app_about_input_from_json`, `app_about_refresh_notice`, `app_about_restart_daemon`, `app_about_view`, `app_daemon_check_from_json`, `app_launch_input_from_json`, `app_refresh_report_from_json`, `AppAboutInput`, `AppAboutLink`, `AppAboutLinkId`, `AppAboutUpdates`, `AppAboutView`, `AppCliInstaller`, `AppCliInstallPlan`, `AppCliInstallRequest`, `AppDaemonCheck`, `AppInstallMethod`, `AppLaunchInput`, `AppLaunchPlan`, `AppRefreshReport`, `AppUpdateChannel`
-**Spaces app core**: [`app_account_app_url`](#app_account_app_url), [`AppResourceEdit`](#appresourceedit-record), [`AppResourceEditView`](#appresourceeditview-record), [`AppResourceField`](#appresourcefield-enum), [`AppVaultPassword`](#appvaultpassword-record), [`cua_spaces_register`](#cua_spaces_register)
+**Spaces app core**: [`app_account_app_url`](#app_account_app_url), [`AppPlanCard`](#appplancard-record), [`AppPlanLink`](#appplanlink-record), [`AppResourceEdit`](#appresourceedit-record), [`AppResourceEditView`](#appresourceeditview-record), [`AppResourceField`](#appresourcefield-enum), [`AppVaultPassword`](#appvaultpassword-record), [`cua_spaces_register`](#cua_spaces_register)
**[Settings, Agents](/cua-sdk/reference/spaces/app-core/agent-keys)**: `app_agent_key_form`, `app_agent_key_form_input_from_json`, `app_agent_key_name_problem`, `app_agent_key_remove_confirm`, `app_agent_keys_input_from_json`, `app_agent_keys_view`, `app_agent_settings_rows`, `app_agent_setup_outcome`, `app_agent_setup_outcomes_from_json`, `app_agent_setup_status`, `app_agent_setup_statuses_from_json`, `app_agent_setup_summary`, `AppAgentKeyConfirm`, `AppAgentKeyFormInput`, `AppAgentKeyFormView`, `AppAgentKeyInput`, `AppAgentKeyRow`, `AppAgentKeysInput`, `AppAgentKeysView`, `AppAgentSettingsRow`, `AppAgentSetupOutcomeInput`, `AppAgentSetupStatus`, `AppAgentSetupSummary`
diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdx
index f2c0990184..27d1b286ac 100644
--- a/docs/content/docs/cua-sdk/reference/types.mdx
+++ b/docs/content/docs/cua-sdk/reference/types.mdx
@@ -50,7 +50,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f
292 items. Methods are listed on their object.
-The 779 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items), [App core: billing, relay usage and Teams](/cua-sdk/reference/spaces/account-app-core#all-items), [Machines page](/cua-sdk/reference/spaces/machines-app-core), [Getting started and the command palette](/cua-sdk/reference/spaces/app-checklist-palette).
+The 781 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items), [App core: billing, relay usage and Teams](/cua-sdk/reference/spaces/account-app-core#all-items), [Machines page](/cua-sdk/reference/spaces/machines-app-core), [Getting started and the command palette](/cua-sdk/reference/spaces/app-checklist-palette).
| Item | Kind | Summary |
| --- | --- | --- |
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index 16d315546c..b8f6c8b329 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -17,7 +17,7 @@ use crate::{
CoreError, about, agent_keys, agents, checklist, cloud_connect, devices, drive_mount_preview,
drive_page, drive_settings, driver_preview, experiments, host, login_item, machines, notch,
notifications, onboarding, onboarding_preview, palette, paths, persistent, presence,
- relay_usage, settings, share, telemetry, window, wizard,
+ relay_usage, settings, share, telemetry, upsell, window, wizard,
};
use serde::Serialize;
use serde::de::DeserializeOwned;
@@ -286,6 +286,9 @@ pub const METHODS: &[&str] = &[
"experiments.choose",
"wizard.placementOptions",
"relayUsage.view",
+ "upsell.prompt",
+ "upsell.allows",
+ "telemetry.upsell",
];
struct Args(Value);
@@ -474,6 +477,25 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
_ => relay_usage::view(&usage),
})
}
+ // The Pro and Teams prompts: the rules and words are `upsell`'s.
+ "upsell.prompt" => {
+ let usage = a.get("usage")?;
+ let app = a
+ .get::<Option<String>>("accountApp")?
+ .filter(|u| u.starts_with("https://"))
+ .unwrap_or_else(cua_home::env::account_app_url);
+ out(upsell::prompt(
+ &a.get::<String>("surface")?,
+ &usage,
+ &app,
+ &a.get("state")?,
+ ))
+ }
+ "upsell.allows" => out(upsell::allows(&a.get("state")?)),
+ "telemetry.upsell" => out(telemetry::upsell(
+ &a.get::<String>("surface")?,
+ &a.get::<String>("action")?,
+ )),
"wizard.pickerImages" => out(wizard::picker_images()),
"wizard.pickerGroups" => out(wizard::picker_groups()),
"wizard.findImage" => out(wizard::find_image(&a.get::<String>("ref")?)),
@@ -1096,6 +1118,48 @@ mod tests {
use super::*;
use serde_json::json;
+ #[test]
+ fn upsell_prompts_follow_the_rules_through_dispatch() {
+ let usage =
+ json!({"metered": true, "plan": "free", "liveSessionsLimit": 2, "hoursLimit": 20.0});
+ let state = |quiet: bool| json!({"nowMs": 1_000_000_000_000u64, "quiet": quiet});
+ let p = call_value(
+ "upsell.prompt",
+ json!({"surface": "share", "usage": usage, "accountApp": "https://app.cua.ai", "state": state(false)}),
+ )
+ .unwrap();
+ assert_eq!(
+ p["cta"]["url"],
+ "https://app.cua.ai/buy/teams?from=app_share"
+ );
+ let quiet = call_value(
+ "upsell.prompt",
+ json!({"surface": "share", "usage": usage, "state": state(true)}),
+ )
+ .unwrap();
+ assert!(quiet.is_null());
+ assert_eq!(
+ call_value("upsell.allows", json!({"state": state(true)})).unwrap(),
+ json!(false)
+ );
+ assert_eq!(
+ call_value(
+ "telemetry.upsell",
+ json!({"surface": "meter", "action": "shown"})
+ )
+ .unwrap(),
+ json!([{"type": "feature", "feature": "upsell_meter_shown"}])
+ );
+ assert_eq!(
+ call_value(
+ "telemetry.upsell",
+ json!({"surface": "plan_card", "action": "shown"})
+ )
+ .unwrap(),
+ json!([])
+ );
+ }
+
#[test]
fn dispatch_covers_every_method() {
for m in METHODS {
@@ -1113,10 +1177,10 @@ mod tests {
));
}
- /// The page's core has no environment: Upgrade's billing fallback is the
+ /// The page's core has no environment: Upgrade's checkout is on the
/// account app the host names, else production's; only https is taken.
#[test]
- fn relay_upgrade_falls_back_to_the_hosts_account_app() {
+ fn relay_upgrade_opens_the_hosts_account_app() {
let usage = json!({
"metered": true, "plan": "free", "hoursUsed": 20.2, "hoursLimit": 20.0,
"softLimitReached": true, "reasons": ["hours"], "upgradeUrl": null,
@@ -1126,15 +1190,21 @@ mod tests {
};
assert_eq!(
upgrade(json!({"usage": usage, "accountApp": "https://app.staging.cua.ai"})),
- json!("https://app.staging.cua.ai/billing")
+ json!("https://app.staging.cua.ai/buy/pro?from=app_meter")
);
assert_eq!(
upgrade(json!({"usage": usage, "accountApp": "javascript:alert(1)"})),
- json!(format!("{}/billing", cua_home::env::account_app_url()))
+ json!(format!(
+ "{}/buy/pro?from=app_meter",
+ cua_home::env::account_app_url()
+ ))
);
assert_eq!(
upgrade(json!({"usage": usage})),
- json!(format!("{}/billing", cua_home::env::account_app_url()))
+ json!(format!(
+ "{}/buy/pro?from=app_meter",
+ cua_home::env::account_app_url()
+ ))
);
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
index 0ad7179b60..2b03b49488 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
@@ -89,6 +89,7 @@ pub mod spaces;
pub mod teams;
pub mod telemetry;
pub mod teleport;
+pub mod upsell;
mod util;
pub mod window;
pub mod wizard;
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 dacc20e7a0..9d95566d02 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
@@ -24,6 +24,20 @@ pub const UPGRADE: &str = "Upgrade";
/// The notice's close button (accessibility label).
pub const DISMISS: &str = "Dismiss";
+/// The share of the month's relay hours at which the early notice shows
+/// (80%). The hard notice shows when the relay says the allowance is used.
+pub const WARN_AT: f64 = 0.8;
+
+/// What Pro gives (cua.ai/pricing): one person, per month.
+pub const PRO_SESSIONS: u32 = 5;
+/// See [`PRO_SESSIONS`].
+pub const PRO_HOURS: u32 = 200;
+
+/// Where Pro is bought, on the account app.
+pub const BUY_PRO_PATH: &str = "/buy/pro";
+/// Where Teams is bought, on the account app.
+pub const BUY_TEAMS_PATH: &str = "/buy/teams";
+
/// The team whose allowance is pooled.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
@@ -80,6 +94,37 @@ pub struct RelayAllowanceNotice {
/// What a dismissal remembers: the month and the reasons. A new month,
/// or another limit reached, shows the notice again.
pub dismiss_key: String,
+ /// `warn` (80% of the relay hours) or `limit` (the allowance is used).
+ /// A `warn` is a prompt: the shells hold it back while a live session
+ /// or an agent run is going ([`crate::upsell`]). A `limit` is only the
+ /// status, so it always shows.
+ pub level: String,
+}
+
+/// A button that opens a page on the account app.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PlanLink {
+ /// "Get Pro".
+ pub label: String,
+ /// https, on the account app.
+ pub url: String,
+}
+
+/// The plan as Settings draws it: always there, never a prompt.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PlanCard {
+ /// `free`, `pro` or `teams`.
+ pub plan: String,
+ /// "Free plan".
+ pub label: String,
+ /// What the plan includes, in one sentence.
+ pub detail: String,
+ /// The main button ("Get Pro"); none when there is nothing to buy.
+ pub primary: Option<PlanLink>,
+ /// The other one ("Start a team").
+ pub secondary: Option<PlanLink>,
}
/// The allowance as drawn.
@@ -93,8 +138,10 @@ pub struct RelayUsageView {
pub line: String,
/// "Free plan" (empty when the relay names none).
pub plan: String,
- /// Past the allowance.
+ /// At 80% of the relay hours, or past the allowance.
pub notice: Option<RelayAllowanceNotice>,
+ /// Settings' plan card.
+ pub plan_card: PlanCard,
}
/// The answer as the apps keep it: an upgrade link that is not https is
@@ -136,15 +183,44 @@ pub fn usage_line(u: &RelayUsage) -> String {
/// "Free plan", "Pro plan"; empty when the relay names none.
pub fn plan_text(plan: &str) -> String {
- let mut c = plan.trim().chars();
+ let plan = match plan.trim() {
+ "team" => "teams",
+ p => p,
+ };
+ let mut c = plan.chars();
match c.next() {
Some(f) => format!("{}{} plan", f.to_uppercase(), c.as_str()),
None => String::new(),
}
}
+/// `free`, `pro` or `teams`; anything else the relay names is its own plan.
+pub(crate) fn plan_kind(plan: &str) -> &str {
+ match plan.trim() {
+ "team" | "teams" => "teams",
+ p => p,
+ }
+}
+
+/// The share of the month's relay hours used (none: no hour limit).
+pub fn hours_share(u: &RelayUsage) -> Option<f64> {
+ u.hours_limit.filter(|l| *l > 0.0).map(|l| u.hours_used / l)
+}
+
+/// The early notice applies: 80% or more of the hours, not yet past the
+/// allowance, on the Free plan (the plan with something to buy that adds
+/// hours: Pro).
+pub fn warns(u: &RelayUsage) -> bool {
+ !u.soft_limit_reached
+ && plan_kind(&u.plan) == "free"
+ && hours_share(u).is_some_and(|s| s >= WARN_AT)
+}
+
/// See [`RelayAllowanceNotice::dismiss_key`].
pub fn dismiss_key(u: &RelayUsage) -> String {
+ if !u.soft_limit_reached {
+ return format!("{}:warn", u.period);
+ }
let mut reasons = u.reasons.clone();
reasons.sort();
format!("{}:{}", u.period, reasons.join(","))
@@ -152,20 +228,113 @@ pub fn dismiss_key(u: &RelayUsage) -> String {
/// The notice's sentence.
pub fn notice_text(u: &RelayUsage) -> String {
- let free = if u.plan == "free" { "free " } else { "" };
- format!(
- "You've used your {free}relay allowance for this month. Your Spaces keep working. Upgrade for more."
- )
+ if warns(u) {
+ return format!(
+ "You've used {} of {} relay hours this month. Nothing stops at the limit. Pro gives you {PRO_HOURS} hours and {PRO_SESSIONS} live sessions.",
+ hours(u.hours_used),
+ hours(u.hours_limit.unwrap_or_default()),
+ );
+ }
+ match plan_kind(&u.plan) {
+ "free" => "You've used your free relay allowance for this month. Your Spaces keep working. Pro gives you more.".into(),
+ "pro" => "You've used your relay allowance for this month. Your Spaces keep working. Teams pools hours across seats.".into(),
+ _ => "You've used your relay allowance for this month. Your Spaces keep working. Add seats for more.".into(),
+ }
+}
+
+/// A page on the account app. A checkout page carries where the person came
+/// from (`?from=app_meter`, a fixed word, never anything about them), so the
+/// account app's anonymous purchase funnel can tell the in-app surfaces apart.
+pub(crate) fn buy(account_app: &str, path: &str, from: &str) -> String {
+ let base = format!("{}{path}", account_app.trim_end_matches('/'));
+ if path.starts_with("/buy/") {
+ format!("{base}?from={from}")
+ } else {
+ base
+ }
+}
+
+/// What the notice's Upgrade opens: Free goes to Pro, Pro to Teams, a team
+/// to its billing page; a plan the relay names that this app does not know
+/// keeps the relay's own link, else the billing page.
+fn upgrade_target(u: &RelayUsage, account_app: &str) -> String {
+ match plan_kind(&u.plan) {
+ "free" => buy(account_app, BUY_PRO_PATH, "app_meter"),
+ "pro" => buy(account_app, BUY_TEAMS_PATH, "app_meter"),
+ "teams" => buy(account_app, "/billing", "app_meter"),
+ _ => checked(u.clone())
+ .upgrade_url
+ .unwrap_or_else(|| buy(account_app, "/billing", "app_meter")),
+ }
+}
+
+/// Settings' plan card.
+pub fn plan_card(u: &RelayUsage, account_app: &str) -> PlanCard {
+ let kind = plan_kind(&u.plan);
+ let link = |label: &str, path: &str| PlanLink {
+ label: label.into(),
+ url: buy(account_app, path, "app_plan_card"),
+ };
+ let allowance = |s: Option<u32>, h: Option<f64>| match (s, h) {
+ (Some(s), Some(h)) => format!("{s} live sessions and {} relay hours a month", hours(h)),
+ _ => "No relay limit".into(),
+ };
+ let (detail, primary, secondary) = match kind {
+ "free" => (
+ format!(
+ "{} on the hosted relay. Spaces you reach on your own network don't count.",
+ allowance(u.live_sessions_limit, u.hours_limit)
+ ),
+ Some(link("Get Pro", BUY_PRO_PATH)),
+ Some(link("Start a team", BUY_TEAMS_PATH)),
+ ),
+ "pro" => (
+ format!(
+ "{}, for you. Teams adds team-owned machines, roles and device approval.",
+ allowance(u.live_sessions_limit, u.hours_limit)
+ ),
+ Some(link("Manage plan", "/billing")),
+ Some(link("See Teams", BUY_TEAMS_PATH)),
+ ),
+ "teams" => (
+ match &u.team {
+ Some(t) => format!(
+ "{} across {} {}, shared by the team.",
+ allowance(u.live_sessions_limit, u.hours_limit),
+ t.seats,
+ if t.seats == 1 { "seat" } else { "seats" }
+ ),
+ None => format!(
+ "{}, shared by the team.",
+ allowance(u.live_sessions_limit, u.hours_limit)
+ ),
+ },
+ Some(link("Manage seats", "/billing")),
+ None,
+ ),
+ _ => (
+ allowance(u.live_sessions_limit, u.hours_limit),
+ Some(link("Billing and plans", "/billing")),
+ None,
+ ),
+ };
+ PlanCard {
+ plan: kind.into(),
+ label: plan_text(&u.plan),
+ detail,
+ primary,
+ secondary,
+ }
}
-/// The row and the notice; none when the relay meters nothing (the apps
-/// show nothing about it). Upgrade opens the relay's page, else the account
-/// app's billing page.
+/// 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`]).
pub fn view(u: &RelayUsage) -> Option<RelayUsageView> {
view_for(u, &cua_home::env::account_app_url())
}
-/// [`view`] with Upgrade falling back to `account_app`'s billing page.
+/// [`view`] against `account_app`'s pages.
pub fn view_for(u: &RelayUsage, account_app: &str) -> Option<RelayUsageView> {
if !u.metered {
return None;
@@ -185,15 +354,20 @@ pub fn view_for(u: &RelayUsage, account_app: &str) -> Option<RelayUsageView> {
label: ROW_LABEL.into(),
line: format!("{}{team}", usage_line(u)),
plan: plan_text(&u.plan),
- notice: u.soft_limit_reached.then(|| RelayAllowanceNotice {
+ notice: (u.soft_limit_reached || warns(u)).then(|| RelayAllowanceNotice {
text: notice_text(u),
upgrade: UPGRADE.into(),
- upgrade_url: checked(u.clone())
- .upgrade_url
- .or_else(|| Some(format!("{}/billing", account_app.trim_end_matches('/')))),
+ upgrade_url: Some(upgrade_target(u, account_app)),
dismiss: DISMISS.into(),
dismiss_key: dismiss_key(u),
+ level: if u.soft_limit_reached {
+ "limit"
+ } else {
+ "warn"
+ }
+ .into(),
}),
+ plan_card: plan_card(u, account_app),
})
}
@@ -242,7 +416,7 @@ mod tests {
}),
..free()
};
- let v = view(&u).unwrap();
+ let v = view_for(&u, "https://app.cua.ai").unwrap();
assert_eq!(
v.line,
"Live sessions 1 of 2 \u{b7} Relay hours 20.2 of 20 this month \u{b7} Team pool, 3 seats"
@@ -250,24 +424,147 @@ mod tests {
let n = v.notice.unwrap();
assert_eq!(
n.text,
- "You've used your free relay allowance for this month. Your Spaces keep working. Upgrade for more."
+ "You've used your free relay allowance for this month. Your Spaces keep working. Pro gives you more."
);
assert_eq!(n.upgrade, "Upgrade");
- assert_eq!(n.upgrade_url.as_deref(), Some("https://cua.ai/pricing"));
+ assert_eq!(n.level, "limit");
+ assert_eq!(
+ n.upgrade_url.as_deref(),
+ Some("https://app.cua.ai/buy/pro?from=app_meter")
+ );
assert_eq!(n.dismiss_key, "2026-10:hours,sessions");
+ // Pro past the allowance: Teams pools hours across seats.
let pro = RelayUsage {
plan: "pro".into(),
- team: Some(RelayUsageTeam {
- id: "acme".into(),
- seats: 1,
- }),
+ ..u.clone()
+ };
+ let n = view_for(&pro, "https://app.cua.ai")
+ .unwrap()
+ .notice
+ .unwrap();
+ assert!(n.text.starts_with("You've used your relay"), "{}", n.text);
+ assert_eq!(
+ n.upgrade_url.as_deref(),
+ Some("https://app.cua.ai/buy/teams?from=app_meter")
+ );
+
+ // A team: its own billing page.
+ let team = RelayUsage {
+ plan: "team".into(),
..u
};
- let v = view(&pro).unwrap();
- assert!(v.line.ends_with("Team pool, 1 seat"), "{}", v.line);
- assert_eq!(v.plan, "Pro plan");
- assert!(v.notice.unwrap().text.starts_with("You've used your relay"));
+ let v = view_for(&team, "https://app.cua.ai").unwrap();
+ assert!(v.line.ends_with("Team pool, 3 seats"), "{}", v.line);
+ assert_eq!(v.plan, "Teams plan");
+ assert_eq!(
+ v.notice.unwrap().upgrade_url.as_deref(),
+ Some("https://app.cua.ai/billing")
+ );
+ }
+
+ #[test]
+ fn at_eighty_percent_of_hours_a_free_plan_gets_the_early_notice() {
+ let mut u = free();
+ u.hours_used = 15.9;
+ assert!(view_for(&u, "https://app.cua.ai").unwrap().notice.is_none());
+ u.hours_used = 16.0;
+ let n = view_for(&u, "https://app.cua.ai").unwrap().notice.unwrap();
+ assert_eq!(n.level, "warn");
+ assert_eq!(
+ n.text,
+ "You've used 16 of 20 relay hours this month. Nothing stops at the limit. Pro gives you 200 hours and 5 live sessions."
+ );
+ assert_eq!(
+ n.upgrade_url.as_deref(),
+ Some("https://app.cua.ai/buy/pro?from=app_meter")
+ );
+ assert_eq!(n.dismiss_key, "2026-10:warn");
+ // The hard notice has its own key: a dismissed warning does not hide it.
+ u.soft_limit_reached = true;
+ u.reasons = vec!["hours".into()];
+ let n = view_for(&u, "https://app.cua.ai").unwrap().notice.unwrap();
+ assert_eq!(n.level, "limit");
+ assert_eq!(n.dismiss_key, "2026-10:hours");
+ // Paid plans have no early notice.
+ let pro = RelayUsage {
+ plan: "pro".into(),
+ hours_used: 190.0,
+ hours_limit: Some(200.0),
+ ..free()
+ };
+ assert!(
+ view_for(&pro, "https://app.cua.ai")
+ .unwrap()
+ .notice
+ .is_none()
+ );
+ // Nor a plan with no hour limit.
+ let open = RelayUsage {
+ hours_limit: None,
+ hours_used: 500.0,
+ ..free()
+ };
+ assert!(
+ view_for(&open, "https://app.cua.ai")
+ .unwrap()
+ .notice
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn the_plan_card_names_the_plan_and_what_to_buy() {
+ let card = |u: RelayUsage| view_for(&u, "https://app.cua.ai/").unwrap().plan_card;
+ let f = card(free());
+ assert_eq!((f.plan.as_str(), f.label.as_str()), ("free", "Free plan"));
+ assert_eq!(
+ f.detail,
+ "2 live sessions and 20 relay hours a month on the hosted relay. Spaces you reach on your own network don't count."
+ );
+ let p = f.primary.unwrap();
+ assert_eq!(
+ (p.label.as_str(), p.url.as_str()),
+ ("Get Pro", "https://app.cua.ai/buy/pro?from=app_plan_card")
+ );
+ let s = f.secondary.unwrap();
+ assert_eq!(
+ (s.label.as_str(), s.url.as_str()),
+ (
+ "Start a team",
+ "https://app.cua.ai/buy/teams?from=app_plan_card"
+ )
+ );
+
+ let pro = card(RelayUsage {
+ plan: "pro".into(),
+ live_sessions_limit: Some(5),
+ hours_limit: Some(200.0),
+ ..free()
+ });
+ assert_eq!(pro.label, "Pro plan");
+ assert_eq!(pro.primary.unwrap().url, "https://app.cua.ai/billing");
+ assert_eq!(
+ pro.secondary.unwrap().url,
+ "https://app.cua.ai/buy/teams?from=app_plan_card"
+ );
+
+ let team = card(RelayUsage {
+ plan: "team".into(),
+ team: Some(RelayUsageTeam {
+ id: "t".into(),
+ seats: 2,
+ }),
+ live_sessions_limit: Some(10),
+ hours_limit: Some(400.0),
+ ..free()
+ });
+ assert_eq!(team.plan, "teams");
+ assert_eq!(
+ team.detail,
+ "10 live sessions and 400 relay hours a month across 2 seats, shared by the team."
+ );
+ assert!(team.secondary.is_none());
}
#[test]
@@ -292,17 +589,18 @@ mod tests {
}
#[test]
- fn upgrade_falls_back_to_the_account_app_billing_page() {
- let mut u = free();
- u.soft_limit_reached = true;
- u.reasons = vec!["hours".into()];
- // The relay's page wins.
+ fn an_unknown_plan_keeps_the_relays_link_else_the_billing_page() {
+ let mut u = RelayUsage {
+ plan: "enterprise".into(),
+ soft_limit_reached: true,
+ reasons: vec!["hours".into()],
+ ..free()
+ };
let n = view_for(&u, "https://app.staging.cua.ai")
.unwrap()
.notice
.unwrap();
assert_eq!(n.upgrade_url.as_deref(), Some("https://cua.ai/pricing"));
- // None from the relay: the account app's billing page.
u.upgrade_url = None;
let n = view_for(&u, "https://app.staging.cua.ai/")
.unwrap()
@@ -315,16 +613,15 @@ mod tests {
}
#[test]
- fn only_https_upgrade_links_are_kept() {
+ fn only_https_links_are_kept() {
for bad in ["http://cua.ai/pricing", "javascript:alert(1)", ""] {
let u = RelayUsage {
+ plan: "enterprise".into(),
upgrade_url: Some(bad.into()),
soft_limit_reached: true,
..free()
};
assert_eq!(checked(u.clone()).upgrade_url, None, "{bad}");
- // A link that is not https is dropped; Upgrade opens the
- // account app's billing page instead.
assert_eq!(
view_for(&u, "https://app.cua.ai")
.unwrap()
diff --git a/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs b/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
index c5dba9d6f7..b0de43a52f 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
@@ -202,6 +202,24 @@ pub fn feature_used(name: &str) -> Vec<TelemetrySignal> {
vec![feature(name)]
}
+/// The in-app Pro and Teams prompts, as `cua_spaces_feature_used`
+/// `upsell_<surface>_<action>`: `meter`, `share` and `machine` are shown,
+/// clicked or dismissed; the always-visible `plan_card` (Settings) and
+/// `account_menu` (the plan under the account name) are only clicked.
+/// Anything else: nothing.
+pub fn upsell(surface: &str, action: &str) -> Vec<TelemetrySignal> {
+ let ok = match surface {
+ "meter" | "share" | "machine" => matches!(action, "shown" | "click" | "dismiss"),
+ "plan_card" | "account_menu" => action == "click",
+ _ => false,
+ };
+ if ok {
+ vec![feature(&format!("upsell_{surface}_{action}"))]
+ } else {
+ vec![]
+ }
+}
+
// ---- Getting started -----------------------------------------------------------
/// The getting-started checklist's steps, in the order it lists them.
diff --git a/libs/cua/crates/cua-spaces-app-core/src/upsell.rs b/libs/cua/crates/cua-spaces-app-core/src/upsell.rs
new file mode 100644
index 0000000000..2f24a79eca
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/upsell.rs
@@ -0,0 +1,215 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The in-app Pro and Teams prompts, as every app shows them. A prompt is a
+//! value moment, never a nag: it shows after something that worked, says one
+//! plain thing, links to the plan's checkout on the account app, and can be
+//! closed.
+//!
+//! The rules live here so every shell follows the same ones:
+//!
+//! * At most one prompt every [`PROMPT_GAP_DAYS`] days, across all surfaces.
+//! * Never during a live session or an agent run (`quiet`).
+//! * A closed prompt stays closed for [`REDISMISS_DAYS`] days.
+//! * Free is the default and nothing is cut off, so no prompt blocks work.
+//!
+//! The plan card in Settings and the plan under the account name are not
+//! prompts: they are always there ([`crate::relay_usage::PlanCard`]). The
+//! relay meter's 80% and 100% notices are in [`crate::relay_usage`]; the
+//! 80% one follows the `quiet` rule too ([`allows`]).
+
+use serde::{Deserialize, Serialize};
+
+use crate::relay_usage::{
+ BUY_PRO_PATH, BUY_TEAMS_PATH, PRO_HOURS, PRO_SESSIONS, PlanLink, RelayUsage, buy, hours,
+ plan_kind,
+};
+
+/// Days between two prompts, whatever their surface.
+pub const PROMPT_GAP_DAYS: u64 = 3;
+
+/// Days a closed prompt stays closed.
+pub const REDISMISS_DAYS: u64 = 30;
+
+const DAY_MS: u64 = 86_400_000;
+
+/// Where a prompt shows.
+pub const SURFACES: [&str; 3] = ["meter", "share", "machine"];
+
+/// What an app remembers between launches, and what is going on now.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct UpsellState {
+ /// Now, ms since the epoch.
+ pub now_ms: u64,
+ /// When any prompt was last shown (none: never).
+ pub last_prompt_ms: Option<u64>,
+ /// When this surface's prompt was last closed (none: never).
+ pub dismissed_ms: Option<u64>,
+ /// A live session or an agent run is going.
+ pub quiet: bool,
+}
+
+/// A prompt as drawn.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UpsellPrompt {
+ /// `share` or `machine`.
+ pub surface: String,
+ /// One or two plain sentences.
+ pub text: String,
+ /// The button; opens the plan's checkout.
+ pub cta: PlanLink,
+ /// "Not now" (accessibility label of the close button).
+ pub dismiss: String,
+}
+
+/// The rules every prompt follows: not while quiet, not within the gap of
+/// the last prompt, not while this one is closed.
+pub fn allows(s: &UpsellState) -> bool {
+ if s.quiet {
+ return false;
+ }
+ let within =
+ |at: Option<u64>, days: u64| at.is_some_and(|t| s.now_ms < t.saturating_add(days * DAY_MS));
+ !within(s.last_prompt_ms, PROMPT_GAP_DAYS) && !within(s.dismissed_ms, REDISMISS_DAYS)
+}
+
+fn link(account_app: &str, label: &str, path: &str, from: &str) -> PlanLink {
+ PlanLink {
+ label: label.into(),
+ url: buy(account_app, path, from),
+ }
+}
+
+/// The prompt for `surface`, when its moment fits the plan and the rules.
+///
+/// * `share`: you shared a Space with a person and are not on Teams.
+/// (Sharing with named people is free; Teams adds team-owned machines,
+/// roles and device approval.)
+/// * `machine`: a second machine is reached over the relay and you are on
+/// Free.
+pub fn prompt(
+ surface: &str,
+ usage: &RelayUsage,
+ account_app: &str,
+ state: &UpsellState,
+) -> Option<UpsellPrompt> {
+ if !usage.metered || !allows(state) {
+ return None;
+ }
+ let kind = plan_kind(&usage.plan);
+ match surface {
+ "share" if kind != "teams" => Some(UpsellPrompt {
+ surface: "share".into(),
+ text: "Sharing with people you work with? Teams adds team-owned machines, roles and device approval, from $30 a seat.".into(),
+ cta: link(account_app, "See Teams", BUY_TEAMS_PATH, "app_share"),
+ dismiss: "Not now".into(),
+ }),
+ "machine" if kind == "free" => Some(UpsellPrompt {
+ surface: "machine".into(),
+ text: format!(
+ "Two machines now. Free includes {} live sessions and {} relay hours a month. Pro makes it {PRO_SESSIONS} and {PRO_HOURS}, for $18 a month.",
+ usage.live_sessions_limit.unwrap_or(2),
+ hours(usage.hours_limit.unwrap_or(20.0)),
+ ),
+ cta: link(account_app, "Get Pro", BUY_PRO_PATH, "app_machine"),
+ dismiss: "Not now".into(),
+ }),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const APP: &str = "https://app.cua.ai";
+ const NOW: u64 = 100 * DAY_MS;
+
+ fn usage(plan: &str) -> RelayUsage {
+ RelayUsage {
+ metered: true,
+ plan: plan.into(),
+ live_sessions_limit: Some(2),
+ hours_limit: Some(20.0),
+ ..Default::default()
+ }
+ }
+
+ fn state() -> UpsellState {
+ UpsellState {
+ now_ms: NOW,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn share_leads_to_teams_unless_already_on_teams() {
+ let p = prompt("share", &usage("free"), APP, &state()).unwrap();
+ assert_eq!(
+ p.text,
+ "Sharing with people you work with? Teams adds team-owned machines, roles and device approval, from $30 a seat."
+ );
+ assert_eq!(p.cta.url, "https://app.cua.ai/buy/teams?from=app_share");
+ assert!(prompt("share", &usage("pro"), APP, &state()).is_some());
+ assert!(prompt("share", &usage("team"), APP, &state()).is_none());
+ }
+
+ #[test]
+ fn a_second_machine_leads_free_to_pro() {
+ let p = prompt("machine", &usage("free"), APP, &state()).unwrap();
+ assert_eq!(
+ p.text,
+ "Two machines now. Free includes 2 live sessions and 20 relay hours a month. Pro makes it 5 and 200, for $18 a month."
+ );
+ assert_eq!(p.cta.label, "Get Pro");
+ assert_eq!(p.cta.url, "https://app.cua.ai/buy/pro?from=app_machine");
+ assert!(prompt("machine", &usage("pro"), APP, &state()).is_none());
+ assert!(prompt("machine", &usage("team"), APP, &state()).is_none());
+ }
+
+ #[test]
+ fn no_prompt_when_the_relay_meters_nothing_or_the_surface_is_unknown() {
+ let none = RelayUsage {
+ metered: false,
+ ..usage("free")
+ };
+ assert!(prompt("share", &none, APP, &state()).is_none());
+ assert!(prompt("settings", &usage("free"), APP, &state()).is_none());
+ }
+
+ #[test]
+ fn never_during_a_live_session_or_agent_run() {
+ let s = UpsellState {
+ quiet: true,
+ ..state()
+ };
+ assert!(!allows(&s));
+ assert!(prompt("share", &usage("free"), APP, &s).is_none());
+ }
+
+ #[test]
+ fn one_prompt_every_three_days() {
+ let at = |ago_days: u64| UpsellState {
+ last_prompt_ms: Some(NOW - ago_days * DAY_MS + 1),
+ ..state()
+ };
+ assert!(!allows(&at(3)), "a prompt just under three days ago");
+ assert!(allows(&UpsellState {
+ last_prompt_ms: Some(NOW - 3 * DAY_MS),
+ ..state()
+ }));
+ assert!(allows(&state()));
+ }
+
+ #[test]
+ fn a_closed_prompt_stays_closed_for_thirty_days() {
+ let closed = |ago_days: u64| UpsellState {
+ dismissed_ms: Some(NOW - ago_days * DAY_MS),
+ ..state()
+ };
+ assert!(!allows(&closed(29)));
+ assert!(allows(&closed(30)));
+ }
+}
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 3c1cde8569..5bac9bfaef 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -2938,7 +2938,7 @@ mod relay_usage_tests {
let notice = app_relay_usage_view(u).unwrap().notice.unwrap();
assert_eq!(
notice.upgrade_url.as_deref(),
- Some("https://cua.ai/pricing")
+ Some("https://app.cua.ai/buy/pro?from=app_meter")
);
assert_eq!(notice.dismiss_key, "2026-10:hours");
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 5563db6c68..2ac8326192 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
@@ -9569,6 +9569,37 @@ pub struct AppRelayAllowanceNotice {
/// What a dismissal remembers: the month and the reasons. A new month,
/// or another limit reached, shows the notice again.
pub dismiss_key: String,
+ /// `warn` (80% of the relay hours) or `limit` (the allowance is used).
+ /// A `warn` is a prompt: the shells hold it back while a live session
+ /// or an agent run is going ([`crate::upsell`]). A `limit` is only the
+ /// status, so it always shows.
+ pub level: String,
+}
+
+/// A button that opens a page on the account app.
+pub type AppPlanLink = core::relay_usage::PlanLink;
+#[uniffi::remote(Record)]
+pub struct AppPlanLink {
+ /// "Get Pro".
+ pub label: String,
+ /// https, on the account app.
+ pub url: String,
+}
+
+/// The plan as Settings draws it: always there, never a prompt.
+pub type AppPlanCard = core::relay_usage::PlanCard;
+#[uniffi::remote(Record)]
+pub struct AppPlanCard {
+ /// `free`, `pro` or `teams`.
+ pub plan: String,
+ /// "Free plan".
+ pub label: String,
+ /// What the plan includes, in one sentence.
+ pub detail: String,
+ /// The main button ("Get Pro"); none when there is nothing to buy.
+ pub primary: Option<AppPlanLink>,
+ /// The other one ("Start a team").
+ pub secondary: Option<AppPlanLink>,
}
/// The allowance as drawn.
@@ -9582,6 +9613,8 @@ pub struct AppRelayUsageView {
pub line: String,
/// "Free plan" (empty when the relay names none).
pub plan: String,
- /// Past the allowance.
+ /// At 80% of the relay hours, or past the allowance.
pub notice: Option<AppRelayAllowanceNotice>,
+ /// Settings' plan card.
+ pub plan_card: AppPlanCard,
}
diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rs
index 92fc3faecc..90fd290664 100644
--- a/libs/cua/crates/cua-telemetry/src/schema.rs
+++ b/libs/cua/crates/cua-telemetry/src/schema.rs
@@ -270,6 +270,20 @@ pub const FEATURES: &[&str] = &[
// Settings, General: Launch Cua Spaces at login turned on or off.
"launch_at_login_on",
"launch_at_login_off",
+ // The in-app Pro and Teams prompts (`cua-spaces-app-core` `upsell`):
+ // a value-moment prompt shown, clicked or dismissed; the always-visible
+ // plan card and account-menu plan only clicked.
+ "upsell_meter_shown",
+ "upsell_meter_click",
+ "upsell_meter_dismiss",
+ "upsell_share_shown",
+ "upsell_share_click",
+ "upsell_share_dismiss",
+ "upsell_machine_shown",
+ "upsell_machine_click",
+ "upsell_machine_dismiss",
+ "upsell_plan_card_click",
+ "upsell_account_menu_click",
];
pub const ONBOARDING_STEPS: &[&str] = &[
"installer_started",
diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.py
index c52ce3b1cc..38c5e48213 100644
--- a/libs/cua/scripts/generate-app-core-ffi.py
+++ b/libs/cua/scripts/generate-app-core-ffi.py
@@ -69,7 +69,7 @@ TYPES = [
("checklist.rs", "checklist", ["ChecklistStep", "ChecklistState", "ChecklistAction", "ChecklistSeen", "ChecklistTransition", "ChecklistRow", "ChecklistView"]),
("palette.rs", "palette", ["Keybinding", "PaletteEntry"]),
("teams.rs", "teams", ["TeamPersonInput", "TeamInput", "TeamsState", "TeamsInput"]),
- ("relay_usage.rs", "relay_usage", ["RelayUsageTeam", "RelayUsage", "RelayAllowanceNotice", "RelayUsageView"]),
+ ("relay_usage.rs", "relay_usage", ["RelayUsageTeam", "RelayUsage", "RelayAllowanceNotice", "PlanLink", "PlanCard", "RelayUsageView"]),
]
# FFI names that read better than the plain prefix.
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 65cd0d5b1c..3f7ab19bf2 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -24640,6 +24640,168 @@ public func FfiConverterTypeAppPlacementOption_lower(_ value: AppPlacementOption
}
+public struct AppPlanCard: Equatable, Hashable {
+ /**
+ * `free`, `pro` or `teams`.
+ */
+ public var plan: String
+ /**
+ * "Free plan".
+ */
+ public var label: String
+ /**
+ * What the plan includes, in one sentence.
+ */
+ public var detail: String
+ /**
+ * The main button ("Get Pro"); none when there is nothing to buy.
+ */
+ public var primary: AppPlanLink?
+ /**
+ * The other one ("Start a team").
+ */
+ public var secondary: AppPlanLink?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `free`, `pro` or `teams`.
+ */plan: String,
+ /**
+ * "Free plan".
+ */label: String,
+ /**
+ * What the plan includes, in one sentence.
+ */detail: String,
+ /**
+ * The main button ("Get Pro"); none when there is nothing to buy.
+ */primary: AppPlanLink?,
+ /**
+ * The other one ("Start a team").
+ */secondary: AppPlanLink?) {
+ self.plan = plan
+ self.label = label
+ self.detail = detail
+ self.primary = primary
+ self.secondary = secondary
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppPlanCard: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppPlanCard: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppPlanCard {
+ return
+ try AppPlanCard(
+ plan: FfiConverterString.read(from: &buf),
+ label: FfiConverterString.read(from: &buf),
+ detail: FfiConverterString.read(from: &buf),
+ primary: FfiConverterOptionTypeAppPlanLink.read(from: &buf),
+ secondary: FfiConverterOptionTypeAppPlanLink.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppPlanCard, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.plan, into: &buf)
+ FfiConverterString.write(value.label, into: &buf)
+ FfiConverterString.write(value.detail, into: &buf)
+ FfiConverterOptionTypeAppPlanLink.write(value.primary, into: &buf)
+ FfiConverterOptionTypeAppPlanLink.write(value.secondary, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppPlanCard_lift(_ buf: RustBuffer) throws -> AppPlanCard {
+ return try FfiConverterTypeAppPlanCard.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppPlanCard_lower(_ value: AppPlanCard) -> RustBuffer {
+ return FfiConverterTypeAppPlanCard.lower(value)
+}
+
+
+public struct AppPlanLink: Equatable, Hashable {
+ /**
+ * "Get Pro".
+ */
+ public var label: String
+ /**
+ * https, on the account app.
+ */
+ public var url: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * "Get Pro".
+ */label: String,
+ /**
+ * https, on the account app.
+ */url: String) {
+ self.label = label
+ self.url = url
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppPlanLink: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppPlanLink: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppPlanLink {
+ return
+ try AppPlanLink(
+ label: FfiConverterString.read(from: &buf),
+ url: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppPlanLink, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.label, into: &buf)
+ FfiConverterString.write(value.url, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppPlanLink_lift(_ buf: RustBuffer) throws -> AppPlanLink {
+ return try FfiConverterTypeAppPlanLink.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppPlanLink_lower(_ value: AppPlanLink) -> RustBuffer {
+ return FfiConverterTypeAppPlanLink.lower(value)
+}
+
+
public struct AppPlanStepView: Equatable, Hashable {
/**
* `install`, `files`, `state`, `launch`.
@@ -25554,6 +25716,13 @@ public struct AppRelayAllowanceNotice: Equatable, Hashable {
* or another limit reached, shows the notice again.
*/
public var dismissKey: String
+ /**
+ * `warn` (80% of the relay hours) or `limit` (the allowance is used).
+ * A `warn` is a prompt: the shells hold it back while a live session
+ * or an agent run is going ([`crate::upsell`]). A `limit` is only the
+ * status, so it always shows.
+ */
+ public var level: String
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -25573,12 +25742,19 @@ public struct AppRelayAllowanceNotice: Equatable, Hashable {
/**
* What a dismissal remembers: the month and the reasons. A new month,
* or another limit reached, shows the notice again.
- */dismissKey: String) {
+ */dismissKey: String,
+ /**
+ * `warn` (80% of the relay hours) or `limit` (the allowance is used).
+ * A `warn` is a prompt: the shells hold it back while a live session
+ * or an agent run is going ([`crate::upsell`]). A `limit` is only the
+ * status, so it always shows.
+ */level: String) {
self.text = text
self.upgrade = upgrade
self.upgradeUrl = upgradeUrl
self.dismiss = dismiss
self.dismissKey = dismissKey
+ self.level = level
}
@@ -25601,7 +25777,8 @@ public struct FfiConverterTypeAppRelayAllowanceNotice: FfiConverterRustBuffer {
upgrade: FfiConverterString.read(from: &buf),
upgradeUrl: FfiConverterOptionString.read(from: &buf),
dismiss: FfiConverterString.read(from: &buf),
- dismissKey: FfiConverterString.read(from: &buf)
+ dismissKey: FfiConverterString.read(from: &buf),
+ level: FfiConverterString.read(from: &buf)
)
}
@@ -25611,6 +25788,7 @@ public struct FfiConverterTypeAppRelayAllowanceNotice: FfiConverterRustBuffer {
FfiConverterOptionString.write(value.upgradeUrl, into: &buf)
FfiConverterString.write(value.dismiss, into: &buf)
FfiConverterString.write(value.dismissKey, into: &buf)
+ FfiConverterString.write(value.level, into: &buf)
}
}
@@ -25877,9 +26055,13 @@ public struct AppRelayUsageView: Equatable, Hashable {
*/
public var plan: String
/**
- * Past the allowance.
+ * At 80% of the relay hours, or past the allowance.
*/
public var notice: AppRelayAllowanceNotice?
+ /**
+ * Settings' plan card.
+ */
+ public var planCard: AppPlanCard
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -25895,12 +26077,16 @@ public struct AppRelayUsageView: Equatable, Hashable {
* "Free plan" (empty when the relay names none).
*/plan: String,
/**
- * Past the allowance.
- */notice: AppRelayAllowanceNotice?) {
+ * At 80% of the relay hours, or past the allowance.
+ */notice: AppRelayAllowanceNotice?,
+ /**
+ * Settings' plan card.
+ */planCard: AppPlanCard) {
self.label = label
self.line = line
self.plan = plan
self.notice = notice
+ self.planCard = planCard
}
@@ -25922,7 +26108,8 @@ public struct FfiConverterTypeAppRelayUsageView: FfiConverterRustBuffer {
label: FfiConverterString.read(from: &buf),
line: FfiConverterString.read(from: &buf),
plan: FfiConverterString.read(from: &buf),
- notice: FfiConverterOptionTypeAppRelayAllowanceNotice.read(from: &buf)
+ notice: FfiConverterOptionTypeAppRelayAllowanceNotice.read(from: &buf),
+ planCard: FfiConverterTypeAppPlanCard.read(from: &buf)
)
}
@@ -25931,6 +26118,7 @@ public struct FfiConverterTypeAppRelayUsageView: FfiConverterRustBuffer {
FfiConverterString.write(value.line, into: &buf)
FfiConverterString.write(value.plan, into: &buf)
FfiConverterOptionTypeAppRelayAllowanceNotice.write(value.notice, into: &buf)
+ FfiConverterTypeAppPlanCard.write(value.planCard, into: &buf)
}
}
@@ -58822,6 +59010,30 @@ fileprivate struct FfiConverterOptionTypeAppOpenFileInput: FfiConverterRustBuffe
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppPlanLink: FfiConverterRustBuffer {
+ typealias SwiftType = AppPlanLink?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppPlanLink.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppPlanLink.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif