An open-source, faster Devin alternative
TypeScript
billing: address review on the web billing surfaces
Mohamed Habib via Computere34d5bf52790
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts b/cloudflare-workers/api-edge/src/autumn_webhook.test.tsindex 5e4b5a05..f9dabbc6 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts@@ -243,6 +243,25 @@ describe("Autumn shared-credit plan purchases", () => {);});+ it("does not carry the trial's credit into a paid plan", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(Response.json({+ id: "org_1",+ subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],+ purchases: [],+ }))+ .mockResolvedValueOnce(Response.json({ payment_url: null }));++ await autumnUsagePlanPurchase(env, {+ customerId: "org_1",+ planId: "pro",+ successUrl: "https://example.test/billing?usage-plan=pro",+ });++ const body = JSON.parse(String(fetchMock.mock.lastCall?.[1]?.body));+ expect(body.carry_over_balances).toBeUndefined();+ });+it("does not roll paid monthly grants into another paid plan", async () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(Response.json({diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 8ab55f62..a03d73e4 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -1144,6 +1144,9 @@ export async function autumnUsagePlanPurchase(},): Promise<{ url: string | null }> {const customer = await getAutumnCustomer(env, params.customerId);+ // Only the pre-trial `base` grant carries. The 7-day trial's minutes and $10+ // token credit do not (serverless-agents-ws 086 "Plan changes": trial → paid+ // starts the paid allowance fresh).const upgradingFromUsage = (customer?.subscriptions ?? []).some((subscription) =>subscription.plan_id === "base" &&diff --git a/web/src/components/billing-surfaces.tsx b/web/src/components/billing-surfaces.tsxindex 933bd23e..a3d58f15 100644--- a/web/src/components/billing-surfaces.tsx+++ b/web/src/components/billing-surfaces.tsx@@ -86,14 +86,15 @@ export function BillingWarningBanner() {)}-// Blocks every page while the org is halted. The Billing page is the one+// Blocks every page while the org's halt stops work. 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 { billing, sessionsBlocked, haltReason, usagePlan } = useCreditState()const onBilling = location.pathname.startsWith('/billing')- const open = isHalted && !onBilling+ // A paid org on the fallback model keeps working, so it isn't blocked.+ const open = sessionsBlocked && !onBillingconst reason = haltReason ?? 'unknown'useEffect(() => {if (open) trackPaywallShown(reason)diff --git a/web/src/hooks/useBillingActions.ts b/web/src/hooks/useBillingActions.tsindex 74ef7bb8..7396091c 100644--- a/web/src/hooks/useBillingActions.ts+++ b/web/src/hooks/useBillingActions.ts@@ -10,6 +10,7 @@ import { notifyError } from '@/lib/errors'import {PLAN_NAMES,formatUsd,+ planChangeTiming,trackCheckoutStarted,trackPlanActivated,type PaidPlanId,@@ -38,6 +39,18 @@ export function useBillingActions(options: {window.location.href = data.urlreturn}+ // $200 → $20 is only scheduled: the current plan runs to the period end,+ // so nothing is activated yet.+ if (+ options.usagePlan &&+ planChangeTiming(options.usagePlan, plan) === 'period_end'+ ) {+ toast.success(`${PLAN_NAMES[plan]} plan scheduled`, {+ description: 'It starts at the end of your current period.',+ })+ refresh()+ return+ }toast.success(`${PLAN_NAMES[plan]} plan updated`, {description: 'Your minutes and billing status are refreshing.',})diff --git a/web/src/hooks/useCreditState.ts b/web/src/hooks/useCreditState.tsindex 8f8cb2d7..2b9a4c9d 100644--- a/web/src/hooks/useCreditState.ts+++ b/web/src/hooks/useCreditState.ts@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'import { getAutumnBilling } from '@/api/client'import type { AutumnBilling } from '@/api/schemas'import {+ haltBlocksAgents,upgradePlanFor,type UpgradePlanId,type UsagePlanId,@@ -13,7 +14,8 @@ export interface CreditState {creditsRemainingCents: number | undefinedisHalted: boolean// Halted orgs can't start agent sessions until they pay (serverless-agents-ws- // 086: no fallback model on any plan).+ // 086), except a paid org on the old credit rule, which keeps the fallback+ // model (see haltBlocksAgents).sessionsBlocked: boolean// orgs.halt_reason while halted, and orgs.billing_warning before that.haltReason: string | null@@ -38,7 +40,7 @@ export function useCreditState(): CreditState {usagePlan,creditsRemainingCents: data?.creditsRemainingCents,isHalted,- sessionsBlocked: isHalted,+ sessionsBlocked: haltBlocksAgents(data),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 775acc87..867c9996 100644--- a/web/src/hooks/useHalted.ts+++ b/web/src/hooks/useHalted.ts@@ -1,9 +1,10 @@import { useQuery } from '@tanstack/react-query'import { getAutumnBilling } from '@/api/client'+import { haltBlocksAgents } from '@/lib/billing-onramp'// 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).+// sharing the app shell's 30s poll. Every work-minute halt blocks them; a paid+// org halted by the old credit rule keeps the fallback model (haltBlocksAgents).// Autumn orgs only; legacy orgs 404 on /billing/autumn → error → treated as not halted.export function useHalted(): boolean {const { data } = useQuery({@@ -12,5 +13,5 @@ export function useHalted(): boolean {retry: false,refetchInterval: (q) => (q.state.error ? false : 30_000),})- return data?.isHalted ?? false+ return haltBlocksAgents(data)}diff --git a/web/src/lib/billing-onramp.test.ts b/web/src/lib/billing-onramp.test.tsindex 96e4afd3..71111973 100644--- a/web/src/lib/billing-onramp.test.ts+++ b/web/src/lib/billing-onramp.test.ts@@ -6,12 +6,14 @@ import {billingPillText,deepLinkedPlanFor,formatCredits,+ haltBlocksAgents,haltNotice,planChangeTiming,planPriceLabel,upgradeHref,upgradePlanFor,warningNotice,+ withSavedOption,} from '@/lib/billing-onramp'const NOW = new Date('2026-06-26T12:00:00Z').getTime()@@ -119,6 +121,50 @@ describe('haltNotice', () => {})})+describe('haltBlocksAgents', () => {+ const halted = (+ usagePlan: 'trial' | 'base' | 'pro' | 'max',+ haltReason: string | null,+ ) => ({ isHalted: true, usagePlan, haltReason })++ it('lets a paid org on the old credit rule keep its fallback model', () => {+ expect(haltBlocksAgents(halted('pro', 'credits_exhausted'))).toBe(false)+ expect(haltBlocksAgents(halted('max', null))).toBe(false)+ })++ it('blocks every work-minute halt and every unpaid halt', () => {+ expect(haltBlocksAgents(halted('pro', 'credits_empty'))).toBe(true)+ expect(haltBlocksAgents(halted('max', 'payment'))).toBe(true)+ expect(haltBlocksAgents(halted('pro', 'lapsed'))).toBe(true)+ expect(haltBlocksAgents(halted('trial', 'trial_minutes'))).toBe(true)+ expect(haltBlocksAgents(halted('base', 'credits_exhausted'))).toBe(true)+ })++ it('is false when not halted or not loaded', () => {+ expect(haltBlocksAgents(undefined)).toBe(false)+ expect(+ haltBlocksAgents({+ isHalted: false,+ usagePlan: 'trial',+ haltReason: null,+ }),+ ).toBe(false)+ })+})++describe('withSavedOption', () => {+ it('keeps a saved value outside the presets selectable', () => {+ expect(withSavedOption([10, 50, 200], 25)).toEqual([10, 25, 50, 200])+ expect(withSavedOption([1, 2, 3, 5, 10], 4)).toEqual([1, 2, 3, 4, 5, 10])+ })++ it('leaves the presets alone otherwise', () => {+ expect(withSavedOption([10, 50, 200], 50)).toEqual([10, 50, 200])+ expect(withSavedOption([10, 50, 200], undefined)).toEqual([10, 50, 200])+ expect(withSavedOption([10, 50, 200], 0)).toEqual([10, 50, 200])+ })+})+describe('warningNotice', () => {const billing = {creditsRemainingCents: 250,diff --git a/web/src/lib/billing-onramp.ts b/web/src/lib/billing-onramp.tsindex 2fe645dc..05732a7a 100644--- a/web/src/lib/billing-onramp.ts+++ b/web/src/lib/billing-onramp.ts@@ -72,6 +72,33 @@ export function planChangeTiming(return current === 'max' && target === 'pro' ? 'period_end' : 'now'}+// Whether a halt stops agent sessions. Mirrors the edge's managed-agent+// admission (getManagedAgentBillingAdmission): a paid org halted by the old+// credit rule (`credits_exhausted`, or no reason recorded) keeps running on the+// fallback model; every work-minute halt stops it.+export function haltBlocksAgents(+ billing:+ | { isHalted: boolean; usagePlan: UsagePlanId; haltReason?: string | null }+ | undefined,+): boolean {+ if (!billing?.isHalted) return false+ const paid = billing.usagePlan === 'pro' || billing.usagePlan === 'max'+ const reason = billing.haltReason ?? null+ return !(paid && (reason === null || reason === 'credits_exhausted'))+}++// A picker's preset values plus the saved one, so a value set before the+// presets existed (e.g. a $25 auto top-up pack) shows and saves unchanged.+export function withSavedOption(+ presets: readonly number[],+ saved: number | null | undefined,+): number[] {+ if (saved == null || !Number.isInteger(saved) || saved < 1)+ return [...presets]+ if (presets.includes(saved)) return [...presets]+ return [...presets, saved].sort((a, b) => a - b)+}+// `?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(diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex fe9704a5..c6baaa13 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -50,6 +50,7 @@ import {planPriceLabel,trackPlanActivated,trackUpsellShown,+ withSavedOption,type CreditPackUsd,type PaidPlanId,type UsagePlanId,@@ -1043,20 +1044,23 @@ function AutoTopupCard({const [draft, setDraft] = useState<{enabled?: booleanthreshold?: number- quantity?: CreditPackUsd+ quantity?: numberperMonth?: number}>({})- const savedPack = CREDIT_PACKS_USD.find((usd) => usd === current?.quantity)- const enabled = draft.enabled ?? current?.enabled ?? false- const threshold = draft.threshold ?? current?.threshold ?? 5- const quantity: CreditPackUsd = draft.quantity ?? savedPack ?? 10+ // A policy saved before the presets (e.g. $25 packs, a $100 cap) stays+ // selectable, so saving another field never rewrites it.+ const savedPack =+ current && current.quantity > 0 ? current.quantity : undefinedconst 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)+ : undefined+ const packOptions = withSavedOption(CREDIT_PACKS_USD, savedPack)+ const perMonthOptions = withSavedOption(TOPUPS_PER_MONTH, savedPerMonth)+ const enabled = draft.enabled ?? current?.enabled ?? false+ const threshold = draft.threshold ?? current?.threshold ?? 5+ const quantity = draft.quantity ?? savedPack ?? 10+ const perMonth = draft.perMonth ?? savedPerMonth ?? 3const budget = quantity * perMonthconst [saved, markSaved] = useTransientFlag(3000)const [confirm, setConfirm] = useState(false)@@ -1112,12 +1116,9 @@ function AutoTopupCard({id="topup-pack"value={String(quantity)}onValueChange={(v) =>- setDraft((d) => ({- ...d,- quantity: Number(v) as CreditPackUsd,- }))+ setDraft((d) => ({ ...d, quantity: Number(v) }))}- options={CREDIT_PACKS_USD.map((usd) => ({+ options={packOptions.map((usd) => ({value: String(usd),label: `$${usd} pack`,}))}@@ -1152,7 +1153,7 @@ function AutoTopupCard({onValueChange={(v) =>setDraft((d) => ({ ...d, perMonth: Number(v) }))}- options={TOPUPS_PER_MONTH.map((n) => ({+ options={perMonthOptions.map((n) => ({value: String(n),label: `${n}× a month ($${n * quantity})`,}))}