An open-source, faster Devin alternative
TypeScript
fixes for prepaid
Brian Reardone93d21208b45
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 3587d942..f58be606 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -434,19 +434,26 @@ export async function autumnAttach(}}-// autumnPurchase buys a product (top-up or concurrency tier), handling both-// Autumn flows: a customer with NO card gets a hosted-checkout url to redirect-// to; a customer WITH a card on file gets url=null from /checkout, so we charge-// directly via /attach. Returns the url to redirect to, or null when the charge-// already completed (caller should just refresh the balance — no redirect).+// autumnPurchase buys a product (concurrency tier), handling both Autumn flows.+// It gates the direct /attach on hasToppedUp — a real prior charge means a card+// is RELIABLY on file. We deliberately do NOT use the /checkout `url` probe to+// detect a card: it can spuriously return null for a CARDLESS org, which then+// takes the attach path → Autumn returns checkout_created → autumnAttach throws+// → 502 (the same failure we fixed for top-up via autumnTopUpCharge). So:+// card on file (hasToppedUp) → /attach, immediate charge, return url=null+// no card → hosted checkout to collect a card + purchase+// Returns the url to redirect to, or null when the charge already completed+// (caller should just refresh the balance — no redirect).export async function autumnPurchase(env: AutumnApiEnv,params: { customerId: string; productId: string; options?: AutumnCheckoutOption[]; successUrl: string },): Promise<{ url: string | null }> {+ if (await autumnHasToppedUp(env, params.customerId)) {+ await autumnAttach(env, { customerId: params.customerId, productId: params.productId, options: params.options });+ return { url: null };+ }const co = await autumnCheckout(env, params);- if (co.url) return { url: co.url };- await autumnAttach(env, { customerId: params.customerId, productId: params.productId, options: params.options });- return { url: null };+ return { url: co.url };}// autumnSetupPayment creates a Stripe SETUP session that saves a card for futurediff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex b07ef55d..369b960a 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -1106,16 +1106,22 @@ async function handleBillingPortal(req: Request, env: DashboardEnv, caller: { or// ── Per-sandbox usage breakdown ──────────────────────────────────────────-// Compute $/sec per memory tier. MUST stay in sync with-// internal/billing/pricing.go TierPricePerSecond (and the Autumn credit-// schema, which mirrors the same rates).-const TIER_RATE_PER_SEC: Record<number, number> = {- 1024: 0.000001080246914,- 4096: 0.000005787037037,- 8192: 0.00001350308642,- 16384: 0.00002700617284,- 32768: 0.0001929012346,- 65536: 0.0005401234568,+// Per-sandbox DISPLAY rate for PREPAID (autumn) orgs only — this breakdown is+// rendered solely in the autumn billing view, and this constant has exactly one+// consumer (handleSandboxUsage below). It is intentionally decoupled from+// internal/billing/pricing.go (legacy billing): the source of truth for prepaid+// charges is the Autumn `credits` credit-schema (credit_cost per compute+// feature), and these values MUST mirror it exactly or the breakdown won't+// reconcile with what's actually deducted. Current basis: $0.06/GB-hour+// (0.00001666666666 per GB-second × the tier's GB). Change the Autumn schema →+// change these too.+const AUTUMN_TIER_RATE_PER_SEC: Record<number, number> = {+ 1024: 0.00001666666666,+ 4096: 0.00006666666664,+ 8192: 0.00013333333328,+ 16384: 0.00026666666656,+ 32768: 0.00053333333312,+ 65536: 0.00106666666624,};// GET /api/dashboard/usage/sandboxes?days=N — per-sandbox compute cost over a@@ -1143,7 +1149,7 @@ async function handleSandboxUsage(req: Request, env: DashboardEnv, caller: { org// Fold per-(sandbox, tier) rows into per-sandbox totals.const bySandbox = new Map<string, { costCents: number; seconds: number; status: string | null; createdAt: number | null }>();for (const r of rows.results ?? []) {- const rate = TIER_RATE_PER_SEC[r.memory_mb] ?? 0;+ const rate = AUTUMN_TIER_RATE_PER_SEC[r.memory_mb] ?? 0;const secs = r.secs ?? 0;const cur = bySandbox.get(r.sandbox_id) ?? { costCents: 0, seconds: 0, status: r.status, createdAt: r.created_at };cur.costCents += secs * rate * 100;@@ -1159,7 +1165,11 @@ async function handleSandboxUsage(req: Request, env: DashboardEnv, caller: { orgstatus: v.status ?? "deleted",createdAt: v.createdAt ?? undefined,seconds: Math.round(v.seconds),- costCents: Math.round(v.costCents),+ // Keep FRACTIONAL cents. Rounding each sandbox to whole cents here meant a+ // cheap/short sandbox (e.g. 4GB for ~15 min ≈ 0.5¢) showed $0.00, and the+ // total summed already-zeroed rows — so a page of real usage read $0.00.+ // The frontend formats the precision for display.+ costCents: v.costCents,})).sort((a, b) => b.costCents - a.costCents);diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsxindex ce51bd8a..3855bdd3 100644--- a/web/src/components/Layout.tsx+++ b/web/src/components/Layout.tsx@@ -1,7 +1,8 @@import { useState } from 'react'-import { NavLink, Outlet } from 'react-router-dom'+import { NavLink, Outlet, useLocation, Link } from 'react-router-dom'+import { useQuery } from '@tanstack/react-query'import { useAuth } from '../hooks/useAuth'-import { logout } from '../api/client'+import { logout, getAutumnBilling } from '../api/client'/* ── SVG Icons (inline, no extra deps) ────────────────────── */const icons = {@@ -69,6 +70,43 @@ const navItems = [{ to: '/settings', label: 'Settings', icon: icons.gear },]+// Org-wide halt notice. Prepaid (autumn) orgs that exhaust their credits get+// halted — sandboxes hibernate — so show a small banner on every page except+// Billing (where the fix already lives) so they understand why things paused+// and where to resolve it. Legacy orgs 404 on /billing/autumn → no data → no+// banner, which is the desired behavior.+function HaltBanner() {+ const location = useLocation()+ const { data } = useQuery({+ queryKey: ['autumn-billing'],+ queryFn: getAutumnBilling,+ retry: false,+ refetchInterval: (q) => (q.state.error ? false : 30_000),+ })+ const halted = data?.isHalted ?? false+ if (!halted || location.pathname.startsWith('/billing')) return null+ return (+ <div style={{+ margin: '-32px -36px 28px',+ padding: '9px 36px',+ background: 'var(--accent-indigo)',+ color: '#fff',+ fontSize: 13,+ fontWeight: 500,+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ textAlign: 'center',+ }}>+ <span>+ Your sandboxes are paused — you're out of prepaid credits.{' '}+ <Link to="/billing" style={{ color: '#fff', fontWeight: 700, textDecoration: 'underline' }}>+ Top up & turn on auto-recharge+ </Link>{' '}+ to resume now and prevent future pauses.+ </span>+ </div>+ )+}+export default function Layout() {const { user, switchOrg } = useAuth()const [orgSwitcherOpen, setOrgSwitcherOpen] = useState(false)@@ -253,6 +291,7 @@ export default function Layout() {minHeight: '100vh',background: 'radial-gradient(ellipse 80% 50% at 50% -10%, rgba(99,102,241,0.04) 0%, transparent 70%)',}}>+ <HaltBanner /><Outlet /></main></div>diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex 66bb6b1c..545129ef 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useState, type ReactNode } from 'react'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import {getBilling, billingSetup, billingPortal, getBillingInvoices, redeemPromoCode,@@ -270,11 +270,61 @@ const CONCURRENCY_TIERS = [{ id: 'concurrency_pro_plus_plus', label: 'Pro++', limit: 1000, price: 1000 },]+// Confirmation gate shown before any action that charges a card. The purchase+// flows (top-up, concurrency upgrade, first auto-recharge) charge immediately+// when a card is on file, so a misclick = a real charge — this is the guard.+function ConfirmModal({+ title, body, confirmLabel, pending, error, onConfirm, onCancel,+}: {+ title: string+ body: ReactNode+ confirmLabel: string+ pending: boolean+ error?: string | null+ onConfirm: () => void+ onCancel: () => void+}) {+ return (+ <div+ onClick={() => { if (!pending) onCancel() }}+ style={{+ position: 'fixed', inset: 0, zIndex: 1000, padding: 20,+ background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(2px)',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ }}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="glass-card animate-in"+ style={{ padding: 28, maxWidth: 440, width: '100%' }}+ >+ <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>{title}</span>+ <div style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 22 }}>+ {body}+ </div>+ {error && (+ <div style={{ fontSize: 12, color: 'var(--accent-rose)', marginBottom: 16 }}>{error}</div>+ )}+ <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>+ <button className="btn-secondary" onClick={onCancel} disabled={pending} style={{ padding: '8px 18px' }}>+ Cancel+ </button>+ <button className="btn-primary" onClick={onConfirm} disabled={pending} style={{ padding: '8px 18px' }}>+ {pending ? 'Processing…' : confirmLabel}+ </button>+ </div>+ </div>+ </div>+ )+}+function PrepaidPlan() {const { data: autumn, isLoading } = useQuery({queryKey: ['autumn-billing'], queryFn: getAutumnBilling, refetchInterval: 30_000,})const [amount, setAmount] = useState<number>(25)+ const [confirmTopup, setConfirmTopup] = useState(false)+ const [confirmPlanId, setConfirmPlanId] = useState<string | null>(null)const queryClient = useQueryClient()// url present → redirect to hosted checkout (collect a new card); url null →@@ -285,11 +335,11 @@ function PrepaidPlan() {}const topupMutation = useMutation({mutationFn: () => autumnTopup(amount),- onSuccess: onPurchase,+ onSuccess: (d) => { setConfirmTopup(false); onPurchase(d) },})const planMutation = useMutation({mutationFn: (plan: string) => autumnSubscribeConcurrency(plan),- onSuccess: onPurchase,+ onSuccess: (d) => { setConfirmPlanId(null); onPurchase(d) },})@@ -368,17 +418,12 @@ function PrepaidPlan() {</div><buttonclassName="btn-primary"- disabled={topupMutation.isPending || amount < 1}- onClick={() => topupMutation.mutate()}+ disabled={amount < 1}+ onClick={() => setConfirmTopup(true)}style={{ padding: '10px 20px' }}>- {topupMutation.isPending ? 'Redirecting…' : `Top up $${amount}`}+ {`Top up $${amount}`}</button>- {topupMutation.isError && (- <div style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>- {(topupMutation.error as Error).message}- </div>- )}</div></div>@@ -416,8 +461,8 @@ function PrepaidPlan() {</div><buttonclassName="btn-secondary"- disabled={active || planMutation.isPending}- onClick={() => planMutation.mutate(tier.id)}+ disabled={active}+ onClick={() => setConfirmPlanId(tier.id)}style={{ padding: '8px 16px' }}>{active ? 'Current' : 'Subscribe'}@@ -429,14 +474,36 @@ function PrepaidPlan() {Need more than 1000? <a href="mailto:[email protected]" style={{ color: 'var(--accent-indigo)' }}>Contact us</a>.</div></div>- {planMutation.isError && (- <div style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>- {(planMutation.error as Error).message}- </div>- )}</div><UsageBreakdown />++ {confirmTopup && (+ <ConfirmModal+ title="Confirm top-up"+ body={<>Add <strong style={{ color: 'var(--text-primary)' }}>${amount}</strong> in prepaid credits. If a payment method is on file you'll be charged <strong style={{ color: 'var(--text-primary)' }}>${amount}</strong> now; otherwise you'll continue to checkout to add one.</>}+ confirmLabel={`Top up $${amount}`}+ pending={topupMutation.isPending}+ error={topupMutation.isError ? (topupMutation.error as Error).message : null}+ onConfirm={() => topupMutation.mutate()}+ onCancel={() => setConfirmTopup(false)}+ />+ )}+ {confirmPlanId && (() => {+ const tier = CONCURRENCY_TIERS.find((t) => t.id === confirmPlanId)+ if (!tier) return null+ return (+ <ConfirmModal+ title="Confirm subscription"+ body={<>Subscribe to <strong style={{ color: 'var(--text-primary)' }}>{tier.label}</strong> ({tier.limit} concurrent sandboxes) for <strong style={{ color: 'var(--text-primary)' }}>${tier.price}/mo</strong>. If a payment method is on file you'll be charged now and monthly; otherwise you'll continue to checkout.</>}+ confirmLabel={`Subscribe — $${tier.price}/mo`}+ pending={planMutation.isPending}+ error={planMutation.isError ? (planMutation.error as Error).message : null}+ onConfirm={() => planMutation.mutate(tier.id)}+ onCancel={() => setConfirmPlanId(null)}+ />+ )+ })()}</>)}@@ -493,7 +560,7 @@ function UsageBreakdown() {{formatDuration(r.seconds)}</span><span style={{ textAlign: 'right', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontWeight: 600 }}>- ${(r.costCents / 100).toFixed(2)}+ {formatCost(r.costCents)}</span></div>))}@@ -504,7 +571,7 @@ function UsageBreakdown() {}}><span style={{ color: 'var(--text-secondary)' }}>Total</span><span style={{ textAlign: 'right', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)' }}>- ${((data?.totalCents ?? 0) / 100).toFixed(2)}+ {formatCost(data?.totalCents ?? 0)}</span></div></div>@@ -519,6 +586,15 @@ function formatDuration(seconds: number): string {return `${(seconds / 3600).toFixed(1)}h`}+// Cost can be fractional cents (cheap tiers / short runs). Show the real value+// at higher precision below a cent rather than rounding it down to $0.00.+function formatCost(cents: number): string {+ const dollars = cents / 100+ if (dollars <= 0) return '$0.00'+ if (dollars < 0.01) return `$${dollars.toFixed(4)}`+ return `$${dollars.toFixed(2)}`+}+const autoTopupInputStyle = {width: 80, padding: '6px 10px', borderRadius: 8, border: '1px solid var(--border-subtle)',background: 'transparent', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontSize: 13,@@ -530,6 +606,7 @@ function AutoTopupCard({ current, hasToppedUp }: { current: AutumnBilling['autoTconst [threshold, setThreshold] = useState(current?.threshold ?? 5)const [quantity, setQuantity] = useState(current?.quantity ?? 25)const [saved, setSaved] = useState(false)+ const [confirm, setConfirm] = useState(false)const mutation = useMutation({mutationFn: () => setAutumnAutoTopup({ enabled, threshold, quantity }),@@ -537,6 +614,7 @@ function AutoTopupCard({ current, hasToppedUp }: { current: AutumnBilling['autoT// Auto-recharge needs a saved off-session card. If enabling without one, the// server returns a no-charge Stripe setup URL — redirect to capture the card,// after which auto-recharge is live. Otherwise just confirm the save.+ setConfirm(false)if (data?.url) { window.location.href = data.url; return }queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })setSaved(true)@@ -544,6 +622,12 @@ function AutoTopupCard({ current, hasToppedUp }: { current: AutumnBilling['autoT},})+ // Saving only charges when enabling WITHOUT a card on file (the first recharge+ // arms the card). That's the one path we gate behind a confirm; disabling or+ // editing thresholds with a card already saved is just config — save directly.+ const willCharge = enabled && !hasToppedUp+ const onSave = () => { if (willCharge) setConfirm(true); else mutation.mutate() }+return (<div className="glass-card animate-in stagger-2" style={{ padding: 28, marginBottom: 14 }}><span className="section-title" style={{ marginBottom: 8, display: 'block' }}>@@ -586,11 +670,22 @@ function AutoTopupCard({ current, hasToppedUp }: { current: AutumnBilling['autoT<buttonclassName="btn-secondary"disabled={mutation.isPending}- onClick={() => mutation.mutate()}+ onClick={onSave}style={{ padding: '8px 16px' }}>{mutation.isPending ? 'Saving…' : saved ? 'Saved ✓' : 'Save'}</button>+ {confirm && (+ <ConfirmModal+ title="Enable automatic top-up"+ body={<>You don't have a saved card yet, so enabling runs your first <strong style={{ color: 'var(--text-primary)' }}>${quantity}</strong> recharge now to set it up — you'll be charged <strong style={{ color: 'var(--text-primary)' }}>${quantity}</strong>. After that we top up automatically whenever your balance drops below ${threshold}.</>}+ confirmLabel={`Charge $${quantity} & enable`}+ pending={mutation.isPending}+ error={mutation.isError ? (mutation.error as Error).message : null}+ onConfirm={() => mutation.mutate()}+ onCancel={() => setConfirm(false)}+ />+ )}{enabled && (<div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 10 }}>Charges your saved card automatically when the balance drops below the threshold.