Open source CapCut alternative.
TypeScript
feat(site): show balances as credits
David Le71ae3e46a88d
diff --git a/site/src/app/api/billing/credits/auto-reload/route.ts b/site/src/app/api/billing/credits/auto-reload/route.tsindex b6cd07ac..24b6c55d 100644--- a/site/src/app/api/billing/credits/auto-reload/route.ts+++ b/site/src/app/api/billing/credits/auto-reload/route.ts@@ -1,7 +1,7 @@import { NextResponse } from "next/server";import { z } from "zod";-import { creditMicrosPerCredit } from "@/lib/credits/amounts";+import { creditMicrosPerDollar } from "@/lib/credits/amounts";import {creditTopUpMaxDollars,creditTopUpMinDollars,@@ -23,7 +23,7 @@ type AutoReloadRow = {};function dollarsFromMicros(micros: bigint): number {- return Number(micros / creditMicrosPerCredit);+ return Number(micros / creditMicrosPerDollar);}function serialize(config: AutoReloadRow | null) {@@ -87,9 +87,9 @@ export const PUT = withDonkeyAuth(async (request) => {);}- const amountMicros = BigInt(parsed.data.amountDollars) * creditMicrosPerCredit;+ const amountMicros = BigInt(parsed.data.amountDollars) * creditMicrosPerDollar;const thresholdMicros =- BigInt(parsed.data.thresholdDollars) * creditMicrosPerCredit;+ BigInt(parsed.data.thresholdDollars) * creditMicrosPerDollar;await prisma.creditAutoReload.upsert({create: {diff --git a/site/src/app/api/billing/credits/checkout/route.ts b/site/src/app/api/billing/credits/checkout/route.tsindex 99ddd77b..1bf3e922 100644--- a/site/src/app/api/billing/credits/checkout/route.ts+++ b/site/src/app/api/billing/credits/checkout/route.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { auth } from "@/lib/auth";import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";+import { creditCountLabel, creditsPerDollar } from "@/lib/credits/format-credits";import {creditTopUpKind,creditTopUpMaxDollars,@@ -36,7 +37,7 @@ export const POST = withDonkeyAuth(async (request) => {return NextResponse.json({error: "invalid_request",- message: `Enter a whole-dollar amount between $${creditTopUpMinDollars} and $${creditTopUpMaxDollars}.`,+ message: `Choose between ${creditCountLabel(creditTopUpMinDollars * creditsPerDollar)} and ${creditCountLabel(creditTopUpMaxDollars * creditsPerDollar)}, in whole thousands.`,},{ status: 400 },);@@ -65,7 +66,7 @@ export const POST = withDonkeyAuth(async (request) => {price_data: {currency: "usd",product_data: {- description: `$${amountDollars} of Donkey inference credits`,+ description: creditCountLabel(amountDollars * creditsPerDollar),name: "Donkey credits",},unit_amount: dollarsToStripeCents(amountDollars),diff --git a/site/src/app/api/credits/offers/claim/route.ts b/site/src/app/api/credits/offers/claim/route.tsindex 0b001e6b..a77ced57 100644--- a/site/src/app/api/credits/offers/claim/route.ts+++ b/site/src/app/api/credits/offers/claim/route.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { getActiveProSubscription } from "@/lib/billing/pro-subscription";import { creditMicrosToString } from "@/lib/credits/amounts";-import { formatUsdPlain } from "@/lib/credits/format-usd";+import { formatCredits } from "@/lib/credits/format-credits";import { getCreditBalance } from "@/lib/credits/inference";import { isLinkClaimedKind, isSubscribeClaimedKind } from "@/lib/credits/offerKinds";import {@@ -54,7 +54,8 @@ export const GET = withDonkeyAuth(async (request) => {claim,claimed: offer.claimedAt !== null,closesAt: offer.closesAt?.toISOString() ?? null,- credits: formatUsdPlain(creditMicrosToString(offer.amountMicros)),+ credits: formatCredits(creditMicrosToString(offer.amountMicros)),+ dollars: creditMicrosToString(offer.amountMicros),expiresAt: offer.grant?.expiresAt?.toISOString() ?? null,lifetimeDays: offer.expiresAfterDays,});diff --git a/site/src/app/cut/_components/landing/cutPricingPlans.ts b/site/src/app/cut/_components/landing/cutPricingPlans.tsindex 090e720d..20a6c141 100644--- a/site/src/app/cut/_components/landing/cutPricingPlans.ts+++ b/site/src/app/cut/_components/landing/cutPricingPlans.ts@@ -1,5 +1,11 @@import type { PricingPlan } from "@/app/_components/landing/pricingPlans";import { promotionCovers, type AllowancePromotion } from "@/lib/billing/allowance-promotion";+import { creditsPerDollar, formatCreditCount } from "@/lib/credits/format-credits";++// The Pro price in USD a month; the included AI allowance equals it, so the+// card names the credits it buys.+const proMonthlyDollars = 20;+const proMonthlyCredits = formatCreditCount(proMonthlyDollars * creditsPerDollar);// What Pro costs and what it gets you, in one place: the landing card below// and the welcome sequence's last slide both read it, so the price can't say@@ -7,12 +13,12 @@ import { promotionCovers, type AllowancePromotion } from "@/lib/billing/allowancexport const CUT_PRO = {body: "Generate rich media with AI.",// The plan price in USD a month. The included AI allowance equals it.- monthlyDollars: 20,+ monthlyDollars: proMonthlyDollars,// What Pro adds. The landing card sits beside the Free card and opens with a// line pointing at it; nothing else does, so that line isn't in here.features: ["100 GB of cloud storage",- "Generous AI credits every month",+ `${proMonthlyCredits} AI credits every month`,"Image, video, voiceover, and music generation",],price: "$20/month",diff --git a/site/src/app/cut/app/(home)/settings/_components/CreditsCard.tsx b/site/src/app/cut/app/(home)/settings/_components/CreditsCard.tsxindex 32ca1f46..545123ed 100644--- a/site/src/app/cut/app/(home)/settings/_components/CreditsCard.tsx+++ b/site/src/app/cut/app/(home)/settings/_components/CreditsCard.tsx@@ -14,7 +14,13 @@ import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Skeleton } from "@/components/ui/skeleton";import { track } from "@/lib/analytics";-import { formatUsd } from "@/lib/credits/format-usd";+import {+ creditCountLabel,+ creditsPerDollar,+ dollarsForCredits,+ formatCredits,+} from "@/lib/credits/format-credits";+import { formatUsdPlain } from "@/lib/credits/format-usd";import {creditTopUpDefaultDollars,creditTopUpMaxDollars,@@ -29,6 +35,22 @@ import {useUpdateCreditAutoReload,} from "@/queries/credits";+// Credits are sold in whole thousands, so every pack is a whole-dollar Stripe+// charge: 5,000 credits is $5.+const creditPackStep = creditsPerDollar;+const minPackCredits = creditTopUpMinDollars * creditsPerDollar;+const maxPackCredits = creditTopUpMaxDollars * creditsPerDollar;++/** Whole dollars a credit amount typed in a field costs, or null when it is not a whole pack. */+function packDollars(value: string): number | null {+ // The whole field must be a count: "5000.9" or "5e3" is no pack.+ const credits = value.trim() === "" ? Number.NaN : Number(value);+ if (!Number.isInteger(credits) || credits % creditPackStep !== 0) {+ return null;+ }+ return dollarsForCredits(credits);+}+export function CreditsCard() {const balance = useCreditBalance();const checkout = useStartCreditCheckout();@@ -41,11 +63,12 @@ export function CreditsCard() {});};- const customValue = Number.parseInt(customAmount, 10);+ // The field holds credits; checkout takes the dollars they cost.+ const customDollars = packDollars(customAmount);const customValid =- Number.isFinite(customValue) &&- customValue >= creditTopUpMinDollars &&- customValue <= creditTopUpMaxDollars;+ customDollars !== null &&+ customDollars >= creditTopUpMinDollars &&+ customDollars <= creditTopUpMaxDollars;return (<Card>@@ -61,7 +84,7 @@ export function CreditsCard() {<Skeleton className="h-9 w-32" />) : (<div className="text-3xl font-semibold tabular-nums">- {formatUsd(balance.data?.balance ?? "0")}+ {formatCredits(balance.data?.balance ?? "0")}</div>)}<p className="mt-1 text-sm text-muted-foreground">Available balance</p>@@ -70,39 +93,47 @@ export function CreditsCard() {<div className="space-y-3"><Label>Buy credits</Label><div className="flex flex-wrap gap-2">- {creditTopUpPresetsDollars.map((amount) => (- <Button- disabled={checkout.isPending}- key={amount}- onClick={() => setCustomAmount(String(amount))}- variant={customAmount === String(amount) ? "default" : "outline"}- >- ${amount}- </Button>- ))}+ {creditTopUpPresetsDollars.map((amount) => {+ const credits = String(amount * creditsPerDollar);+ return (+ <Button+ disabled={checkout.isPending}+ key={amount}+ onClick={() => setCustomAmount(credits)}+ variant={customAmount === credits ? "default" : "outline"}+ >+ {creditCountLabel(amount * creditsPerDollar)} · {formatUsdPlain(String(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">- Amount (USD)+ Credits</Label><InputclassName="w-32"id="custom-amount"inputMode="numeric"- max={creditTopUpMaxDollars}- min={creditTopUpMinDollars}+ max={maxPackCredits}+ min={minPackCredits}onChange={(event) => setCustomAmount(event.target.value)}- placeholder="50"+ placeholder="50000"+ step={creditPackStep}type="number"value={customAmount}/></div><Buttondisabled={!customValid || checkout.isPending}- onClick={() => startCheckout(customValue)}+ onClick={() => customDollars !== null && startCheckout(customDollars)}>- {checkout.isPending ? "Starting…" : "Buy"}+ {checkout.isPending+ ? "Starting…"+ : customValid+ ? `Buy for ${formatUsdPlain(String(customDollars))}`+ : "Buy"}</Button></div>{checkout.isError ? (@@ -154,10 +185,11 @@ function AutoReloadSection({ onNeedsCard }: { onNeedsCard: () => void }) {onSubmit={(event) => {event.preventDefault();const form = new FormData(event.currentTarget);+ // The fields hold credits; the saved config is in whole dollars.save({- amountDollars: Number(form.get("amount")),+ amountDollars: Math.round(dollarsForCredits(Number(form.get("amount")))),enabled: form.get("enabled") === "on",- thresholdDollars: Number(form.get("threshold")),+ thresholdDollars: Math.round(dollarsForCredits(Number(form.get("threshold")))),});}}>@@ -173,25 +205,28 @@ function AutoReloadSection({ onNeedsCard }: { onNeedsCard: () => void }) {<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}+ className="w-28"+ defaultValue={(data?.thresholdDollars ?? 10) * creditsPerDollar}min={0}name="threshold"+ step={creditPackStep}type="number"/>+ <span>credits</span></div><span>automatically buy</span><div className="flex items-center gap-1">- <span>$</span><Input- className="w-20"- defaultValue={data?.amountDollars ?? creditTopUpDefaultDollars}- min={5}+ className="w-28"+ defaultValue={(data?.amountDollars ?? creditTopUpDefaultDollars) * creditsPerDollar}+ max={maxPackCredits}+ min={minPackCredits}name="amount"+ step={creditPackStep}type="number"/>+ <span>credits</span></div><Button disabled={update.isPending} size="sm" type="submit">{update.isPending ? "Saving…" : "Save"}diff --git a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsxindex 62336d65..47dee8f0 100644--- a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx+++ b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx@@ -19,10 +19,16 @@ import { Skeleton } from "@/components/ui/skeleton";import { activeProPromotion, CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";import { creditLifeClause, formatDeadline, minutesLeft } from "@/cut/components/SubscribeBonusPill";import { track } from "@/lib/analytics";-import { formatUsd } from "@/lib/credits/format-usd";+import { creditCountLabel, creditsFromDollars, creditsPerDollar, formatCreditCount, formatCredits } from "@/lib/credits/format-credits";import { useSubscribeBonus } from "@/queries/credits";import { useAccountConfig } from "@/queries/accountConfig";+// A whole-dollar allowance as the credits it buys: $20 → "20,000 credits".+const allowanceCredits = (dollars: number) => creditCountLabel(dollars * creditsPerDollar);++// The left-over half of "12,300 of 20,000 credits"; the total carries the unit.+const leftCount = (dollars: string) => formatCreditCount(creditsFromDollars(dollars, "down"));+// The promotion's last day, the way the card names it.const lastDayLabel = (day: string) =>new Date(`${day}T00:00:00Z`).toLocaleDateString(undefined, {@@ -76,13 +82,13 @@ export function ProCard() {{promotion.lastDay !== null ? (<><span className="font-medium">Get Pro by {lastDayLabel(promotion.lastDay)}</span> and every- month that starts by then includes ${promotion.allowanceDollars} of AI, {promotion.multiplier}× the- usual ${CUT_PRO.monthlyDollars}.+ month that starts by then includes {allowanceCredits(promotion.allowanceDollars)}, {promotion.multiplier}× the+ usual {allowanceCredits(CUT_PRO.monthlyDollars)}.</>) : (<>- Every month currently includes ${promotion.allowanceDollars} of AI, {promotion.multiplier}× the- usual ${CUT_PRO.monthlyDollars}.+ Every month currently includes {allowanceCredits(promotion.allowanceDollars)}, {promotion.multiplier}× the+ usual {allowanceCredits(CUT_PRO.monthlyDollars)}.</>)}</CardContent>@@ -91,8 +97,8 @@ export function ProCard() {<CardContent className="text-sm text-muted-foreground"><div className="space-y-1"><div className="text-foreground">- {formatUsd(data.allowanceRemaining)} of{" "}- {formatUsd(data.monthlyAllowance)} included left this month+ {leftCount(data.allowanceRemaining)} of{" "}+ {formatCredits(data.monthlyAllowance)} left this month</div>{data.endsAt ? (<div className="text-foreground">@@ -109,13 +115,13 @@ export function ProCard() {{promotion ? (<div>{promotion.lastDay !== null- ? `Months that start by ${lastDayLabel(promotion.lastDay)} include $${promotion.allowanceDollars} of AI.`- : `Each new month includes $${promotion.allowanceDollars} of AI.`}+ ? `Months that start by ${lastDayLabel(promotion.lastDay)} include ${allowanceCredits(promotion.allowanceDollars)}.`+ : `Each new month includes ${allowanceCredits(promotion.allowanceDollars)}.`}</div>) : null}{offer?.status === "claimed" ? (<div>- Your {formatUsd(offer.dollars)} {offer.origin === "app" ? "subscribe bonus" : "credit offer"} landed in+ Your {formatCredits(offer.dollars)} {offer.origin === "app" ? "subscribe bonus" : "credit offer"} landed inyour credits.</div>) : null}@@ -124,7 +130,7 @@ export function ProCard() {) : offer && offerOpen ? (<CardContent className="text-sm text-foreground">Subscribe for {CUT_PRO.price} by {formatDeadline(offer.closesAt)} and get a one-time{" "}- {formatUsd(offer.dollars)} in credits.{creditLifeClause(offer)}+ {formatCredits(offer.dollars)}.{creditLifeClause(offer)}</CardContent>) : null}<CardFooter className="gap-3">diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.tsindex 6d4fc477..e8d53318 100644--- a/site/src/clients/chatgpt/server/mcp.ts+++ b/site/src/clients/chatgpt/server/mcp.ts@@ -20,6 +20,7 @@ import { MAX_COMMANDS_PER_BATCH } from "@/cut/server/cloud/commands";import { DOC_EXPORT_PRESETS } from "@/cut/lib/exportPresets";import { bindCutLoudness, cutLoudness, LOUDNESS_CHOICES, LOUDNESS_IDS } from "@/cut/lib/loudnessSettings";import { getGlobalSetting } from "@/lib/config/effective";+import { formatCredits } from "@/lib/credits/format-credits";import {chatgptConfig,RESOURCE_METADATA_PATH,@@ -517,7 +518,7 @@ function describeProjectView(view: ProjectView): string {if (view.account) {const { credits, storageBytes, storageQuotaBytes, plan } = view.account;const storage = typeof storageQuotaBytes !== "number" ? `${mb(storageBytes)} MB used` : `${mb(storageBytes)} of ${mb(storageQuotaBytes)} MB used`;- return `Plan: ${plan}. AI credits: $${credits}. Cloud storage: ${storage}. Editing, previews and exports spend no credits.`;+ return `Plan: ${plan}. AI credit balance: ${formatCredits(credits)}. Cloud storage: ${storage}. Editing, previews and exports spend no credits.`;}if (view.view === "projects") {if (!view.projects.length) {diff --git a/site/src/components/UsageHistoryCard.tsx b/site/src/components/UsageHistoryCard.tsxindex da7fc70a..8edc363a 100644--- a/site/src/components/UsageHistoryCard.tsx+++ b/site/src/components/UsageHistoryCard.tsx@@ -21,6 +21,7 @@ import {TableHeader,TableRow,} from "@/components/ui/table";+import { formatCreditCharge } from "@/lib/credits/format-credits";import { cn } from "@/lib/utils";type RecentCall = UsageHistory["recent"][number];@@ -31,19 +32,13 @@ function callKey(call: RecentCall): string {return `${call.createdAt}-${call.requestKind}-${call.costCredits}`;}-// Cents by default, but show a third decimal when a value carries sub-cent-// precision (many app calls cost a fraction of a cent) so they aren't all-// "$0.00". Clean values stay at 2 decimals — min 2 / max 3 fraction digits.+// A charge in credits, rounded up so a sub-credit call reads as 1; a zero or+// unreadable value reads as 0 credits.function formatCostValue(value: number): string {if (!Number.isFinite(value) || value <= 0) {- return "$0.00";+ return formatCreditCharge(0);}- return value.toLocaleString("en-US", {- style: "currency",- currency: "USD",- minimumFractionDigits: 2,- maximumFractionDigits: 3,- });+ return formatCreditCharge(value);}function formatCallCost(call: RecentCall): string {@@ -60,7 +55,7 @@ function conversationLabel(conversationId: string): string {}// A conversation block's combined cost for its header. An all-included block has-// no credit cost, so label it "Included" rather than "$0.00".+// no credit cost, so label it "Included".function blockCostSummary(calls: RecentCall[]): string {if (calls.every((call) => call.billingStatus === "included")) {return "Included";diff --git a/site/src/cut/components/ClaimCreditsDialog.tsx b/site/src/cut/components/ClaimCreditsDialog.tsxindex c04bbb80..98cc3ec8 100644--- a/site/src/cut/components/ClaimCreditsDialog.tsx+++ b/site/src/cut/components/ClaimCreditsDialog.tsx@@ -61,7 +61,7 @@ function OpenDialog({ token, onClose }: { token: string; onClose: () => void })const subscribe = () => {if (!offer.data) return;track("subscribe_bonus_checkout_started", {- dollars: Number(offer.data.credits.replace(/[^0-9.]/g, "")),+ dollars: Number(offer.data.dollars),minutesLeft: offer.data.closesAt ? Math.max(0, Math.ceil((Date.parse(offer.data.closesAt) - Date.now()) / 60_000)) : 0,source: "email",});@@ -94,14 +94,14 @@ function OpenDialog({ token, onClose }: { token: string; onClose: () => void })cta = <OfferButton onClick={onClose}>OK</OfferButton>;secondary = null;} else if (done) {- title = `${offer.data.credits} is on your account`;- body = `${offer.data.credits} in AI credits is ready to spend.${- done.expiresAt ? ` It expires ${formatCreditExpiry(new Date(done.expiresAt))}.` : ""+ title = `${offer.data.credits} added to your account`;+ body = `They’re ready to spend.${+ done.expiresAt ? ` They expire ${formatCreditExpiry(new Date(done.expiresAt))}.` : ""}`;cta = <OfferButton onClick={onClose}>Start editing</OfferButton>;secondary = null;} else if (offer.data.claim === "subscribe") {- title = `Get ${offer.data.credits} in credits with Pro`;+ title = `Get ${offer.data.credits} with Pro`;({ body, terms } = subscribeOfferCopy({credits: offer.data.credits,expiresAt: null,@@ -114,7 +114,7 @@ function OpenDialog({ token, onClose }: { token: string; onClose: () => void })</OfferButton>);} else {- title = `${offer.data.credits} in credits is waiting`;+ title = `${offer.data.credits} are waiting`;({ body, terms } = claimOfferCopy({credits: offer.data.credits,closesAt: offer.data.closesAt,diff --git a/site/src/cut/components/CreditsPill.tsx b/site/src/cut/components/CreditsPill.tsxindex 77f89507..2e817566 100644--- a/site/src/cut/components/CreditsPill.tsx+++ b/site/src/cut/components/CreditsPill.tsx@@ -15,7 +15,7 @@ import { useHostedBalance, useInvalidateOnSettle } from "@/cut/lib/hosted";import { useCutBase } from "@/cut/lib/nav";import { useUpgradeToPro } from "@/cut/lib/proUpgrade";import { track } from "@/lib/analytics";-import { formatUsd } from "@/lib/credits/format-usd";+import { compactCredits, creditsFromDollars, formatCredits } from "@/lib/credits/format-credits";import { CREDITS_PILL_FLAG } from "@/lib/feature-flags";import { useProSubscription } from "@/queries/billing";import { creditBalanceQueryKey, useCreditBalance, type CreditBalance } from "@/queries/credits";@@ -26,20 +26,6 @@ import { useAccountFlags } from "@/queries/featureFlags";const PILL ="flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border border-transparent px-3 py-1.5 text-xs font-medium tabular-nums text-muted-foreground transition-colors hover:border-border hover:bg-card hover:shadow-xs";-/** The bar's reading of a balance: cents while there is less than $10, where- * each one changes what the next generation can be, and whole dollars past- * that, where they are noise. A round amount drops the ".00" either way. */-export function compactUsd(dollars: number): string {- const cents = Math.round(dollars * 100);- const showCents = dollars < 10 && cents % 100 !== 0;- return dollars.toLocaleString("en-US", {- currency: "USD",- style: "currency",- minimumFractionDigits: showCents ? 2 : 0,- maximumFractionDigits: showCents ? 2 : 0,- });-}-export function CreditsPill() {const user = useEngineUser();// Mounted above the account check so the hook order is stable; idle until@@ -50,9 +36,10 @@ export function CreditsPill() {return <BalancePill />;}-function BalancePill() {+/** Keeps the cached balance current with this tab's own charges: whoever+ * reads the balance mounts this, so it holds with the pill hidden too. */+export function useLiveCreditBalance() {const queryClient = useQueryClient();- const balance = useCreditBalance();const reported = useHostedBalance((s) => s.balance);// A charged call reported the balance it left: that is the balance, with no@@ -65,6 +52,12 @@ function BalancePill() {}, [reported, queryClient]);// A call that answered without one: re-read once its charge has landed.useInvalidateOnSettle(creditBalanceQueryKey);+}++function BalancePill() {+ const queryClient = useQueryClient();+ const balance = useCreditBalance();+ useLiveCreditBalance();// Background work — renders, cloud jobs — charges without a call from this// tab, and a top-up happens on another page; a slow poll keeps the number// honest between them, and a focus refetch catches the trip back from billing.@@ -86,12 +79,14 @@ function BalancePill() {return (<Popover><PopoverTrigger- aria-label={`Credits: ${compactUsd(dollars)}`}- onClick={() => track("cut_credits_pill_clicked", { dollars })}+ aria-label={`Credits: ${formatCredits(balance.data.balance)}`}+ onClick={() =>+ track("cut_credits_pill_clicked", { credits: creditsFromDollars(balance.data.balance, "down"), dollars })+ }className={PILL}><Zap className="size-3.5" />- {compactUsd(dollars)}+ {compactCredits(balance.data.balance)}</PopoverTrigger><PopoverContent side="bottom" align="end" sideOffset={6} className="w-64 p-0"><PlanCard balance={balance.data.balance} />@@ -127,7 +122,7 @@ function PlanCard({ balance }: { balance: string }) {<div className="flex items-center gap-2.5 border-t border-border px-4 py-3"><Zap className="size-4 text-muted-foreground" /><span className="flex-1 text-muted-foreground">Credits</span>- <span className="font-medium tabular-nums">{formatUsd(balance)}</span>+ <span className="font-medium tabular-nums">{formatCredits(balance)}</span></div></div>);diff --git a/site/src/cut/components/OfferDialog.tsx b/site/src/cut/components/OfferDialog.tsxindex cdf06bd1..a2863cd5 100644--- a/site/src/cut/components/OfferDialog.tsx+++ b/site/src/cut/components/OfferDialog.tsx@@ -44,7 +44,7 @@ export function creditValidity(offer: { expiresAt: string | null; lifetimeDays:export function claimOfferCopy(offer: { credits: string; closesAt: string | null; lifetimeDays: number | null }): OfferCopy {const by = offer.closesAt ? ` Claim them by ${formatCreditExpiry(new Date(offer.closesAt))}.` : "";return {- body: `You have ${offer.credits} in AI credits.${by}`,+ body: `You have ${offer.credits} to claim.${by}`,terms: offer.lifetimeDays !== null ? `Once claimed, they’re valid for ${offer.lifetimeDays} days.` : null,};}@@ -57,7 +57,7 @@ export function subscribeOfferCopy(offer: {lifetimeDays: number | null;}): OfferCopy {return {- body: `Subscribe to Pro for ${CUT_PRO.price} and get ${offer.credits} in extra AI credits.`,+ body: `Subscribe to Pro for ${CUT_PRO.price} and get an extra ${offer.credits}.`,terms: creditValidity(offer),};}diff --git a/site/src/cut/components/SubscribeBonusPill.tsx b/site/src/cut/components/SubscribeBonusPill.tsxindex b40ac44e..e8e4ba47 100644--- a/site/src/cut/components/SubscribeBonusPill.tsx+++ b/site/src/cut/components/SubscribeBonusPill.tsx@@ -12,7 +12,7 @@ import { creditValidity, OfferButton, OfferDialog, OfferDismiss, subscribeOfferCimport { useEngineUser } from "@/cut/lib/backend/hooks";import { useInvalidateOnSettle } from "@/cut/lib/hosted";import { track } from "@/lib/analytics";-import { formatUsd } from "@/lib/credits/format-usd";+import { compactCredits, formatCredits } from "@/lib/credits/format-credits";import { useStartCheckout } from "@/queries/billing";import { subscribeBonusQueryKey, useSubscribeBonus, type SubscribeBonus } from "@/queries/credits";@@ -105,7 +105,7 @@ function OpenOffer({ offer }: { offer: SubscribeBonus }) {}, [minutes, queryClient]);if (minutes === 0) return null;- const dollars = formatUsd(offer.dollars);+ const credits = formatCredits(offer.dollars);const subscribe = () => {track("subscribe_bonus_checkout_started", {dollars: Number(offer.dollars),@@ -122,20 +122,20 @@ function OpenOffer({ offer }: { offer: SubscribeBonus }) {<buttontype="button"className={PILL}- aria-label={`${dollars} in credits with Pro, ${timeLeftLabel(minutes)}`}+ aria-label={`${credits} with Pro, ${timeLeftLabel(minutes)}`}onClick={() => setOpen(true)}><Gift className="size-3.5" />- {dollars} with Pro · {timeLeftLabel(minutes)}+ {compactCredits(offer.dollars)} credits with Pro · {timeLeftLabel(minutes)}</button><OfferDialogopen={open}onOpenChange={setOpen}banner="subscribe"- title={`Get ${dollars} in credits with Pro`}+ title={`Get ${credits} with Pro`}closesAt={offer.closesAt}{...subscribeOfferCopy({- credits: dollars,+ credits,expiresAt: offer.creditsExpireAt,lifetimeDays: offer.creditsLifetimeDays,})}diff --git a/site/src/cut/components/onboarding/slides/Credits.tsx b/site/src/cut/components/onboarding/slides/Credits.tsxindex 7b5cf289..a50d756c 100644--- a/site/src/cut/components/onboarding/slides/Credits.tsx+++ b/site/src/cut/components/onboarding/slides/Credits.tsx@@ -3,11 +3,12 @@import { useEffect, useRef } from "react";import { burstConfetti } from "@/cut/components/onboarding/confetti";+import { creditCountLabel, creditsFromDollars } from "@/lib/credits/format-credits";import { formatCreditExpiry } from "@/lib/credits/top-up";// The signup grant already landed when the account was created, so this slide-// never grants anything — it says what's there: the USD the grant carried, read-// from the account. That's as true on a replay as on a first run, so the words+// never grants anything — it says what's there: the credits the grant carried,+// read from the account. That's as true on a replay as on a first run, so the words// don't change between them; the burst fires every time the slide is reached.// A grant with an expiry names the date under the amount.export function CreditsSlide({@@ -38,20 +39,19 @@ export function CreditsSlide({/><div className="relative max-w-[900px]">{/* One line, two sizes: the amount at display size in coral, the words- a couple of steps down and thin beside it. Cents belong on a- balance, not on the offer. */}+ a couple of steps down and thin beside it. */}<h2 className="flex flex-wrap items-baseline justify-center gap-x-4 leading-[1.02] tracking-[-0.03em]"><span className="text-[clamp(40px,7.4vw,84px)] font-semibold text-coral tabular-nums">- ${credits}+ {creditCountLabel(creditsFromDollars(credits, "down"))}</span><span className="text-[clamp(26px,4.4vw,52px)] font-light">- in AI credits is on us+ on us</span></h2>{/* Ragged right on a narrow measure: the line breaks stay put insteadof the last line floating in the middle of the slide. */}<p className="mx-auto mt-4 max-w-[460px] text-left text-[16px] leading-[1.55] text-[#454545]">- Already in your account — nothing to claim. Spend it on generated+ Already in your account — nothing to claim. Spend them on generatedvideo, audio and images.</p>{expiresAt !== null && (diff --git a/site/src/emails/credits-expiring.tsx b/site/src/emails/credits-expiring.tsxindex 094a31a1..64c3e90c 100644--- a/site/src/emails/credits-expiring.tsx+++ b/site/src/emails/credits-expiring.tsx@@ -21,7 +21,7 @@ import { DonkeyMark } from "./_components/DonkeyMark";type CreditsExpiringEmailProps = {name: string;- // What is left of the grant, as USD ("$2.57").+ // What is left of the grant, in credits ("2,570 credits").credits: string;// The day it expires, already worded ("September 14, 2026").expiresOn: string;@@ -40,7 +40,7 @@ export default function CreditsExpiringEmail({<Html><Head /><Preview>- The {credits} in AI credits on your Donkey Cut account expires on {expiresOn}.+ The {credits} on your Donkey Cut account expire on {expiresOn}.</Preview><Tailwind config={{ presets: [pixelBasedPreset] }}><Body className="bg-white font-sans text-[#0F0E0D]">@@ -48,8 +48,8 @@ export default function CreditsExpiringEmail({<DonkeyMark /><Text className="text-[15px] leading-relaxed">Hey {name},</Text><Text className="text-[15px] leading-relaxed">- Just a quick heads up: the {credits} in AI credits on your Donkey- Cut account expires on {expiresOn}. Any unused credits will+ Just a quick heads up: the {credits} on your Donkey Cut account+ expire on {expiresOn}. Any unused credits willdisappear after that.</Text><Text className="text-[15px] leading-relaxed">@@ -88,7 +88,7 @@ export default function CreditsExpiringEmail({CreditsExpiringEmail.PreviewProps = {name: "Ada",- credits: "$2.57",+ credits: "2,570 credits",expiresOn: "September 14, 2026",editorUrl: "https://donkeycut.com/app",unsubscribeUrl: "https://donkeycut.com/unsubscribe?token=preview",diff --git a/site/src/emails/credits-offered.tsx b/site/src/emails/credits-offered.tsxindex 6dc31a9a..e0ce935e 100644--- a/site/src/emails/credits-offered.tsx+++ b/site/src/emails/credits-offered.tsx@@ -22,7 +22,7 @@ import { DonkeyMark } from "./_components/DonkeyMark";type CreditsOfferedEmailProps = {name: string;- // The offer, as USD ("$25.00").+ // The offer, in credits ("25,000 credits").credits: string;// How long the credits live once claimed, already worded ("7 days"), or// null when they never expire.@@ -44,21 +44,21 @@ export default function CreditsOfferedEmail({return (<Html><Head />- <Preview>{credits} in AI credits is waiting on your Donkey Cut account.</Preview>+ <Preview>{credits} are waiting on your Donkey Cut account.</Preview><Tailwind config={{ presets: [pixelBasedPreset] }}><Body className="bg-white font-sans text-[#0F0E0D]"><Container className="mx-auto max-w-[520px] px-6 py-12"><DonkeyMark /><Text className="text-[15px] leading-relaxed">Hey {name},</Text><Text className="text-[15px] leading-relaxed">- I added {credits} in AI credits to your Donkey Cut account. Click+ I added {credits} to your Donkey Cut account. Clickbelow to claim them.</Text><Buttonhref={claimUrl}className="rounded-lg bg-[#0F0E0D] px-6 py-3 text-[15px] font-semibold text-[#F5EFE0]">- Claim {credits} in credits+ Claim {credits}</Button><Text className="text-[15px] leading-relaxed">The link works until {claimBy}.{" "}@@ -94,7 +94,7 @@ export default function CreditsOfferedEmail({CreditsOfferedEmail.PreviewProps = {name: "Ada",- credits: "$25.00",+ credits: "25,000 credits",lifetime: "7 days",claimBy: "September 10, 2026",claimUrl: "https://donkeycut.com/app?claim=preview",diff --git a/site/src/emails/promotion.tsx b/site/src/emails/promotion.tsxindex 801e6478..b134c857 100644--- a/site/src/emails/promotion.tsx+++ b/site/src/emails/promotion.tsx@@ -90,7 +90,7 @@ PromotionEmail.PreviewProps = {preview: "Hey Ada,",blocks: [{ kind: "text", text: "Hey Ada," },- { kind: "text", text: "Get Pro before October 29 and every month that starts by then includes $100 of AI, 5× the usual $20." },+ { kind: "text", text: "Get Pro before October 29 and every month that starts by then includes 100,000 AI credits, 5× the usual 20,000." },{ kind: "button" },{ kind: "text", text: "David" },],diff --git a/site/src/emails/welcome.tsx b/site/src/emails/welcome.tsxindex 99a76337..fd3f2846 100644--- a/site/src/emails/welcome.tsx+++ b/site/src/emails/welcome.tsx@@ -23,7 +23,8 @@ import { DonkeyMark } from "./_components/DonkeyMark";type WelcomeEmailProps = {name: string;- // Null when the account received no signup credits.+ // The signup grant as people read it ("500 credits"); null when the+ // account received none.credits: string | null;unsubscribeUrl: string;};@@ -63,7 +64,7 @@ export default function WelcomeEmail({</Text>{credits !== null && (<Text className="text-[15px] leading-relaxed">- I also added ${credits} in AI credits to your account so you+ I also added {credits} to your account so youcan try AI Chat or generate videos, images, audio, and more.</Text>)}@@ -105,6 +106,6 @@ export default function WelcomeEmail({WelcomeEmail.PreviewProps = {name: "Ada",- credits: "3",+ credits: "500 credits",unsubscribeUrl: "https://donkeycut.com/unsubscribe?token=preview",} satisfies WelcomeEmailProps;diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.tsindex 9daa1755..16c636bf 100644--- a/site/src/lib/analytics.ts+++ b/site/src/lib/analytics.ts@@ -30,7 +30,7 @@ export type AnalyticsEvents = {// Cut cloud storage limits.cut_storage_pill_clicked: void;// The top bar's credits pill.- cut_credits_pill_clicked: { dollars: number };+ cut_credits_pill_clicked: { credits: number; dollars: number };cut_storage_upgrade_shown: { source: "quota-413" | "render" | "pill" };cut_grace_banner_shown: void;// First exposure to an experiment variant; the same value rides everydiff --git a/site/src/lib/config/registry.test.ts b/site/src/lib/config/registry.test.tsindex f4d07e02..0a3af21d 100644--- a/site/src/lib/config/registry.test.ts+++ b/site/src/lib/config/registry.test.ts@@ -28,6 +28,16 @@ describe("the product's settings registry", () => {expect(resolved.invalid).toEqual([{ key: "experimentResults", layer: "override" }]);});+ test("the signup grant is set to the cent", () => {+ // Cents are the smallest step su can set: 0.5 is 500 credits, and a stored+ // whole-dollar override keeps parsing.+ const schema = SETTINGS.signupCredits.schema;+ for (const dollars of [0, 0.07, 0.29, 0.5, 3]) {+ expect(schema.safeParse({ dollars, expiresAfterDays: 7 }).success).toBe(true);+ }+ expect(schema.safeParse({ dollars: 0.005, expiresAfterDays: 7 }).success).toBe(false);+ });+test("an override of one field replaces the whole value", () => {const value = { ...SETTINGS.experimentResults.default, shipPValue: 0.1 };const resolved = resolveSettings({ experimentResults: value }, []);diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex c96b38d5..d7ddc392 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -536,8 +536,9 @@ export const SETTINGS = defineSettings({signupCredits: {schema: z.object({- // USD the signup hook grants a new account; 0 grants nothing.- dollars: z.number().int().min(0).max(maxCreditGrantDollars),+ // USD the signup hook grants a new account, to the cent; 0 grants+ // nothing. People see it as credits: 0.5 → 500 credits.+ dollars: z.number().multipleOf(0.01).min(0).max(maxCreditGrantDollars),// Days the grant stays spendable; null keeps it forever.expiresAfterDays: z.number().int().min(1).max(maxCreditGrantExpiryDays).nullable(),})@@ -545,7 +546,7 @@ export const SETTINGS = defineSettings({default: { dollars: 0, expiresAfterDays: 7 },public: false,title: "Signup credits",- description: "USD a new account is granted at signup, and how many days the grant lives.",+ description: "USD a new account is granted at signup, shown as 1,000 credits per dollar, and how many days the grant lives.",},emailSendBudget: {schema: zdiff --git a/site/src/lib/credits/amounts.ts b/site/src/lib/credits/amounts.tsindex cce1573b..450db25d 100644--- a/site/src/lib/credits/amounts.ts+++ b/site/src/lib/credits/amounts.ts@@ -1,8 +1,8 @@export const zeroCreditMicros = BigInt(0);-export const creditMicrosPerCredit = BigInt("1000000");+export const creditMicrosPerDollar = BigInt("1000000");// $1 = 100 cents = 1,000,000 micros, so 1 cent = 10,000 micros. Single source for// the Stripe-cents conversion used by subscription allowances and off-session charges.-export const creditMicrosPerCent = creditMicrosPerCredit / BigInt(100);+export const creditMicrosPerCent = creditMicrosPerDollar / BigInt(100);export function creditStringToMicros(value: string | undefined) {const trimmed = value?.trim();@@ -16,7 +16,7 @@ export function creditStringToMicros(value: string | undefined) {}const sign = match[1] === "-" ? -BigInt(1) : BigInt(1);- const whole = BigInt(match[2]) * creditMicrosPerCredit;+ const whole = BigInt(match[2]) * creditMicrosPerDollar;const fractional = BigInt((match[3] ?? "").padEnd(6, "0"));return sign * (whole + fractional);@@ -25,8 +25,8 @@ export function creditStringToMicros(value: string | undefined) {export function creditMicrosToString(value: bigint) {const sign = value < zeroCreditMicros ? "-" : "";const absolute = value < zeroCreditMicros ? -value : value;- const whole = absolute / creditMicrosPerCredit;- const fractional = absolute % creditMicrosPerCredit;+ const whole = absolute / creditMicrosPerDollar;+ const fractional = absolute % creditMicrosPerDollar;const fractionalText = fractional.toString().padStart(6, "0").replace(/0+$/u, "");return fractionalText ? `${sign}${whole}.${fractionalText}` : `${sign}${whole}`;diff --git a/site/src/lib/credits/format-credits.test.ts b/site/src/lib/credits/format-credits.test.tsnew file mode 100644index 00000000..de026c25--- /dev/null+++ b/site/src/lib/credits/format-credits.test.ts@@ -0,0 +1,43 @@+import { describe, expect, test } from "bun:test";++import {+ compactCredits,+ creditsFromDollars,+ dollarsForCredits,+ formatCreditCharge,+ formatCredits,+} from "@/lib/credits/format-credits";++describe("credits display", () => {+ test("a balance rounds down and a charge rounds up", () => {+ expect(creditsFromDollars("0.4999", "down")).toBe(499);+ expect(creditsFromDollars("0.0001", "up")).toBe(1);+ expect(creditsFromDollars("0.5", "down")).toBe(500);+ expect(creditsFromDollars(0.5, "up")).toBe(500);+ });++ test("an overdraft never reads as less owed", () => {+ expect(creditsFromDollars("-0.0005", "down")).toBe(-1);+ expect(formatCredits("-2.4")).toBe("-2,400 credits");+ });++ test("labels count and pluralize", () => {+ expect(formatCredits("0.5")).toBe("500 credits");+ expect(formatCredits("0.001")).toBe("1 credit");+ expect(formatCredits(null)).toBe("—");+ expect(formatCreditCharge("0.0585")).toBe("59 credits");+ expect(formatCreditCharge("0")).toBe("0 credits");+ });++ test("the bar compacts past ten thousand", () => {+ expect(compactCredits("0.5")).toBe("500");+ expect(compactCredits("9.999")).toBe("9,999");+ expect(compactCredits("12.48")).toBe("12.4k");+ expect(compactCredits("20")).toBe("20k");+ expect(compactCredits("1234.5")).toBe("1.2M");+ });++ test("credits convert back to dollars", () => {+ expect(dollarsForCredits(5000)).toBe(5);+ });+});diff --git a/site/src/lib/credits/format-credits.ts b/site/src/lib/credits/format-credits.tsnew file mode 100644index 00000000..25a10be4--- /dev/null+++ b/site/src/lib/credits/format-credits.ts@@ -0,0 +1,77 @@+import { creditStringToMicros, zeroCreditMicros } from "@/lib/credits/amounts";++// Balances and prices live in USD micros; people read them as credits, at a+// fixed 1,000 credits per dollar (1 credit = 1,000 micros = $0.001). The rate+// is a unit definition: changing it reprices every number already shown.+export const creditsPerDollar = 1000;+const creditMicrosPerDisplayCredit = BigInt(1000);++// Which way a fraction of a credit goes. A balance rounds down so it never+// claims more than the account has; a charge rounds up so a cheap call still+// reads as one credit.+export type CreditRounding = "down" | "up";++const COUNT = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });++/** Whole credits in a dollar amount: "0.4999" down → 499, "0.0001" up → 1. */+export function creditsFromDollars(dollars: string | number, rounding: CreditRounding): number {+ const micros = creditStringToMicros(typeof dollars === "number" ? dollars.toFixed(6) : dollars);+ const whole = micros / creditMicrosPerDisplayCredit;+ const rest = micros % creditMicrosPerDisplayCredit;++ // BigInt division truncates toward zero; step one credit outward when a+ // remainder points the other way from the rounding.+ if (rest === zeroCreditMicros) {+ return Number(whole);+ }+ if (rounding === "down" && micros < zeroCreditMicros) {+ return Number(whole) - 1;+ }+ if (rounding === "up" && micros > zeroCreditMicros) {+ return Number(whole) + 1;+ }+ return Number(whole);+}++/** Dollars a whole number of credits costs: 5,000 → 5. */+export function dollarsForCredits(credits: number): number {+ return credits / creditsPerDollar;+}++/** A bare credit count: "12,480". */+export function formatCreditCount(credits: number): string {+ return COUNT.format(credits);+}++/** A credit count with its unit: "1 credit", "12,480 credits". */+export function creditCountLabel(credits: number): string {+ return `${formatCreditCount(credits)} ${Math.abs(credits) === 1 ? "credit" : "credits"}`;+}++/** A balance in a sentence: "500 credits". null/undefined → an em dash. */+export function formatCredits(dollars: string | number | null | undefined): string {+ if (dollars === null || dollars === undefined) {+ return "—";+ }+ return creditCountLabel(creditsFromDollars(dollars, "down"));+}++/** What a call cost: rounds up, so any non-zero charge reads as at least 1. */+export function formatCreditCharge(dollars: string | number): string {+ return creditCountLabel(creditsFromDollars(dollars, "up"));+}++/** The top bar's reading: "500", "12.4k", "1.2M", rounded down at each step. */+export function compactCredits(dollars: string | number): string {+ const credits = creditsFromDollars(dollars, "down");+ const size = Math.abs(credits);++ // Below ten thousand every credit shows; past it one decimal of the+ // thousand or million is enough to plan a session around.+ if (size < 10_000) {+ return formatCreditCount(credits);+ }+ const [divisor, suffix] = size < 1_000_000 ? [1_000, "k"] : [1_000_000, "M"];+ const tenths = Math.trunc((credits / divisor) * 10) / 10;+ return `${tenths.toLocaleString("en-US", { maximumFractionDigits: 1 })}${suffix}`;+}diff --git a/site/src/lib/credits/format-usd.ts b/site/src/lib/credits/format-usd.tsindex abee5cae..205ae5d3 100644--- a/site/src/lib/credits/format-usd.ts+++ b/site/src/lib/credits/format-usd.ts@@ -1,17 +1,3 @@-// Shared USD formatter for the settings cards so money renders identically-// everywhere. null/undefined → an em dash (no value yet); a non-numeric string-// → "$0.00"; otherwise a localized currency string.-export function formatUsd(value: string | null | undefined): string {- if (value === null || value === undefined) {- return "—";- }- const parsed = Number.parseFloat(value);- if (!Number.isFinite(parsed)) {- return "$0.00";- }- return parsed.toLocaleString("en-US", { currency: "USD", style: "currency" });-}-// Money in a sentence: whole dollars carry no cents ("$25"), anything else// its two ("$2.57").export function formatUsdPlain(value: string): string {diff --git a/site/src/lib/email/send-credits-expiring.ts b/site/src/lib/email/send-credits-expiring.tsindex 48895409..56a70959 100644--- a/site/src/lib/email/send-credits-expiring.ts+++ b/site/src/lib/email/send-credits-expiring.ts@@ -1,7 +1,7 @@import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";import { DONKEY_LOGO_CID, DONKEY_LOGO_PNG_BASE64 } from "@/emails/_components/logo";import CreditsExpiringEmail from "@/emails/credits-expiring";-import { formatUsdPlain } from "@/lib/credits/format-usd";+import { formatCredits } from "@/lib/credits/format-credits";import { formatCreditExpiry } from "@/lib/credits/top-up";import { bulkFrom, emailFrom, type EmailMessage, type EmailUser } from "@/lib/email/resend";import { unsubscribeActionUrl, unsubscribePageUrl } from "@/lib/email/unsubscribe";@@ -20,9 +20,9 @@ export function buildCreditsExpiringEmail(user: EmailUser, credits: string, expifrom,to: user.email,replyTo: emailFrom() || from,- subject: `Your ${formatUsdPlain(credits)} in AI credits expires ${formatCreditExpiry(expiresAt)}`,+ subject: `Your ${formatCredits(credits)} expire ${formatCreditExpiry(expiresAt)}`,react: CreditsExpiringEmail({- credits: formatUsdPlain(credits),+ credits: formatCredits(credits),editorUrl: `${DONKEYCUT_CANONICAL}/app`,expiresOn: formatCreditExpiry(expiresAt),name: firstName,diff --git a/site/src/lib/email/send-credits-offered.ts b/site/src/lib/email/send-credits-offered.tsindex 81cbd42e..8cd34b89 100644--- a/site/src/lib/email/send-credits-offered.ts+++ b/site/src/lib/email/send-credits-offered.ts@@ -1,7 +1,7 @@import { DONKEY_LOGO_CID, DONKEY_LOGO_PNG_BASE64 } from "@/emails/_components/logo";import CreditsOfferedEmail from "@/emails/credits-offered";import { creditMicrosToString } from "@/lib/credits/amounts";-import { formatUsdPlain } from "@/lib/credits/format-usd";+import { formatCredits } from "@/lib/credits/format-credits";import { formatCreditExpiry } from "@/lib/credits/top-up";import { bulkFrom, emailFrom, type EmailMessage, type EmailUser } from "@/lib/email/resend";import { unsubscribeActionUrl, unsubscribePageUrl } from "@/lib/email/unsubscribe";@@ -24,13 +24,13 @@ export function buildCreditsOfferedEmail(): EmailMessage {const from = bulkFrom();if (!from) throw new Error("No bulk sender configured.");- const credits = formatUsdPlain(creditMicrosToString(offer.amountMicros));+ const credits = formatCredits(creditMicrosToString(offer.amountMicros));const firstName = user.name.trim().split(/\s+/)[0] || user.name;return {from,to: user.email,replyTo: emailFrom() || from,- subject: `${credits} in AI credits is waiting for you`,+ subject: `${credits} are waiting for you`,react: CreditsOfferedEmail({claimBy: formatCreditExpiry(offer.closesAt),claimUrl: offer.claimUrl,diff --git a/site/src/lib/email/send-welcome.ts b/site/src/lib/email/send-welcome.tsindex bc71cbfa..f6aa040a 100644--- a/site/src/lib/email/send-welcome.ts+++ b/site/src/lib/email/send-welcome.ts@@ -1,5 +1,6 @@import { DONKEY_LOGO_CID, DONKEY_LOGO_PNG_BASE64 } from "@/emails/_components/logo";import WelcomeEmail from "@/emails/welcome";+import { formatCredits } from "@/lib/credits/format-credits";import { bulkFrom, emailFrom, type EmailMessage, type EmailUser } from "@/lib/email/resend";import { unsubscribeActionUrl, unsubscribePageUrl } from "@/lib/email/unsubscribe";import { prisma } from "@/lib/prisma";@@ -25,7 +26,7 @@ export function buildWelcomeEmail(user: EmailUser, credits: string | null): EmaireplyTo: emailFrom() || from,subject: "Thanks for signing up ❤️",react: WelcomeEmail({- credits,+ credits: credits === null ? null : formatCredits(credits),name: firstName,unsubscribeUrl: unsubscribePageUrl(user.id),}),diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsindex 15e33449..f69044e0 100644--- a/site/src/queries/credits.ts+++ b/site/src/queries/credits.ts@@ -139,8 +139,10 @@ export type CreditOffer = {claimed: boolean;// The last moment the offer can be claimed; null keeps it open.closesAt: string | null;- // Formatted USD, "$5".+ // The amount as people read it, "5,000 credits".credits: string;+ // The same amount in USD, "5", for analytics.+ dollars: string;// When the claimed credit expires; null before the claim and for a credit// that keeps forever.expiresAt: string | null;