Open source CapCut alternative.
TypeScript
feat(site): self-serve credits, auto-reload, superuser grants, and Donkey Pro
David Le1793e9c8cdb7
diff --git a/site/.env.example b/site/.env.exampleindex ae1a0c4b..004db2cb 100644--- a/site/.env.example+++ b/site/.env.example@@ -30,13 +30,18 @@ GEMINI_API_KEY="replace-with-gemini-api-key"RUNPOD_API_KEY="replace-with-runpod-api-key"RUNPOD_VISION_ENDPOINT_ID="replace-with-endpoint-id"-# Stripe, for the self-serve Vision API subscription. STRIPE_VISION_PRICE_ID is-# the recurring price; set its metadata key "monthlyCallQuota" to control the-# included call quota without a deploy. STRIPE_WEBHOOK_SECRET signs events-# delivered to /api/billing/webhook.+# Stripe. Two separate subscription products plus one-time credit top-ups all+# run through STRIPE_SECRET_KEY and the /api/billing/webhook endpoint (signed by+# STRIPE_WEBHOOK_SECRET).+# STRIPE_VISION_PRICE_ID — recurring price for the Vision API plan; metadata+# key "monthlyCallQuota" tunes the included call quota without a deploy.+# STRIPE_PRO_PRICE_ID — recurring price for the Donkey Pro app plan; the+# included monthly inference allowance equals this price (a $20/mo plan+# includes $20 of inference), read straight from the price's amount.STRIPE_SECRET_KEY="replace-with-stripe-secret-key"STRIPE_WEBHOOK_SECRET="replace-with-stripe-webhook-signing-secret"STRIPE_VISION_PRICE_ID="replace-with-stripe-price-id"+STRIPE_PRO_PRICE_ID="replace-with-stripe-pro-price-id"STRIPE_PORTAL_CONFIGURATION_ID="replace-with-stripe-portal-configuration-id"# Browser Use Cloud (agentic web automation via /api/browser/run). Backend-onlydiff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prismaindex 62f1c438..a7eb4ec1 100644--- a/site/prisma/Auth.prisma+++ b/site/prisma/Auth.prisma@@ -14,8 +14,10 @@ model User {creditLedgerEntries UserCreditLedgerEntry[]inferenceUsageEvents InferenceUsageEvent[]creditLimits UserCreditLimit[]+ creditAutoReload CreditAutoReload?apiKeys Apikey[]visionApiSubscription VisionApiSubscription?+ proSubscription ProSubscription?@@map("user")}diff --git a/site/prisma/Billing.prisma b/site/prisma/Billing.prismaindex 49750d35..99bd053d 100644--- a/site/prisma/Billing.prisma+++ b/site/prisma/Billing.prisma@@ -24,6 +24,30 @@ model VisionApiSubscription {updatedAt DateTime @updatedAt}+// Donkey Pro: the Mac app subscription. Kept entirely separate from the Vision+// API product above. While active it includes a monthly inference allowance+// equal to the plan price, granted into the user's credit balance as an+// expiring grant (source "pro_subscription") so it is drawn down before+// never-expiring purchased credits and does not roll over.+// monthlyAllowanceMicros mirrors the included amount (the price), for display.+model ProSubscription {+ id String @id @default(cuid())+ userId String @unique+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ stripeCustomerId String?+ stripeSubscriptionId String? @unique+ status String @default("incomplete")+ planKey String @default("pro")+ monthlyAllowanceMicros BigInt @default(0)+ currentPeriodStart DateTime?+ currentPeriodEnd DateTime?+ cancelAtPeriodEnd Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@map("pro_subscription")+}+// Mirrors the Better Auth @better-auth/api-key plugin schema (generated via the// Better Auth CLI). The plugin owns reads/writes through auth.api.* and links a// key to its owner via referenceId (= User.id). We keep verificationdiff --git a/site/prisma/Credits.prisma b/site/prisma/Credits.prismaindex 96935910..6c321882 100644--- a/site/prisma/Credits.prisma+++ b/site/prisma/Credits.prisma@@ -126,6 +126,28 @@ model InferenceCreditRate {@@map("inference_credit_rate")}+// Per-user auto-reload config. When enabled, the credit balance dropping below+// thresholdMicros triggers an off-session Stripe charge of amountMicros against+// the saved payment method; the resulting credits are granted from the webhook.+// status guards against concurrent charges ("idle" | "charging" | "failed").+model CreditAutoReload {+ id String @id @default(cuid())+ userId String @unique+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ enabled Boolean @default(false)+ thresholdMicros BigInt @default(0)+ amountMicros BigInt @default(0)+ stripeCustomerId String?+ stripePaymentMethodId String?+ status String @default("idle")+ lastChargeAt DateTime?+ lastError String?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@map("credit_auto_reload")+}+model UserCreditLimit {id String @id @default(cuid())userId Stringdiff --git a/site/src/app/api/account/me/route.ts b/site/src/app/api/account/me/route.tsnew file mode 100644index 00000000..2cc297a4--- /dev/null+++ b/site/src/app/api/account/me/route.ts@@ -0,0 +1,21 @@+import { NextResponse } from "next/server";++import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import { prisma } from "@/lib/prisma";++export const dynamic = "force-dynamic";++// Minimal identity for the settings UI: who am I, and am I a super user (which+// gates the manual credit-grant card). Session-only.+export const GET = withDonkeyAuth(async (request) => {+ const user = await prisma.user.findUnique({+ select: { email: true, superUser: true },+ where: { id: request.donkey.userId },+ });++ return NextResponse.json({+ email: user?.email ?? null,+ superUser: user?.superUser === true,+ userId: request.donkey.userId,+ });+});diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.tsindex 345f4cdb..74e12eca 100644--- a/site/src/app/api/billing/checkout/route.ts+++ b/site/src/app/api/billing/checkout/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server";import { auth } from "@/lib/auth";+import { proPriceId } from "@/lib/billing/pro-subscription";import {ensureStripeCustomer,getStripe,@@ -14,24 +15,36 @@ import {export const dynamic = "force-dynamic";-// Start a Stripe Checkout session for the Vision API subscription. Session-only-// (API keys are not accepted here, the default for withDonkeyAuth). This route-// keeps its getSession call because it needs the user's email/name for Stripe.+// Resolve the Stripe price for a self-serve subscription plan, or null if the+// plan is unknown or not configured. Pro and Vision are separate products.+function subscriptionPriceId(planKey: string): string | null {+ if (planKey === "vision") {+ return visionPriceId();+ }+ if (planKey === "pro") {+ return proPriceId() ?? null;+ }+ return null;+}++// Start a Stripe Checkout session for a subscription (Vision API or Pro).+// Session-only (API keys are not accepted here, the default for withDonkeyAuth).+// This route keeps its getSession call because it needs the user's email/name.export const POST = withDonkeyAuth(async (request) => {const session = await auth.api.getSession({ headers: request.headers });if (!session) {return unauthorizedResponse();}- // Only the Vision API plan is self-serve. Other plan keys (e.g. the Mac app- // "pro" plan) are not wired to Stripe yet. This stays a 404 rather than a 401- // so the landing card does not treat it as a sign-in prompt.const body = (await request.json().catch(() => ({}))) as {planKey?: unknown;};const planKey =typeof body.planKey === "string" ? body.planKey : "vision";- if (planKey !== "vision") {+ // An unknown or not-yet-configured plan stays a 404 (not 401) so the landing+ // card does not treat it as a sign-in prompt.+ const priceId = subscriptionPriceId(planKey);+ if (!priceId) {return notFoundResponse();}@@ -47,7 +60,7 @@ export const POST = withDonkeyAuth(async (request) => {cancel_url: `${origin}/app/settings?checkout=cancelled`,client_reference_id: session.user.id,customer: customerId,- line_items: [{ price: visionPriceId(), quantity: 1 }],+ line_items: [{ price: priceId, quantity: 1 }],mode: "subscription",subscription_data: { metadata: { userId: session.user.id } },success_url: `${origin}/app/settings?checkout=success`,diff --git a/site/src/app/api/billing/credits/auto-reload/route.ts b/site/src/app/api/billing/credits/auto-reload/route.tsnew file mode 100644index 00000000..bd27677f--- /dev/null+++ b/site/src/app/api/billing/credits/auto-reload/route.ts@@ -0,0 +1,114 @@+import { NextResponse } from "next/server";+import { z } from "zod";++import {+ creditTopUpMaxDollars,+ creditTopUpMinDollars,+} from "@/lib/billing/credit-purchases";+import { creditMicrosPerCredit } from "@/lib/credits/amounts";+import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import { prisma } from "@/lib/prisma";++export const dynamic = "force-dynamic";++// Defaults shown before the user has saved any config.+const defaultThresholdDollars = 10;+const defaultAmountDollars = 25;++type AutoReloadRow = {+ enabled: boolean;+ thresholdMicros: bigint;+ amountMicros: bigint;+ stripePaymentMethodId: string | null;+ status: string;+ lastError: string | null;+};++function dollarsFromMicros(micros: bigint): number {+ return Number(micros / creditMicrosPerCredit);+}++function serialize(config: AutoReloadRow | null) {+ return {+ amountDollars: config ? dollarsFromMicros(config.amountMicros) : defaultAmountDollars,+ enabled: config?.enabled ?? false,+ hasPaymentMethod: Boolean(config?.stripePaymentMethodId),+ lastError: config?.lastError ?? null,+ status: config?.status ?? "idle",+ thresholdDollars: config+ ? dollarsFromMicros(config.thresholdMicros)+ : defaultThresholdDollars,+ };+}++export const GET = withDonkeyAuth(async (request) => {+ const config = await prisma.creditAutoReload.findUnique({+ where: { userId: request.donkey.userId },+ });+ return NextResponse.json(serialize(config));+});++const updateSchema = z+ .object({+ amountDollars: z.coerce+ .number()+ .int()+ .min(creditTopUpMinDollars)+ .max(creditTopUpMaxDollars),+ enabled: z.boolean(),+ thresholdDollars: z.coerce.number().int().min(0).max(creditTopUpMaxDollars),+ })+ .strict();++export const PUT = withDonkeyAuth(async (request) => {+ const parsed = updateSchema.safeParse(await request.json().catch(() => ({})));+ if (!parsed.success) {+ return NextResponse.json(+ {+ error: "invalid_request",+ message: "Provide enabled, thresholdDollars, and amountDollars.",+ },+ { status: 400 },+ );+ }++ const existing = await prisma.creditAutoReload.findUnique({+ where: { userId: request.donkey.userId },+ });++ // Enabling needs a saved card, which is captured the first time the user buys+ // credits. Surface a distinct code so the UI can prompt a one-time top-up.+ if (parsed.data.enabled && !existing?.stripePaymentMethodId) {+ return NextResponse.json(+ {+ error: "no_payment_method",+ message:+ "Buy credits once to save a card, then turn on auto-reload.",+ },+ { status: 409 },+ );+ }++ const amountMicros = BigInt(parsed.data.amountDollars) * creditMicrosPerCredit;+ const thresholdMicros =+ BigInt(parsed.data.thresholdDollars) * creditMicrosPerCredit;++ const config = await prisma.creditAutoReload.upsert({+ create: {+ amountMicros,+ enabled: parsed.data.enabled,+ thresholdMicros,+ userId: request.donkey.userId,+ },+ update: {+ amountMicros,+ enabled: parsed.data.enabled,+ thresholdMicros,+ // Re-enabling after a failure clears the stale error and lock.+ ...(parsed.data.enabled ? { lastError: null, status: "idle" } : {}),+ },+ where: { userId: request.donkey.userId },+ });++ return NextResponse.json(serialize(config));+});diff --git a/site/src/app/api/billing/credits/checkout/route.ts b/site/src/app/api/billing/credits/checkout/route.tsnew file mode 100644index 00000000..41a3fe8e--- /dev/null+++ b/site/src/app/api/billing/credits/checkout/route.ts@@ -0,0 +1,92 @@+import { NextResponse } from "next/server";+import { z } from "zod";++import { auth } from "@/lib/auth";+import {+ creditTopUpKind,+ creditTopUpMaxDollars,+ creditTopUpMinDollars,+ dollarsToStripeCents,+} from "@/lib/billing/credit-purchases";+import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";+import { unauthorizedResponse, withDonkeyAuth } from "@/lib/donkey-api-auth";++export const dynamic = "force-dynamic";++const checkoutRequestSchema = z+ .object({+ amountDollars: z.coerce+ .number()+ .int()+ .min(creditTopUpMinDollars)+ .max(creditTopUpMaxDollars),+ })+ .strict();++// Start a one-time Stripe Checkout to buy credits. Session-only (no API keys).+// The card is saved (setup_future_usage) so auto-reload can charge it later.+export const POST = withDonkeyAuth(async (request) => {+ const session = await auth.api.getSession({ headers: request.headers });+ if (!session) {+ return unauthorizedResponse();+ }++ const parsed = checkoutRequestSchema.safeParse(+ await request.json().catch(() => ({})),+ );+ if (!parsed.success) {+ return NextResponse.json(+ {+ error: "invalid_request",+ message: `Enter a whole-dollar amount between $${creditTopUpMinDollars} and $${creditTopUpMaxDollars}.`,+ },+ { status: 400 },+ );+ }+ const amountDollars = parsed.data.amountDollars;++ const customerId = await ensureStripeCustomer({+ email: session.user.email,+ name: session.user.name,+ userId: session.user.id,+ });+ const stripe = getStripe();+ const origin = request.nextUrl.origin;+ const metadata = {+ amountDollars: String(amountDollars),+ kind: creditTopUpKind,+ userId: session.user.id,+ };++ const checkout = await stripe.checkout.sessions.create({+ cancel_url: `${origin}/app/settings?topup=cancelled`,+ client_reference_id: session.user.id,+ customer: customerId,+ line_items: [+ {+ price_data: {+ currency: "usd",+ product_data: {+ description: `$${amountDollars} of Donkey inference credits`,+ name: "Donkey credits",+ },+ unit_amount: dollarsToStripeCents(amountDollars),+ },+ quantity: 1,+ },+ ],+ metadata,+ mode: "payment",+ payment_intent_data: { metadata, setup_future_usage: "off_session" },+ success_url: `${origin}/app/settings?topup=success`,+ });++ if (!checkout.url) {+ return NextResponse.json(+ { error: "server-error", message: "Stripe did not return a URL." },+ { status: 502 },+ );+ }++ return NextResponse.json({ url: checkout.url });+});diff --git a/site/src/app/api/billing/pro/route.ts b/site/src/app/api/billing/pro/route.tsnew file mode 100644index 00000000..c9706222--- /dev/null+++ b/site/src/app/api/billing/pro/route.ts@@ -0,0 +1,48 @@+import { NextResponse } from "next/server";++import { getActiveProSubscription } from "@/lib/billing/pro-subscription";+import { creditMicrosToString, zeroCreditMicros } from "@/lib/credits/amounts";+import { creditGrantUnit } from "@/lib/credits/inference";+import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import { prisma } from "@/lib/prisma";++export const dynamic = "force-dynamic";++// Pro subscription status for the settings UI, plus how much of this period's+// included allowance is left — the remaining balance on the active+// "pro_subscription" grant(s).+export const GET = withDonkeyAuth(async (request) => {+ const userId = request.donkey.userId;+ const now = new Date();++ const [subscription, grants] = await Promise.all([+ getActiveProSubscription(userId),+ prisma.userCreditGrant.findMany({+ select: { remainingAmountMicros: true },+ where: {+ OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],+ remainingAmountMicros: { gt: zeroCreditMicros },+ source: "pro_subscription",+ status: "active",+ unit: creditGrantUnit,+ userId,+ },+ }),+ ]);++ const allowanceRemainingMicros = grants.reduce(+ (sum, grant) => sum + grant.remainingAmountMicros,+ zeroCreditMicros,+ );++ return NextResponse.json({+ allowanceRemaining: creditMicrosToString(allowanceRemainingMicros),+ cancelAtPeriodEnd: subscription?.cancelAtPeriodEnd ?? false,+ currentPeriodEnd: subscription?.currentPeriodEnd?.toISOString() ?? null,+ isActive: Boolean(subscription),+ monthlyAllowance: subscription+ ? creditMicrosToString(subscription.monthlyAllowanceMicros)+ : null,+ status: subscription?.status ?? null,+ });+});diff --git a/site/src/app/api/billing/webhook/route.ts b/site/src/app/api/billing/webhook/route.tsindex 4b1c7af4..22652f22 100644--- a/site/src/app/api/billing/webhook/route.ts+++ b/site/src/app/api/billing/webhook/route.ts@@ -1,6 +1,15 @@import { NextResponse } from "next/server";import type Stripe from "stripe";+import {+ handleAutoReloadPaymentFailed,+ handleAutoReloadPaymentSucceeded,+ handleCreditTopUpCheckout,+} from "@/lib/billing/credit-purchases";+import {+ subscriptionIsPro,+ syncProSubscription,+} from "@/lib/billing/pro-subscription";import {getStripe,stripeId,@@ -10,6 +19,16 @@ import { notFoundResponse } from "@/lib/donkey-api-auth";export const dynamic = "force-dynamic";+// Two subscription products share these webhook events; route each Stripe+// subscription to the right sync by its price (Pro vs Vision, the default).+async function syncSubscription(subscription: Stripe.Subscription) {+ if (subscriptionIsPro(subscription)) {+ await syncProSubscription(subscription);+ return;+ }+ await syncVisionSubscription(subscription);+}+// Public, signature-verified Stripe webhook. This is an intentional exception to// the "wrap every route with withDonkeyAuth" rule (see docs/guides/backend-apis):// Stripe authenticates via the webhook signature, not a Donkey session.@@ -43,17 +62,29 @@ export async function POST(request: Request) {switch (event.type) {case "checkout.session.completed": {- const subscriptionId = stripeId(event.data.object.subscription);+ const checkoutSession = event.data.object;+ const subscriptionId = stripeId(checkoutSession.subscription);if (subscriptionId) {const subscription = await stripe.subscriptions.retrieve(subscriptionId);- await syncVisionSubscription(subscription);+ await syncSubscription(subscription);+ } else {+ // A one-time credit top-up (mode=payment) has no subscription.+ await handleCreditTopUpCheckout(stripe, checkoutSession);}break;}+ case "payment_intent.succeeded": {+ await handleAutoReloadPaymentSucceeded(event.data.object);+ break;+ }+ case "payment_intent.payment_failed": {+ await handleAutoReloadPaymentFailed(event.data.object);+ break;+ }case "customer.subscription.created":case "customer.subscription.updated":case "customer.subscription.deleted": {- await syncVisionSubscription(event.data.object);+ await syncSubscription(event.data.object);break;}case "invoice.paid":@@ -64,7 +95,7 @@ export async function POST(request: Request) {const subscriptionId = stripeId(invoice.subscription);if (subscriptionId) {const subscription = await stripe.subscriptions.retrieve(subscriptionId);- await syncVisionSubscription(subscription);+ await syncSubscription(subscription);}break;}diff --git a/site/src/app/api/credits/grants/route.ts b/site/src/app/api/credits/grants/route.tsindex 2b0584dd..ad685944 100644--- a/site/src/app/api/credits/grants/route.ts+++ b/site/src/app/api/credits/grants/route.ts@@ -12,12 +12,20 @@ import { prisma } from "@/lib/prisma";export const dynamic = "force-dynamic";-const creditGrantRequestSchema = z.object({- amountDollars: z.coerce.number().int().positive().max(100),- description: z.string().trim().min(1).max(500).optional(),- sourceId: z.string().trim().min(1).max(160).optional(),- userId: z.string().trim().min(1),-}).strict();+// The target is identified by userId (e.g. "+$100 to me") or by email (the+// grant-to-user form). At least one is required.+const creditGrantRequestSchema = z+ .object({+ amountDollars: z.coerce.number().int().positive().max(100),+ description: z.string().trim().min(1).max(500).optional(),+ email: z.string().trim().email().optional(),+ sourceId: z.string().trim().min(1).max(160).optional(),+ userId: z.string().trim().min(1).optional(),+ })+ .strict()+ .refine((data) => Boolean(data.userId || data.email), {+ message: "Provide a userId or an email.",+ });export const POST = withDonkeyAuth(async (request) => {if (!(await isDonkeySuperUser(request.donkey.userId))) {@@ -49,9 +57,9 @@ export const POST = withDonkeyAuth(async (request) => {email: true,id: true,},- where: {- id: parsed.data.userId,- },+ where: parsed.data.userId+ ? { id: parsed.data.userId }+ : { email: parsed.data.email },});if (!targetUser) {diff --git a/site/src/app/app/settings/_components/CreditsCard.tsx b/site/src/app/app/settings/_components/CreditsCard.tsxnew file mode 100644index 00000000..87ec6977--- /dev/null+++ b/site/src/app/app/settings/_components/CreditsCard.tsx@@ -0,0 +1,217 @@+"use client";++import { useState } from "react";++import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Skeleton } from "@/components/ui/skeleton";+import { ApiError } from "@/queries/apiClient";+import {+ useCreditAutoReload,+ useCreditBalance,+ useStartCreditCheckout,+ useUpdateCreditAutoReload,+} from "@/queries/credits";++const presets = [5, 25, 50, 100];++function formatDollars(value: string): string {+ const parsed = Number.parseFloat(value);+ if (!Number.isFinite(parsed)) {+ return "$0.00";+ }+ return parsed.toLocaleString("en-US", {+ currency: "USD",+ style: "currency",+ });+}++export function CreditsCard() {+ const balance = useCreditBalance();+ const checkout = useStartCreditCheckout();+ const [customAmount, setCustomAmount] = useState("");++ const startCheckout = (amountDollars: number) => {+ checkout.mutate(amountDollars, {+ onSuccess: (result) => window.location.assign(result.url),+ });+ };++ const customValue = Number.parseInt(customAmount, 10);+ const customValid = Number.isFinite(customValue) && customValue >= 5;++ return (+ <Card>+ <CardHeader>+ <CardTitle>Credits</CardTitle>+ <CardDescription>+ Pay-as-you-go balance for the Donkey app. Buy more any time.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-6">+ <div>+ {balance.isLoading ? (+ <Skeleton className="h-9 w-32" />+ ) : (+ <div className="text-3xl font-semibold tabular-nums">+ {formatDollars(balance.data?.balance ?? "0")}+ </div>+ )}+ <p className="mt-1 text-sm text-muted-foreground">Available balance</p>+ </div>++ <div className="space-y-3">+ <Label>Buy credits</Label>+ <div className="flex flex-wrap gap-2">+ {presets.map((amount) => (+ <Button+ disabled={checkout.isPending}+ key={amount}+ onClick={() => startCheckout(amount)}+ variant="outline"+ >+ ${amount}+ </Button>+ ))}+ </div>+ <div className="flex items-end gap-2">+ <div className="space-y-1">+ <Label className="text-xs text-muted-foreground" htmlFor="custom-amount">+ Custom amount (USD)+ </Label>+ <Input+ className="w-32"+ id="custom-amount"+ inputMode="numeric"+ min={5}+ onChange={(event) => setCustomAmount(event.target.value)}+ placeholder="50"+ type="number"+ value={customAmount}+ />+ </div>+ <Button+ disabled={!customValid || checkout.isPending}+ onClick={() => startCheckout(customValue)}+ >+ {checkout.isPending ? "Starting…" : "Buy"}+ </Button>+ </div>+ {checkout.isError ? (+ <p className="text-sm text-destructive">+ Couldn't start checkout. Try again in a moment.+ </p>+ ) : null}+ </div>++ <AutoReloadSection onNeedsCard={() => startCheckout(presets[1])} />+ </CardContent>+ </Card>+ );+}++function AutoReloadSection({ onNeedsCard }: { onNeedsCard: () => void }) {+ const autoReload = useCreditAutoReload();+ const update = useUpdateCreditAutoReload();+ const [needsCard, setNeedsCard] = useState(false);++ if (autoReload.isLoading) {+ return <Skeleton className="h-24 w-full" />;+ }++ const data = autoReload.data;+ const enabled = data?.enabled ?? false;++ const save = (next: {+ enabled: boolean;+ thresholdDollars: number;+ amountDollars: number;+ }) => {+ setNeedsCard(false);+ update.mutate(next, {+ onError: (error) => {+ if (error instanceof ApiError && error.code === "no_payment_method") {+ setNeedsCard(true);+ }+ },+ });+ };++ return (+ <form+ className="space-y-3 border-t pt-5"+ onSubmit={(event) => {+ event.preventDefault();+ const form = new FormData(event.currentTarget);+ save({+ amountDollars: Number(form.get("amount")),+ enabled: form.get("enabled") === "on",+ thresholdDollars: Number(form.get("threshold")),+ });+ }}+ >+ <label className="flex items-center gap-2 text-sm font-medium">+ <input+ className="size-4 accent-primary"+ defaultChecked={enabled}+ name="enabled"+ type="checkbox"+ />+ Auto-reload when my balance runs low+ </label>+ <div className="flex flex-wrap items-end gap-3 text-sm text-muted-foreground">+ <span>When balance falls below</span>+ <div className="flex items-center gap-1">+ <span>$</span>+ <Input+ className="w-20"+ defaultValue={data?.thresholdDollars ?? 10}+ min={0}+ name="threshold"+ type="number"+ />+ </div>+ <span>automatically buy</span>+ <div className="flex items-center gap-1">+ <span>$</span>+ <Input+ className="w-20"+ defaultValue={data?.amountDollars ?? 25}+ min={5}+ name="amount"+ type="number"+ />+ </div>+ <Button disabled={update.isPending} size="sm" type="submit">+ {update.isPending ? "Saving…" : "Save"}+ </Button>+ </div>+ {data?.status === "failed" && data.lastError ? (+ <p className="text-sm text-destructive">+ Last auto-reload failed: {data.lastError}+ </p>+ ) : null}+ {needsCard ? (+ <p className="text-sm text-muted-foreground">+ Auto-reload needs a saved card.{" "}+ <button+ className="text-primary underline-offset-4 hover:underline"+ onClick={onNeedsCard}+ type="button"+ >+ Buy credits once+ </button>{" "}+ to save one, then turn this on.+ </p>+ ) : null}+ </form>+ );+}diff --git a/site/src/app/app/settings/_components/ProCard.tsx b/site/src/app/app/settings/_components/ProCard.tsxnew file mode 100644index 00000000..11284036--- /dev/null+++ b/site/src/app/app/settings/_components/ProCard.tsx@@ -0,0 +1,126 @@+"use client";++import {+ useOpenBillingPortal,+ useProSubscription,+ useStartCheckout,+} from "@/queries/billing";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Skeleton } from "@/components/ui/skeleton";++function formatDollars(value: string | null): string {+ if (value === null) {+ return "—";+ }+ const parsed = Number.parseFloat(value);+ if (!Number.isFinite(parsed)) {+ return "—";+ }+ return parsed.toLocaleString("en-US", { currency: "USD", style: "currency" });+}++export function ProCard() {+ const pro = useProSubscription();+ const checkout = useStartCheckout();+ const portal = useOpenBillingPortal();++ if (pro.isLoading) {+ return (+ <Card>+ <CardHeader>+ <Skeleton className="h-6 w-40" />+ </CardHeader>+ <CardContent>+ <Skeleton className="h-16 w-full" />+ </CardContent>+ </Card>+ );+ }++ const data = pro.data;+ const isActive = data?.isActive ?? false;++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-3">+ Donkey Pro+ {isActive && data ? (+ <Badge variant="default">{data.status}</Badge>+ ) : null}+ </CardTitle>+ <CardDescription>+ A monthly usage allowance for the Donkey app. The included+ allowance is spent before your purchased credits, and resets each+ month.+ </CardDescription>+ </CardHeader>+ <CardContent className="text-sm text-muted-foreground">+ {isActive && data ? (+ <div className="space-y-1">+ <div className="text-foreground">+ {formatDollars(data.allowanceRemaining)} of{" "}+ {formatDollars(data.monthlyAllowance)} included left this month+ </div>+ <div>+ Renews:{" "}+ {data.currentPeriodEnd+ ? new Date(data.currentPeriodEnd).toLocaleDateString()+ : "—"}+ </div>+ {data.cancelAtPeriodEnd ? (+ <div className="text-foreground">+ Cancels at the end of the current period.+ </div>+ ) : null}+ </div>+ ) : (+ <p>+ Subscribe to include a monthly usage allowance. You can still buy+ credits any time; the included allowance is used first.+ </p>+ )}+ </CardContent>+ <CardFooter className="gap-3">+ {isActive ? (+ <Button+ disabled={portal.isPending}+ onClick={() =>+ portal.mutate(undefined, {+ onSuccess: (result) => window.location.assign(result.url),+ })+ }+ variant="secondary"+ >+ {portal.isPending ? "Opening…" : "Manage billing"}+ </Button>+ ) : (+ <Button+ disabled={checkout.isPending}+ onClick={() =>+ checkout.mutate("pro", {+ onSuccess: (result) => window.location.assign(result.url),+ })+ }+ >+ {checkout.isPending ? "Starting…" : "Subscribe to Pro"}+ </Button>+ )}+ {checkout.isError || portal.isError ? (+ <span className="text-sm text-destructive">+ Billing is unavailable right now.+ </span>+ ) : null}+ </CardFooter>+ </Card>+ );+}diff --git a/site/src/app/app/settings/_components/SuperuserCreditsCard.tsx b/site/src/app/app/settings/_components/SuperuserCreditsCard.tsxnew file mode 100644index 00000000..f327e577--- /dev/null+++ b/site/src/app/app/settings/_components/SuperuserCreditsCard.tsx@@ -0,0 +1,113 @@+"use client";++import { useState } from "react";++import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { useAccount, useGrantCredits } from "@/queries/credits";++// Super users top up in $100 increments — the manual grant route caps a single+// grant at $100, so larger top-ups are repeated clicks.+const incrementDollars = 100;++export function SuperuserCreditsCard() {+ const account = useAccount();+ const grant = useGrantCredits();+ const [email, setEmail] = useState("");+ const [lastResult, setLastResult] = useState<string | null>(null);++ // Render nothing for non-super users (and while we don't yet know).+ if (!account.data?.superUser) {+ return null;+ }++ const grantToSelf = () => {+ setLastResult(null);+ grant.mutate(+ { amountDollars: incrementDollars, userId: account.data.userId },+ {+ onSuccess: (result) =>+ setLastResult(+ `Added $${incrementDollars} to ${result.targetUser.email} — new balance $${result.balance.balance}.`,+ ),+ },+ );+ };++ const grantToEmail = () => {+ if (!email.trim()) {+ return;+ }+ setLastResult(null);+ grant.mutate(+ { amountDollars: incrementDollars, email: email.trim() },+ {+ onSuccess: (result) => {+ setLastResult(+ `Added $${incrementDollars} to ${result.targetUser.email} — new balance $${result.balance.balance}.`,+ );+ setEmail("");+ },+ },+ );+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ Super user · Credits+ </CardTitle>+ <CardDescription>+ Grant credits in ${incrementDollars} increments. Visible to super users+ only.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-5">+ <div>+ <Button disabled={grant.isPending} onClick={grantToSelf}>+ {grant.isPending ? "Adding…" : `+ $${incrementDollars} to my account`}+ </Button>+ </div>++ <div className="space-y-2 border-t pt-5">+ <Label htmlFor="grant-email">Grant to a user</Label>+ <div className="flex items-end gap-2">+ <Input+ className="max-w-xs"+ id="grant-email"+ onChange={(event) => setEmail(event.target.value)}+ placeholder="[email protected]"+ type="email"+ value={email}+ />+ <Button+ disabled={grant.isPending || !email.trim()}+ onClick={grantToEmail}+ variant="secondary"+ >+ Grant ${incrementDollars}+ </Button>+ </div>+ </div>++ {lastResult ? (+ <p className="text-sm text-muted-foreground">{lastResult}</p>+ ) : null}+ {grant.isError ? (+ <p className="text-sm text-destructive">+ Grant failed. Check the email and try again.+ </p>+ ) : null}+ </CardContent>+ </Card>+ );+}diff --git a/site/src/app/app/settings/page.tsx b/site/src/app/app/settings/page.tsxindex d7d58f10..3ecff364 100644--- a/site/src/app/app/settings/page.tsx+++ b/site/src/app/app/settings/page.tsx@@ -1,6 +1,9 @@"use client";+import { CreditsCard } from "@/app/app/settings/_components/CreditsCard";+import { ProCard } from "@/app/app/settings/_components/ProCard";import { SubscriptionCard } from "@/app/app/settings/_components/SubscriptionCard";+import { SuperuserCreditsCard } from "@/app/app/settings/_components/SuperuserCreditsCard";import { UsageCard } from "@/app/app/settings/_components/UsageCard";export default function SettingsOverviewPage() {@@ -9,11 +12,15 @@ export default function SettingsOverviewPage() {<div><h1 className="text-2xl font-semibold">Overview</h1><p className="mt-1 text-sm text-muted-foreground">- Your Vision API subscription and usage this billing period.+ Your subscriptions, credit balance, and+ usage this billing period.</p></div>+ <ProCard />+ <CreditsCard /><SubscriptionCard /><UsageCard />+ <SuperuserCreditsCard /></div>);}diff --git a/site/src/lib/billing/credit-auto-reload.ts b/site/src/lib/billing/credit-auto-reload.tsnew file mode 100644index 00000000..a23da288--- /dev/null+++ b/site/src/lib/billing/credit-auto-reload.ts@@ -0,0 +1,70 @@+import {+ creditAutoReloadKind,+ dollarsToStripeCents,+} from "@/lib/billing/credit-purchases";+import { getStripe } from "@/lib/billing/stripe";+import { creditMicrosPerCredit, zeroCreditMicros } from "@/lib/credits/amounts";+import { prisma } from "@/lib/prisma";++// Fired after an inference charge commits (best-effort, non-blocking). If the+// balance fell below the user's auto-reload threshold, start an off-session+// Stripe charge against the saved card. The actual credit grant happens in the+// payment_intent.succeeded webhook, not here — this only kicks off the charge.+export async function maybeTriggerCreditAutoReload(userId: string): Promise<void> {+ const config = await prisma.creditAutoReload.findUnique({ where: { userId } });+ if (+ !config ||+ !config.enabled ||+ !config.stripeCustomerId ||+ !config.stripePaymentMethodId ||+ config.status === "charging" ||+ config.amountMicros <= zeroCreditMicros+ ) {+ return;+ }++ const account = await prisma.userCreditAccount.findUnique({+ select: { balanceMicros: true },+ where: { userId },+ });+ if (!account || account.balanceMicros > config.thresholdMicros) {+ return;+ }++ // Claim the charging lock atomically. If another concurrent run already+ // claimed it, count is 0 and we bail — never double-charge.+ const claimed = await prisma.creditAutoReload.updateMany({+ data: { status: "charging" },+ where: { status: { not: "charging" }, userId },+ });+ if (claimed.count === 0) {+ return;+ }++ const amountDollars = Number(config.amountMicros / creditMicrosPerCredit);+ try {+ const stripe = getStripe();+ await stripe.paymentIntents.create({+ amount: dollarsToStripeCents(amountDollars),+ confirm: true,+ currency: "usd",+ customer: config.stripeCustomerId,+ metadata: {+ amountDollars: String(amountDollars),+ kind: creditAutoReloadKind,+ userId,+ },+ off_session: true,+ payment_method: config.stripePaymentMethodId,+ });+ } catch (error) {+ await prisma.creditAutoReload.updateMany({+ data: {+ lastError:+ error instanceof Error ? error.message : "Auto-reload charge failed.",+ status: "failed",+ },+ where: { userId },+ });+ }+}diff --git a/site/src/lib/billing/credit-purchases.ts b/site/src/lib/billing/credit-purchases.tsnew file mode 100644index 00000000..d0a44023--- /dev/null+++ b/site/src/lib/billing/credit-purchases.ts@@ -0,0 +1,178 @@+import type Stripe from "stripe";++import { stripeId } from "@/lib/billing/stripe";+import { creditStringToMicros } from "@/lib/credits/amounts";+import { grantCredits } from "@/lib/credits/inference";+import { prisma } from "@/lib/prisma";++// Self-serve credit top-ups. Presets drive the quick-buy buttons; the custom+// field accepts any whole-dollar amount in [min, max]. Amounts are whole dollars+// so they map cleanly to Stripe unit_amount cents and the grant ledger.+export const creditTopUpPresetsDollars = [5, 25, 50, 100] as const;+export const creditTopUpMinDollars = 5;+export const creditTopUpMaxDollars = 2_000;++// Stripe metadata "kind" tags that route a completed payment to a credit grant.+export const creditTopUpKind = "credit_topup";+export const creditAutoReloadKind = "credit_topup_autoreload";++export function dollarsToStripeCents(amountDollars: number): number {+ return Math.round(amountDollars * 100);+}++function parseAmountDollars(value: string | undefined): number | null {+ if (!value) {+ return null;+ }+ const parsed = Number.parseInt(value, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;+}++// Grant purchased credits. Idempotent on (source, sourceId): Stripe can deliver+// the same event more than once, and grantCredits dedupes by sourceId, so the+// Stripe payment_intent id is used as the sourceId.+//+// Purchased credits NEVER expire: no expiresAt / periodEnd is set. That is also+// what places them last in the debit queue (see compareGrantConsumptionOrder in+// credits/inference.ts) — a subscription's periodic allotment is drawn down+// first, and prepaid purchased credit is only spent once that runs out.+async function grantPurchasedCredits(input: {+ userId: string;+ amountDollars: number;+ source: string;+ sourceId: string;+ description: string;+}) {+ await grantCredits({+ amountMicros: creditStringToMicros(String(input.amountDollars)),+ description: input.description,+ // No expiresAt / periodEnd — purchased credits are permanent.+ metadata: {+ amountDollars: String(input.amountDollars),+ purchaseSource: input.source,+ },+ source: input.source,+ sourceId: input.sourceId,+ userId: input.userId,+ });+}++// A one-time top-up Checkout completed. Grant the credits and remember the saved+// payment method so auto-reload can charge it off-session later. The card is+// saved via setup_future_usage on the Checkout session.+export async function handleCreditTopUpCheckout(+ stripe: Stripe,+ session: Stripe.Checkout.Session,+): Promise<void> {+ if (session.mode !== "payment" || session.metadata?.kind !== creditTopUpKind) {+ return;+ }++ const userId = session.metadata?.userId;+ const amountDollars = parseAmountDollars(session.metadata?.amountDollars);+ const paymentIntentId = stripeId(session.payment_intent);+ if (!userId || !amountDollars || !paymentIntentId) {+ console.error("[billing] incomplete credit top-up checkout", {+ amountDollars,+ paymentIntentId,+ session: session.id,+ userId,+ });+ return;+ }++ await grantPurchasedCredits({+ amountDollars,+ description: `$${amountDollars} credit top-up`,+ source: "stripe_topup",+ sourceId: paymentIntentId,+ userId,+ });++ // Saving the card for auto-reload is best-effort: it must never fail the+ // webhook (and thus the already-granted top-up) if it errors.+ try {+ await rememberSavedPaymentMethod(stripe, {+ customerId: stripeId(session.customer),+ paymentIntentId,+ userId,+ });+ } catch (error) {+ console.error("[billing] failed to save auto-reload payment method", error);+ }+}++// An off-session auto-reload charge succeeded. Grant the credits and clear the+// charging lock so a future low balance can trigger again.+export async function handleAutoReloadPaymentSucceeded(+ paymentIntent: Stripe.PaymentIntent,+): Promise<void> {+ if (paymentIntent.metadata?.kind !== creditAutoReloadKind) {+ return;+ }+ const userId = paymentIntent.metadata?.userId;+ const amountDollars = parseAmountDollars(paymentIntent.metadata?.amountDollars);+ if (!userId || !amountDollars) {+ return;+ }++ await grantPurchasedCredits({+ amountDollars,+ description: `$${amountDollars} auto-reload`,+ source: "stripe_autoreload",+ sourceId: paymentIntent.id,+ userId,+ });++ await prisma.creditAutoReload.updateMany({+ data: { lastChargeAt: new Date(), lastError: null, status: "idle" },+ where: { userId },+ });+}++// An off-session auto-reload charge failed (e.g. card declined). Record it and+// release the lock; the UI surfaces lastError so the user can fix the card.+export async function handleAutoReloadPaymentFailed(+ paymentIntent: Stripe.PaymentIntent,+): Promise<void> {+ if (paymentIntent.metadata?.kind !== creditAutoReloadKind) {+ return;+ }+ const userId = paymentIntent.metadata?.userId;+ if (!userId) {+ return;+ }++ await prisma.creditAutoReload.updateMany({+ data: {+ lastError:+ paymentIntent.last_payment_error?.message ?? "The auto-reload charge failed.",+ status: "failed",+ },+ where: { userId },+ });+}++async function rememberSavedPaymentMethod(+ stripe: Stripe,+ input: { userId: string; paymentIntentId: string; customerId: string | null },+): Promise<void> {+ const paymentIntent = await stripe.paymentIntents.retrieve(input.paymentIntentId);+ const paymentMethodId = stripeId(paymentIntent.payment_method);+ if (!paymentMethodId) {+ return;+ }++ await prisma.creditAutoReload.upsert({+ create: {+ stripeCustomerId: input.customerId,+ stripePaymentMethodId: paymentMethodId,+ userId: input.userId,+ },+ update: {+ ...(input.customerId ? { stripeCustomerId: input.customerId } : {}),+ stripePaymentMethodId: paymentMethodId,+ },+ where: { userId: input.userId },+ });+}diff --git a/site/src/lib/billing/pro-subscription.ts b/site/src/lib/billing/pro-subscription.tsnew file mode 100644index 00000000..7b89debb--- /dev/null+++ b/site/src/lib/billing/pro-subscription.ts@@ -0,0 +1,152 @@+import type Stripe from "stripe";++import { stripeId } from "@/lib/billing/stripe";+import { zeroCreditMicros } from "@/lib/credits/amounts";+import { grantCredits } from "@/lib/credits/inference";+import { prisma } from "@/lib/prisma";++// Credit micros per Stripe cent. $1 = 100 cents = 1,000,000 micros, so 1 cent = 10,000 micros.+const creditMicrosPerCent = BigInt(10_000);++// Donkey Pro: the Mac app subscription, separate from the Vision API product.+export const proPlanKey = "pro";++// Stripe subscription statuses that include the Pro allowance.+const activeStatuses = new Set(["active", "trialing"]);++export function isActiveProStatus(status: string): boolean {+ return activeStatuses.has(status);+}++export function proPriceId(): string | undefined {+ return process.env.STRIPE_PRO_PRICE_ID || undefined;+}++// The included monthly inference allowance equals the Pro plan price: a $20/mo+// plan includes $20 of app inference each period. Read straight from the+// recurring price's unit_amount (cents) — no separate metadata to configure.+export function allowanceMicrosFromPrice(+ price: Stripe.Price | null | undefined,+): bigint {+ const cents = price?.unit_amount;+ if (typeof cents === "number" && Number.isFinite(cents) && cents > 0) {+ return BigInt(Math.round(cents)) * creditMicrosPerCent;+ }+ return zeroCreditMicros;+}++export async function getActiveProSubscription(userId: string) {+ const subscription = await prisma.proSubscription.findUnique({+ where: { userId },+ });+ if (!subscription || !isActiveProStatus(subscription.status)) {+ return null;+ }+ return subscription;+}++// True when a Stripe subscription belongs to the Pro product (vs Vision). Used+// to route shared subscription webhook events to the right sync.+export function subscriptionIsPro(subscription: Stripe.Subscription): boolean {+ const priceId = subscription.items.data[0]?.price?.id;+ return Boolean(priceId && proPriceId() && priceId === proPriceId());+}++// Source of truth for a Pro subscription's lifecycle. Maps the Stripe object+// onto our row and, for each active billing period, grants the included+// allowance into the credit balance as an expiring grant. The grant is+// idempotent per (subscription, period start), so repeated webhook deliveries+// and the create/update/invoice events for one period grant the allowance once.+export async function syncProSubscription(+ subscription: Stripe.Subscription,+): Promise<void> {+ const userId = await resolveUserIdForSubscription(subscription);+ const customerId = stripeId(subscription.customer);+ if (!userId) {+ console.error("[billing] could not resolve user for Pro subscription", {+ customer: customerId,+ subscription: subscription.id,+ });+ return;+ }++ const item = subscription.items.data[0];+ const price = item?.price;+ const periodStart = unixToDate(item?.current_period_start ?? null);+ const periodEnd = unixToDate(item?.current_period_end ?? null);+ const allowanceMicros = allowanceMicrosFromPrice(price);++ await prisma.proSubscription.upsert({+ create: {+ cancelAtPeriodEnd: subscription.cancel_at_period_end,+ currentPeriodEnd: periodEnd,+ currentPeriodStart: periodStart,+ monthlyAllowanceMicros: allowanceMicros,+ planKey: proPlanKey,+ status: subscription.status,+ stripeCustomerId: customerId,+ stripeSubscriptionId: subscription.id,+ userId,+ },+ update: {+ cancelAtPeriodEnd: subscription.cancel_at_period_end,+ currentPeriodEnd: periodEnd,+ currentPeriodStart: periodStart,+ monthlyAllowanceMicros: allowanceMicros,+ status: subscription.status,+ stripeCustomerId: customerId,+ stripeSubscriptionId: subscription.id,+ },+ where: { userId },+ });++ // Grant the period's included allowance once it is active and the period is+ // known. expiresAt = period end means it is spent before never-expiring+ // purchased credits (see compareGrantConsumptionOrder) and does not roll over.+ if (+ isActiveProStatus(subscription.status) &&+ periodStart &&+ periodEnd &&+ allowanceMicros > BigInt(0)+ ) {+ await grantCredits({+ amountMicros: allowanceMicros,+ description: "Donkey Pro monthly allowance",+ expiresAt: periodEnd,+ metadata: { plan: proPlanKey },+ periodEnd,+ periodStart,+ source: "pro_subscription",+ sourceId: `pro:${subscription.id}:${item?.current_period_start ?? 0}`,+ userId,+ });+ }+}++async function resolveUserIdForSubscription(+ subscription: Stripe.Subscription,+): Promise<string | null> {+ const metadataUserId = subscription.metadata?.userId;+ if (metadataUserId) {+ return metadataUserId;+ }++ const customerId = stripeId(subscription.customer);+ if (customerId) {+ const row = await prisma.proSubscription.findFirst({+ where: { stripeCustomerId: customerId },+ });+ if (row) {+ return row.userId;+ }+ }++ return null;+}++function unixToDate(seconds: number | null | undefined): Date | null {+ if (!seconds) {+ return null;+ }+ return new Date(seconds * 1000);+}diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.tsindex dd65728b..be8fac4a 100644--- a/site/src/lib/credits/inference.ts+++ b/site/src/lib/credits/inference.ts@@ -326,7 +326,7 @@ export async function requireInferenceCredits(input: CreditPreflightInput) {}export async function recordInferenceUsage(input: InferenceUsageInput) {- return prisma.$transaction(+ const recorded = await prisma.$transaction(async (tx): Promise<RecordedInferenceUsage> => {const included = input.billingMode === "included";// "included" calls never read or charge the balance, so skip the@@ -419,6 +419,18 @@ export async function recordInferenceUsage(input: InferenceUsageInput) {isolationLevel: Prisma.TransactionIsolationLevel.Serializable,},);++ // After a real charge commits, top up the balance via auto-reload if it fell+ // below the user's threshold. Best-effort and non-blocking: a dynamic import+ // breaks the module cycle (billing -> credits -> billing), and failures never+ // affect the inference response. The grant lands later via the Stripe webhook.+ if (input.billingMode !== "included" && recorded.creditCostMicros > zeroCreditMicros) {+ void import("@/lib/billing/credit-auto-reload")+ .then((module) => module.maybeTriggerCreditAutoReload(input.userId))+ .catch(() => {});+ }++ return recorded;}export async function recordFailedInferenceUsage(input: {@@ -722,17 +734,6 @@ async function debitGrants() {let remainingCostMicros = creditCostMicros;const grants = await tx.userCreditGrant.findMany({- orderBy: [- {- expiresAt: {- sort: "asc",- nulls: "last",- },- },- {- createdAt: "asc",- },- ],where: {accountId,remainingAmountMicros: {@@ -745,7 +746,14 @@ async function debitGrants(},});- for (const grant of grants) {+ // Consumption priority: spend the subscription / periodic allotment (any grant with an expiry or a+ // billing period) BEFORE prepaid purchased credits, which never expire. Within the expiring set the+ // soonest-to-expire is spent first so nothing is wasted; permanent purchased credits are spent last,+ // oldest first. This ordering is exactly why top-ups are granted with no expiry (see grantCredits+ // callers): a non-expiring grant sorts to the back of the queue.+ const ordered = [...grants].sort(compareGrantConsumptionOrder);++ for (const grant of ordered) {if (remainingCostMicros <= zeroCreditMicros) {return;}@@ -768,6 +776,41 @@ async function debitGrants(}+type GrantConsumptionFields = {+ expiresAt: Date | null;+ periodEnd: Date | null;+ createdAt: Date;+};++// When a grant runs out (its expiry or billing-period end), as epoch millis, or null if it never+// expires. A subscription/periodic grant has one of these; a purchased top-up has neither.+function grantConsumptionDeadline(grant: GrantConsumptionFields): number | null {+ const deadline = grant.expiresAt ?? grant.periodEnd;+ return deadline ? deadline.getTime() : null;+}++// Orders grants for debit: expiring (subscription/periodic) credits ahead of non-expiring (purchased)+// ones, soonest deadline first, then oldest grant first. Keeps use-it-or-lose-it credit from being+// wasted while never-expiring purchased credit waits at the back.+function compareGrantConsumptionOrder(+ left: GrantConsumptionFields,+ right: GrantConsumptionFields,+): number {+ const leftDeadline = grantConsumptionDeadline(left);+ const rightDeadline = grantConsumptionDeadline(right);++ if (leftDeadline === null && rightDeadline !== null) {+ return 1;+ }+ if (leftDeadline !== null && rightDeadline === null) {+ return -1;+ }+ if (leftDeadline !== null && rightDeadline !== null && leftDeadline !== rightDeadline) {+ return leftDeadline - rightDeadline;+ }+ return left.createdAt.getTime() - right.createdAt.getTime();+}+async function assertWithinConfiguredLimits(input: CreditPreflightInput) {const now = new Date();const limits = await prisma.userCreditLimit.findMany({diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.tsindex 604477aa..bafe252f 100644--- a/site/src/queries/billing.ts+++ b/site/src/queries/billing.ts@@ -6,6 +6,24 @@ import { apiFetch } from "@/queries/apiClient";export const subscriptionQueryKey = ["billing", "subscription"] as const;export const usageQueryKey = ["billing", "usage"] as const;+export const proSubscriptionQueryKey = ["billing", "pro"] as const;++export type ProSubscription = {+ isActive: boolean;+ status: string | null;+ cancelAtPeriodEnd: boolean;+ currentPeriodEnd: string | null;+ // Included monthly allowance (USD) and how much is left this period.+ monthlyAllowance: string | null;+ allowanceRemaining: string;+};++export function useProSubscription() {+ return useQuery({+ queryFn: () => apiFetch<ProSubscription>("/api/billing/pro"),+ queryKey: proSubscriptionQueryKey,+ });+}// Plans that the checkout route understands. Only "vision" is self-serve today;// "pro" (the Mac app plan) is accepted by the landing card but the route returnsdiff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsnew file mode 100644index 00000000..5c0b5360--- /dev/null+++ b/site/src/queries/credits.ts@@ -0,0 +1,108 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";++import { apiFetch } from "@/queries/apiClient";++export const creditBalanceQueryKey = ["credits", "balance"] as const;+export const creditAutoReloadQueryKey = ["credits", "auto-reload"] as const;+export const accountQueryKey = ["account", "me"] as const;++export type CreditBalance = {+ balance: string;+ balanceMicros: string;+ lifetimeCharged: string;+ lifetimeGranted: string;+ recentUsageTotals: {+ count: number;+ creditsCharged: string;+ failedCount: number;+ model: string;+ provider: string;+ route: string;+ }[];+};++export type CreditAutoReload = {+ enabled: boolean;+ thresholdDollars: number;+ amountDollars: number;+ hasPaymentMethod: boolean;+ status: string;+ lastError: string | null;+};++export type Account = {+ userId: string;+ email: string | null;+ superUser: boolean;+};++export function useCreditBalance() {+ return useQuery({+ queryFn: () => apiFetch<CreditBalance>("/api/credits/balance"),+ queryKey: creditBalanceQueryKey,+ });+}++export function useAccount() {+ return useQuery({+ queryFn: () => apiFetch<Account>("/api/account/me"),+ queryKey: accountQueryKey,+ });+}++// Returns the Stripe Checkout URL; the caller redirects the browser. No+// invalidation here because the user leaves the page for Stripe and returns to+// /app/settings, which refetches on mount.+export function useStartCreditCheckout() {+ return useMutation({+ mutationFn: (amountDollars: number) =>+ apiFetch<{ url: string }>("/api/billing/credits/checkout", {+ body: JSON.stringify({ amountDollars }),+ method: "POST",+ }),+ });+}++export function useCreditAutoReload() {+ return useQuery({+ queryFn: () => apiFetch<CreditAutoReload>("/api/billing/credits/auto-reload"),+ queryKey: creditAutoReloadQueryKey,+ });+}++export function useUpdateCreditAutoReload() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (input: {+ enabled: boolean;+ thresholdDollars: number;+ amountDollars: number;+ }) =>+ apiFetch<CreditAutoReload>("/api/billing/credits/auto-reload", {+ body: JSON.stringify(input),+ method: "PUT",+ }),+ onSuccess: () =>+ queryClient.invalidateQueries({ queryKey: creditAutoReloadQueryKey }),+ });+}++// Super-user only: grant credits to a user (by email) or to self (by userId).+export function useGrantCredits() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (input: {+ amountDollars: number;+ email?: string;+ userId?: string;+ }) =>+ apiFetch<{ balance: CreditBalance; targetUser: { email: string } }>(+ "/api/credits/grants",+ { body: JSON.stringify(input), method: "POST" },+ ),+ onSuccess: () =>+ queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey }),+ });+}