An open-source, faster Devin alternative
TypeScript
ungate portal
Brian Reardon4c04663f69d1
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 324cf694..22840f40 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -478,6 +478,32 @@ export async function autumnSetupPayment(return { url: d.url ?? null };}+// autumnOpenCustomerPortal creates a Stripe billing-portal session (hosted by+// Stripe, brokered by Autumn) so the customer can view / update / remove their+// saved card and download invoices — POST /billing.open_customer_portal.+// Compliance: anyone with a card on file must be able to manage it. The card for+// an Autumn org lives under Autumn's Stripe account, so this — NOT the edge's+// direct /billing/portal — is the correct surface for prepaid orgs. Returns the+// hosted portal URL (null if the customer has no billing account yet).+export async function autumnOpenCustomerPortal(+ env: AutumnApiEnv,+ params: { customerId: string; returnUrl: string },+): Promise<{ url: string | null }> {+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;+ const resp = await fetch(`${base}/billing.open_customer_portal`, {+ 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, return_url: params.returnUrl }),+ });+ if (!resp.ok) throw new Error(`autumn open_customer_portal ${resp.status}: ${await resp.text()}`);+ const d = (await resp.json()) as { url?: string };+ return { url: d.url ?? null };+}+// 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/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 2c6df874..85842671 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -24,6 +24,7 @@ import {autumnHasToppedUp,syncAutumnToD1,autumnSetAutoTopup,+ autumnOpenCustomerPortal,} from "./autumn_webhook";import { handleWebhooksAPI, type WebhookEnv } from "./webhooks";@@ -1081,10 +1082,31 @@ export async function handleDashboard(console.error("billing: DO snapshot failed, falling back to D1 mirror:", e);}}+ // Whether a card is on file + any Stripe promotional credit. Both drive the+ // Billing UI (the "manage payment method" portal gate + the promo-credit+ // line) and are REQUIRED by the client schema, so we must always return+ // them. Derived from the Stripe customer when one exists; a fetch failure+ // degrades to (no card, no credit) rather than breaking the billing page.+ // Only the direct-Stripe (legacy/Pro) path uses this; Autumn orgs manage+ // their card through Autumn's portal + surface hasToppedUp in /billing/autumn,+ // and this edge has no STRIPE_API_KEY for Autumn's account anyway.+ let hasPaymentMethod = false;+ let stripeCreditCents = 0;+ if (org.stripe_customer_id && org.billing_provider !== "autumn") {+ try {+ const cust = await stripeApi(env, `/v1/customers/${org.stripe_customer_id}`, null, "GET");+ hasPaymentMethod = !!(cust?.invoice_settings?.default_payment_method || cust?.default_source);+ if (typeof cust?.balance === "number" && cust.balance < 0) stripeCreditCents = -cust.balance;+ } catch (e) {+ console.error("billing: stripe customer fetch failed:", e);+ }+ }return json({plan: org.plan,stripeCustomerId: org.stripe_customer_id ?? undefined,stripeSubscriptionId: org.stripe_subscription_id ?? undefined,+ hasPaymentMethod,+ stripeCreditCents,freeCreditsRemainingCents: liveBalance,creditBalanceCents: org.credit_balance_cents,isHalted: !!org.is_halted,@@ -1131,6 +1153,9 @@ export async function handleDashboard(if (sub === "/billing/autumn/auto-topup" && method === "POST") {return handleAutumnAutoTopup(req, env, caller);}+ if (sub === "/billing/autumn/portal" && method === "POST") {+ return handleAutumnPortal(req, env, caller);+ }if (sub === "/billing/autumn/finalize-arm" && method === "GET") {return handleAutumnFinalizeArm(req, env, caller);}@@ -1275,7 +1300,7 @@ async function handleBillingPortal(req: Request, env: DashboardEnv, caller: { orconst org = await loadOrgStripe(env, caller.orgID);if (!org) return json({ error: "org not found" }, 404);if (!org.stripe_customer_id) {- return json({ error: "no billing customer — upgrade to Pro first" }, 400);+ return json({ error: "no billing account on file yet — add a payment method first" }, 400);}// Bounce back wherever the dashboard came from when the user closes the portal.const returnURL = req.headers.get("referer") ?? `${new URL(req.url).origin}/dashboard/billing`;@@ -1291,6 +1316,21 @@ async function handleBillingPortal(req: Request, env: DashboardEnv, caller: { or}}+// Autumn-org billing portal — the card lives under Autumn's Stripe account, so+// we broker the portal session through Autumn (the org id IS the Autumn+// customer id), NOT the edge's direct STRIPE_API_KEY.+async function handleAutumnPortal(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {+ const returnURL = req.headers.get("referer") ?? `${new URL(req.url).origin}/dashboard/billing`;+ try {+ const { url } = await autumnOpenCustomerPortal(env, { customerId: caller.orgID, returnUrl: returnURL });+ if (!url) return json({ error: "no billing account on file yet — add a payment method first" }, 400);+ return json({ url });+ } catch (e) {+ console.error("billing/autumn/portal:", e);+ return json({ error: (e as Error).message }, 500);+ }+}+// ── Per-sandbox usage breakdown ──────────────────────────────────────────// Per-sandbox DISPLAY rate for PREPAID (autumn) orgs only — this breakdown isdiff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 14b626af..8c34360c 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -369,6 +369,10 @@ export const autumnSubscribeConcurrency = (plan: string) =>body: JSON.stringify({ plan }),})+// Open Autumn's Stripe-hosted billing portal to manage the saved card + invoices.+export const autumnBillingPortal = () =>+ apiFetch<{ url: string }>('/billing/autumn/portal', { method: 'POST' })+// url is non-null when enabling auto-recharge requires capturing an off-session// card first — the caller redirects there (a no-charge Stripe setup session).export const setAutumnAutoTopup = (cfg: {diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex fb40354c..01928449 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -5,6 +5,7 @@ import { CircleAlert, CircleCheck } from 'lucide-react'import { notifyError } from '@/lib/errors'import { useTransientFlag } from '@/lib/use-transient-flag'import {+ autumnBillingPortal,autumnSubscribeConcurrency,autumnTopup,billingPortal,@@ -180,7 +181,7 @@ function PlanTab() {</p></Panel>- {isPro ? (+ {isPro || billing?.hasPaymentMethod ? (<Panel className="p-6"><h2 className="mb-2 text-sm font-semibold">Usage & payment method@@ -280,12 +281,25 @@ function PrepaidPlan() {onError: (e) => notifyError("Couldn't update your subscription.", e),})+ // 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.+ const { data: billing } = useQuery({ 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 credits = (autumn?.creditsRemainingCents ?? 0) / 100const halted = autumn?.isHalted ?? falseconst currentPlan = autumn?.concurrencyPlan ?? 'base'const tier = CONCURRENCY_TIERS.find((t) => t.id === confirmPlanId)+ const hasCard =+ (billing?.hasPaymentMethod ?? false) || (autumn?.hasToppedUp ?? false)return (<div className="grid max-w-5xl grid-cols-1 gap-4 lg:grid-cols-2 lg:items-start">@@ -348,6 +362,25 @@ function PrepaidPlan() {hasToppedUp={autumn?.hasToppedUp ?? false}/>+ {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>+ ) : null}+<ModelUsageCard usage={autumn?.modelUsage ?? null} />{/* Concurrency */}