Open source CapCut alternative.
TypeScript
feat(cut): price each generation before it runs [rebuild]
David Le4d3051a73302
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex b6b21642..08ac91f0 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -131,13 +131,13 @@ provider-enforced schema when Vertex rejects the schema parameters.## Hosted Model Credits-Hosted inference is metered per signed-in user, and the backend owns the meter.-The Mac app sends provider-neutral requests; the backend checks credits, knows-the rates, debits, and writes the audit rows. Each user has one visible balance,-with grants, expirations, usage charges, and adjustments recorded behind it.+Hosted inference is metered per signed-in user, and the backend owns the meter:+it checks credits, knows the rates, debits, and writes the audit rows. Balances+are USD micros; people see 1,000 credits per dollar, and a price sheet shows each+flat-priced generation's cost before it runs.A provider-invoking route checks credits before it calls the model and charges-after the provider succeeds. Listing models is free. If the provider or runtime+after the provider succeeds. If the provider or runtimefails after a successful preflight, the route records a zero-cost failed-usageevent with a sanitized error code.@@ -163,8 +163,7 @@ counted from that moment.Outreach notes can place `{{button}}` in its own paragraph when a credit offeris enabled. The offer supplies the recipient's claim URL and the button label:“Subscribe to Pro” for a subscription offer, or “Claim my AI credits” for a-direct claim. Validation, test sends, and recipient sends share the same copy-renderer. Button notes carry HTML and a plain-text version with the link;+direct claim. Button notes carry HTML and a plain-text version with the link;`{{claimUrl}}` remains available as a URL in the text.Known OpenAI, Gemini, and ElevenLabs models fall back to backend-owned pricesdiff --git a/site/src/app/api/credits/prices/route.ts b/site/src/app/api/credits/prices/route.tsnew file mode 100644index 00000000..9528e3c9--- /dev/null+++ b/site/src/app/api/credits/prices/route.ts@@ -0,0 +1,9 @@+import { NextResponse } from "next/server";++import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import { loadCreditPriceSheet } from "@/lib/credits/price-sheet.server";++// What each flat-priced generation costs, read by the Generate buttons.+export const GET = withDonkeyAuth(async () => {+ return NextResponse.json(await loadCreditPriceSheet());+});diff --git a/site/src/clients/chatgpt/server/catalog.ts b/site/src/clients/chatgpt/server/catalog.tsindex d7160f17..f4d08107 100644--- a/site/src/clients/chatgpt/server/catalog.ts+++ b/site/src/clients/chatgpt/server/catalog.ts@@ -65,6 +65,7 @@ export const READ_COMMANDS = new Set(["read_color_stats","stock_search","list_voices",+ "credit_prices","library_list","read_folder","notes_list",diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxindex 987d697b..51b8fe88 100644--- a/site/src/cut/components/AudioPanel.tsx+++ b/site/src/cut/components/AudioPanel.tsx@@ -48,6 +48,8 @@ import { STOCK_MUSIC } from "@/cut/lib/stockMusicManifest";import { stockAssetInDoc } from "@/cut/lib/genvideo/docWriter";import { signInUrl, useSignedIn } from "@/cut/lib/generate";import { HostedErrorText } from "./hostedError";+import { CostTag, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";+import { musicMicros } from "@/lib/credits/price-sheet";import { genPulseOverlay, useActiveWork, useGenNotify } from "@/cut/lib/genNotify";import { enrichAsset } from "@/cut/lib/media";import { waveGain } from "@/cut/lib/waveform";@@ -224,6 +226,8 @@ function MusicGenerator({ projectId }: { projectId: string }) {};const variantLabel = MUSIC_VARIANTS.find((v) => v.id === variant) ?? MUSIC_VARIANTS[0];+ // Every take renders a track at the length's flat price.+ const cost = useGenerateCost((sheet) => musicMicros(sheet, variant, takes));return (<div className="music-generator flex flex-col gap-3.5">@@ -307,12 +311,13 @@ function MusicGenerator({ projectId }: { projectId: string }) {</div><ButtonclassName="music-generate w-full"- disabled={!prompt.trim() || signedOut}+ disabled={!prompt.trim() || signedOut || cost.short}title={!prompt.trim() ? "Describe the music above to generate" : undefined}onClick={() => void generate()}><Music data-icon="inline-start" />- Generate music+ {cost.short ? NOT_ENOUGH_CREDITS : "Generate music"}+ <CostTag cost={cost} /></Button>{pending > 0 && (<div className="flex items-center gap-2 text-[11px] text-muted-foreground">diff --git a/site/src/cut/components/GenerateCost.tools.ts b/site/src/cut/components/GenerateCost.tools.tsnew file mode 100644index 00000000..975ddf31--- /dev/null+++ b/site/src/cut/components/GenerateCost.tools.ts@@ -0,0 +1,19 @@+/**+ * The assistant's price check — what each hosted generation costs and what+ * the account holds — kept beside the Generate buttons that show the same+ * prices. The catalog spreads this list into the model's toolset and+ * `aiTools.ts` keys its handler on `CreditToolName`.+ */++import { obj, type AiToolDef } from "@/cut/lib/aiToolDef";+import { creditCountLabel, creditsPerDollar } from "@/lib/credits/format-credits";++export const CREDIT_TOOLS = [+ {+ name: "credit_prices",+ description: `What each hosted generation costs right now, in credits (${creditCountLabel(creditsPerDollar)} = $1): a video by resolution and length in seconds ("auto" is the model's own length), one image, a music track by length, and a minute of voiceover; plus the account's credit balance. Call it before quoting a price or when the user asks what something costs or how much they have left. Chat and edits bill by use and have no set price. Needs the user signed in to Donkey.`,+ inputSchema: obj({}),+ },+] as const satisfies readonly AiToolDef[];++export type CreditToolName = (typeof CREDIT_TOOLS)[number]["name"];diff --git a/site/src/cut/components/GenerateCost.tsx b/site/src/cut/components/GenerateCost.tsxnew file mode 100644index 00000000..0c71884a--- /dev/null+++ b/site/src/cut/components/GenerateCost.tsx@@ -0,0 +1,59 @@+"use client";++// The price of the next generation, shown on its Generate button before it+// spends anything. A price above the balance disables the button; the 402 the+// server would answer is the same check, in the same micros.+import { Zap } from "lucide-react";+import { useEnvironment } from "@/cut/lib/environment";+import { useSignedIn } from "@/cut/lib/generate";+import { creditMicrosToString, creditStringToMicros } from "@/lib/credits/amounts";+import { creditsFromDollars, formatCreditCount } from "@/lib/credits/format-credits";+import type { CreditPriceSheet } from "@/lib/credits/price-sheet";+import { useCreditBalance, useCreditPriceSheet } from "@/queries/credits";+import { useLiveCreditBalance } from "./CreditsPill";++/** The button's label when the balance can't cover the price. */+export const NOT_ENOUGH_CREDITS = "Not enough credits";++export type GenerateCost = {+ /** Credits the generation costs, rounded up; null until the prices are read. */+ credits: number | null;+ /** The balance is read and falls short of the price. */+ short: boolean;+};++const UNPRICED: GenerateCost = { credits: null, short: false };++/** Prices one generation from the sheet, in micros; null leaves it unpriced.+ * The ChatGPT card carries no credit readings, so the price stays off there. */+export function useGenerateCost(price: (sheet: CreditPriceSheet) => bigint | null): GenerateCost {+ const { chatgpt } = useEnvironment();+ const enabled = useSignedIn() === true && !chatgpt;+ const sheet = useCreditPriceSheet({ enabled });+ const balance = useCreditBalance({ enabled, freshness: "reuse" });+ useLiveCreditBalance();+ if (!enabled || !sheet.data) {+ return UNPRICED;+ }++ const micros = price(sheet.data);+ if (micros === null) {+ return UNPRICED;+ }+ const credits = creditsFromDollars(creditMicrosToString(micros), "up");+ const short = balance.data ? creditStringToMicros(balance.data.balance) < micros : false;+ return { credits, short };+}++/** The price beside the button label: "⚡ 1,318". */+export function CostTag({ cost }: { cost: GenerateCost }) {+ if (cost.credits === null) {+ return null;+ }+ return (+ <span className="ml-1 inline-flex items-center gap-0.5 tabular-nums opacity-80">+ <Zap className="size-3" />+ {formatCreditCount(cost.credits)}+ </span>+ );+}diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsxindex c37496aa..db5ec4cb 100644--- a/site/src/cut/components/GeneratePanel.tsx+++ b/site/src/cut/components/GeneratePanel.tsx@@ -34,11 +34,13 @@ import {type VideoResolution,DEFAULT_VIDEO_RESOLUTION,} from "@/cut/lib/videoModels";+import { videoRenderMicros } from "@/lib/credits/price-sheet";import { cn } from "@/lib/utils";import { CopyHandlePill, MentionTextarea, RefChips } from "./AssetRefs";import { DictationControl } from "./MicDictation";import { GeneratedAssetMenu } from "./GeneratedAssetMenu";import { HostedErrorText } from "./hostedError";+import { CostTag, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";import { cardIconButton } from "./iconButton";import { PillSelect } from "./PillSelect";import { ScrollArea } from "@/components/ui/scroll-area";@@ -92,6 +94,9 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {durationSeconds !== null && durationSeconds >= minSeconds && durationSeconds <= maxSeconds? durationSeconds: null;+ // The render's price follows the size and length picked; Auto bills the+ // model's longest clip.+ const cost = useGenerateCost((sheet) => videoRenderMicros(sheet, effResolution, effDuration));const durationOptions = [{ value: "auto", label: "Auto length" },...Array.from({ length: maxSeconds - minSeconds + 1 }, (_, i) => {@@ -265,11 +270,12 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {<ButtonclassName="gen-go w-full shrink-0"- disabled={!prompt.trim() || signedIn === false}+ disabled={!prompt.trim() || signedIn === false || cost.short}onClick={go}><Sparkles data-icon="inline-start" />- Generate video+ {cost.short ? NOT_ENOUGH_CREDITS : "Generate video"}+ <CostTag cost={cost} /></Button>{signedIn === false ? (diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxindex 64abf139..0d4ab546 100644--- a/site/src/cut/components/ImageGenPanel.tsx+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -23,6 +23,7 @@ import { useLightbox } from "@/cut/lib/lightbox";import { refsFromDroppedFiles } from "@/cut/lib/refMedia";import { useEditor } from "@/cut/lib/store";import { nearestAspect, type MediaAsset } from "@/cut/lib/types";+import { imageMicros } from "@/lib/credits/price-sheet";import { cn } from "@/lib/utils";import { CopyHandlePill, MentionTextarea, RefChips } from "./AssetRefs";import { DictationControl } from "./MicDictation";@@ -30,6 +31,7 @@ import { cardIconButton } from "./iconButton";import { PillSelect } from "./PillSelect";import { GeneratedAssetMenu } from "./GeneratedAssetMenu";import { HostedErrorText } from "./hostedError";+import { CostTag, NOT_ENOUGH_CREDITS, useGenerateCost } from "./GenerateCost";import { ScrollArea } from "@/components/ui/scroll-area";// The generate-image panel: an always-on column in the Image tab, sitting left@@ -96,6 +98,9 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {.setAspect(nearestAspect(useEditor.getState().aspect, IMAGE_ASPECTS));}, []);+ // One image per press, at a flat price whatever its size.+ const cost = useGenerateCost((sheet) => imageMicros(sheet, 1));+const go = () => {const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates);if (!text) return;@@ -178,11 +183,12 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {<ButtonclassName="w-full shrink-0"- disabled={!prompt.trim() || signedIn === false}+ disabled={!prompt.trim() || signedIn === false || cost.short}onClick={go}><Sparkles data-icon="inline-start" />- Generate image+ {cost.short ? NOT_ENOUGH_CREDITS : "Generate image"}+ <CostTag cost={cost} /></Button>{signedIn === false && (diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 89d8d73f..4b863d46 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -130,6 +130,7 @@ import type { EditorToolName } from "@/cut/components/Editor.tools";import type { EffectsToolName } from "@/cut/components/EffectsPanel.tools";import { SHAPE_KINDS, SVG_STICKER_MAX_CHARS, type ElementsToolName } from "@/cut/components/ElementsPanel.tools";import type { VideoGenToolName } from "@/cut/components/GeneratePanel.tools";+import type { CreditToolName } from "@/cut/components/GenerateCost.tools";import type { ImageGenToolName } from "@/cut/components/ImageGenPanel.tools";import { STICKER_W_MIN, type InspectorToolName } from "@/cut/components/Inspector.tools";import type { GroupPanelToolName } from "@/cut/components/GroupPanel.tools";@@ -281,7 +282,10 @@ import { synthesizeMusic } from "./audioGen";import { composeMusicPrompt } from "./composeGen";import { stockAssetInDoc } from "./genvideo/docWriter";import { resolveVoiceAsk, synthesizeSpeech, SPEECH_VOICES } from "./tts";-import { hostedPost } from "./hosted";+import { hostedFetch, hostedPost } from "./hosted";+import { readHostedError } from "./hostedError";+import { creditPriceQuote, type CreditPriceSheet } from "@/lib/credits/price-sheet";+import { creditsFromDollars } from "@/lib/credits/format-credits";import { blockAsset } from "./blockSource";import { cutClip, cutJudge } from "./chatRuntime";import { FOLLOW_MODES } from "./trackKeys";@@ -607,6 +611,7 @@ type BrowserToolName = Exclude<| AiPanelToolName| AudioToolName| CameraCardToolName+ | CreditToolName| EditorToolName| EffectsToolName| ElementsToolName@@ -5015,6 +5020,22 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {};},+ credit_prices: async () => {+ // Read live, so a quote follows the same rates the charge uses.+ const [prices, balance] = await Promise.all([+ hostedFetch("/api/credits/prices", { cache: "no-store" }),+ hostedFetch("/api/credits/balance", { cache: "no-store" }),+ ]);+ for (const res of [prices, balance]) {+ if (!res.ok) {+ throw new ToolError(await readHostedError(res, "Sign in to Donkey to see credit prices.", "Could not read credit prices."));+ }+ }+ const sheet = (await prices.json()) as CreditPriceSheet;+ const { balance: dollars } = (await balance.json()) as { balance: string };+ return { ...creditPriceQuote(sheet), balance: creditsFromDollars(dollars, "down") };+ },+list_voices: () => {// Gemini's prebuilt voice catalog is fixed and ships hardcoded.return {diff --git a/site/src/cut/lib/audioGen.ts b/site/src/cut/lib/audioGen.tsindex c026ad6c..85266210 100644--- a/site/src/cut/lib/audioGen.ts+++ b/site/src/cut/lib/audioGen.ts@@ -6,6 +6,7 @@ import { hostedPost } from "./hosted";import { importFileToProject } from "./media";import { NoCreditsError } from "./tts";import { mediaSlug, type MediaAsset } from "./types";+import type { MusicLength } from "@/lib/credits/price-sheet";// Client side of AI music generation: Gemini/Lyria on Donkey's hosted inference// routes, with the user's Donkey sign-in and credits (same-origin on the cut@@ -14,7 +15,7 @@ import { mediaSlug, type MediaAsset } from "./types";// instrumental bed when asked — that comes back inline and saves into the// project through the local engine like any other media file.-export type MusicVariant = "clip" | "song";+export type MusicVariant = MusicLength;/** The length choices the Music generator offers — the clip model renders a* short bed, the pro model a full-length track. */diff --git a/site/src/cut/lib/pi/mutationLedger.ts b/site/src/cut/lib/pi/mutationLedger.tsindex 60114114..3d7ce412 100644--- a/site/src/cut/lib/pi/mutationLedger.ts+++ b/site/src/cut/lib/pi/mutationLedger.ts@@ -27,6 +27,7 @@ const READ_ONLY = new Set(["library_list_folder","stock_search","list_voices",+ "credit_prices","wait_for_renders","wait_for_uploads","seek",diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 54ca56d0..c2d8e4c4 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -37,6 +37,7 @@ import { EDITOR_TOOLS } from "@/cut/components/Editor.tools";import { EFFECT_TREATMENTS, EFFECTS_TOOLS } from "@/cut/components/EffectsPanel.tools";import { ELEMENTS_TOOLS, SHAPE_KINDS } from "@/cut/components/ElementsPanel.tools";import { VIDEO_GEN_TOOLS } from "@/cut/components/GeneratePanel.tools";+import { CREDIT_TOOLS } from "@/cut/components/GenerateCost.tools";import { IMAGE_GEN_TOOLS } from "@/cut/components/ImageGenPanel.tools";import { INSPECTOR_TOOLS } from "@/cut/components/Inspector.tools";import { GROUP_PANEL_TOOLS } from "@/cut/components/GroupPanel.tools";@@ -91,6 +92,7 @@ export const AI_TOOLS: AiToolDef[] = [...AUDIO_TOOLS,...IMAGE_GEN_TOOLS,...VIDEO_GEN_TOOLS,+ ...CREDIT_TOOLS,...SCENE_TOOLS,...STOCK_TOOLS,...LIBRARY_TOOLS,@@ -158,19 +160,19 @@ export const TOOL_AREAS: Record<string, { blurb: string; tools: AiToolDef[] }> =},audio: {blurb: "voiceover, music generation, reading subtitles aloud, the voice list",- tools: [...AUDIO_TOOLS],+ tools: [...AUDIO_TOOLS, ...CREDIT_TOOLS],},image_gen: {blurb: "generate an image with a hosted model",- tools: [...IMAGE_GEN_TOOLS],+ tools: [...IMAGE_GEN_TOOLS, ...CREDIT_TOOLS],},video_gen: {blurb: "generate a video clip or a talking character video with a hosted model; a better version or another take of an existing clip is a fresh render",- tools: [...VIDEO_GEN_TOOLS],+ tools: [...VIDEO_GEN_TOOLS, ...CREDIT_TOOLS],},scene: {blurb: "scene productions: plan, approve, regenerate, recut and restyle a narrated multi-shot cut",- tools: [...SCENE_TOOLS],+ tools: [...SCENE_TOOLS, ...CREDIT_TOOLS],},stock: {blurb: "search the bundled stock footage, images, characters and sound effects, and add one to the project",@@ -541,7 +543,7 @@ subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (ambeCaption look: set_caption_look carries the whole look — the visual presets (${Object.keys(CAPTION_STYLES).join(", ")}), size, font, and the word effect with its color, swell and fade settings; the Subtitles panel offers the same, and each track's caption drags to a new spot in the preview. The word effects play the caption as it is said:\n${wordEffectCatalog()}\ncaptions_generate's clean/hook/punchy choice shapes the caption text it writes; the visual preset is separate.`,"ai-generation": `# Stock media & AI generation-Three ways to get footage the user doesn't have: bundled stock (local, free), a URL they point at (import_url downloads TikTok / YouTube / Instagram / direct links, free), and hosted generation (signed in, spends credits). Prefer stock when it genuinely fits; generate when the shot needs to be specific.+Three ways to get footage the user doesn't have: bundled stock (local, free), a URL they point at (import_url downloads TikTok / YouTube / Instagram / direct links, free), and hosted generation (signed in, spends credits; credit_prices gives what each costs and the balance, so call it before quoting a price). Prefer stock when it genuinely fits; generate when the shot needs to be specific.Stock: stock_search browses the bundled catalogs — footage clips and images in 8 categories, ~20 UGC talking characters, and one-shot sound effects in ${STOCK_SFX_CATEGORIES.length} families (${STOCK_SFX_CATEGORIES.join(", ")}) — matching prompts, categories, and tags. stock_add imports an item into the project as a chat card; add_to_timeline:true (or a start) also drops it on the timeline when the user asked — footage and stills on the video track, a sound on the soundtrack at the playhead or the start given. A sound effect is a file placed on the beat — a whoosh on a scene change, a click when something pops up, a riser into a reveal, a hit on the landing shot, a glitch on a jump cut — searched with kind "sound"; an audio treatment (add_effect) changes how what is already there sounds. In the UI footage and images live in the Video and Image tabs beside the generators (clicking a stock tile seeds the generate panel with its prompt), and the sound effects sit in the Effects tab's Sound family under the treatments.Generation:- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: the supported shape closest to the project aspect) and 1K/2K/4K. The still previews in the chat; placed (add_to_timeline:true or an index) it rides video track 0 as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.diff --git a/site/src/lib/credits/price-sheet.server.test.ts b/site/src/lib/credits/price-sheet.server.test.tsnew file mode 100644index 00000000..08133def--- /dev/null+++ b/site/src/lib/credits/price-sheet.server.test.ts@@ -0,0 +1,130 @@+import { describe, expect, test } from "bun:test";++import { creditMicrosToString } from "@/lib/credits/amounts";+import { providerCreditPricing, providerPricingCostMicros, type NormalizedUsage } from "@/lib/credits/provider-pricing";+import { createGeminiImageAssetProvider } from "@/lib/inference/adapters/gemini-image";+import { createGeminiMusicAssetProvider } from "@/lib/inference/adapters/gemini-music";+import { createGeminiOmniVideoAssetProvider } from "@/lib/inference/adapters/gemini-omni-video";+import { createGeminiSpeechAssetProvider } from "@/lib/inference/adapters/gemini-speech";+import { geminiOmniDurationSeconds, geminiOmniResolutions } from "@/lib/inference/gemini-models";+import type { AssetGenerationRequest, InferenceProvider } from "@/lib/inference/providers";+import { stubModule } from "@/lib/testing/stubModule";++// The Generate buttons read the sheet the asset route bills by: the adapter+// names the billed model and unit count, and the charge prices that usage,+// with a database rate overriding the code price.++type RateRow = { route: string | null; provider: string | null; model: string | null; baseCostMicros: bigint };+let rows: RateRow[] = [];++const ZERO = BigInt(0);+const prisma = {+ inferenceCreditRate: {+ findMany: async () =>+ rows.map((row, index) => ({+ ...row,+ id: `rate-${index}`,+ version: 1,+ inputTokenCostMicros: ZERO,+ outputTokenCostMicros: ZERO,+ totalTokenCostMicros: ZERO,+ characterCostMicros: ZERO,+ fallbackCostMicros: ZERO,+ })),+ },+};++await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });+const { loadCreditPriceSheet } = await import("./price-sheet.server");++const ENV = {+ GOOGLE_APPLICATION_CREDENTIALS_JSON: JSON.stringify({+ project_id: "p",+ client_email: "[email protected]",+ private_key: "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n",+ }),+};+const NO_CLIENT = () => ({}) as never;+const PROVIDERS: Record<string, InferenceProvider> = {+ video: createGeminiOmniVideoAssetProvider(ENV, NO_CLIENT),+ image: createGeminiImageAssetProvider(ENV, NO_CLIENT),+ music: createGeminiMusicAssetProvider(ENV, NO_CLIENT),+ speech: createGeminiSpeechAssetProvider(ENV, NO_CLIENT),+};+const providerFor = (request: AssetGenerationRequest) => PROVIDERS[request.kind];++const EMPTY_USAGE: NormalizedUsage = {+ billableOutputTokens: ZERO,+ cachedInputTokens: ZERO,+ characterCost: ZERO,+ durationMillis: ZERO,+ generationCount: ZERO,+ inputAudioTokens: ZERO,+ inputTokens: ZERO,+ outputAudioTokens: ZERO,+ outputTokens: ZERO,+ totalTokens: ZERO,+};++const request = (kind: string, parameters: Record<string, unknown> = {}) =>+ ({ kind, prompt: "p", parameters }) as AssetGenerationRequest;++// What the route charges for one request at the code price.+async function charged(request: AssetGenerationRequest): Promise<string> {+ const provider = providerFor(request);+ const model = provider.assetModelFor!(request)!;+ const count = provider.assetGenerationCountFor+ ? await provider.assetGenerationCountFor(request, async () => request)+ : 1;+ const micros = providerPricingCostMicros(providerCreditPricing(provider.id, model), {+ ...EMPTY_USAGE,+ generationCount: BigInt(count),+ });+ return creditMicrosToString(micros);+}++describe("the price sheet the buttons read", () => {+ test("video matches the charge at every size and length", async () => {+ rows = [];+ const sheet = await loadCreditPriceSheet(providerFor);+ const { min, max } = geminiOmniDurationSeconds;+ for (const resolution of geminiOmniResolutions) {+ for (let seconds = min; seconds <= max; seconds++) {+ expect(sheet.video[resolution][String(seconds)]).toBe(+ await charged(request("video", { resolution, durationSeconds: seconds })),+ );+ }+ expect(sheet.video[resolution].auto).toBe(await charged(request("video", { resolution })));+ }+ });++ test("an image and each music length match the charge", async () => {+ rows = [];+ const sheet = await loadCreditPriceSheet(providerFor);+ expect(sheet.image).toBe(await charged(request("image")));+ expect(sheet.music.clip).toBe(await charged(request("music", { variant: "clip" })));+ expect(sheet.music.song).toBe(await charged(request("music", { variant: "song" })));+ });++ test("a minute of speech bills at the speech model's rate", async () => {+ rows = [];+ const sheet = await loadCreditPriceSheet(providerFor);+ const speech = request("speech");+ const model = PROVIDERS.speech.assetModelFor!(speech)!;+ const minute = providerPricingCostMicros(providerCreditPricing(PROVIDERS.speech.id, model), {+ ...EMPTY_USAGE,+ durationMillis: BigInt(60_000),+ });+ expect(sheet.speechMinute).toBe(creditMicrosToString(minute));+ });++ test("an override bills its base once, whatever the render's length", async () => {+ const video = request("video", { resolution: "720p", durationSeconds: 10 });+ const model = PROVIDERS.video.assetModelFor!(video)!;+ rows = [{ route: null, provider: PROVIDERS.video.id, model, baseCostMicros: BigInt(100_000) }];+ const sheet = await loadCreditPriceSheet(providerFor);+ expect(sheet.video["720p"]["10"]).toBe("0.1");+ expect(sheet.video["4k"]["4"]).toBe("0.1");+ expect(sheet.image).not.toBe("0.1");+ });+});diff --git a/site/src/lib/credits/price-sheet.server.ts b/site/src/lib/credits/price-sheet.server.tsnew file mode 100644index 00000000..9bc7ad42--- /dev/null+++ b/site/src/lib/credits/price-sheet.server.ts@@ -0,0 +1,105 @@+import { creditMicrosToString, zeroCreditMicros } from "@/lib/credits/amounts";+import { inferenceUsageRoutes, usageCostMicros } from "@/lib/credits/inference";+import {+ autoVideoLength,+ musicLengths,+ type CreditPriceSheet,+ type MusicLength,+} from "@/lib/credits/price-sheet";+import type { NormalizedUsage } from "@/lib/credits/provider-pricing";+import { geminiOmniDurationSeconds, geminiOmniResolutions } from "@/lib/inference/gemini-models";+import type { AssetGenerationRequest, InferenceProvider } from "@/lib/inference/providers";+import { createProviderRegistry } from "@/lib/inference/router";++// Prices each option the editor offers the way the asset route bills it: the+// adapter names the billed model and unit count for the request, and the+// charge's own rate lookup prices that usage, database overrides included.++/** Picks the provider that serves a request, as the asset route does. */+export type AssetProviderLookup = (request: AssetGenerationRequest) => InferenceProvider;++const SPEECH_MINUTE_MILLIS = BigInt(60_000);++const EMPTY_USAGE: NormalizedUsage = {+ billableOutputTokens: zeroCreditMicros,+ cachedInputTokens: zeroCreditMicros,+ characterCost: zeroCreditMicros,+ durationMillis: zeroCreditMicros,+ generationCount: zeroCreditMicros,+ inputAudioTokens: zeroCreditMicros,+ inputTokens: zeroCreditMicros,+ outputAudioTokens: zeroCreditMicros,+ outputTokens: zeroCreditMicros,+ totalTokens: zeroCreditMicros,+};++/** The sheet as the asset route bills it now. */+export async function loadCreditPriceSheet(+ providerFor: AssetProviderLookup = registryLookup(),+): Promise<CreditPriceSheet> {+ const price = (request: AssetGenerationRequest, usage?: Partial<NormalizedUsage>) =>+ requestPrice(providerFor, request, usage);++ // Every size at every length, plus "auto" for a render that names none.+ const { min, max } = geminiOmniDurationSeconds;+ const lengths = [...Array.from({ length: max - min + 1 }, (_, i) => min + i), null];+ const video = Object.fromEntries(+ await Promise.all(+ geminiOmniResolutions.map(async (resolution) => {+ const byLength = await Promise.all(+ lengths.map(async (seconds) => {+ const parameters = seconds === null ? { resolution } : { resolution, durationSeconds: seconds };+ return [seconds === null ? autoVideoLength : String(seconds), await price(assetRequest("video", parameters))] as const;+ }),+ );+ return [resolution, Object.fromEntries(byLength)] as const;+ }),+ ),+ );++ const music = Object.fromEntries(+ await Promise.all(+ musicLengths.map(async (length) => [length, await price(assetRequest("music", { variant: length }))] as const),+ ),+ ) as Record<MusicLength, string>;++ // Speech bills by the audio it returns, so the sheet prices a minute of it.+ const speechMinute = await price(assetRequest("speech"), {+ generationCount: zeroCreditMicros,+ durationMillis: SPEECH_MINUTE_MILLIS,+ });++ return { video, image: await price(assetRequest("image")), music, speechMinute };+}++function registryLookup(): AssetProviderLookup {+ const registry = createProviderRegistry();+ return (request) => registry.assetProvider(request);+}++function assetRequest(kind: string, parameters: Record<string, unknown> = {}): AssetGenerationRequest {+ return { kind, prompt: "", parameters } as AssetGenerationRequest;+}++// One request priced the way the asset route charges it.+async function requestPrice(+ providerFor: AssetProviderLookup,+ request: AssetGenerationRequest,+ usage: Partial<NormalizedUsage> = {},+): Promise<string> {+ const provider = providerFor(request);+ const model = provider.assetModelFor?.(request) ?? request.model;+ if (!model) {+ throw new Error(`No billed model for a ${request.kind} request.`);+ }++ const count = provider.assetGenerationCountFor+ ? await provider.assetGenerationCountFor(request, async () => request)+ : 1;+ const micros = await usageCostMicros(inferenceUsageRoutes.assets, provider.id, model, {+ ...EMPTY_USAGE,+ generationCount: BigInt(count),+ ...usage,+ });+ return creditMicrosToString(micros);+}diff --git a/site/src/lib/credits/price-sheet.ts b/site/src/lib/credits/price-sheet.tsnew file mode 100644index 00000000..3c51150b--- /dev/null+++ b/site/src/lib/credits/price-sheet.ts@@ -0,0 +1,75 @@+import { creditStringToMicros } from "@/lib/credits/amounts";+import { creditsFromDollars, creditsPerDollar } from "@/lib/credits/format-credits";++// What a flat-priced generation costs before it runs, keyed by what the editor+// offers (a video size and length, a music length). The server prices each+// entry as one whole request through the charge's own rate lookup, so the+// number on the Generate button is the number billed. This module carries no+// model ids or rates: the page reads the sheet from /api/credits/prices.++/** The music lengths the generator offers. */+export const musicLengths = ["clip", "song"] as const;+export type MusicLength = (typeof musicLengths)[number];++/** A video render that names no length bills the model's longest clip. */+export const autoVideoLength = "auto";++/** One request of each generation, as dollar strings exact to the micro. */+export type CreditPriceSheet = {+ /** A whole render by resolution, then by length in seconds or "auto". */+ video: Record<string, Record<string, string>>;+ /** One generated image. */+ image: string;+ /** One music track per length. */+ music: Record<MusicLength, string>;+ /** A minute of synthesized speech. */+ speechMinute: string;+};++/** Micros a video render costs; null for a size or length the sheet lacks. */+export function videoRenderMicros(+ sheet: CreditPriceSheet,+ resolution: string,+ durationSeconds: number | null,+): bigint | null {+ const length = durationSeconds === null ? autoVideoLength : String(durationSeconds);+ const price = sheet.video[resolution]?.[length];+ return price === undefined ? null : creditStringToMicros(price);+}++/** Micros for `count` separate image requests. */+export function imageMicros(sheet: CreditPriceSheet, count: number): bigint {+ return creditStringToMicros(sheet.image) * BigInt(count);+}++/** Micros for `takes` separate music requests of one length. */+export function musicMicros(sheet: CreditPriceSheet, length: MusicLength, takes: number): bigint {+ return creditStringToMicros(sheet.music[length]) * BigInt(takes);+}++/** The sheet in whole credits, rounded up, as the assistant quotes it. */+export type CreditPriceQuote = {+ creditsPerDollar: number;+ video: Record<string, Record<string, number>>;+ image: number;+ music: Record<MusicLength, number>;+ voiceoverPerMinute: number;+};++/** Every sheet entry in whole credits. */+export function creditPriceQuote(sheet: CreditPriceSheet): CreditPriceQuote {+ const credits = (dollars: string) => creditsFromDollars(dollars, "up");+ const video = Object.fromEntries(+ Object.entries(sheet.video).map(([resolution, byLength]) => [+ resolution,+ Object.fromEntries(Object.entries(byLength).map(([length, price]) => [length, credits(price)])),+ ]),+ );+ return {+ creditsPerDollar,+ video,+ image: credits(sheet.image),+ music: { clip: credits(sheet.music.clip), song: credits(sheet.music.song) },+ voiceoverPerMinute: credits(sheet.speechMinute),+ };+}diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsindex f69044e0..4f4c4561 100644--- a/site/src/queries/credits.ts+++ b/site/src/queries/credits.ts@@ -2,6 +2,7 @@import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";+import type { CreditPriceSheet } from "@/lib/credits/price-sheet";import { apiFetch } from "@/queries/apiClient";export const creditBalanceQueryKey = ["credits", "balance"] as const;@@ -44,10 +45,17 @@ const readCreditBalance = () => apiFetch<CreditBalance>("/api/credits/balance");// How long a read balance stands in for the account's before it is read again.const BALANCE_FRESH_MS = 60_000;-export function useCreditBalance() {+// How a mount treats a cached balance: "refetch" reads it again, "reuse"+// keeps a read younger than BALANCE_FRESH_MS (a panel that remounts on every+// tab switch).+export type BalanceFreshness = "refetch" | "reuse";++export function useCreditBalance(options: { enabled?: boolean; freshness?: BalanceFreshness } = {}) {return useQuery({+ enabled: options.enabled ?? true,queryFn: readCreditBalance,queryKey: creditBalanceQueryKey,+ staleTime: options.freshness === "reuse" ? BALANCE_FRESH_MS : 0,});}@@ -181,3 +189,17 @@ export function useClaimCreditOffer() {},});}++export const creditPriceSheetQueryKey = ["credits", "prices"] as const;++// Prices move with a deploy or a rate change, so a read holds for an hour.+const PRICE_SHEET_FRESH_MS = 60 * 60_000;++export function useCreditPriceSheet(options: { enabled?: boolean } = {}) {+ return useQuery({+ enabled: options.enabled ?? true,+ queryFn: () => apiFetch<CreditPriceSheet>("/api/credits/prices"),+ queryKey: creditPriceSheetQueryKey,+ staleTime: PRICE_SHEET_FRESH_MS,+ });+}