An open-source, faster Devin alternative
TypeScript
billing: work-minute plans on the web (plan picker, packs, pill, banner, halt modal)
Mohamed Habib via Computer0c8ba9436953
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex f9183079..8ab55f62 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -101,6 +101,9 @@ export interface AutumnSubscription {plan_id: string;add_on: boolean;status: string;+ // Set when the subscription is cancelled at the period end.+ canceled_at?: number | null;+ current_period_end?: number | null;}export interface AutumnAutoTopup {feature_id: string;@@ -137,6 +140,7 @@ export interface AutumnBalanceBreakdown {}export interface AutumnBalance {+ granted?: number;remaining?: number;next_reset_at?: number | null;breakdown?: AutumnBalanceBreakdown[];@@ -1131,7 +1135,13 @@ export async function autumnPurchase(// stack; paid-plan switches keep Autumn's normal replacement/proration rules.export async function autumnUsagePlanPurchase(env: AutumnApiEnv,- params: { customerId: string; planId: "pro" | "max"; successUrl: string },+ params: {+ customerId: string;+ planId: "pro" | "max";+ successUrl: string;+ // A downgrade waits for the period end (086 "Plan changes").+ planSchedule?: "immediate" | "end_of_cycle";+ },): Promise<{ url: string | null }> {const customer = await getAutumnCustomer(env, params.customerId);const upgradingFromUsage = (customer?.subscriptions ?? []).some(@@ -1143,7 +1153,7 @@ export async function autumnUsagePlanPurchase(customer_id: params.customerId,plan_id: params.planId,success_url: params.successUrl,- plan_schedule: "immediate",+ plan_schedule: params.planSchedule ?? "immediate",};if (upgradingFromUsage) {body.carry_over_balances = {@@ -1213,6 +1223,27 @@ export async function autumnOpenCustomerPortal(return { url: d.url ?? null };}+// autumnCancelPlan cancels a paid plan at the end of its period, or with+// `uncancel` keeps it (also dropping a scheduled downgrade) —+// POST /billing.update. Autumn re-enables the trial when the plan ends, which+// the halt rules read as lapsed.+export async function autumnCancelPlan(+ env: AutumnApiEnv,+ params: { customerId: string; planId: "pro" | "max"; action: "cancel_end_of_cycle" | "uncancel" },+): Promise<void> {+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;+ const resp = await fetch(`${base}/billing.update`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}`,+ "content-type": "application/json",+ "x-api-version": "2.3.0",+ },+ body: JSON.stringify({ customer_id: params.customerId, plan_id: params.planId, cancel_action: params.action }),+ });+ if (!resp.ok) throw new Error(`autumn billing.update ${resp.status}: ${await resp.text()}`);+}+// autumnTopUpCharge buys `quantity` credits while ensuring the card ends up saved// OFF-SESSION — so a top-up also ARMS auto-recharge. No single Autumn hosted flow// does both (a /checkout top-up charges but leaves the card on-session-only;diff --git a/cloudflare-workers/api-edge/src/billing_summary.test.ts b/cloudflare-workers/api-edge/src/billing_summary.test.tsnew file mode 100644index 00000000..4d00d5fc--- /dev/null+++ b/cloudflare-workers/api-edge/src/billing_summary.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";+import type { AutumnCustomer } from "./autumn_webhook";+import { planSchedule, summarizeWorkMinutePlan, trialEndsAt } from "./billing_summary";++const customer = (c: Partial<AutumnCustomer>) => ({ id: "org_1", ...c }) as AutumnCustomer;++describe("summarizeWorkMinutePlan", () => {+ it("names the trial, which activeUsagePlan reads as base", () => {+ const s = summarizeWorkMinutePlan(+ customer({+ subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],+ balances: { work_minutes: { granted: 600, remaining: 411.6, next_reset_at: null } },+ }),+ );+ expect(s.usagePlan).toBe("trial");+ expect(s.workMinutes).toEqual({ granted: 600, remaining: 411, resetsAt: null });+ expect(s.periodEndsAt).toBeNull();+ expect(s.scheduledChange).toBeNull();+ });++ it("keeps base for a pre-launch free org", () => {+ const s = summarizeWorkMinutePlan(customer({ subscriptions: [{ plan_id: "base", add_on: false, status: "active" }] }));+ expect(s.usagePlan).toBe("base");+ expect(s.workMinutes).toBeNull();+ });++ it("reports the minute pool and its reset, never below zero", () => {+ const s = summarizeWorkMinutePlan(+ customer({+ subscriptions: [{ plan_id: "pro", add_on: false, status: "active", current_period_end: 1_793_000_000_000 }],+ balances: { work_minutes: { granted: 2_000, remaining: -30, next_reset_at: 1_793_000_000_000 } },+ }),+ );+ expect(s.usagePlan).toBe("pro");+ expect(s.workMinutes).toEqual({ granted: 2_000, remaining: 0, resetsAt: new Date(1_793_000_000_000).toISOString() });+ expect(s.periodEndsAt).toBe(new Date(1_793_000_000_000).toISOString());+ });++ it("shows a scheduled $200 → $20 downgrade with the period end", () => {+ const s = summarizeWorkMinutePlan(+ customer({+ subscriptions: [+ { plan_id: "max", add_on: false, status: "active", current_period_end: 1_793_000_000 },+ { plan_id: "pro", add_on: false, status: "scheduled" },+ ],+ }),+ );+ expect(s.usagePlan).toBe("max");+ expect(s.scheduledChange).toEqual({ to: "pro", at: new Date(1_793_000_000_000).toISOString() });+ });++ it("shows a cancellation at the period end", () => {+ const s = summarizeWorkMinutePlan(+ customer({+ subscriptions: [+ { plan_id: "pro", add_on: false, status: "active", canceled_at: 1_792_000_000_000, current_period_end: 1_793_000_000_000 },+ ],+ }),+ );+ expect(s.scheduledChange).toEqual({ to: "cancel", at: new Date(1_793_000_000_000).toISOString() });+ });+});++describe("plan changes", () => {+ it("downgrades $200 → $20 at the period end and applies everything else now", () => {+ expect(planSchedule("max", "pro")).toBe("end_of_cycle");+ expect(planSchedule("pro", "max")).toBe("immediate");+ expect(planSchedule("trial", "pro")).toBe("immediate");+ expect(planSchedule("trial", "max")).toBe("immediate");+ });++ it("ends the trial seven days after it starts", () => {+ expect(trialEndsAt(1_790_000_000)).toBe(new Date((1_790_000_000 + 7 * 86_400) * 1_000).toISOString());+ expect(trialEndsAt(null)).toBeNull();+ });+});diff --git a/cloudflare-workers/api-edge/src/billing_summary.ts b/cloudflare-workers/api-edge/src/billing_summary.tsnew file mode 100644index 00000000..d937875f--- /dev/null+++ b/cloudflare-workers/api-edge/src/billing_summary.ts@@ -0,0 +1,84 @@+// What the dashboard shows of an org's work-minute plan (serverless-agents-ws+// 086, "Surfaces"): the plan by name (the trial included), the minute pool, and+// a plan change Autumn has scheduled for the end of the period. Read from the+// Autumn customer the Billing endpoint already loads; no extra calls.++import { activeUsagePlan, TRIAL_DAYS, type AutumnCustomer } from "./autumn_webhook";++const WORK_MINUTES_FEATURE_ID = "work_minutes";+const DAY_MS = 86_400_000;++// `base` stays until every pre-launch free org is migrated to the trial (step 8).+export type DashboardUsagePlan = "trial" | "base" | "pro" | "max";++export interface WorkMinutes {+ granted: number;+ remaining: number;+ resetsAt: string | null;+}++// A change that takes effect at the end of the paid period: the $200 → $20+// downgrade, or a cancellation.+export interface ScheduledPlanChange {+ to: "pro" | "cancel";+ at: string | null;+}++export interface WorkMinutePlanSummary {+ usagePlan: DashboardUsagePlan;+ workMinutes: WorkMinutes | null;+ periodEndsAt: string | null;+ scheduledChange: ScheduledPlanChange | null;+}++function isLive(status: string | undefined): boolean {+ return !status || status === "active";+}++// Autumn reports times in milliseconds; older payloads used seconds.+function iso(value: number | null | undefined): string | null {+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;+ return new Date(value < 1e12 ? value * 1_000 : value).toISOString();+}++export function summarizeWorkMinutePlan(customer: AutumnCustomer): WorkMinutePlanSummary {+ const subs = customer.subscriptions ?? [];+ const paid = activeUsagePlan(customer);+ const onTrial = subs.some((s) => s.plan_id === "trial" && isLive(s.status));+ const usagePlan: DashboardUsagePlan = paid === "base" && onTrial ? "trial" : paid;++ const balance = customer.balances?.[WORK_MINUTES_FEATURE_ID];+ const workMinutes = balance+ ? {+ granted: Math.max(0, Math.round(balance.granted ?? 0)),+ // Shown as whole minutes; overage draws credits, so never below zero.+ remaining: Math.max(0, Math.floor(balance.remaining ?? 0)),+ resetsAt: iso(balance.next_reset_at),+ }+ : null;++ const current = subs.find((s) => s.plan_id === paid && isLive(s.status));+ const periodEndsAt = paid === "base" ? null : iso(current?.current_period_end);+ let scheduledChange: ScheduledPlanChange | null = null;+ if (current?.canceled_at != null) {+ scheduledChange = { to: "cancel", at: periodEndsAt };+ } else if (paid === "max" && subs.some((s) => s.plan_id === "pro" && s.status === "scheduled")) {+ scheduledChange = { to: "pro", at: periodEndsAt };+ }++ return { usagePlan, workMinutes, periodEndsAt, scheduledChange };+}++// The day the trial ends, from orgs.trial_started_at (seconds).+export function trialEndsAt(trialStartedAtSec: number | null | undefined): string | null {+ if (trialStartedAtSec == null) return null;+ return new Date(trialStartedAtSec * 1_000 + TRIAL_DAYS * DAY_MS).toISOString();+}++// Upgrades apply now (086 "Plan changes"); $200 → $20 waits for the period end.+export function planSchedule(+ current: DashboardUsagePlan,+ target: "pro" | "max",+): "immediate" | "end_of_cycle" {+ return current === "max" && target === "pro" ? "end_of_cycle" : "immediate";+}diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex e042a375..9d9627e1 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -27,7 +27,9 @@ import {summarizeAutumnCreditBalance,autumnSetAutoTopup,autumnOpenCustomerPortal,+ autumnCancelPlan,} from "./autumn_webhook";+import { planSchedule, summarizeWorkMinutePlan, trialEndsAt } from "./billing_summary";import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";import { handleWebhooksAPI, type WebhookEnv } from "./webhooks";import {@@ -1400,6 +1402,9 @@ export async function handleDashboard(if (sub === "/billing/autumn/concurrency" && method === "POST") {return handleAutumnConcurrency(req, env, caller);}+ if (sub === "/billing/autumn/cancel" && method === "POST") {+ return handleAutumnCancel(req, env, caller);+ }if (sub === "/billing/autumn/auto-topup" && method === "POST") {return handleAutumnAutoTopup(req, env, caller);}@@ -1711,6 +1716,15 @@ async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { oconst hasToppedUp = (r.customer.purchases ?? []).some((p) => p.plan_id === "top_up");const hasPaidSubscription = usagePlan === "pro" || usagePlan === "max";const creditBreakdown = summarizeAutumnCreditBalance(r.customer, usagePlan);+ const plan = summarizeWorkMinutePlan(r.customer);+ const billingState = await env.OPENCOMPUTER_DB.prepare(+ "SELECT halt_reason, payment_past_due_at, trial_started_at FROM orgs WHERE id = ?1",+ ).bind(caller.orgID).first<{+ halt_reason: string | null;+ payment_past_due_at: number | null;+ trial_started_at: number | null;+ }>();+ const warning = await billingWarning(env, caller.orgID);const model = await env.OPENCOMPUTER_DB.prepare(`SELECT@@ -1760,8 +1774,16 @@ async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { o},maxConcurrentSandboxes: r.maxConcurrent,concurrencyPlan,- usagePlan,+ usagePlan: plan.usagePlan,isHalted: r.halted,+ haltReason: r.haltReason,+ warning,+ paymentPastDueAt: secondsToIso(billingState?.payment_past_due_at),+ trialStartedAt: secondsToIso(billingState?.trial_started_at),+ trialEndsAt: trialEndsAt(billingState?.trial_started_at),+ workMinutes: plan.workMinutes,+ periodEndsAt: plan.periodEndsAt,+ scheduledChange: plan.scheduledChange,hasToppedUp,hasPaidSubscription,autoTopup: at@@ -1790,6 +1812,23 @@ async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { o});}+function secondsToIso(value: number | null | undefined): string | null {+ return value == null ? null : new Date(value * 1_000).toISOString();+}++// orgs.billing_warning (migration 0015) is written by the billing clock; read+// apart so the page still loads on a database that does not have it yet.+async function billingWarning(env: DashboardEnv, orgID: string): Promise<string | null> {+ try {+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT billing_warning FROM orgs WHERE id = ?1")+ .bind(orgID)+ .first<{ billing_warning: string | null }>();+ return row?.billing_warning ?? null;+ } catch {+ return null;+ }+}+// Where a checkout was opened from (086 funnel); anything else is the Billing page.const CHECKOUT_FROM = new Set(["paywall", "warning", "billing_page", "signup"]);@@ -1810,10 +1849,14 @@ async function handleAutumnUsagePlan(req: Request, env: DashboardEnv, caller: {}const origin = new URL(req.url).origin;try {+ const current = await env.OPENCOMPUTER_DB.prepare("SELECT usage_plan FROM orgs WHERE id = ?1")+ .bind(caller.orgID)+ .first<{ usage_plan: string | null }>();const co = await autumnUsagePlanPurchase(env, {customerId: caller.orgID,planId: plan,successUrl: `${origin}/billing?usage-plan=${plan}`,+ planSchedule: planSchedule(current?.usage_plan === "max" ? "max" : "base", plan),});await emitBillingEvent(env, "billing.checkout_opened", {orgId: caller.orgID,@@ -1827,6 +1870,34 @@ async function handleAutumnUsagePlan(req: Request, env: DashboardEnv, caller: {}}+// POST /api/dashboard/billing/autumn/cancel { plan, undo? } — cancel the paid+// plan at the end of its period, or (undo) keep it, which also drops a+// scheduled $200 → $20 downgrade.+async function handleAutumnCancel(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {+ if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);+ let body: { plan?: string; undo?: boolean };+ try {+ body = await req.json();+ } catch {+ return json({ error: "bad json" }, 400);+ }+ const plan = body.plan ?? "";+ if (plan !== "pro" && plan !== "max") {+ return json({ error: `unknown usage plan '${plan}'` }, 400);+ }+ try {+ await autumnCancelPlan(env, {+ customerId: caller.orgID,+ planId: plan,+ action: body.undo ? "uncancel" : "cancel_end_of_cycle",+ });+ return json({ ok: true });+ } catch (e) {+ console.error("billing/autumn cancel:", e);+ return json({ error: (e as Error).message }, 502);+ }+}+// POST /api/dashboard/billing/autumn/auto-topup// { enabled, threshold, quantity, budget } — configure automatic credit// recharge. Monetary values are integer credits ($1 each). Autumn expresses thediff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 032cebb2..0398371d 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -496,10 +496,25 @@ export const autumnSubscribeConcurrency = (plan: string) =>body: JSON.stringify({ plan }),})-export const autumnSubscribeUsagePlan = (plan: 'pro' | 'max') =>+// Where a checkout was opened from; the edge records it on+// billing.checkout_opened.+export type CheckoutFrom = 'paywall' | 'warning' | 'billing_page' | 'signup'++export const autumnSubscribeUsagePlan = (+ plan: 'pro' | 'max',+ from: CheckoutFrom = 'billing_page',+) =>apiFetch<{ url: string | null }>('/billing/autumn/plan', {method: 'POST',- body: JSON.stringify({ plan }),+ body: JSON.stringify({ plan, from }),+ })++// Cancel the paid plan at the end of the period, or undo that (undo also+// drops a scheduled $200 → $20 downgrade).+export const autumnCancelPlan = (plan: 'pro' | 'max', undo = false) =>+ apiFetch<{ ok: boolean }>('/billing/autumn/cancel', {+ method: 'POST',+ body: JSON.stringify({ plan, undo }),})// Open Autumn's Stripe-hosted billing portal to manage the saved card + invoices.diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex aa0cf8b7..a2525046 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -337,16 +337,85 @@ const apiKeys = [},]-const autumn = {- isHalted: false,- creditsRemainingCents: 4210,- concurrencyPlan: 'base',- usagePlan: 'base',- maxConcurrentSandboxes: 5,- autoTopup: { enabled: false, threshold: 5, quantity: 25, budget: 100 },- hasToppedUp: true,- hasPaidSubscription: false,- currency: 'usd',+// `?billing=` picks a billing state to review: trial (default), pro, max,+// max_downgrade, halted_<halt_reason>, warning_<warning>.+function autumnMock() {+ // Trial and period dates follow the real clock so "days left" reads right.+ const fromNow = (days: number) =>+ new Date(Date.now() + days * 86_400_000).toISOString()+ const scenario =+ typeof window === 'undefined'+ ? null+ : new URLSearchParams(window.location.search).get('billing')+ const trial = {+ isHalted: false,+ haltReason: null as string | null,+ warning: null as string | null,+ creditsRemainingCents: 1_000,+ creditBreakdown: {+ available: true,+ planRemainingCents: 1_000,+ topupRemainingCents: 0,+ otherRemainingCents: 0,+ planResetsAt: null,+ },+ concurrencyPlan: 'base',+ usagePlan: 'trial' as string,+ maxConcurrentSandboxes: 5,+ autoTopup: { enabled: false, threshold: 5, quantity: 10, budget: 100 },+ hasToppedUp: false,+ hasPaidSubscription: false,+ currency: 'usd',+ paymentPastDueAt: null,+ trialStartedAt: fromNow(-2),+ trialEndsAt: fromNow(4.9),+ workMinutes: { granted: 600, remaining: 412, resetsAt: null },+ periodEndsAt: null as string | null,+ scheduledChange: null as { to: 'pro' | 'cancel'; at: string | null } | null,+ }+ const paid = (plan: 'pro' | 'max') => ({+ ...trial,+ usagePlan: plan,+ hasPaidSubscription: true,+ hasToppedUp: true,+ creditsRemainingCents: 1_200,+ creditBreakdown: {+ ...trial.creditBreakdown,+ planRemainingCents: 0,+ topupRemainingCents: 1_200,+ },+ autoTopup: { enabled: true, threshold: 5, quantity: 10, budget: 100 },+ trialStartedAt: fromNow(-30),+ trialEndsAt: fromNow(-23),+ workMinutes: {+ granted: plan === 'pro' ? 2_000 : 25_000,+ remaining: plan === 'pro' ? 1_240 : 18_400,+ resetsAt: fromNow(12),+ },+ periodEndsAt: fromNow(12),+ })+ if (!scenario || scenario === 'trial') return trial+ if (scenario === 'pro' || scenario === 'max') return paid(scenario)+ if (scenario === 'max_downgrade')+ return {+ ...paid('max'),+ scheduledChange: { to: 'pro' as const, at: fromNow(12) },+ }+ if (scenario.startsWith('warning_'))+ return { ...trial, warning: scenario.slice('warning_'.length) }+ if (scenario.startsWith('halted_')) {+ const haltReason = scenario.slice('halted_'.length)+ const base = haltReason.startsWith('trial') ? trial : paid('pro')+ return {+ ...base,+ isHalted: true,+ haltReason,+ workMinutes: { ...base.workMinutes, remaining: 0 },+ creditsRemainingCents:+ haltReason === 'credits_empty' ? 0 : base.creditsRemainingCents,+ }+ }+ return trial}const billing = {@@ -1805,7 +1874,7 @@ const ROUTES: Array<[RegExp, Handler]> = [() => ({ checkpoints, total: checkpoints.length, page: 1, perPage: 20 }),],[/^\/api-keys$/, () => apiKeys],- [/^\/billing\/autumn$/, () => autumn],+ [/^\/billing\/autumn$/, () => autumnMock()],[/^\/billing\/invoices/, () => ({ invoices: [] })],[/^\/billing$/, () => billing],[/^\/usage\/sandboxes/, () => sandboxUsage],diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex 6302876f..363eac10 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -240,8 +240,34 @@ export const AutumnBillingSchema = z.object({}),maxConcurrentSandboxes: z.number(),concurrencyPlan: z.string(),- usagePlan: z.enum(['base', 'pro', 'max']),+ // `trial` is the 7-day trial; `base` is the pre-trial free tier, kept until+ // every free org is migrated (serverless-agents-ws 086).+ usagePlan: z.enum(['trial', 'base', 'pro', 'max']),isHalted: z.boolean(),+ haltReason: z.string().nullable().optional(),+ // orgs.billing_warning: trial_minutes | trial_days | trial_tokens |+ // allowance_80 | credits_low | payment_failed.+ warning: z.string().nullable().optional(),+ paymentPastDueAt: z.string().nullable().optional(),+ trialStartedAt: z.string().nullable().optional(),+ trialEndsAt: z.string().nullable().optional(),+ workMinutes: z+ .object({+ granted: z.number(),+ remaining: z.number(),+ resetsAt: z.string().nullable(),+ })+ .nullable()+ .optional(),+ periodEndsAt: z.string().nullable().optional(),+ // A change Autumn applies at the end of the paid period.+ scheduledChange: z+ .object({+ to: z.enum(['pro', 'cancel']),+ at: z.string().nullable(),+ })+ .nullable()+ .optional(),hasToppedUp: z.boolean(),hasPaidSubscription: z.boolean(),autoTopup: AutumnAutoTopupSchema.nullable(),diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 74b856d2..3722c571 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -6,6 +6,7 @@ import {BrainCircuit,CalendarClock,Computer,+ CreditCard,Database,FolderKanban,KeySquare,@@ -137,6 +138,7 @@ export function managedAgentsNav(options: {? [{ to: '/computer', label: 'Computer', icon: Computer }]: []),{ to: '/automations', label: 'Automations', icon: FolderKanban },+ { to: '/billing', label: 'Billing', icon: CreditCard },],})}diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex f93cdb43..f79e5766 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -14,7 +14,7 @@ describe('managed agents navigation', () => {computerEnabled: true,})expect(nav.map((group) => group.items.map((item) => item.label))).toEqual([- ['Computer', 'Automations'],+ ['Computer', 'Automations', 'Billing'],['Connections'],])expect(nav[0]?.items[0]).toMatchObject({@@ -34,13 +34,13 @@ describe('managed agents navigation', () => {managedAgentsNav({ ...defaults, computerEnabled: true }).map((group) =>group.items.map((item) => item.label),),- ).toEqual([['Computer', 'Automations'], ['Connections']])+ ).toEqual([['Computer', 'Automations', 'Billing'], ['Connections']])})it('hides the computer from organizations without it (rollout flag)', () => {expect(managedAgentsNav(defaults)[0]?.items.map((item) => item.label),- ).toEqual(['Automations'])+ ).toEqual(['Automations', 'Billing'])})it('shows project navigation only after a project is selected', () => {diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsxindex bde97ae1..3c8f659f 100644--- a/web/src/components/app-shell.tsx+++ b/web/src/components/app-shell.tsx@@ -26,7 +26,6 @@ import {Check,Menu,Loader2,- CircleAlert,ChevronRight,type LucideIcon,} from 'lucide-react'@@ -52,18 +51,11 @@ import { ThemeToggle } from '@/components/theme-toggle'import { AgentSecurityAlertBanner } from '@/components/agent-security-alert'import { cn } from '@/lib/utils'import { managedAgentsExperimentEnabled } from '@/managed-agents/feature'-import { useCreditState } from '@/hooks/useCreditState'import {- BASE_GRANT_CENTS,- FREE_CREDITS_USED,- UPGRADE_PLAN,- UPGRADE_PLAN_LABEL,- billingOnrampV2Enabled,- formatCredits,- trackUpsellClicked,- trackUpsellShown,- upgradeHref,-} from '@/lib/billing-onramp'+ BillingPill,+ BillingWarningBanner,+ HaltModal,+} from '@/components/billing-surfaces'import {getManagedMemoryResources,getManagedProject,@@ -451,7 +443,6 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {))}</nav>- <SidebarCreditMeter onNavigate={onNavigate} /><div className="border-t p-3">{managedAgentsExperimentEnabled ? (@@ -481,166 +472,6 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {)}-// Always-visible balance for prepaid orgs that haven't subscribed yet, so the-// first "you should pay" moment isn't the hard stop. Paid plans and legacy-// orgs (404 on /billing/autumn) render nothing.-function SidebarCreditMeter({ onNavigate }: { onNavigate?: () => void }) {- const { usagePlan, creditsRemainingCents, isLow, isHalted } = useCreditState()- const visible =- billingOnrampV2Enabled &&- usagePlan === 'base' &&- creditsRemainingCents !== undefined- useEffect(() => {- if (visible)- trackUpsellShown({- surface: 'sidebar_meter',- plan: UPGRADE_PLAN,- usagePlan,- creditsRemainingCents,- })- // Fire once per mount; balance changes shouldn't re-count an impression.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [visible])- if (!visible) return null- const grant = Math.max(BASE_GRANT_CENTS, creditsRemainingCents)- const pct = Math.max(0, Math.min(100, (creditsRemainingCents / grant) * 100))- return (- <div className="border-t px-3 py-3">- <div className="text-muted-foreground flex items-center justify-between font-mono text-[11px]">- <span>Free credits</span>- <span- className={cn(- isHalted && 'text-destructive',- isLow && 'text-amber-600',- )}- >- {formatCredits(creditsRemainingCents)} left- </span>- </div>- <div className="bg-secondary mt-1.5 h-1 overflow-hidden rounded-full">- <div- className={cn(- 'h-full rounded-full',- isHalted ? 'bg-destructive' : isLow ? 'bg-amber-500' : 'bg-primary',- )}- style={{ width: `${pct}%` }}- />- </div>- <Link- to={upgradeHref()}- onClick={() => {- trackUpsellClicked({- surface: 'sidebar_meter',- plan: UPGRADE_PLAN,- usagePlan,- creditsRemainingCents,- })- onNavigate?.()- }}- className="text-foreground mt-2 block text-xs font-medium underline-offset-2 hover:underline"- >- Upgrade to {UPGRADE_PLAN_LABEL} →- </Link>- </div>- )-}--// Org-wide credit notice. Prepaid (autumn) orgs that exhaust credits get halted-// (sandboxes hibernate); show a banner everywhere except Billing so users know-// why things paused and where to resolve it. A free org sees the paywall: one-// message, one link to the Pro checkout. Below the low-credit threshold the-// banner is an amber nudge instead. Legacy orgs 404 on /billing/autumn → no-// data → no banner. Top-ups are no longer sold, so nothing here offers one.-function HaltBanner() {- const location = useLocation()- const {- isHalted,- isLow,- modelFallback,- usagePlan,- creditsRemainingCents,- upgradePlan,- } = useCreditState()- const onBilling = location.pathname.startsWith('/billing')- const state = isHalted ? 'halted' : isLow ? 'low' : null- useEffect(() => {- if (state && !onBilling && upgradePlan)- trackUpsellShown({- surface: state === 'halted' ? 'halt_banner' : 'low_credit_banner',- plan: upgradePlan,- usagePlan,- creditsRemainingCents,- })- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [state, onBilling])- if (!state || onBilling) return null- const click = () => {- if (!upgradePlan) return- trackUpsellClicked({- surface: state === 'halted' ? 'halt_banner' : 'low_credit_banner',- plan: upgradePlan,- usagePlan,- creditsRemainingCents,- })- }- const upgradeLink = (label: string) => (- <Link- to={upgradeHref()}- onClick={click}- className="font-semibold underline underline-offset-2"- >- {label}- </Link>- )- if (state === 'low') {- return (- <div className="flex items-center justify-center gap-2 border-b border-amber-500/40 bg-amber-500/10 px-4 py-2.5 text-center text-sm font-medium text-amber-700 sm:px-8 dark:text-amber-400">- <CircleAlert className="size-4 shrink-0" />- <span>- {formatCredits(creditsRemainingCents ?? 0)}{' '}- {usagePlan === 'base'- ? 'of free credits left — sessions pause at 0.'- : 'left this month.'}- {upgradePlan ? (- <>- {' '}- {upgradeLink(`Upgrade to ${UPGRADE_PLAN_LABEL}`)} to keep going.- </>- ) : null}- </span>- </div>- )- }- if (modelFallback) {- return (- <div className="flex items-center justify-center gap-2 border-b border-amber-500/40 bg-amber-500/10 px-4 py-2.5 text-center text-sm font-medium text-amber-700 sm:px-8 dark:text-amber-400">- <CircleAlert className="size-4 shrink-0" />- <span>- You've used this month's credits — agents keep running on an- open-weight model (GLM)- {upgradePlan ? (- <>- . {upgradeLink(`Upgrade to ${UPGRADE_PLAN_LABEL}`)} to switch back- to your selected models.- </>- ) : (- ' until your plan renews.'- )}- </span>- </div>- )- }- return (- <div className="border-destructive/40 bg-status-error-bg text-destructive flex items-center justify-center gap-2 border-b px-4 py-2.5 text-center text-sm font-medium sm:px-8">- <CircleAlert className="size-4 shrink-0" />- <span>- {FREE_CREDITS_USED} {upgradeLink(`Upgrade to ${UPGRADE_PLAN_LABEL}`)} to- keep going.- </span>- </div>- )-}-export default function AppShell() {const { user } = useAuth()const [drawerOpen, setDrawerOpen] = useState(false)@@ -700,7 +531,8 @@ export default function AppShell() {/></div>) : null}- <div className="ml-auto flex items-center px-4">+ <div className="ml-auto flex items-center gap-3 px-4">+ <BillingPill /><ThemeToggle /></div></header>@@ -738,7 +570,8 @@ export default function AppShell() {onChange={changeProjectEnvironment}/>) : null}- <div className="ml-auto">+ <div className="ml-auto flex items-center gap-2">+ <BillingPill className="hidden sm:inline" /><ThemeToggle /></div></header>@@ -746,9 +579,10 @@ export default function AppShell() {{/* Main content */}<div className="flex flex-1 flex-col md:pt-16 md:pl-60"><div className="sticky top-14 z-20 md:top-16">- <HaltBanner />+ <BillingWarningBanner /><AgentSecurityAlertBanner /></div>+ <HaltModal /><mainclassName={cn('mx-auto flex w-full flex-1 flex-col px-4 py-6 sm:px-8',diff --git a/web/src/components/billing-surfaces.tsx b/web/src/components/billing-surfaces.tsxnew file mode 100644index 00000000..933bd23e--- /dev/null+++ b/web/src/components/billing-surfaces.tsx@@ -0,0 +1,216 @@+import { useEffect, type ReactNode } from 'react'+import { Link, useLocation } from 'react-router-dom'+import { CircleAlert, Loader2 } from 'lucide-react'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { useCreditState } from '@/hooks/useCreditState'+import { useBillingActions } from '@/hooks/useBillingActions'+import {+ BILLING_ACTION_LABELS,+ CREDIT_PACKS_USD,+ PAID_PLANS,+ PLAN_NAMES,+ PLAN_OFFERS,+ billingActionHref,+ billingOnrampV2Enabled,+ billingPillText,+ formatMinutes,+ haltNotice,+ trackPaywallShown,+ trackWarningShown,+ warningNotice,+} from '@/lib/billing-onramp'+import { cn } from '@/lib/utils'++// The app-shell billing surfaces of serverless-agents-ws 086 ("Surfaces"):+// the header pill, the warning banner and the halt modal. All read the shared+// 'autumn-billing' poll; legacy orgs 404 there and see none of them.++export function BillingPill({ className }: { className?: string }) {+ const { billing } = useCreditState()+ const text = billing ? billingPillText(billing) : null+ if (!billingOnrampV2Enabled || !text) return null+ return (+ <Link+ to="/billing"+ className={cn(+ 'text-muted-foreground hover:text-foreground hover:border-foreground/30 rounded-full border px-3 py-1 font-mono text-[11px] whitespace-nowrap transition-colors',+ billing?.isHalted && 'border-destructive/40 text-destructive',+ className,+ )}+ >+ {text}+ </Link>+ )+}++export function BillingWarningBanner() {+ const location = useLocation()+ const { billing, warning } = useCreditState()+ const onBilling = location.pathname.startsWith('/billing')+ useEffect(() => {+ if (warning) trackWarningShown(warning)+ }, [warning])+ if (!billingOnrampV2Enabled || !warning || !billing) return null+ const notice = warningNotice(warning, billing)+ const urgent = warning === 'payment_failed'+ return (+ <div+ role="status"+ className={cn(+ 'flex items-center justify-center gap-2 border-b px-4 py-2.5 text-center text-sm font-medium sm:px-8',+ urgent+ ? 'border-destructive/40 bg-status-error-bg text-destructive'+ : 'border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400',+ )}+ >+ <CircleAlert className="size-4 shrink-0" />+ <span>+ {notice.text}{' '}+ {onBilling ? null : (+ <Link+ to={billingActionHref(notice.action, 'warning')}+ className="font-semibold underline underline-offset-2"+ >+ {BILLING_ACTION_LABELS[notice.action]}+ </Link>+ )}+ </span>+ </div>+ )+}++// Blocks every page while the org is halted. The Billing page is the one+// exception: it shows the same notice inline so plans, packs and the card+// stay reachable there.+export function HaltModal() {+ const location = useLocation()+ const { billing, isHalted, haltReason, usagePlan } = useCreditState()+ const onBilling = location.pathname.startsWith('/billing')+ const open = isHalted && !onBilling+ const reason = haltReason ?? 'unknown'+ useEffect(() => {+ if (open) trackPaywallShown(reason)+ }, [open, reason])+ if (!open || !billing) return null+ return (+ <Dialog open>+ <DialogContent+ showCloseButton={false}+ onEscapeKeyDown={(e) => e.preventDefault()}+ onInteractOutside={(e) => e.preventDefault()}+ className="sm:max-w-md"+ >+ <HaltNoticeBody+ reason={haltReason}+ usagePlan={usagePlan}+ from="paywall"+ title={(t) => <DialogTitle>{t}</DialogTitle>}+ description={(d) => <DialogDescription>{d}</DialogDescription>}+ />+ <Link+ to="/billing"+ className="text-muted-foreground hover:text-foreground text-center text-xs underline-offset-2 hover:underline"+ >+ See billing details+ </Link>+ </DialogContent>+ </Dialog>+ )+}++// The notice and its actions, shared by the modal and the Billing page.+export function HaltNoticeBody({+ reason,+ usagePlan,+ from,+ title = (t) => <h2 className="text-base font-semibold">{t}</h2>,+ description = (d) => <p className="text-muted-foreground text-sm">{d}</p>,+}: {+ reason: string | null | undefined+ usagePlan: ReturnType<typeof useCreditState>['usagePlan']+ from: 'paywall' | 'billing_page'+ title?: (text: string) => ReactNode+ description?: (text: string) => ReactNode+}) {+ const notice = haltNotice(reason)+ const actions = useBillingActions({ from, usagePlan })+ // Never offer the plan the org is already on (out of credits on Max).+ const plans = PAID_PLANS.filter(+ (plan) => reason === 'lapsed' || plan !== usagePlan,+ )+ return (+ <div className="grid gap-4">+ <DialogHeader className="text-left">+ {title(notice.title)}+ {description(notice.body)}+ </DialogHeader>+ {notice.actions.map((action) => {+ if (action === 'plans' && plans.length > 0) {+ return (+ <div key={action} className="grid gap-2 sm:grid-cols-2">+ {plans.map((plan) => (+ <Button+ key={plan}+ className="h-auto flex-col items-start gap-0.5 py-2.5"+ variant={plan === 'pro' ? 'default' : 'outline'}+ disabled={actions.pending}+ onClick={() => actions.subscribe.mutate(plan)}+ >+ <span>+ {PLAN_NAMES[plan]} · ${PLAN_OFFERS[plan].priceUsd}/mo+ </span>+ <span className="text-xs font-normal opacity-80">+ {formatMinutes(PLAN_OFFERS[plan].minutes)} a month+ </span>+ </Button>+ ))}+ </div>+ )+ }+ if (action === 'credits') {+ return (+ <div key={action} className="grid gap-1.5">+ <span className="text-muted-foreground text-xs">+ {BILLING_ACTION_LABELS.credits}+ </span>+ <div className="grid grid-cols-3 gap-2">+ {CREDIT_PACKS_USD.map((usd) => (+ <Button+ key={usd}+ variant="outline"+ disabled={actions.pending}+ onClick={() => actions.buyPack.mutate(usd)}+ >+ ${usd}+ </Button>+ ))}+ </div>+ </div>+ )+ }+ if (action === 'card') {+ return (+ <Button+ key={action}+ disabled={actions.pending}+ onClick={() => actions.portal.mutate()}+ >+ {actions.portal.isPending ? (+ <Loader2 className="animate-spin" />+ ) : null}+ {BILLING_ACTION_LABELS.card}+ </Button>+ )+ }+ return null+ })}+ </div>+ )+}diff --git a/web/src/components/post-session-upsell.tsx b/web/src/components/post-session-upsell.tsxindex 6dc9fe4d..5e197f30 100644--- a/web/src/components/post-session-upsell.tsx+++ b/web/src/components/post-session-upsell.tsx@@ -5,11 +5,11 @@ import { Panel } from '@/components/panel'import { Button } from '@/components/ui/button'import { useCreditState } from '@/hooks/useCreditState'import {- BASE_GRANT_CENTS,+ PLAN_OFFERS,UPGRADE_PLAN,- UPGRADE_PLAN_LABEL,billingOnrampV2Enabled,- formatCredits,+ formatMinutes,+ planPriceLabel,trackFirstSessionCompleted,trackUpsellClicked,trackUpsellShown,@@ -39,9 +39,9 @@ function rememberSession(sessionId: string): { index: number; show: boolean } {}}-// Shown under a serverless-agent session once it has finished a turn. Sessions-// don't expose per-session cost, so the card speaks in terms of the org's free-// credit grant instead.+// Shown under a serverless-agent session once it has finished a turn, during+// the trial. Sessions don't expose per-session cost, so the card speaks in+// terms of the trial's work minutes instead.export function PostSessionUpsell({sessionId,completed,@@ -51,18 +51,19 @@ export function PostSessionUpsell({completed: booleanclassName?: string}) {- const { usagePlan, isHalted, creditsRemainingCents } = useCreditState()- const spentCents =- creditsRemainingCents === undefined- ? null- : Math.max(0, BASE_GRANT_CENTS - creditsRemainingCents)+ const { billing, usagePlan, isHalted, creditsRemainingCents } =+ useCreditState()+ const minutes = billing?.workMinutes ?? null+ const spentMinutes = minutes+ ? Math.max(0, minutes.granted - minutes.remaining)+ : nullconst eligible =billingOnrampV2Enabled &&completed &&- usagePlan === 'base' &&+ usagePlan === 'trial' &&!isHalted &&- spentCents !== null &&- spentCents > 0+ spentMinutes !== null &&+ spentMinutes > 0const seen = eligible ? rememberSession(sessionId) : nullconst show = seen?.show ?? false@@ -71,7 +72,6 @@ export function PostSessionUpsell({if (seen?.index === 0)trackFirstSessionCompleted({sessionId,- costCents: spentCents ?? 0,usagePlan,})trackUpsellShown({@@ -83,7 +83,7 @@ export function PostSessionUpsell({// eslint-disable-next-line react-hooks/exhaustive-deps}, [show, sessionId])- if (!show || spentCents === null) return null+ if (!show || !minutes || spentMinutes === null) return nullreturn (<PanelclassName={`flex flex-wrap items-center justify-between gap-4 p-4 ${className ?? ''}`}@@ -92,18 +92,19 @@ export function PostSessionUpsell({<Sparkles className="text-muted-foreground mt-0.5 size-4 shrink-0" /><div className="text-sm"><p className="font-medium">- You've used {formatCredits(spentCents)} of your{' '}- {formatCredits(BASE_GRANT_CENTS)} free —{' '}- {formatCredits(creditsRemainingCents ?? 0)} left.+ You've used {formatMinutes(spentMinutes)} of your{' '}+ {formatMinutes(minutes.granted)} trial —{' '}+ {formatMinutes(minutes.remaining)} left.</p><p className="text-muted-foreground mt-0.5">- Upgrade to {UPGRADE_PLAN_LABEL} to keep going when they run out.+ {planPriceLabel(UPGRADE_PLAN)} gives you{' '}+ {formatMinutes(PLAN_OFFERS[UPGRADE_PLAN].minutes)} a month.</p></div></div><Button asChild size="sm"><Link- to={upgradeHref()}+ to={upgradeHref(UPGRADE_PLAN)}onClick={() =>trackUpsellClicked({surface: 'post_session_card',@@ -113,7 +114,7 @@ export function PostSessionUpsell({})}>- Upgrade to {UPGRADE_PLAN_LABEL}+ Upgrade to {planPriceLabel(UPGRADE_PLAN)}</Link></Button></Panel>diff --git a/web/src/components/session-conversation.test.tsx b/web/src/components/session-conversation.test.tsxindex ac6da674..c302de2a 100644--- a/web/src/components/session-conversation.test.tsx+++ b/web/src/components/session-conversation.test.tsx@@ -33,15 +33,14 @@ describe('HttpRequestCard', () => {})describe('MessageBubble', () => {- it('offers the Pro upgrade, not a top-up, when the agent is out of credits', () => {+ it('sends an out-of-credits agent to the plan picker', () => {const markup = renderToStaticMarkup(<MemoryRouter><MessageBubble label="Agent" text="Out of credits" outOfCredits /></MemoryRouter>,)- expect(markup).toContain('href="/billing?plan=max"')- expect(markup).toContain('Upgrade to Pro ($200/mo)')- expect(markup).not.toMatch(/top.?up/i)+ expect(markup).toContain('href="/billing#plans"')+ expect(markup).toContain('Choose a plan')})})diff --git a/web/src/components/session-conversation.tsx b/web/src/components/session-conversation.tsxindex 45df343f..b121fdc6 100644--- a/web/src/components/session-conversation.tsx+++ b/web/src/components/session-conversation.tsx@@ -3,7 +3,7 @@ import { Link } from 'react-router-dom'import { Hourglass } from 'lucide-react'import type { SessionEvent } from '@/api/client'import { Button } from '@/components/ui/button'-import { UPGRADE_PLAN_LABEL, upgradeHref } from '@/lib/billing-onramp'+import { CHOOSE_PLAN_LABEL, upgradeHref } from '@/lib/billing-onramp'import {bodyText,httpRequestPayloadText,@@ -75,7 +75,7 @@ export function MessageBubble({<p className="text-foreground/90 text-sm whitespace-pre-wrap">{text}</p>{outOfCredits ? (<Button asChild size="sm" className="mt-2">- <Link to={upgradeHref()}>Upgrade to {UPGRADE_PLAN_LABEL}</Link>+ <Link to={upgradeHref()}>{CHOOSE_PLAN_LABEL}</Link></Button>) : null}</div>diff --git a/web/src/hooks/useBillingActions.ts b/web/src/hooks/useBillingActions.tsnew file mode 100644index 00000000..74ef7bb8--- /dev/null+++ b/web/src/hooks/useBillingActions.ts@@ -0,0 +1,78 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'+import {+ autumnBillingPortal,+ autumnSubscribeUsagePlan,+ autumnTopup,+ type CheckoutFrom,+} from '@/api/client'+import { notifyError } from '@/lib/errors'+import {+ PLAN_NAMES,+ formatUsd,+ trackCheckoutStarted,+ trackPlanActivated,+ type PaidPlanId,+ type UsagePlanId,+} from '@/lib/billing-onramp'++// The three ways out of a billing prompt: open a plan checkout, buy a credit+// pack, or fix the card on Stripe. A returned url is a hosted Stripe page+// (no card on file yet); null means Autumn charged the saved card already.+export function useBillingActions(options: {+ from: CheckoutFrom+ usagePlan?: UsagePlanId+ onPlanChanged?: (plan: PaidPlanId) => void+}) {+ const queryClient = useQueryClient()+ const refresh = () =>+ void queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })++ const subscribe = useMutation({+ mutationFn: (plan: PaidPlanId) =>+ autumnSubscribeUsagePlan(plan, options.from),+ onSuccess: (data, plan) => {+ trackCheckoutStarted({ plan, usagePlan: options.usagePlan })+ options.onPlanChanged?.(plan)+ if (data.url) {+ window.location.href = data.url+ return+ }+ toast.success(`${PLAN_NAMES[plan]} plan updated`, {+ description: 'Your minutes and billing status are refreshing.',+ })+ trackPlanActivated({ plan, usagePlan: options.usagePlan })+ refresh()+ },+ onError: (e) => notifyError("Couldn't update your plan.", e),+ })++ const buyPack = useMutation({+ // 1 credit = $1 in the Autumn catalog.+ mutationFn: (usd: number) => autumnTopup(usd),+ onSuccess: (data, usd) => {+ if (data.url) {+ window.location.href = data.url+ return+ }+ toast.success(`${formatUsd(usd * 100)} of credits added`)+ refresh()+ },+ onError: (e) => notifyError("Couldn't buy credits.", e),+ })++ const portal = useMutation({+ mutationFn: autumnBillingPortal,+ onSuccess: (data) => {+ window.location.href = data.url+ },+ onError: (e) => notifyError("Couldn't open the billing portal.", e),+ })++ return {+ subscribe,+ buyPack,+ portal,+ pending: subscribe.isPending || buyPack.isPending || portal.isPending,+ }+}diff --git a/web/src/hooks/useCreditState.ts b/web/src/hooks/useCreditState.tsindex 6301b30f..8f8cb2d7 100644--- a/web/src/hooks/useCreditState.ts+++ b/web/src/hooks/useCreditState.ts@@ -2,8 +2,6 @@ import { useQuery } from '@tanstack/react-query'import { getAutumnBilling } from '@/api/client'import type { AutumnBilling } from '@/api/schemas'import {- billingOnrampV2Enabled,- lowCreditThresholdCents,upgradePlanFor,type UpgradePlanId,type UsagePlanId,@@ -14,19 +12,18 @@ export interface CreditState {usagePlan: UsagePlanId | undefinedcreditsRemainingCents: number | undefinedisHalted: boolean- // Out of credits on base: agent sessions are blocked until the org upgrades.+ // Halted orgs can't start agent sessions until they pay (serverless-agents-ws+ // 086: no fallback model on any plan).sessionsBlocked: boolean- // Out of credits on Pro/Max: agents keep running on the fallback model.- modelFallback: boolean- // Below the low-credit threshold but not yet halted; only for prepaid orgs- // with the on-ramp experiment enabled.- isLow: boolean- // The plan to prompt for (always the $200 Pro, Autumn id `max`); null when- // the org is already on it. Legacy $20 Pro is never offered.+ // orgs.halt_reason while halted, and orgs.billing_warning before that.+ haltReason: string | null+ warning: string | null+ // The plan to prompt for: Pro from the trial, Max from Pro; null on Max.upgradePlan: UpgradePlanId | null}-// Shares the same 30s poll as useHalted/HaltBanner via the 'autumn-billing' key.+// Shares the same 30s poll as useHalted and the app shell via the+// 'autumn-billing' key.export function useCreditState(): CreditState {const { data } = useQuery({queryKey: ['autumn-billing'],@@ -36,20 +33,14 @@ export function useCreditState(): CreditState {})const usagePlan = data?.usagePlanconst isHalted = data?.isHalted ?? false- const paid = usagePlan === 'pro' || usagePlan === 'max'- const isLow =- billingOnrampV2Enabled &&- !isHalted &&- data !== undefined &&- data.creditsRemainingCents <= lowCreditThresholdCents(data.usagePlan)return {billing: data,usagePlan,creditsRemainingCents: data?.creditsRemainingCents,isHalted,- sessionsBlocked: isHalted && !paid,- modelFallback: isHalted && paid,- isLow,- upgradePlan: upgradePlanFor(usagePlan ?? 'base'),+ sessionsBlocked: isHalted,+ haltReason: isHalted ? (data?.haltReason ?? null) : null,+ warning: isHalted ? null : (data?.warning ?? null),+ upgradePlan: upgradePlanFor(usagePlan ?? 'trial'),}}diff --git a/web/src/hooks/useHalted.ts b/web/src/hooks/useHalted.tsindex 0a80fcbf..775acc87 100644--- a/web/src/hooks/useHalted.ts+++ b/web/src/hooks/useHalted.ts@@ -1,9 +1,9 @@import { useQuery } from '@tanstack/react-query'import { getAutumnBilling } from '@/api/client'-// Out-of-credits state for the credit-gated agent controls (composer,-// new-session), sharing the halt banner's 30s poll. Only base orgs are blocked:-// Pro/Max orgs keep running agents on the fallback model once credits run out.+// Halted state for the credit-gated agent controls (composer, new-session),+// sharing the app shell's 30s poll. Every plan halts the same way now+// (serverless-agents-ws 086: no fallback model for paid orgs).// Autumn orgs only; legacy orgs 404 on /billing/autumn → error → treated as not halted.export function useHalted(): boolean {const { data } = useQuery({@@ -12,6 +12,5 @@ export function useHalted(): boolean {retry: false,refetchInterval: (q) => (q.state.error ? false : 30_000),})- if (!data?.isHalted) return false- return data.usagePlan !== 'pro' && data.usagePlan !== 'max'+ return data?.isHalted ?? false}diff --git a/web/src/lib/billing-onramp.test.ts b/web/src/lib/billing-onramp.test.tsindex b2873b61..96e4afd3 100644--- a/web/src/lib/billing-onramp.test.ts+++ b/web/src/lib/billing-onramp.test.ts@@ -1,54 +1,142 @@import { describe, expect, it } from 'vitest'import {- FREE_CREDITS_PAYWALL,PLAN_NAMES,- UPGRADE_PLAN,- UPGRADE_PLAN_LABEL,+ TRIAL_PAYWALL,+ billingActionHref,+ billingPillText,deepLinkedPlanFor,formatCredits,- selectablePaidPlans,+ haltNotice,+ planChangeTiming,+ planPriceLabel,upgradeHref,upgradePlanFor,+ warningNotice,} from '@/lib/billing-onramp'+const NOW = new Date('2026-06-26T12:00:00Z').getTime()+const inDays = (days: number) => new Date(NOW + days * 86_400_000).toISOString()+describe('billing on-ramp plans', () => {- it('sells only the $200 plan (Autumn id max), named Pro', () => {- expect(UPGRADE_PLAN).toBe('max')+ it('names the trial and the $20 / $200 plans', () => {expect(PLAN_NAMES).toEqual({+ trial: 'Trial',base: 'Free',- pro: 'Pro (legacy)',- max: 'Pro',+ pro: 'Pro',+ max: 'Max',})- expect(UPGRADE_PLAN_LABEL).toBe('Pro ($200/mo)')- expect(upgradeHref()).toBe('/billing?plan=max')+ expect(planPriceLabel('pro')).toBe('Pro ($20/mo)')+ expect(planPriceLabel('max')).toBe('Max ($200/mo)')+ expect(upgradeHref()).toBe('/billing#plans')+ expect(upgradeHref('pro')).toBe('/billing?plan=pro')+ expect(billingActionHref('card', 'warning')).toBe(+ '/billing?from=warning#payment',+ )+ expect(billingActionHref('credits')).toBe('/billing#credits')})- it('prompts Free and legacy Pro orgs to the $200 Pro, and nobody to legacy Pro', () => {- expect(upgradePlanFor('base')).toBe('max')+ it('prompts the trial to Pro and Pro to Max', () => {+ expect(upgradePlanFor('trial')).toBe('pro')+ expect(upgradePlanFor('base')).toBe('pro')expect(upgradePlanFor('pro')).toBe('max')expect(upgradePlanFor('max')).toBeNull()})- it('lists legacy Pro only to its own subscribers', () => {- expect(selectablePaidPlans('base')).toEqual(['max'])- expect(selectablePaidPlans('max')).toEqual(['max'])- expect(selectablePaidPlans('pro')).toEqual(['pro', 'max'])+ it('upgrades now and moves $200 to $20 at the end of the period', () => {+ expect(planChangeTiming('trial', 'pro')).toBe('now')+ expect(planChangeTiming('pro', 'max')).toBe('now')+ expect(planChangeTiming('max', 'pro')).toBe('period_end')})- it('opens the $200 Pro checkout for ?plan= deep links, old plan=pro links included', () => {- expect(deepLinkedPlanFor('max', 'base')).toBe('max')- expect(deepLinkedPlanFor('pro', 'base')).toBe('max')- expect(deepLinkedPlanFor('pro', 'pro')).toBe('max')- expect(deepLinkedPlanFor('max', 'max')).toBeNull()- expect(deepLinkedPlanFor(null, 'base')).toBeNull()- expect(deepLinkedPlanFor('top_up', 'base')).toBeNull()+ it('opens the linked checkout for upgrades only', () => {+ expect(deepLinkedPlanFor('pro', 'trial')).toBe('pro')+ expect(deepLinkedPlanFor('max', 'trial')).toBe('max')+ expect(deepLinkedPlanFor('max', 'pro')).toBe('max')+ expect(deepLinkedPlanFor('pro', 'pro')).toBeNull()+ expect(deepLinkedPlanFor('pro', 'max')).toBeNull()+ expect(deepLinkedPlanFor(null, 'trial')).toBeNull()+ expect(deepLinkedPlanFor('top_up', 'trial')).toBeNull()})- it('uses one paywall message without the grant amount or a top-up', () => {- expect(FREE_CREDITS_PAYWALL).toBe(- "You've used your free credits. Upgrade to Pro ($200/mo) to keep going.",+ it('states both plans in the paywall', () => {+ expect(TRIAL_PAYWALL).toBe(+ 'Your free trial is over. Choose $20 or $200 a month to keep going.',)- expect(FREE_CREDITS_PAYWALL).not.toMatch(/top.?up|\$5\b|\$10\b/i)+ })+})++describe('billingPillText', () => {+ it('shows the trial minutes and days left', () => {+ expect(+ billingPillText(+ {+ usagePlan: 'trial',+ creditsRemainingCents: 1_000,+ workMinutes: { granted: 600, remaining: 412 },+ trialEndsAt: inDays(4.5),+ },+ NOW,+ ),+ ).toBe('Trial · 412 min · 5 days left')+ })++ it('shows minutes left of the allowance and credits on a paid plan', () => {+ expect(+ billingPillText({+ usagePlan: 'pro',+ creditsRemainingCents: 1_200,+ workMinutes: { granted: 2_000, remaining: 1_240 },+ }),+ ).toBe('1,240 / 2,000 min · $12 credits')+ })++ it('shows nothing for the old free tier', () => {+ expect(+ billingPillText({ usagePlan: 'base', creditsRemainingCents: 500 }),+ ).toBeNull()+ })+})++describe('haltNotice', () => {+ it.each([+ ['trial_minutes', ['plans']],+ ['trial_days', ['plans']],+ ['trial_tokens', ['plans']],+ ['credits_empty', ['credits', 'plans']],+ ['credits_exhausted', ['credits', 'plans']],+ ['payment', ['card']],+ ['lapsed', ['plans']],+ [null, ['plans']],+ ])('offers the way out of %s', (reason, actions) => {+ expect(haltNotice(reason).actions).toEqual(actions)+ })++ it('words the trial halts as the end of the trial', () => {+ const notice = haltNotice('trial_days')+ expect(notice.title).toBe('Your free trial is over')+ expect(notice.body).toContain('7-day trial has ended')+ expect(notice.body).toContain('$20')+ })+})++describe('warningNotice', () => {+ const billing = {+ creditsRemainingCents: 250,+ workMinutes: { remaining: 45 },+ trialEndsAt: inDays(2),+ }++ it.each([+ ['trial_minutes', 'Your trial has 45 min of work left.', 'plans'],+ ['trial_days', 'Your trial ends in 2 days.', 'plans'],+ ['credits_low', 'Your credits are running low ($2.50 left).', 'credits'],+ [+ 'payment_failed',+ 'Your last payment failed. Update your card to avoid a pause.',+ 'card',+ ],+ ])('words %s', (warning, text, action) => {+ expect(warningNotice(warning, billing, NOW)).toEqual({ text, action })})})diff --git a/web/src/lib/billing-onramp.ts b/web/src/lib/billing-onramp.tsindex f69010ab..2fe645dc 100644--- a/web/src/lib/billing-onramp.ts+++ b/web/src/lib/billing-onramp.ts@@ -1,84 +1,254 @@import posthog from 'posthog-js'import { USAGE_PLAN_NAMES } from '@/lib/plan-label'-// Payment on-ramp experiment (low-credit banner, sidebar meter, post-session-// upsell, Pro paywall copy). Set the build-time value to "0" to fall back to-// the halt-only behaviour.+// Payment on-ramp experiment (header pill, warning banner, post-session+// upsell). Set the build-time value to "0" to fall back to the halt-only+// behaviour.export const billingOnrampV2Enabled =import.meta.env.VITE_BILLING_ONRAMP_V2 !== '0'-export type UsagePlanId = 'base' | 'pro' | 'max'-export type PaidPlanId = Exclude<UsagePlanId, 'base'>+export type UsagePlanId = 'trial' | 'base' | 'pro' | 'max'+export type PaidPlanId = 'pro' | 'max'-// The one plan new customers can buy. Its Autumn id stays `max`; it is shown-// as "Pro". The old $20/mo plan (Autumn id `pro`) is retired: it shows as-// "Pro (legacy)" to its existing subscribers and is never offered to anyone-// else. Top-ups are no longer sold.-export const UPGRADE_PLAN = 'max' as const satisfies PaidPlanId-export type UpgradePlanId = typeof UPGRADE_PLAN+// Work-minute plans (serverless-agents-ws 086): a 7-day trial with 600 work+// minutes and $10 of model credits, then Pro ($20/mo, 2,000 min) or Max+// ($200/mo, 25,000 min). Past the allowance, work draws prepaid credits at+// $0.01/min, bought in packs.+export const TRIAL_DAYS = 7+export const TRIAL_MINUTES = 600+export const TRIAL_CREDITS_USD = 10+export const OVERAGE_USD_PER_MINUTE = 0.01+export const CREDIT_PACKS_USD = [10, 50, 200] as const+export type CreditPackUsd = (typeof CREDIT_PACKS_USD)[number]++export const PAID_PLANS: PaidPlanId[] = ['pro', 'max']export const PLAN_OFFERS: Record<PaidPlanId,- { priceUsd: number; creditsUsd: number }+ { priceUsd: number; minutes: number }> = {- pro: { priceUsd: 20, creditsUsd: 200 },- max: { priceUsd: 200, creditsUsd: 2000 },+ pro: { priceUsd: 20, minutes: 2_000 },+ max: { priceUsd: 200, minutes: 25_000 },}export const PLAN_NAMES: Record<UsagePlanId, string> = USAGE_PLAN_NAMES-export const UPGRADE_OFFER = PLAN_OFFERS[UPGRADE_PLAN]--// "Pro ($200/mo)": how every upgrade prompt names the plan to buy.-export const UPGRADE_PLAN_LABEL = `${PLAN_NAMES[UPGRADE_PLAN]} ($${UPGRADE_OFFER.priceUsd}/mo)`--// The free-tier paywall, the same on every surface. It does not state the-// grant amount: that is still $5 today and changes in a later step.-export const FREE_CREDITS_USED = "You've used your free credits."-export const FREE_CREDITS_PAYWALL = `${FREE_CREDITS_USED} Upgrade to ${UPGRADE_PLAN_LABEL} to keep going.`+// The entry plan, offered first wherever one plan is named.+export const UPGRADE_PLAN = 'pro' as const satisfies PaidPlanId+export type UpgradePlanId = PaidPlanId-// Monthly grant per plan; the base grant is the signup allowance.-export const BASE_GRANT_CENTS = 1_000-const PLAN_GRANT_CENTS: Record<UsagePlanId, number> = {- base: BASE_GRANT_CENTS,- pro: 20_000,- max: 200_000,+// "Pro ($20/mo)".+export function planPriceLabel(plan: PaidPlanId): string {+ return `${PLAN_NAMES[plan]} ($${PLAN_OFFERS[plan].priceUsd}/mo)`}-const LOW_CREDIT_FRACTION = 0.3-export function planGrantCents(plan: UsagePlanId): number {- return PLAN_GRANT_CENTS[plan]-}+// How a prompt that doesn't name one plan sends people to the picker.+export const CHOOSE_PLAN_LABEL = 'Choose a plan'-export function lowCreditThresholdCents(plan: UsagePlanId): number {- return Math.round(PLAN_GRANT_CENTS[plan] * LOW_CREDIT_FRACTION)-}+// Composer and new-session gates while halted; the halt modal says why.+export const WORK_PAUSED = 'Work is paused.'+export const WORK_PAUSED_TITLE = `${WORK_PAUSED} Open Billing to resume.`++export const TRIAL_OVER = 'Your free trial is over.'+export const TRIAL_PAYWALL = `${TRIAL_OVER} Choose $20 or $200 a month to keep going.`-// The plan an org is prompted to upgrade to: always the $200 Pro, from Free-// and from legacy Pro alike. null when the org is already on it.+// The plan an org is prompted to upgrade to: Pro from the trial, Max from Pro.export function upgradePlanFor(plan: UsagePlanId): UpgradePlanId | null {- return plan === UPGRADE_PLAN ? null : UPGRADE_PLAN+ if (plan === 'max') return null+ return plan === 'pro' ? 'max' : 'pro'}-export function upgradeHref(plan: PaidPlanId = UPGRADE_PLAN): string {- return `/billing?plan=${plan}`+// No plan → the picker on the Billing page.+export function upgradeHref(plan?: PaidPlanId): string {+ return plan ? `/billing?plan=${plan}` : '/billing#plans'}-// Paid plans an org may pick on the Billing page: the $200 Pro for everyone,-// plus legacy Pro only for an org already subscribed to it.-export function selectablePaidPlans(current: UsagePlanId): PaidPlanId[] {- return current === 'pro' ? ['pro', UPGRADE_PLAN] : [UPGRADE_PLAN]+// When a switch to `target` takes effect: upgrades now, $200 → $20 at the end+// of the period (the edge asks Autumn for the same).+export function planChangeTiming(+ current: UsagePlanId,+ target: PaidPlanId,+): 'now' | 'period_end' {+ return current === 'max' && target === 'pro' ? 'period_end' : 'now'}-// `?plan=` deep link → the plan whose checkout to open. Older links (and-// agent transcripts) still carry `plan=pro`; for anyone not on legacy Pro they-// mean "upgrade", so they open the $200 Pro. Never opens legacy Pro checkout.+// `?plan=` deep link → the checkout to open. Only upgrades: a link never+// downgrades an org or reopens the plan it is on.export function deepLinkedPlanFor(requested: string | null,current: UsagePlanId,-): UpgradePlanId | null {+): PaidPlanId | null {if (requested !== 'pro' && requested !== 'max') return null- return current === UPGRADE_PLAN ? null : UPGRADE_PLAN+ if (requested === current) return null+ return planChangeTiming(current, requested) === 'now' ? requested : null+}++const minuteNumber = new Intl.NumberFormat('en-US', {+ maximumFractionDigits: 0,+})++export function formatMinutes(minutes: number): string {+ return `${minuteNumber.format(minutes)} min`+}++// "$12", "$2.50".+export function formatUsd(cents: number): string {+ const whole = cents % 100 === 0+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+ minimumFractionDigits: whole ? 0 : 2,+ maximumFractionDigits: whole ? 0 : 2,+ }).format(cents / 100)+}++// Whole days left until `iso`, never negative.+export function daysUntil(iso: string, now = Date.now()): number {+ return Math.max(0, Math.ceil((new Date(iso).getTime() - now) / 86_400_000))+}++interface PillSource {+ usagePlan: UsagePlanId+ creditsRemainingCents: number+ workMinutes?: { granted: number; remaining: number } | null+ trialEndsAt?: string | null+}++// The header pill: "Trial · 412 min · 5 days left" or+// "1,240 / 2,000 min · $12 credits" (minutes left of the month's allowance).+export function billingPillText(+ b: PillSource,+ now = Date.now(),+): string | null {+ const minutes = b.workMinutes+ if (b.usagePlan === 'trial') {+ const parts = ['Trial']+ if (minutes) parts.push(formatMinutes(minutes.remaining))+ if (b.trialEndsAt) {+ const days = daysUntil(b.trialEndsAt, now)+ parts.push(`${days} ${days === 1 ? 'day' : 'days'} left`)+ }+ return parts.join(' · ')+ }+ if (b.usagePlan === 'base' || !minutes) return null+ return `${minuteNumber.format(minutes.remaining)} / ${formatMinutes(minutes.granted)} · ${formatUsd(b.creditsRemainingCents)} credits`+}++export type BillingAction = 'plans' | 'credits' | 'card'++export interface BillingNotice {+ title: string+ body: string+ actions: BillingAction[]+}++const TRIAL_HALTS: Record<string, string> = {+ trial_minutes: `You've used the trial's ${TRIAL_MINUTES} work minutes.`,+ trial_days: `Your ${TRIAL_DAYS}-day trial has ended.`,+ trial_tokens: `You've used the trial's $${TRIAL_CREDITS_USD} of model credits.`,+}++// The blocking modal shown on every page while the org is halted, worded by+// orgs.halt_reason.+export function haltNotice(reason: string | null | undefined): BillingNotice {+ if (reason && reason in TRIAL_HALTS) {+ return {+ title: TRIAL_OVER.replace(/\.$/, ''),+ body: `${TRIAL_HALTS[reason]} Choose Pro ($20/mo) or Max ($200/mo) to keep your computer and automations running.`,+ actions: ['plans'],+ }+ }+ if (reason === 'credits_empty' || reason === 'credits_exhausted') {+ return {+ title: "You're out of credits",+ body: "You've used this month's work minutes and your prepaid credits. Buy credits or upgrade to keep going.",+ actions: ['credits', 'plans'],+ }+ }+ if (reason === 'payment') {+ return {+ title: 'Your payment failed',+ body: "We couldn't charge your card, so work is paused. Update your card to keep going.",+ actions: ['card'],+ }+ }+ return {+ title: 'Your plan has ended',+ body: 'Work is paused. Choose a plan to keep going.',+ actions: ['plans'],+ }+}++// The banner shown while orgs.billing_warning is set, before any halt.+export function warningNotice(+ warning: string,+ b: {+ workMinutes?: { remaining: number } | null+ trialEndsAt?: string | null+ creditsRemainingCents: number+ },+ now = Date.now(),+): { text: string; action: BillingAction } {+ switch (warning) {+ case 'trial_minutes':+ return {+ text: `Your trial has ${formatMinutes(b.workMinutes?.remaining ?? 0)} of work left.`,+ action: 'plans',+ }+ case 'trial_days': {+ const days = b.trialEndsAt ? daysUntil(b.trialEndsAt, now) : 0+ return {+ text:+ days <= 1+ ? 'Your trial ends tomorrow.'+ : `Your trial ends in ${days} days.`,+ action: 'plans',+ }+ }+ case 'trial_tokens':+ return {+ text: "Your trial's model credits are almost used up.",+ action: 'plans',+ }+ case 'allowance_80':+ return {+ text: "You've used 80% of this month's work minutes. After that, work draws credits at $0.01/min.",+ action: 'credits',+ }+ case 'credits_low':+ return {+ text: `Your credits are running low (${formatUsd(b.creditsRemainingCents)} left).`,+ action: 'credits',+ }+ case 'payment_failed':+ return {+ text: 'Your last payment failed. Update your card to avoid a pause.',+ action: 'card',+ }+ default:+ return { text: 'Check your plan and credits.', action: 'plans' }+ }+}++export const BILLING_ACTION_LABELS: Record<BillingAction, string> = {+ plans: CHOOSE_PLAN_LABEL,+ credits: 'Buy credits',+ card: 'Update card',+}++const ACTION_SECTIONS: Record<BillingAction, string> = {+ plans: 'plans',+ credits: 'credits',+ card: 'payment',+}++// Where each action lands on the Billing page; `from` rides along so a+// checkout opened there is attributed to the prompt (billing.checkout_opened).+export function billingActionHref(+ action: BillingAction,+ from?: 'paywall' | 'warning',+): string {+ return `/billing${from ? `?from=${from}` : ''}#${ACTION_SECTIONS[action]}`}// Cents of usage per credit (1 credit = $1 in the Autumn catalog today).@@ -99,9 +269,9 @@ export function formatCredits(cents: number): string {}export type UpsellSurface =- | 'sidebar_meter'- | 'low_credit_banner'- | 'halt_banner'+ | 'header_pill'+ | 'warning_banner'+ | 'halt_modal'| 'session_composer'| 'post_session_card'| 'byok_gate'@@ -171,3 +341,13 @@ export function trackFirstSessionCompleted(props: {}): void {posthog.capture('first_session_completed', props)}++// Work-minute plan funnel (serverless-agents-ws 086, "Surfaces"): the same+// events the CLI and the edge send, tagged with where they were seen.+export function trackWarningShown(reason: string): void {+ posthog.capture('billing.warning_shown', { reason, surface: 'web' })+}++export function trackPaywallShown(reason: string): void {+ posthog.capture('billing.paywall_shown', { reason, surface: 'web' })+}diff --git a/web/src/lib/plan-label.test.ts b/web/src/lib/plan-label.test.tsindex 06637c6b..1d16b1b3 100644--- a/web/src/lib/plan-label.test.ts+++ b/web/src/lib/plan-label.test.ts@@ -22,9 +22,10 @@ describe('planLabel', () => {describe('usagePlanLabel', () => {it.each([+ ['trial', 'Trial'],['base', 'Free'],- ['pro', 'Pro (legacy)'],- ['max', 'Pro'],+ ['pro', 'Pro'],+ ['max', 'Max'],['enterprise_custom', 'Enterprise Custom'],])('names usage plan %s as %s', (plan, label) => {expect(usagePlanLabel(plan)).toBe(label)@@ -46,14 +47,17 @@ describe('organizationPlanLabel', () => {usagePlan: 'max',},),- ).toBe('Pro')+ ).toBe('Max')})- it('labels the retired $20 plan as legacy and the free plan as Free', () => {+ it('names the $20 plan Pro, the trial Trial and the old free tier Free', () => {const autumnBilling = { plan: 'free', billingProvider: 'autumn' }expect(organizationPlanLabel(org, autumnBilling, { usagePlan: 'pro' }),- ).toBe('Pro (legacy)')+ ).toBe('Pro')+ expect(+ organizationPlanLabel(org, autumnBilling, { usagePlan: 'trial' }),+ ).toBe('Trial')expect(organizationPlanLabel(org, autumnBilling, { usagePlan: 'base' }),).toBe('Free')diff --git a/web/src/lib/plan-label.ts b/web/src/lib/plan-label.tsindex aa202da8..9764d1ef 100644--- a/web/src/lib/plan-label.ts+++ b/web/src/lib/plan-label.ts@@ -1,13 +1,18 @@-// Display names of the Autumn usage plans. `max` ($200/mo) is sold as "Pro";-// the retired $20/mo plan (id `pro`) is "Pro (legacy)" for its subscribers.-export const USAGE_PLAN_NAMES: Record<'base' | 'pro' | 'max', string> = {+// Display names of the Autumn usage plans (serverless-agents-ws 086): the+// 7-day trial, Pro ($20/mo, 2,000 work minutes) and Max ($200/mo, 25,000).+// `base` is the pre-trial free tier, until those orgs are migrated.+export const USAGE_PLAN_NAMES: Record<+ 'trial' | 'base' | 'pro' | 'max',+ string+> = {+ trial: 'Trial',base: 'Free',- pro: 'Pro (legacy)',- max: 'Pro',+ pro: 'Pro',+ max: 'Max',}export function usagePlanLabel(plan: string): string {- return plan === 'base' || plan === 'pro' || plan === 'max'+ return plan === 'trial' || plan === 'base' || plan === 'pro' || plan === 'max'? USAGE_PLAN_NAMES[plan]: planLabel(plan)}diff --git a/web/src/managed-agents/AgentStep.test.tsx b/web/src/managed-agents/AgentStep.test.tsxindex 2a589e82..8ab7dc14 100644--- a/web/src/managed-agents/AgentStep.test.tsx+++ b/web/src/managed-agents/AgentStep.test.tsx@@ -257,7 +257,9 @@ describe('choosing the coding agent', () => {await show({ ...empty, agent: fresh }, 'Choose your coding agent')expect(text()).toContain('Step 1 of 4')expect(text()).toContain('Bring your own subscription.')- expect(text()).toContain('No subscription? Start with $10 free.')+ expect(text()).toContain(+ 'No subscription? Your trial includes $10 of model credits.',+ )expect(text()).toContain('Runs Claude Opus 5.5 on our credits.')expect(text()).toContain('Claude Code on its own machine')expect(capture).toHaveBeenCalledWith('computer.setup.agent_shown')@@ -971,11 +973,11 @@ describe('choosing the coding agent', () => {...fresh,choice: 'credits',})- act(() => button('Use free credits')!.click())+ act(() => button('Use OpenComputer credits')!.click())await settle(() => text().includes('Step 2 of 4'), 'Slack step')expect(computerApi.setAgentChoice).toHaveBeenCalledWith('credits')expect(computerApi.disconnectClaudeSubscription).not.toHaveBeenCalled()- expect(text()).toContain('Claude Opus 5.5 · free credits')+ expect(text()).toContain('Claude Opus 5.5 · OpenComputer credits')expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {choice: 'credits',})@@ -998,7 +1000,7 @@ describe('choosing the coding agent', () => {await settle(() => command() !== undefined, 'command')openPaste()expect(button('Replace token')).toBeDefined()- expect(text()).toContain('Switch to free credits.')+ expect(text()).toContain('Switch to OpenComputer credits.')expect(text()).toContain('Disconnects Claude Code')// Free credits behind a subscription: disconnect, then record the choice.computerApi.disconnectClaudeSubscription.mockResolvedValue(undefined)@@ -1006,7 +1008,7 @@ describe('choosing the coding agent', () => {...fresh,choice: 'credits',})- act(() => button('Use free credits')!.click())+ act(() => button('Use OpenComputer credits')!.click())await settle(() => computerApi.setAgentChoice.mock.calls.length === 1,'credits choice',@@ -1014,7 +1016,7 @@ describe('choosing the coding agent', () => {expect(computerApi.disconnectClaudeSubscription).toHaveBeenCalledTimes(1)await settle(() => !text().includes('Your coding agent'), 'dialog closed')await settle(- () => text().includes('Claude Opus 5.5 · free credits'),+ () => text().includes('Claude Opus 5.5 · OpenComputer credits'),'credits row',)expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {diff --git a/web/src/managed-agents/AgentStep.tsx b/web/src/managed-agents/AgentStep.tsxindex 8777a762..38ce75a3 100644--- a/web/src/managed-agents/AgentStep.tsx+++ b/web/src/managed-agents/AgentStep.tsx@@ -35,7 +35,7 @@ import {} from '@/components/ui/dropdown-menu'import { Input } from '@/components/ui/input'import { AuthContext } from '@/hooks/useAuth'-import { BASE_GRANT_CENTS } from '@/lib/billing-onramp'+import { TRIAL_CREDITS_USD } from '@/lib/billing-onramp'import { notifyError, notifySuccess } from '@/lib/errors'import { cn } from '@/lib/utils'import {@@ -100,7 +100,6 @@ const disconnectSubscription = (provider: SubscriptionProvider) =>// `claude setup-token` prints a long-lived OAuth token with this prefix.const SETUP_TOKEN = /^sk-ant-oat01-[A-Za-z0-9_-]{20,400}$/const STILL_CHECKING_MS = 10_000-const FREE_DOLLARS = BASE_GRANT_CENTS / 100const Cmd = ({ children }: { children: ReactNode }) => (<code className="bg-muted rounded px-1 py-0.5 font-mono text-[0.85em]">@@ -219,7 +218,8 @@ export function AgentSetup({await setAgent(next)trackAgentChosen(choice)if (choice !== 'credits') return- if (agent.subscription) notifySuccess('Threads run on free credits now.')+ if (agent.subscription)+ notifySuccess('Threads run on OpenComputer credits now.')onDone?.()},onError: (error, choice) => {@@ -227,7 +227,7 @@ export function AgentSetup({reread()notifyError(choice === 'credits'- ? "Couldn't switch to free credits."+ ? "Couldn't switch to OpenComputer credits.": "Couldn't save your choice.",error,)@@ -284,8 +284,8 @@ export function AgentSetup({<div><p className="text-foreground font-semibold">{agent.subscription- ? 'Switch to free credits.'- : `No subscription? Start with $${FREE_DOLLARS} free.`}+ ? 'Switch to OpenComputer credits.'+ : `No subscription? Your trial includes $${TRIAL_CREDITS_USD} of model credits.`}</p><p>{agent.subscription@@ -302,7 +302,9 @@ export function AgentSetup({{choose.isPending && choose.variables === 'credits' ? (<Loader2 className="size-4 animate-spin" aria-hidden />) : null}- {onCredits ? 'Using free credits' : 'Use free credits'}+ {onCredits+ ? 'Using OpenComputer credits'+ : 'Use OpenComputer credits'}</Button></div></>@@ -978,8 +980,8 @@ const HEALTH: Record<> = {ok: 'Connected',unchecked: "Saved. We'll check it when your computer starts.",- paused: 'Paused. Threads run on free credits.',- limited: 'At its limit. Threads run on free credits',+ paused: 'Paused. Threads run on OpenComputer credits.',+ limited: 'At its limit. Threads run on OpenComputer credits',invalid: 'This token stopped working. Replace it, or resume once fixed.',}@@ -1265,7 +1267,7 @@ function ProviderRow({title={`Disconnect ${name}?`}description={runs- ? `Threads run on free credits (${agent.managedModel}) until you connect one again.`+ ? `Threads run on OpenComputer credits (${agent.managedModel}) until you connect one again.`: `${name} stays off until you connect it again.`}confirmLabel="Disconnect"diff --git a/web/src/managed-agents/BYOK.tsx b/web/src/managed-agents/BYOK.tsxindex 8465d4fa..c1a886de 100644--- a/web/src/managed-agents/BYOK.tsx+++ b/web/src/managed-agents/BYOK.tsx@@ -22,7 +22,7 @@ import {} from './project-context'import {UPGRADE_PLAN,- UPGRADE_PLAN_LABEL,+ planPriceLabel,trackUpsellClicked,trackUpsellShown,upgradeHref,@@ -194,11 +194,11 @@ export function ManagedProjectBYOK({<EmptyStateicon={LockKeyhole}title="BYOK is available on Pro"- description={`Bring your own provider keys and route this project's models through them. Available on ${UPGRADE_PLAN_LABEL}.`}+ description={`Bring your own provider keys and route this project's models through them. Available on ${planPriceLabel('pro')} and ${planPriceLabel('max')}.`}action={<Button asChild><Link- to={upgradeHref()}+ to={upgradeHref(UPGRADE_PLAN)}onClick={() =>trackUpsellClicked({surface: 'byok_gate',@@ -206,7 +206,7 @@ export function ManagedProjectBYOK({})}>- Upgrade to {UPGRADE_PLAN_LABEL}+ Upgrade to {planPriceLabel(UPGRADE_PLAN)}</Link></Button>}diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex e393a9e6..bdabd36b 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -77,11 +77,10 @@ import { useLiveSessionEvents } from './use-live-session-events'import { PostSessionUpsell } from '@/components/post-session-upsell'import { useCreditState } from '@/hooks/useCreditState'import {- FREE_CREDITS_USED,- UPGRADE_PLAN,- UPGRADE_PLAN_LABEL,+ BILLING_ACTION_LABELS,+ billingActionHref,+ haltNotice,trackUpsellClicked,- upgradeHref,} from '@/lib/billing-onramp'import { DebugInspector } from './DebugInspector'import { isNearScrollEnd } from './scroll-follow'@@ -527,22 +526,28 @@ function PlaygroundChat({) : null}{halted ? (<p className="text-destructive mb-2 text-xs">- {FREE_CREDITS_USED}{' '}+ {haltNotice(credits.haltReason).title}.{' '}<Link- to={upgradeHref()}+ to={billingActionHref(+ haltNotice(credits.haltReason).actions[0] ?? 'plans',+ 'paywall',+ )}className="font-medium underline"onClick={() =>trackUpsellClicked({surface: 'session_composer',- plan: UPGRADE_PLAN,+ plan: credits.upgradePlan ?? undefined,usagePlan: credits.usagePlan,creditsRemainingCents: credits.creditsRemainingCents,})}>- Upgrade to {UPGRADE_PLAN_LABEL}- </Link>{' '}- to keep going.+ {+ BILLING_ACTION_LABELS[+ haltNotice(credits.haltReason).actions[0] ?? 'plans'+ ]+ }+ </Link></p>) : error ? (<p className="text-destructive mb-2 text-xs">{error.message}</p>diff --git a/web/src/managed-agents/computer-state.test.ts b/web/src/managed-agents/computer-state.test.tsindex 994cbf14..d4f49109 100644--- a/web/src/managed-agents/computer-state.test.ts+++ b/web/src/managed-agents/computer-state.test.ts@@ -311,7 +311,7 @@ describe('choosing the coding agent (work 081)', () => {it('names what runs the threads', () => {expect(agentSummary(connected)).toBe('Claude Code · your subscription')expect(agentSummary({ ...fresh, choice: 'credits' })).toBe(- 'Claude Opus 5.5 · free credits',+ 'Claude Opus 5.5 · OpenComputer credits',)expect(agentSummary({diff --git a/web/src/managed-agents/computer-state.ts b/web/src/managed-agents/computer-state.tsindex d0db8525..c0215765 100644--- a/web/src/managed-agents/computer-state.ts+++ b/web/src/managed-agents/computer-state.ts@@ -199,7 +199,7 @@ export function setupStep(/** The done row of step 1: what runs the person's threads. */export function agentSummary(agent: ComputerAgent): string {- if (!agent.subscription) return `${agent.managedModel} · free credits`+ if (!agent.subscription) return `${agent.managedModel} · OpenComputer credits`return agent.subscription.provider === 'codex'? 'Codex · your ChatGPT plan': 'Claude Code · your subscription'diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex 85677a64..fe9704a5 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -1,13 +1,12 @@import { useEffect, useRef, useState } from 'react'-import { Link, useSearchParams } from 'react-router-dom'+import { Link, useLocation, useSearchParams } from 'react-router-dom'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'import { CircleAlert, CircleCheck } from 'lucide-react'import { notifyError } from '@/lib/errors'import { useTransientFlag } from '@/lib/use-transient-flag'import {- autumnBillingPortal,- autumnSubscribeUsagePlan,+ autumnCancelPlan,billingPortal,billingSetup,getAutumnBilling,@@ -17,6 +16,7 @@ import {redeemPromoCode,setAutumnAutoTopup,type AutumnBilling,+ type CheckoutFrom,type AgentSessionUsageRow,type StripeInvoice,} from '@/api/client'@@ -25,32 +25,37 @@ import { Panel } from '@/components/panel'import { Button } from '@/components/ui/button'import { Skeleton } from '@/components/ui/skeleton'import { Checkbox } from '@/components/ui/checkbox'-import { Field, Input, Label } from '@/components/form'+import { Field, Input, Label, Select } from '@/components/form'import { StatusBadge } from '@/components/status-badge'import { EmptyState } from '@/components/empty-state'import { ConfirmDialog } from '@/components/confirm-dialog'import { ResourceTable, type Column } from '@/components/resource-table'import { cn } from '@/lib/utils'import {- FREE_CREDITS_PAYWALL,+ CENTS_PER_CREDIT,+ CREDIT_PACKS_USD,+ OVERAGE_USD_PER_MINUTE,+ PAID_PLANS,PLAN_NAMES,PLAN_OFFERS,- CENTS_PER_CREDIT,- UPGRADE_PLAN,- UPGRADE_PLAN_LABEL,+ TRIAL_CREDITS_USD,+ TRIAL_DAYS,+ TRIAL_MINUTES,billingOnrampV2Enabled,deepLinkedPlanFor,formatCreditCount,- formatCredits,- lowCreditThresholdCents,- planGrantCents,- selectablePaidPlans,- trackCheckoutStarted,+ formatMinutes,+ formatUsd,+ planChangeTiming,+ planPriceLabel,trackPlanActivated,trackUpsellShown,+ type CreditPackUsd,type PaidPlanId,type UsagePlanId,} from '@/lib/billing-onramp'+import { useBillingActions } from '@/hooks/useBillingActions'+import { HaltNoticeBody } from '@/components/billing-surfaces'type Tab = 'usage' | 'invoices'@@ -260,79 +265,17 @@ function PlanTab() {/* ── Prepaid (Autumn) ─────────────────────────────────────────────────────── */-// Plans on the Billing page. `max` is the one plan on sale, shown as "Pro".-// The retired $20 plan (id `pro`, "Pro (legacy)") is listed only to orgs-// already subscribed to it; see selectablePaidPlans.-const USAGE_PLANS: Array<{- id: UsagePlanId- label: string- price: number- credits: number | null- description: string-}> = [- {- id: 'base',- label: PLAN_NAMES.base,- price: 0,- credits: null,- description: 'Free credits to get started. Upgrade when they run out.',- },- {- id: 'pro',- label: PLAN_NAMES.pro,- price: PLAN_OFFERS.pro.priceUsd,- credits: PLAN_OFFERS.pro.creditsUsd,- description: `${formatCredits(PLAN_OFFERS.pro.creditsUsd * CENTS_PER_CREDIT)} added every month. No longer offered to new customers.`,- },- {- id: 'max',- label: PLAN_NAMES.max,- price: PLAN_OFFERS.max.priceUsd,- credits: PLAN_OFFERS.max.creditsUsd,- description: `${formatCredits(PLAN_OFFERS.max.creditsUsd * CENTS_PER_CREDIT)} added every month.`,- },-]--// The plans shown to an org: Free, Pro, and legacy Pro only for its subscribers.-function visibleUsagePlans(current: UsagePlanId) {- const paid = selectablePaidPlans(current)- return USAGE_PLANS.filter(- (plan) => plan.id === 'base' || paid.includes(plan.id),- )+// The plan picker of serverless-agents-ws 086: the trial, Pro ($20/mo, 2,000+// work minutes) and Max ($200/mo, 25,000). Upgrades apply now; Max → Pro and+// cancelling take effect at the end of the paid period.+const PLAN_DESCRIPTIONS: Record<UsagePlanId, string> = {+ trial: `${formatMinutes(TRIAL_MINUTES)} of work and $${TRIAL_CREDITS_USD} of model credits for ${TRIAL_DAYS} days. No card needed.`,+ base: 'Free credits to get started.',+ pro: `${formatMinutes(PLAN_OFFERS.pro.minutes)} of work a month.`,+ max: `${formatMinutes(PLAN_OFFERS.max.minutes)} of work a month.`,}-// How much of the plan's grant is left, like the sidebar meter.-function CreditMeter({- remainingCents,- plan,- halted,-}: {- remainingCents: number- plan: UsagePlanId- halted: boolean-}) {- const grant = Math.max(planGrantCents(plan), remainingCents)- const pct = Math.max(0, Math.min(100, (remainingCents / grant) * 100))- const low = !halted && remainingCents <= lowCreditThresholdCents(plan)- return (- <div className="mt-4">- <div className="bg-secondary h-2 overflow-hidden rounded-full">- <div- className={cn(- 'h-full rounded-full transition-[width] duration-700',- halted ? 'bg-destructive' : low ? 'bg-amber-500' : 'bg-primary',- )}- style={{ width: `${pct}%` }}- />- </div>- <p className="text-muted-foreground mt-1.5 font-mono text-[11px]">- {formatCreditCount(remainingCents)} of {formatCredits(grant)} left- </p>- </div>- )-}--function formatResetDate(value: string) {+function formatDate(value: string) {return new Intl.DateTimeFormat(undefined, {month: 'long',day: 'numeric',@@ -340,8 +283,20 @@ function formatResetDate(value: string) {}).format(new Date(value))}+function checkoutFromParam(value: string | null): CheckoutFrom {+ return value === 'paywall' || value === 'warning' || value === 'signup'+ ? value+ : 'billing_page'+}++// A pending plan change waiting for the user's confirmation.+type PlanDialog =+ | { kind: 'switch'; plan: PaidPlanId }+ | { kind: 'cancel'; plan: PaidPlanId }+function PrepaidPlan() {const queryClient = useQueryClient()+ const location = useLocation()const [searchParams, setSearchParams] = useSearchParams()const redirectedPlan = searchParams.get('usage-plan')const pendingUsagePlan =@@ -352,27 +307,44 @@ function PrepaidPlan() {queryFn: getAutumnBilling,refetchInterval: pendingUsagePlan != null ? 1_500 : 30_000,})- // `?plan=` (upsell deep link) opens the Pro ($200) upgrade confirmation- // directly. Old `?plan=pro` links open it too; legacy Pro is never offered.+ const currentPlan: UsagePlanId = autumn?.usagePlan ?? 'trial'+ // `?plan=` (upsell or site deep link) opens that plan's upgrade confirmation.const deepLinkedPlan =billingOnrampV2Enabled && autumn? deepLinkedPlanFor(searchParams.get('plan'), autumn.usagePlan): null- const [confirmUsagePlanId, setConfirmUsagePlanId] =- useState<PaidPlanId | null>(null)+ const [dialog, setDialog] = useState<PlanDialog | null>(null)// While `?plan=` is in the URL it drives the dialog; closing it clears the// param so the same link can reopen it later.- const openUsagePlanId = confirmUsagePlanId ?? deepLinkedPlan- const clearDeepLink = () => {+ const openDialog: PlanDialog | null =+ dialog ?? (deepLinkedPlan ? { kind: 'switch', plan: deepLinkedPlan } : null)+ const closeDialog = () => {+ setDialog(null)if (!searchParams.has('plan')) returnconst next = new URLSearchParams(searchParams)next.delete('plan')setSearchParams(next, { replace: true })}- const closeUsagePlanDialog = () => {- setConfirmUsagePlanId(null)- clearDeepLink()- }++ const actions = useBillingActions({+ from: checkoutFromParam(searchParams.get('from')),+ usagePlan: autumn?.usagePlan,+ onPlanChanged: closeDialog,+ })+ const cancelMutation = useMutation({+ mutationFn: (v: { plan: PaidPlanId; undo: boolean }) =>+ autumnCancelPlan(v.plan, v.undo),+ onSuccess: (_d, v) => {+ closeDialog()+ toast.success(v.undo ? 'Your plan stays as it is' : 'Plan cancelled', {+ description: v.undo+ ? undefined+ : 'It stays active until the end of the period.',+ })+ void queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })+ },+ onError: (e) => notifyError("Couldn't update your plan.", e),+ })useEffect(() => {if (!deepLinkedPlan || !autumn) return@@ -392,7 +364,7 @@ function PrepaidPlan() {if (!activationToastShown.current) {const label = PLAN_NAMES[pendingUsagePlan]toast.success(`${label} plan activated`, {- description: 'Your monthly credits are ready to use.',+ description: 'Your work minutes are ready to use.',})trackPlanActivated({ plan: pendingUsagePlan })activationToastShown.current = true@@ -402,28 +374,13 @@ function PrepaidPlan() {setSearchParams(next, { replace: true })}, [autumn?.usagePlan, pendingUsagePlan, searchParams, setSearchParams])- // url present → redirect to hosted checkout (new card); url null → the- // existing card was charged server-side, so just refresh the balance.- const onPurchase = (data: { url: string | null }) => {- if (data.url) window.location.href = data.url- else void queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })- }- const usagePlanMutation = useMutation({- mutationFn: (plan: 'pro' | 'max') => autumnSubscribeUsagePlan(plan),- onSuccess: (d, plan) => {- closeUsagePlanDialog()- trackCheckoutStarted({ plan, usagePlan: autumn?.usagePlan })- if (!d.url) {- const label = PLAN_NAMES[plan]- toast.success(`${label} plan updated`, {- description: 'Your billing status and credits are refreshing.',- })- trackPlanActivated({ plan, usagePlan: autumn?.usagePlan })- }- onPurchase(d)- },- onError: (e) => notifyError("Couldn't update your plan.", e),- })+ // Prompts link to #plans, #credits or #payment.+ useEffect(() => {+ if (isLoading || !location.hash) return+ document+ .getElementById(location.hash.slice(1))+ ?.scrollIntoView({ block: 'start' })+ }, [isLoading, location.hash])// Whether a card is on file → offer the Stripe portal to manage it. Compliance// requires that anyone with a saved card can view/update/remove it.@@ -431,25 +388,23 @@ function PrepaidPlan() {queryKey: ['billing'],queryFn: getBilling,})- const portalMutation = useMutation({- mutationFn: autumnBillingPortal,- onSuccess: (data) => {- window.location.href = data.url- },- onError: (e) => notifyError("Couldn't open the billing portal.", e),- })if (isLoading) return <Skeleton className="h-64 max-w-2xl" />- const creditBreakdown = autumn?.creditBreakdownconst halted = autumn?.isHalted ?? false- const selectedUsagePlan = USAGE_PLANS.find(- (plan) => plan.id === openUsagePlanId,- )const hasCard =(billing?.hasPaymentMethod ?? false) ||(autumn?.hasToppedUp ?? false) ||(autumn?.hasPaidSubscription ?? false)+ const scheduled = autumn?.scheduledChange ?? null+ const dialogPlan = openDialog?.plan+ const dialogTiming =+ openDialog?.kind === 'switch'+ ? planChangeTiming(currentPlan, openDialog.plan)+ : null+ const periodEnd = autumn?.periodEndsAt+ ? formatDate(autumn.periodEndsAt)+ : 'the end of the period'return (<div className="max-w-5xl space-y-4">@@ -462,242 +417,336 @@ function PrepaidPlan() {Activating {PLAN_NAMES[pendingUsagePlan]}…</h2><p className="text-muted-foreground mt-1 text-sm">- Payment completed. We are waiting for the plan and monthly- credits to synchronize.+ Payment completed. We are waiting for the plan and its work+ minutes to synchronize.</p></div></div></Panel>) : null}- <UsagePlanCard- currentPlan={autumn?.usagePlan ?? 'base'}- onSelectPlan={setConfirmUsagePlanId}- onManage={() => portalMutation.mutate()}- managing={portalMutation.isPending}++ {/* The halt modal stays off this page so its way out is reachable. */}+ {halted ? (+ <Panel className="border-destructive/40 p-6">+ <HaltNoticeBody+ reason={autumn?.haltReason}+ usagePlan={autumn?.usagePlan}+ from={+ searchParams.get('from') === 'paywall'+ ? 'paywall'+ : 'billing_page'+ }+ />+ </Panel>+ ) : null}++ {autumn ? <UsageSummary autumn={autumn} /> : null}++ <PlanPicker+ currentPlan={currentPlan}+ trialEndsAt={autumn?.trialEndsAt ?? null}+ periodEndsAt={autumn?.periodEndsAt ?? null}+ scheduled={scheduled}+ busy={actions.pending || cancelMutation.isPending}+ onSwitch={(plan) => setDialog({ kind: 'switch', plan })}+ onCancel={(plan) => setDialog({ kind: 'cancel', plan })}+ onUndo={(plan) => cancelMutation.mutate({ plan, undo: true })}/>- {/* Credits */}- <Panel className="p-6">- <h2 className="mb-4 text-sm font-semibold">Prepaid credits</h2>- <div className="flex items-baseline gap-3">- <span- className={cn(- 'font-mono text-4xl font-semibold',- halted ? 'text-status-error' : 'text-status-running',- )}- >- {formatCreditCount(autumn?.creditsRemainingCents ?? 0)}- </span>- <span className="text-muted-foreground text-xs">- credits available- </span>- </div>- <CreditMeter- remainingCents={autumn?.creditsRemainingCents ?? 0}- plan={autumn?.usagePlan ?? 'base'}- halted={halted}- />- {creditBreakdown?.available ? (- <div className="mt-5 space-y-3 border-t pt-4 text-sm">- <div className="flex items-start justify-between gap-4">- <div>- <p className="font-medium">- {autumn?.usagePlan === 'base'- ? 'Signup credits'- : `${PLAN_NAMES[autumn?.usagePlan ?? 'max']} plan credits`}- </p>- <p className="text-muted-foreground mt-0.5 text-xs">- {creditBreakdown.planResetsAt- ? `Used first · resets to ${formatCredits((USAGE_PLANS.find((plan) => plan.id === autumn?.usagePlan)?.credits ?? 0) * CENTS_PER_CREDIT)} on ${formatResetDate(creditBreakdown.planResetsAt)}`- : 'One-time included balance'}- </p>- </div>- <span className="font-mono font-medium">- {formatCredits(creditBreakdown.planRemainingCents)}- </span>- </div>- {creditBreakdown.topupRemainingCents > 0 ? (- <div className="flex items-start justify-between gap-4">- <div>- <p className="font-medium">Top-up credits</p>- <p className="text-muted-foreground mt-0.5 text-xs">- Used after plan credits · carries forward- </p>- </div>- <span className="font-mono font-medium">- {formatCredits(creditBreakdown.topupRemainingCents)}- </span>- </div>- ) : null}- {creditBreakdown.otherRemainingCents > 0 ? (- <div className="flex items-start justify-between gap-4">- <div>- <p className="font-medium">Carried or promotional credits</p>- <p className="text-muted-foreground mt-0.5 text-xs">- Preserved separately from this month's allowance- </p>- </div>- <span className="font-mono font-medium">- {formatCredits(creditBreakdown.otherRemainingCents)}- </span>- </div>- ) : null}- </div>- ) : null}- {halted ? (- <div className="text-status-error mt-2 space-y-2 text-sm">- <p className="flex items-center gap-1.5">- <CircleAlert className="size-4 shrink-0" />- {autumn?.usagePlan === 'pro' || autumn?.usagePlan === 'max'- ? 'Credits exhausted — agents are running on an open-weight model (GLM)'- : FREE_CREDITS_PAYWALL}- </p>- {autumn?.usagePlan !== UPGRADE_PLAN ? (- <Button- size="sm"- onClick={() => setConfirmUsagePlanId(UPGRADE_PLAN)}- >- Upgrade to {UPGRADE_PLAN_LABEL}- </Button>- ) : null}- </div>- ) : null}- </Panel><div className="grid grid-cols-1 gap-4 lg:grid-cols-2 lg:items-start">- {/* Top-ups are no longer sold. An org that already turned on- automatic top-up keeps the card so it can change or turn it off. */}- {autumn?.autoTopup?.enabled ? (- <AutoTopupCard- current={autumn.autoTopup}- hasToppedUp={autumn.hasToppedUp}- />- ) : null}+ <CreditPacksCard+ creditsRemainingCents={autumn?.creditsRemainingCents ?? 0}+ busy={actions.pending}+ onBuy={(usd) => actions.buyPack.mutate(usd)}+ />+ <AutoTopupCard+ current={autumn?.autoTopup ?? null}+ hasToppedUp={autumn?.hasToppedUp ?? false}+ />+ </div>+ <Panel id="payment" className="scroll-mt-24 p-6">+ <h2 className="mb-2 text-sm font-semibold">Payment method</h2>+ <p className="text-muted-foreground mb-3 text-sm">+ {hasCard+ ? 'Update your card, download invoices, or remove your payment method on Stripe.'+ : 'No card on file yet. You add one when you choose a plan or buy credits.'}+ </p>{hasCard ? (- <Panel className="p-6">- <h2 className="mb-2 text-sm font-semibold">Payment method</h2>- <p className="text-muted-foreground mb-3 text-sm">- Update your card, download invoices, or remove your payment method- on Stripe.- </p>- <Button- variant="outline"- onClick={() => portalMutation.mutate()}- disabled={portalMutation.isPending}- >- {portalMutation.isPending- ? 'Opening Stripe…'- : 'Manage payment method ↗'}- </Button>- </Panel>+ <Button+ variant="outline"+ onClick={() => actions.portal.mutate()}+ disabled={actions.portal.isPending}+ >+ {actions.portal.isPending ? 'Opening Stripe…' : 'Update card ↗'}+ </Button>) : null}- </div>+ </Panel><AgentUsageBreakdown usage={autumn?.modelUsage ?? null} /><ConfirmDialog- open={!!selectedUsagePlan}- onOpenChange={(open) => !open && closeUsagePlanDialog()}- title={`Switch to ${selectedUsagePlan?.label ?? ''}`}+ open={openDialog?.kind === 'switch' && !!dialogPlan}+ onOpenChange={(open) => !open && closeDialog()}+ title={+ dialogTiming === 'period_end'+ ? `Switch to ${dialogPlan ? PLAN_NAMES[dialogPlan] : ''} on ${periodEnd}`+ : `Upgrade to ${dialogPlan ? PLAN_NAMES[dialogPlan] : ''}`+ }description={- selectedUsagePlan- ? `${selectedUsagePlan.label} costs $${selectedUsagePlan.price}/month and adds ${formatCredits((selectedUsagePlan.credits ?? 0) * CENTS_PER_CREDIT)} each month. Autumn applies the plan change and any required proration through Stripe.`+ dialogPlan+ ? dialogTiming === 'period_end'+ ? `You keep Max until ${periodEnd}. Then Pro starts at $${PLAN_OFFERS.pro.priceUsd}/month with ${formatMinutes(PLAN_OFFERS.pro.minutes)} a month.`+ : `${planPriceLabel(dialogPlan)} starts now with ${formatMinutes(PLAN_OFFERS[dialogPlan].minutes)} a month. Stripe prorates any change from your current plan.`: ''}confirmLabel={- selectedUsagePlan- ? `${selectedUsagePlan.label} — $${selectedUsagePlan.price}/mo`+ dialogPlan+ ? dialogTiming === 'period_end'+ ? `Switch on ${periodEnd}`+ : `${PLAN_NAMES[dialogPlan]} — $${PLAN_OFFERS[dialogPlan].priceUsd}/mo`: 'Continue'}- pending={usagePlanMutation.isPending}+ pending={actions.subscribe.isPending}+ onConfirm={() => dialogPlan && actions.subscribe.mutate(dialogPlan)}+ />+ <ConfirmDialog+ open={openDialog?.kind === 'cancel'}+ onOpenChange={(open) => !open && closeDialog()}+ title={`Cancel ${dialogPlan ? PLAN_NAMES[dialogPlan] : ''}?`}+ description={`Your plan stays active until ${periodEnd}. After that, work pauses until you choose a plan again.`}+ confirmLabel={`Cancel on ${periodEnd}`}+ cancelLabel="Keep plan"+ destructive+ pending={cancelMutation.isPending}onConfirm={() =>- selectedUsagePlan &&- selectedUsagePlan.id !== 'base' &&- usagePlanMutation.mutate(selectedUsagePlan.id)+ dialogPlan && cancelMutation.mutate({ plan: dialogPlan, undo: false })}/></div>)}-function UsagePlanCard({+// Work minutes left this period (or in the trial) and the credit balance+// overage draws from.+function UsageSummary({ autumn }: { autumn: AutumnBilling }) {+ const minutes = autumn.workMinutes+ const halted = autumn.isHalted+ const pct = minutes+ ? Math.max(+ 0,+ Math.min(100, (minutes.remaining / Math.max(1, minutes.granted)) * 100),+ )+ : 0+ const low = pct <= 20+ const resetLine =+ autumn.usagePlan === 'trial'+ ? autumn.trialEndsAt+ ? `Trial ends ${formatDate(autumn.trialEndsAt)}`+ : null+ : minutes?.resetsAt+ ? `Resets ${formatDate(minutes.resetsAt)}`+ : null+ return (+ <Panel className="grid gap-6 p-6 md:grid-cols-2">+ <div>+ <h2 className="text-sm font-semibold">Work minutes</h2>+ {minutes ? (+ <>+ <div className="mt-3 flex items-baseline gap-2">+ <span+ className={cn(+ 'font-mono text-3xl font-semibold',+ halted && 'text-status-error',+ )}+ >+ {new Intl.NumberFormat('en-US').format(minutes.remaining)}+ </span>+ <span className="text-muted-foreground text-xs">+ of {formatMinutes(minutes.granted)} left+ </span>+ </div>+ <div className="bg-secondary mt-3 h-2 overflow-hidden rounded-full">+ <div+ className={cn(+ 'h-full rounded-full transition-[width] duration-700',+ halted+ ? 'bg-destructive'+ : low+ ? 'bg-amber-500'+ : 'bg-primary',+ )}+ style={{ width: `${pct}%` }}+ />+ </div>+ {resetLine ? (+ <p className="text-muted-foreground mt-1.5 font-mono text-[11px]">+ {resetLine}+ </p>+ ) : null}+ </>+ ) : (+ <p className="text-muted-foreground mt-3 text-sm">+ Choose a plan to get work minutes.+ </p>+ )}+ </div>+ <div>+ <h2 className="text-sm font-semibold">Credits</h2>+ <div className="mt-3 flex items-baseline gap-2">+ <span className="font-mono text-3xl font-semibold">+ {formatUsd(autumn.creditsRemainingCents)}+ </span>+ <span className="text-muted-foreground text-xs">available</span>+ </div>+ <p className="text-muted-foreground mt-3 text-sm">+ {autumn.usagePlan === 'trial'+ ? 'Model credits included with your trial.'+ : `Used past your monthly minutes, at $${OVERAGE_USD_PER_MINUTE}/min, and for models.`}+ </p>+ </div>+ </Panel>+ )+}++function PlanPicker({currentPlan,- onSelectPlan,- onManage,- managing,+ trialEndsAt,+ periodEndsAt,+ scheduled,+ busy,+ onSwitch,+ onCancel,+ onUndo,}: {currentPlan: UsagePlanId- onSelectPlan: (plan: PaidPlanId) => void- onManage: () => void- managing: boolean+ trialEndsAt: string | null+ periodEndsAt: string | null+ scheduled: AutumnBilling['scheduledChange'] | null+ busy: boolean+ onSwitch: (plan: PaidPlanId) => void+ onCancel: (plan: PaidPlanId) => void+ onUndo: (plan: PaidPlanId) => void}) {+ const paidCurrent =+ currentPlan === 'pro' || currentPlan === 'max' ? currentPlan : null+ // The trial (or the old free tier) is listed only while the org is on it.+ const plans: UsagePlanId[] = paidCurrent+ ? PAID_PLANS+ : [currentPlan, ...PAID_PLANS]+ const changeDate = scheduled?.at ? formatDate(scheduled.at) : nullreturn (- <Panel className="p-6">+ <Panel id="plans" className="scroll-mt-24 p-6"><div className="mb-4"><h2 className="text-sm font-semibold">Plan</h2><p className="text-muted-foreground mt-1 text-sm">- Monthly credits are shared by serverless-agent sessions and sandboxes.+ Work minutes cover your computer and automations. Past them, work+ draws prepaid credits at ${OVERAGE_USD_PER_MINUTE}/min.</p></div><divclassName={cn('grid gap-3',- currentPlan === 'pro' ? 'md:grid-cols-3' : 'md:grid-cols-2',+ plans.length === 3 ? 'md:grid-cols-3' : 'md:grid-cols-2',)}>- {visibleUsagePlans(currentPlan).map((plan) => {- const planId = plan.id- const current = plan.id === currentPlan+ {plans.map((plan) => {+ const current = plan === currentPlan+ const paid = plan === 'pro' || plan === 'max' ? plan : null+ const startsLater = scheduled?.to === 'pro' && plan === 'pro'+ const cancelling = current && scheduled?.to === 'cancel'+ let note: string | null = null+ if (current && plan === 'trial' && trialEndsAt)+ note = `Ends ${formatDate(trialEndsAt)}`+ else if (cancelling) note = `Ends ${changeDate ?? 'at period end'}`+ else if (current && scheduled?.to === 'pro')+ note = `Until ${changeDate ?? 'the period ends'}`+ else if (current && paid && periodEndsAt)+ note = `Renews ${formatDate(periodEndsAt)}`+ else if (startsLater) note = `Starts ${changeDate ?? 'at period end'}`return (- <div key={plan.id} className="rounded-md border p-4">+ <div+ key={plan}+ className={cn(+ 'flex flex-col rounded-md border p-4',+ current && 'border-foreground/40',+ )}+ ><div className="flex items-start justify-between gap-3"><div>- <div className="font-medium">{plan.label}</div>+ <div className="font-medium">{PLAN_NAMES[plan]}</div><div className="mt-1 font-mono text-xl font-semibold">- ${plan.price}+ {paid ? `$${PLAN_OFFERS[paid].priceUsd}` : '$0'}<span className="text-muted-foreground text-xs font-normal">- /mo+ {paid ? '/mo' : ` for ${TRIAL_DAYS} days`}</span></div></div>- {current ? <StatusBadge status="active" /> : null}+ {current ? (+ <StatusBadge status="active" label="Current" />+ ) : startsLater ? (+ <StatusBadge status="pending" label="Scheduled" />+ ) : null}</div><p className="text-muted-foreground mt-3 min-h-10 text-sm">- {plan.description}+ {PLAN_DESCRIPTIONS[plan]}</p>- {current ? (- currentPlan === 'base' ? (- <Button className="mt-4 w-full" variant="outline" disabled>+ {note ? (+ <p+ className={cn(+ 'mt-1 font-mono text-[11px]',+ cancelling ? 'text-status-error' : 'text-muted-foreground',+ )}+ >+ {note}+ </p>+ ) : null}+ <div className="mt-auto pt-4">+ {!paid ? (+ <Button className="w-full" variant="outline" disabled>Current plan</Button>+ ) : current ? (+ scheduled ? (+ <Button+ className="w-full"+ variant="outline"+ disabled={busy}+ onClick={() => onUndo(paid)}+ >+ Keep {PLAN_NAMES[paid]}+ </Button>+ ) : (+ <Button+ className="w-full"+ variant="outline"+ disabled={busy}+ onClick={() => onCancel(paid)}+ >+ Cancel plan+ </Button>+ )+ ) : startsLater ? (+ <Button className="w-full" variant="outline" disabled>+ Starts {changeDate ?? 'at period end'}+ </Button>) : (<Button- className="mt-4 w-full"- variant="outline"- disabled={managing}- onClick={onManage}+ className="w-full"+ variant={+ planChangeTiming(currentPlan, paid) === 'now'+ ? 'default'+ : 'outline'+ }+ disabled={busy}+ onClick={() => onSwitch(paid)}>- Manage subscription+ {planChangeTiming(currentPlan, paid) === 'now'+ ? `Upgrade to ${PLAN_NAMES[paid]}`+ : `Switch to ${PLAN_NAMES[paid]}`}</Button>- )- ) : planId === 'base' ? (- <Button- className="mt-4 w-full"- variant="outline"- disabled={currentPlan === 'base' || managing}- onClick={onManage}- >- Manage in Stripe- </Button>- ) : (- <Button- className="mt-4 w-full"- variant="outline"- onClick={() => onSelectPlan(planId)}- >- {plan.id === UPGRADE_PLAN ? 'Upgrade' : 'Switch plan'}- </Button>- )}+ )}+ </div></div>)})}@@ -706,6 +755,51 @@ function UsagePlanCard({)}+function CreditPacksCard({+ creditsRemainingCents,+ busy,+ onBuy,+}: {+ creditsRemainingCents: number+ busy: boolean+ onBuy: (usd: CreditPackUsd) => void+}) {+ const [confirm, setConfirm] = useState<CreditPackUsd | null>(null)+ return (+ <Panel id="credits" className="scroll-mt-24 p-6">+ <h2 className="mb-2 text-sm font-semibold">Buy credits</h2>+ <p className="text-muted-foreground mb-4 text-sm">+ {formatUsd(creditsRemainingCents)} available. Credits cover work past+ your monthly minutes (${OVERAGE_USD_PER_MINUTE}/min) and models.+ </p>+ <div className="grid grid-cols-3 gap-2">+ {CREDIT_PACKS_USD.map((usd) => (+ <Button+ key={usd}+ variant="outline"+ disabled={busy}+ onClick={() => setConfirm(usd)}+ >+ ${usd}+ </Button>+ ))}+ </div>+ <ConfirmDialog+ open={confirm !== null}+ onOpenChange={(open) => !open && setConfirm(null)}+ title={`Buy $${confirm ?? ''} of credits`}+ description={`We charge $${confirm ?? ''} to your saved card, or take you to Stripe to add one.`}+ confirmLabel={`Buy $${confirm ?? ''}`}+ pending={busy}+ onConfirm={() => {+ if (confirm !== null) onBuy(confirm)+ setConfirm(null)+ }}+ />+ </Panel>+ )+}+function ModelUsageCard({usage,}: {@@ -931,6 +1025,10 @@ function AgentUsageBreakdown({)}+// Monthly cap options for automatic top-up, as a number of packs (the edge+// requires the budget to be a whole multiple of the pack).+const TOPUPS_PER_MONTH = [1, 2, 3, 5, 10]+function AutoTopupCard({current,hasToppedUp,@@ -945,13 +1043,21 @@ function AutoTopupCard({const [draft, setDraft] = useState<{enabled?: booleanthreshold?: number- quantity?: number- budget?: number+ quantity?: CreditPackUsd+ perMonth?: number}>({})+ const savedPack = CREDIT_PACKS_USD.find((usd) => usd === current?.quantity)const enabled = draft.enabled ?? current?.enabled ?? falseconst threshold = draft.threshold ?? current?.threshold ?? 5- const quantity = draft.quantity ?? current?.quantity ?? 25- const budget = draft.budget ?? current?.budget ?? 100+ const quantity: CreditPackUsd = draft.quantity ?? savedPack ?? 10+ const savedPerMonth =+ current && current.budget != null && current.quantity > 0+ ? Math.round(current.budget / current.quantity)+ : 3+ const perMonth =+ draft.perMonth ??+ (TOPUPS_PER_MONTH.includes(savedPerMonth) ? savedPerMonth : 3)+ const budget = quantity * perMonthconst [saved, markSaved] = useTransientFlag(3000)const [confirm, setConfirm] = useState(false)@@ -973,9 +1079,7 @@ function AutoTopupCard({// Saving only charges when enabling WITHOUT a card on file. Gate that one path.const willCharge = enabled && !hasToppedUp- const validBudget = budget >= quantity && budget % quantity === 0const onSave = () => {- if (enabled && !validBudget) returnif (willCharge) setConfirm(true)else mutation.mutate()}@@ -984,8 +1088,8 @@ function AutoTopupCard({<Panel className="p-6"><h2 className="mb-2 text-sm font-semibold">Automatic top-up</h2><p className="text-muted-foreground mb-4 text-sm">- Keep your balance from running out — when it drops below the threshold- we automatically add credits to your saved card.+ When your credits drop below the threshold, we buy a pack with your+ saved card so work doesn't pause.</p><div className="flex items-center gap-2">@@ -997,13 +1101,30 @@ function AutoTopupCard({}/><Label htmlFor="auto-topup" className="cursor-pointer font-normal">- Enable automatic top-up+ Top up automatically</Label></div>{enabled ? (<div className="mt-4 flex flex-wrap gap-5">- <Field label="When balance falls below" htmlFor="threshold">+ <Field label="Buy" htmlFor="topup-pack">+ <Select+ id="topup-pack"+ value={String(quantity)}+ onValueChange={(v) =>+ setDraft((d) => ({+ ...d,+ quantity: Number(v) as CreditPackUsd,+ }))+ }+ options={CREDIT_PACKS_USD.map((usd) => ({+ value: String(usd),+ label: `$${usd} pack`,+ }))}+ className="w-32"+ />+ </Field>+ <Field label="When credits fall below" htmlFor="threshold"><div className="flex items-center gap-1.5"><span className="text-muted-foreground text-sm">$</span><Input@@ -1024,63 +1145,27 @@ function AutoTopupCard({/></div></Field>- <Field label="Add credits" htmlFor="quantity">- <div className="flex items-center gap-1.5">- <span className="text-muted-foreground text-sm">$</span>- <Input- id="quantity"- type="number"- min={1}- value={quantity}- onChange={(e) =>- setDraft((d) => ({- ...d,- quantity: Math.max(- 1,- Math.floor(Number(e.target.value) || 0),- ),- }))- }- className="w-24 font-mono"- />- </div>- </Field>- <Field label="Monthly budget" htmlFor="budget">- <div className="flex items-center gap-1.5">- <span className="text-muted-foreground text-sm">$</span>- <Input- id="budget"- type="number"- min={quantity}- step={quantity}- value={budget}- onChange={(e) =>- setDraft((d) => ({- ...d,- budget: Math.max(- 0,- Math.floor(Number(e.target.value) || 0),- ),- }))- }- className="w-24 font-mono"- />- </div>+ <Field label="At most" htmlFor="topup-limit">+ <Select+ id="topup-limit"+ value={String(perMonth)}+ onValueChange={(v) =>+ setDraft((d) => ({ ...d, perMonth: Number(v) }))+ }+ options={TOPUPS_PER_MONTH.map((n) => ({+ value: String(n),+ label: `${n}× a month ($${n * quantity})`,+ }))}+ className="w-44"+ /></Field></div>) : null}- {enabled && !validBudget ? (- <p className="text-status-error mt-3 text-xs">- Monthly budget must be at least ${quantity} and a whole multiple of- the ${quantity} top-up amount.- </p>- ) : null}-<div className="mt-4"><Buttonvariant="outline"- disabled={mutation.isPending || (enabled && !validBudget)}+ disabled={mutation.isPending}onClick={onSave}>{mutation.isPending ? 'Saving…' : saved ? 'Saved' : 'Save'}@@ -1089,17 +1174,17 @@ function AutoTopupCard({{enabled && !hasToppedUp ? (<p className="text-muted-foreground mt-3 text-xs">- Since you haven't topped up yet, enabling runs your first $- {quantity} recharge now to set up your card.+ Since you haven't bought credits yet, enabling buys your first $+ {quantity} pack now to set up your card.</p>) : null}<ConfirmDialogopen={confirm}onOpenChange={(o) => !o && setConfirm(false)}- title="Enable automatic top-up"- description={`You don't have a saved card yet, so enabling runs your first $${quantity} recharge now to set it up — you'll be charged $${quantity}. After that we top up automatically whenever your balance drops below $${threshold}, up to $${budget} per month.`}- confirmLabel={`Charge $${quantity} & enable`}+ title="Turn on automatic top-up"+ description={`You don't have a saved card yet, so turning this on buys your first $${quantity} pack now to set it up. After that we buy a $${quantity} pack whenever your credits drop below $${threshold}, at most ${perMonth}× ($${budget}) a month.`}+ confirmLabel={`Buy $${quantity} & turn on`}pending={mutation.isPending}onConfirm={() => mutation.mutate()}/>diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsxindex 1c86ff5f..c73dc3bd 100644--- a/web/src/pages/SessionDetail.tsx+++ b/web/src/pages/SessionDetail.tsx@@ -14,11 +14,7 @@ import {import { GuidedTour, type GuideStep } from '@/components/guided-tour'import { notifyError } from '@/lib/errors'import { useHalted } from '@/hooks/useHalted'-import {- FREE_CREDITS_USED,- UPGRADE_PLAN_LABEL,- upgradeHref,-} from '@/lib/billing-onramp'+import { WORK_PAUSED, WORK_PAUSED_TITLE } from '@/lib/billing-onramp'import {getSession,getSessionSources,@@ -631,14 +627,14 @@ for await (const event of session.events()) {<div className="text-destructive mb-2 flex items-center gap-1.5 text-xs"><CircleAlert className="size-3.5 shrink-0" /><span>- {FREE_CREDITS_USED}{' '}+ {WORK_PAUSED}{' '}<Link- to={upgradeHref()}+ to="/billing"className="font-medium underline underline-offset-2">- Upgrade to {UPGRADE_PLAN_LABEL}+ Open Billing</Link>{' '}- to keep going.+ to resume.</span></div>)}@@ -665,7 +661,7 @@ for await (const event of session.events()) {}}placeholder={halted- ? `${FREE_CREDITS_USED} Upgrade to ${UPGRADE_PLAN_LABEL} to resume.`+ ? WORK_PAUSED_TITLE: canSteer? 'Send a message to steer the session…': 'Session archived'diff --git a/web/src/pages/Sessions.tsx b/web/src/pages/Sessions.tsxindex 876f34db..8ff119a5 100644--- a/web/src/pages/Sessions.tsx+++ b/web/src/pages/Sessions.tsx@@ -4,7 +4,7 @@ import { Link, useNavigate } from 'react-router-dom'import { MessagesSquare, Plus } from 'lucide-react'import { notifyError } from '@/lib/errors'import { useHalted } from '@/hooks/useHalted'-import { FREE_CREDITS_USED, UPGRADE_PLAN_LABEL } from '@/lib/billing-onramp'+import { WORK_PAUSED_TITLE } from '@/lib/billing-onramp'import { getSessions, getAgents, createSession, ApiError } from '@/api/client'import type { Session } from '@/api/client'import { PageHeader } from '@/components/page-header'@@ -36,7 +36,7 @@ import {usageDisclosure,} from '@/lib/usage'-const HALTED_TITLE = `${FREE_CREDITS_USED} Upgrade to ${UPGRADE_PLAN_LABEL} to resume.`+const HALTED_TITLE = WORK_PAUSED_TITLEexport default function Sessions() {const navigate = useNavigate()const queryClient = useQueryClient()