Skip to content

Open source CapCut alternative.

TypeScript

feat(site): add hosted speech generation to the inference backend

David Le8d79d3d59f93
diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.ts
index 03cd6f0f..f55b3936 100644
--- a/site/src/lib/auth.ts
+++ b/site/src/lib/auth.ts
@@ -15,9 +15,12 @@ export const visionApiKeyPrefix = "dk_live_";
// redirect_uri is pinned to BETTER_AUTH_URL's host. A sign-in started on one
// host would set a host-only state cookie there while the callback lands on the
// other, so better-auth can't find the cookie and rejects it as state_mismatch.
-// Scoping the auth cookies to the registrable host lets them ride across both.
-// Returns undefined for hosts that can't carry a Domain attribute (localhost,
-// bare IPs), so local development keeps working.
+// Scoping the auth cookies to the registrable host lets them ride across both,
+// and across the cut.donkeyuse.com subdomain that serves the editor.
+//
+// Local dev needs none of this: Cut is served from the apex under /cut, so its
+// session cookie is already same-origin. (A Domain=localhost cookie doesn't
+// reach a cut.localhost subdomain in Chrome anyway.)
function crossSubDomainCookieDomain() {
const baseURL = process.env.BETTER_AUTH_URL;
if (!baseURL) return undefined;
@@ -29,19 +32,36 @@ function crossSubDomainCookieDomain() {
return undefined;
}
- if (host === "localhost" || host.endsWith(".localhost") || /^[0-9.]+$/.test(host)) {
- return undefined;
- }
+ if (/^[0-9.]+$/.test(host)) return undefined;
+ if (host === "localhost" || host.endsWith(".localhost")) return undefined;
return host;
}
+// In production the editor is served from cut.donkeyuse.com, a different origin
+// from the apex where Google's redirect_uri is pinned, so a sign-in that starts
+// on Cut redirects back to that origin — it has to be trusted for the redirect
+// to be honored. Local dev serves Cut under /cut on the apex (same origin), so
+// nothing extra is needed there.
+function cutRedirectOrigins(): string[] {
+ const baseURL = process.env.BETTER_AUTH_URL;
+ if (!baseURL) return [];
+ try {
+ const url = new URL(baseURL);
+ if (url.hostname === "localhost" || url.hostname.endsWith(".localhost")) return [];
+ if (!url.hostname.startsWith("cut.")) url.hostname = `cut.${url.hostname}`;
+ return [url.origin];
+ } catch {
+ return [];
+ }
+}
+
const cookieDomain = crossSubDomainCookieDomain();
export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET,
- trustedOrigins: macAuthRedirectOrigins(),
+ trustedOrigins: [...macAuthRedirectOrigins(), ...cutRedirectOrigins()],
// Sessions last a year, and the rolling expiry is refreshed daily on use, so an active user effectively
// never has to sign in again. The Mac app's native session cookie rides this same lifetime, keeping the
// desktop signed in long after the handoff.
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index b43aa3f7..dd402102 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -328,8 +328,30 @@ export async function requireInferenceCredits(input: CreditPreflightInput) {
}
}
+// Prisma raises P2034 when a transaction is aborted by a write conflict or
+// deadlock. A Serializable transaction rolls back entirely on conflict, so
+// nothing partially committed and the whole body is safe to re-run. Concurrent
+// charges against the same credit account (e.g. two generations at once)
+// routinely collide here; retrying transparently avoids surfacing a billing
+// race as a user-facing generation failure.
+async function withWriteConflictRetry<T>(run: () => Promise<T>): Promise<T> {
+ const maxAttempts = 5;
+ for (let attempt = 1; ; attempt += 1) {
+ try {
+ return await run();
+ } catch (error) {
+ const isWriteConflict =
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2034";
+ if (!isWriteConflict || attempt >= maxAttempts) {
+ throw error;
+ }
+ }
+ }
+}
+
export async function recordInferenceUsage(input: InferenceUsageInput) {
- const recorded = await prisma.$transaction(
+ const recorded = await withWriteConflictRetry(() => prisma.$transaction(
async (tx): Promise<RecordedInferenceUsage> => {
const included = input.billingMode === "included";
// "included" calls never read or charge the balance, so skip the
@@ -422,7 +444,7 @@ 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. Scheduled with next/server `after` so it runs
diff --git a/site/src/lib/credits/provider-pricing.ts b/site/src/lib/credits/provider-pricing.ts
index dfe3503c..1c809151 100644
--- a/site/src/lib/credits/provider-pricing.ts
+++ b/site/src/lib/credits/provider-pricing.ts
@@ -8,8 +8,10 @@ import {
} from "@/lib/inference/elevenlabs-models";
import {
geminiModels,
+ geminiTtsModels,
veoModels,
type GeminiModel,
+ type GeminiTtsModel,
type VeoModel,
} from "@/lib/inference/gemini-models";
import { openaiModels, type OpenAIRunModel } from "@/lib/inference/openai-models";
@@ -51,6 +53,10 @@ export function providerCreditPricing(
if (normalizedProvider === "veo") {
return veoCreditPricing(normalizedModel);
}
+ // Gemini TTS ids are hardcoded (gemini-models.ts); speech bills per second of audio.
+ if (normalizedProvider === "gemini-tts") {
+ return geminiTtsCreditPricing(normalizedModel);
+ }
if (normalizedProvider === "elevenlabs") {
return elevenLabsCreditPricing(normalizedModel);
}
@@ -290,6 +296,17 @@ function veoCreditPricing(model: string): ProviderCreditPricing | undefined {
return veoModelPricing[model as VeoModel];
}
+// Generative speech (Gemini TTS) bills by seconds of synthesized audio: audio out runs
+// $20/1M tokens at ~25 tokens per second ≈ $0.0005/s; the tiny text input rides along.
+// The Record is keyed by GeminiTtsModel, so adding a TTS id without a price fails the build.
+const geminiTtsModelPricing: Record<GeminiTtsModel, ProviderCreditPricing> = {
+ [geminiTtsModels.flash]: { durationSecondCostMicros: usdWithMargin("0.0005") },
+};
+
+function geminiTtsCreditPricing(model: string): ProviderCreditPricing | undefined {
+ return geminiTtsModelPricing[model as GeminiTtsModel];
+}
+
function geminiCreditPricing(model: string): ProviderCreditPricing | undefined {
// Exact match wins, so a specific id is never shadowed by a broader prefix entry (e.g. an image
// model "…-flash-image" under the "…-flash" text prefix). For dated/snapshot ids that only match
diff --git a/site/src/lib/inference/adapters/gemini-speech.ts b/site/src/lib/inference/adapters/gemini-speech.ts
new file mode 100644
index 00000000..04d98883
--- /dev/null
+++ b/site/src/lib/inference/adapters/gemini-speech.ts
@@ -0,0 +1,281 @@
+import { Modality } from "@google/genai";
+import type { GenerateContentParameters } from "@google/genai";
+
+import {
+ defaultGeminiClientFactory,
+ geminiApiError,
+ geminiCandidateParts,
+ geminiCandidates,
+ geminiClientConfig,
+ stringValue,
+ type AdapterEnvironment,
+ type GeminiClientFactory,
+} from "@/lib/inference/adapters/gemini-client";
+import { providerCreditPricing } from "@/lib/credits/provider-pricing";
+import { geminiTtsModels } from "@/lib/inference/gemini-models";
+import { ensureConfigured } from "@/lib/inference/http";
+import { isJsonObject, toJsonObject } from "@/lib/inference/json";
+import {
+ InferenceProviderError,
+ type AssetGenerationProviderRequest,
+ type AssetGenerationProviderResult,
+ type GenerationOutputRef,
+ type InferenceModality,
+ type InferenceModel,
+ type InferenceProvider,
+ type JsonValue,
+ type StoredGenerationForProvider,
+} from "@/lib/inference/providers";
+
+// Generative speech provider (Gemini TTS). The registry auto-selects it for
+// kind="speech" when the caller leaves the provider unset. Synchronous like the
+// image adapter — one generateContent call returns the finished audio. A DISTINCT
+// provider id keeps refresh routing from colliding with the image adapter.
+const providerID = "gemini-tts";
+
+// The prompt is what gets spoken; callers steer style, pace, and tone by
+// prefixing a natural-language direction ("Say in a spooky whisper: …") or
+// embedding inline audio tags ("[excited]", "[whispers]") in the text.
+const defaultVoice = "Kore";
+
+export function createGeminiSpeechAssetProvider(
+ environment: AdapterEnvironment = process.env,
+ clientFactory: GeminiClientFactory = defaultGeminiClientFactory,
+): InferenceProvider {
+ const clientConfig = geminiClientConfig(environment);
+ const configured = clientConfig.configured;
+ const defaultModel = geminiTtsModels.flash;
+
+ async function listModels(
+ modalities: InferenceModality[],
+ ): Promise<InferenceModel[]> {
+ if (!modalities.includes("speech") && !modalities.includes("audio")) {
+ return [];
+ }
+ return [
+ {
+ id: defaultModel,
+ name: defaultModel,
+ provider: providerID,
+ inputModalities: ["text"],
+ outputModalities: ["audio"],
+ contextLength: null,
+ pricing: null,
+ metadata: { provider: providerID, api: "generateContent" },
+ },
+ ];
+ }
+
+ async function generateAsset({
+ generationId,
+ request,
+ }: AssetGenerationProviderRequest): Promise<AssetGenerationProviderResult> {
+ ensureConfigured(configured);
+
+ if (request.kind !== "speech") {
+ throw new InferenceProviderError("Provider does not support this asset kind.", {
+ statusCode: 400,
+ code: "unsupported_asset_kind",
+ });
+ }
+
+ const model = request.model?.trim() || defaultModel;
+ // Fail before spending: a caller-supplied model may resolve to an id with no
+ // configured price — never run a generation we can't charge for.
+ if (!providerCreditPricing(providerID, model)) {
+ throw new InferenceProviderError(
+ "No credit price is configured for the selected speech model.",
+ { statusCode: 500, code: "speech_model_not_priced", details: { model } },
+ );
+ }
+
+ const prompt = request.prompt?.trim();
+ if (!prompt) {
+ throw new InferenceProviderError("Speech generation requires text to speak.", {
+ statusCode: 400,
+ code: "empty_speech_request",
+ });
+ }
+
+ const inputs = toJsonObject(request.inputs ?? {});
+ const parameters = toJsonObject(request.parameters ?? {});
+ const voice =
+ stringValue(inputs.voice) ?? stringValue(parameters.voice) ?? defaultVoice;
+ const languageCode = stringValue(parameters.languageCode);
+
+ const params: GenerateContentParameters = {
+ model,
+ contents: [{ role: "user", parts: [{ text: prompt }] }],
+ config: {
+ responseModalities: [Modality.AUDIO],
+ speechConfig: {
+ voiceConfig: { prebuiltVoiceConfig: { voiceName: voice } },
+ ...(languageCode ? { languageCode } : {}),
+ },
+ },
+ };
+ const client = clientFactory(clientConfig.options);
+
+ // The TTS model intermittently returns a well-formed response with an empty
+ // candidate (no audio, finishReason STOP or null) — the model stops before
+ // speaking, most often on short or heavily punctuated text. It is
+ // nondeterministic per call, so a resend usually clears it; retry a few
+ // times before failing, but never retry a permanent block (safety,
+ // recitation), which repeats forever and only burns quota.
+ const maxAttempts = 4;
+ let outputs: GenerationOutputRef[] = [];
+ let finishReason: string | undefined;
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ let rawResponse: unknown;
+ try {
+ rawResponse = await client.models.generateContent(params);
+ } catch (error) {
+ throw geminiApiError("Gemini speech generation failed.", error);
+ }
+
+ outputs = audioOutputs(rawResponse as JsonValue, generationId);
+ if (outputs.length > 0) {
+ break;
+ }
+ finishReason = speechFinishReason(rawResponse as JsonValue);
+ if (attempt >= maxAttempts || isPermanentSpeechBlock(finishReason)) {
+ break;
+ }
+ }
+
+ if (outputs.length === 0) {
+ // A well-formed response with no audio means the model stopped before
+ // speaking — a permanent safety/recitation block, or a transient hiccup
+ // that outlasted the retries. Surface the finishReason so the empty
+ // result is diagnosable instead of opaque.
+ throw new InferenceProviderError("Gemini returned no audio for this request.", {
+ statusCode: 502,
+ code: "empty_speech_generation",
+ details: { model, finishReason: finishReason ?? null },
+ });
+ }
+
+ return {
+ provider: providerID,
+ model,
+ status: "completed",
+ outputs,
+ usage: { durationMillis: outputDurationMillis(outputs) },
+ metadata: { provider: providerID, api: "generateContent", voice },
+ };
+ }
+
+ async function refreshAsset(
+ generation: StoredGenerationForProvider,
+ ): Promise<AssetGenerationProviderResult> {
+ // Speech generation is synchronous — there is nothing to poll. Echo the stored
+ // outputs as completed so the refresh route stays valid for any caller that polls.
+ return {
+ provider: providerID,
+ model: generation.model,
+ status: "completed",
+ outputs: generation.outputs,
+ metadata: { provider: providerID, api: "generateContent" },
+ };
+ }
+
+ return {
+ id: providerID,
+ configured,
+ capabilities: ["speech"],
+ listModels,
+ generateAsset,
+ refreshAsset,
+ };
+}
+
+// The finishReason of the first candidate, if any — the model's own account of
+// why it stopped (e.g. "SAFETY", "RECITATION", "STOP"). Read only to explain an
+// empty audio response; never affects a successful generation.
+function speechFinishReason(raw: JsonValue): string | undefined {
+ for (const candidate of geminiCandidates(raw)) {
+ const reason = stringValue(candidate.finishReason);
+ if (reason) {
+ return reason;
+ }
+ }
+ return undefined;
+}
+
+// finishReasons where the model deliberately refused to speak. Resending the
+// same text just hits the same wall, so an empty response with one of these is
+// final and must not be retried.
+const permanentSpeechBlocks = new Set([
+ "SAFETY",
+ "RECITATION",
+ "BLOCKLIST",
+ "PROHIBITED_CONTENT",
+ "SPII",
+ "IMAGE_SAFETY",
+]);
+
+function isPermanentSpeechBlock(finishReason: string | undefined): boolean {
+ return finishReason !== undefined && permanentSpeechBlocks.has(finishReason);
+}
+
+// Gemini TTS returns raw little-endian 16-bit mono PCM (audio/L16), 24 kHz by default.
+const defaultSampleRate = 24_000;
+
+function audioOutputs(raw: JsonValue, generationId: string): GenerationOutputRef[] {
+ const outputs: GenerationOutputRef[] = [];
+ let index = 0;
+ for (const candidate of geminiCandidates(raw)) {
+ for (const part of geminiCandidateParts(candidate)) {
+ const inline = part.inlineData ?? part.inline_data;
+ if (!isJsonObject(inline)) {
+ continue;
+ }
+ const data = stringValue(inline.data);
+ if (!data) {
+ continue;
+ }
+ const mimeType =
+ stringValue(inline.mimeType) ??
+ stringValue(inline.mime_type) ??
+ `audio/L16;codec=pcm;rate=${defaultSampleRate}`;
+ outputs.push({
+ id: `${generationId}-speech-${index}`,
+ kind: "audio",
+ dataBase64: data,
+ contentType: mimeType,
+ filename: `${generationId}-${index}.pcm`,
+ byteCount: base64ByteCount(data),
+ metadata: { source: "provider-output" },
+ });
+ index += 1;
+ }
+ }
+ return outputs;
+}
+
+// Billable seconds of audio, derived from the PCM payload itself (bytes over
+// sampleRate × 2 bytes per sample). The TTS response carries no usable
+// usageMetadata for billing, so the payload is the source of truth.
+function outputDurationMillis(outputs: GenerationOutputRef[]): number {
+ let millis = 0;
+ for (const output of outputs) {
+ const bytes = output.byteCount ?? 0;
+ const rate = sampleRateFromMime(output.contentType) ?? defaultSampleRate;
+ millis += Math.ceil((bytes / (rate * 2)) * 1000);
+ }
+ return millis;
+}
+
+function sampleRateFromMime(mimeType: string | undefined): number | undefined {
+ const match = mimeType?.match(/rate=(\d+)/);
+ if (!match) {
+ return undefined;
+ }
+ const rate = Number(match[1]);
+ return Number.isFinite(rate) && rate > 0 ? rate : undefined;
+}
+
+function base64ByteCount(data: string): number {
+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
+ return Math.max(0, Math.floor((data.length * 3) / 4) - padding);
+}
diff --git a/site/src/lib/inference/gemini-models.ts b/site/src/lib/inference/gemini-models.ts
index f70f5941..f1024648 100644
--- a/site/src/lib/inference/gemini-models.ts
+++ b/site/src/lib/inference/gemini-models.ts
@@ -32,6 +32,14 @@ export const veoModels = {
export type VeoModel = (typeof veoModels)[keyof typeof veoModels];
+// Generative speech (Gemini TTS): text in, spoken audio out, with prompt-driven
+// style direction and inline audio tags. Bump here when adopting a newer TTS model.
+export const geminiTtsModels = {
+ flash: "gemini-3.1-flash-tts-preview",
+} as const;
+
+export type GeminiTtsModel = (typeof geminiTtsModels)[keyof typeof geminiTtsModels];
+
// Maps the user-facing speed/quality tier (see the `video` SKILL.md picker) to a
// Veo model. An unknown/absent tier falls back to `fast` at the call site.
export const veoTierModels = {
diff --git a/site/src/lib/inference/media-outputs.ts b/site/src/lib/inference/media-outputs.ts
index 5958d392..234b283c 100644
--- a/site/src/lib/inference/media-outputs.ts
+++ b/site/src/lib/inference/media-outputs.ts
@@ -10,16 +10,18 @@ const extensionByKind: Record<AssetGenerationKind, RegExp> = {
image: /\.(png|jpe?g|webp|gif|heic|avif)(\?|#|$)/i,
video: /\.(mp4|webm|mov|m4v)(\?|#|$)/i,
music: /\.(mp3|wav|m4a|aac|ogg|flac)(\?|#|$)/i,
+ speech: /\.(mp3|wav|m4a|aac|ogg|flac|pcm)(\?|#|$)/i,
};
const contentTypeByKind: Record<AssetGenerationKind, string> = {
image: "image/png",
video: "video/mp4",
music: "audio/mpeg",
+ speech: "audio/mpeg",
};
export function mediaKind(kind: AssetGenerationKind): InferenceModality {
- return kind === "music" ? "audio" : kind;
+ return kind === "music" || kind === "speech" ? "audio" : kind;
}
export function extractMediaOutputs(
diff --git a/site/src/lib/inference/providers.ts b/site/src/lib/inference/providers.ts
index 652b1dd0..94decdbe 100644
--- a/site/src/lib/inference/providers.ts
+++ b/site/src/lib/inference/providers.ts
@@ -5,8 +5,8 @@ import type {
} from "@/lib/inference/schemas";
import type { z } from "zod";
-export type InferenceModality = "text" | "image" | "video" | "audio" | "music";
-export type AssetGenerationKind = "image" | "video" | "music";
+export type InferenceModality = "text" | "image" | "video" | "audio" | "music" | "speech";
+export type AssetGenerationKind = "image" | "video" | "music" | "speech";
export type GenerationStatus =
| "pending"
| "in_progress"
diff --git a/site/src/lib/inference/router.ts b/site/src/lib/inference/router.ts
index 6b610c36..bfba6df6 100644
--- a/site/src/lib/inference/router.ts
+++ b/site/src/lib/inference/router.ts
@@ -1,5 +1,6 @@
import { createGeminiComputerUseProvider } from "@/lib/inference/adapters/gemini-computer-use";
import { createGeminiImageAssetProvider } from "@/lib/inference/adapters/gemini-image";
+import { createGeminiSpeechAssetProvider } from "@/lib/inference/adapters/gemini-speech";
import { createGeminiVideoAssetProvider } from "@/lib/inference/adapters/gemini-video";
import { createHostedResponsesProvider } from "@/lib/inference/adapters/hosted-responses";
import {
@@ -153,7 +154,11 @@ export class ProviderRegistry {
}
const preferredCapabilities =
- request.kind === "music" ? ["music", "audio"] : [request.kind];
+ request.kind === "music"
+ ? ["music", "audio"]
+ : request.kind === "speech"
+ ? ["speech", "audio"]
+ : [request.kind];
const provider = this.providers.find((candidate) => {
return (
@@ -216,6 +221,8 @@ export function createProviderRegistry() {
// Veo serves kind="video"; its distinct provider id keeps async refresh routing from
// colliding with the synchronous image adapter.
createGeminiVideoAssetProvider(),
+ // Gemini TTS serves kind="speech" (voiceovers, subtitle read-alouds).
+ createGeminiSpeechAssetProvider(),
// ElevenLabs audio provider disabled for now (not in use).
createGeminiComputerUseProvider(),
createHostedResponsesProvider(),
diff --git a/site/src/lib/inference/schemas.ts b/site/src/lib/inference/schemas.ts
index 740e54b3..ada58268 100644
--- a/site/src/lib/inference/schemas.ts
+++ b/site/src/lib/inference/schemas.ts
@@ -11,9 +11,10 @@ export const inferenceModalitySchema = z.enum([
"video",
"audio",
"music",
+ "speech",
]);
-export const assetGenerationKindSchema = z.enum(["image", "video", "music"]);
+export const assetGenerationKindSchema = z.enum(["image", "video", "music", "speech"]);
export const modelsQuerySchema = z.object({
output_modalities: z.string().optional(),
@@ -128,7 +129,7 @@ export function parseRequestedModalities(value: string | null) {
}
if (value === "all") {
- return ["text", "image", "video", "audio", "music"] as const;
+ return ["text", "image", "video", "audio", "music", "speech"] as const;
}
return value
diff --git a/site/src/proxy.ts b/site/src/proxy.ts
index 57980b0d..3ff73bf3 100644
--- a/site/src/proxy.ts
+++ b/site/src/proxy.ts
@@ -1,6 +1,7 @@
import { NextResponse, type NextRequest } from "next/server";
import { allowedOrigin, corsHeaders, preflightHeaders } from "@/cut/server/cors";
+import { isCutHost } from "@/cut/lib/hosts";
// Cut (the video editor, publicly "Donkey Cut") is served on the
// cut.donkeyuse.com subdomain, but its routes live under /cut in this single
@@ -8,12 +9,12 @@ import { allowedOrigin, corsHeaders, preflightHeaders } from "@/cut/server/cors"
// Cut's root-relative links (/, /library, /p/[id]) resolve to its routes, while
// the apex host keeps serving Donkey.
//
+// Local dev is not a Cut host: the editor is opened at localhost:3000/cut/… so
+// its session cookie is same-origin, and its links carry the "/cut" base
+// directly (see src/cut/lib/nav.tsx), needing no rewrite.
+//
// This file must live in src/ (next to app/) and use the Next 16 `proxy` name;
// a root-level middleware.ts is not loaded when the app is under src/.
-//
-// Local dev: add nothing to /etc/hosts — `cut.localhost` already resolves to
-// 127.0.0.1, so http://cut.localhost:3000/ exercises this path.
-const CUT_HOSTS = new Set(["cut.donkeyuse.com", "cut.localhost"]);
// Cut's server APIs are local-only (see src/cut/server/local-only.ts): the
// hosted deploy serves only Cut's client bundle, and that page drives the
@@ -52,8 +53,7 @@ export function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
if (isCutApi(pathname)) return cutApi(req);
- const host = (req.headers.get("host") ?? "").split(":")[0];
- if (!CUT_HOSTS.has(host)) return NextResponse.next();
+ if (!isCutHost(req.headers.get("host"))) return NextResponse.next();
if (pathname.startsWith("/cut") || pathname.startsWith("/api")) {
return NextResponse.next();