Skip to content

Open source CapCut alternative.

TypeScript

feat(site): omni flash renders all video — veo deleted, clips bill flat at submit

David Lebdeca9005ac6
diff --git a/site/scripts/generate-stock-videos.ts b/site/scripts/generate-stock-videos.ts
index f415433e..b792acce 100644
--- a/site/scripts/generate-stock-videos.ts
+++ b/site/scripts/generate-stock-videos.ts
@@ -1,5 +1,5 @@
-// Generates the bundled Cut stock-video catalog with the same Veo tier the app
-// uses (veo fast), then writes the typed manifest the editor imports.
+// Generates the bundled Cut stock-video catalog with the same omni renderer
+// the app uses, then writes the typed manifest the editor imports.
// Idempotent: items whose file already exists are skipped, so re-running fills
// gaps or picks up new catalog entries only.
//
@@ -23,26 +23,24 @@ import { GoogleGenAI } from "@google/genai";
import { JWT } from "google-auth-library";
import sharp from "sharp";
-import { geminiModels, veoModels } from "../src/lib/inference/gemini-models";
+import { geminiModels, geminiOmniModels } from "../src/lib/inference/gemini-models";
import { characterPrompt, type StockVideoAspect, type StockVideoCategory } from "../src/cut/lib/stock";
interface CatalogItem {
id: string;
category: StockVideoCategory;
aspect: StockVideoAspect;
- /** Rendered length; Veo takes 4, 6, or 8 seconds. */
- seconds: 4 | 6 | 8;
prompt: string;
/** Characters only: the person description, written into the manifest so the
* editor can compose new lines for the same persona. */
persona?: string;
}
-const MODEL = veoModels.fast;
+const MODEL = geminiOmniModels.flashVideo;
const TAG_MODEL = geminiModels.flash;
const OUT_DIR = path.join(import.meta.dirname, "..", "public", "cut-stock-video");
const MANIFEST = path.join(import.meta.dirname, "..", "src", "cut", "lib", "stockVideoManifest.ts");
-// Veo renders take minutes each and quotas are tight; keep the fan-out small.
+// Renders take minutes each and quotas are tight; keep the fan-out small.
const CONCURRENCY = 2;
const POLL_MS = 10_000;
/** Longest thumb edge — the browse grid renders tiles well under this. */
@@ -56,7 +54,7 @@ const clip = (subject: string) =>
const animeClip = (subject: string) =>
`High-quality anime animation: ${subject} Clean line art, vibrant cel shading, detailed background, smooth motion. No text, no watermarks.`;
-// Talking characters: Veo 3.1 renders the spoken line as real dialogue audio.
+// Talking characters: the model renders the spoken line as real dialogue audio.
// The persona lands in the manifest so the editor's character mode can compose
// new lines for the same person; the sample line here is only the stock clip.
const character = (
@@ -68,24 +66,15 @@ const character = (
id,
category: "Characters",
aspect,
- seconds: 8,
persona,
prompt: characterPrompt(persona, line),
});
-// What must never show up in a stock clip, on the channel Veo actually
-// listens to (plain nouns; the prompt's "no text" line is belt-and-braces).
+// What must never show up in a stock clip. The model has no negative-prompt
+// parameter, so this rides the prompt itself as an avoid clause (plain nouns;
+// the prompt's "no text" line is belt-and-braces).
const NEGATIVE_PROMPT = "text overlay, captions, subtitles, watermark, logo, timestamp, split screen";
-/** Per-clip seed. Veo 3's always-on prompt rewriting keeps renders
- * non-deterministic, so this narrows re-run variation rather than pinning a
- * clip — a regenerated file can differ from the shipped one. */
-const seedFromId = (id: string) => {
- let h = 0;
- for (const c of id) h = (h * 31 + c.charCodeAt(0)) % 2147483647;
- return h;
-};
-
const CATALOG: CatalogItem[] = [
// Talking Characters — one editable spoken line each, varied looks and sets.
character("character-studio-host", "16:9", "a friendly man in his 30s with short dreadlocks, wearing a mustard crewneck, acoustic foam panels soft in the background", "So I tested this for thirty days, and honestly? The results surprised me."),
@@ -113,36 +102,36 @@ const CATALOG: CatalogItem[] = [
character("character-business-lead", "16:9", "a polished Korean woman in her late 20s with sleek shoulder-length black hair and pearl earrings, in a tailored ivory blazer, a bright glass high-rise office blurred behind her", "I've sat through a thousand pitches. The good ones all start the same way."),
// Business
- { id: "business-team-walkthrough", category: "Business", aspect: "16:9", seconds: 6, prompt: clip("a slow tracking shot following a small team walking and talking through a bright modern office, glass walls and plants passing by.") },
- { id: "business-typing-macro", category: "Business", aspect: "16:9", seconds: 6, prompt: clip("a close-up of hands typing on a laptop at a tidy desk, soft window light, shallow depth of field.") },
+ { id: "business-team-walkthrough", category: "Business", aspect: "16:9", prompt: clip("a slow tracking shot following a small team walking and talking through a bright modern office, glass walls and plants passing by.") },
+ { id: "business-typing-macro", category: "Business", aspect: "16:9", prompt: clip("a close-up of hands typing on a laptop at a tidy desk, soft window light, shallow depth of field.") },
// Nature
- { id: "nature-coast-aerial", category: "Nature", aspect: "16:9", seconds: 6, prompt: clip("a drone shot rising over a foggy coastline at sunrise, waves rolling onto dark sand far below.") },
- { id: "nature-forest-rays", category: "Nature", aspect: "9:16", seconds: 6, prompt: clip("sunbeams drifting through tall pines as morning fog moves slowly between the trunks, camera gliding forward at ground level.") },
+ { id: "nature-coast-aerial", category: "Nature", aspect: "16:9", prompt: clip("a drone shot rising over a foggy coastline at sunrise, waves rolling onto dark sand far below.") },
+ { id: "nature-forest-rays", category: "Nature", aspect: "9:16", prompt: clip("sunbeams drifting through tall pines as morning fog moves slowly between the trunks, camera gliding forward at ground level.") },
// Travel
- { id: "travel-market-walk", category: "Travel", aspect: "16:9", seconds: 6, prompt: clip("a first-person walk through a lively evening street market, lanterns glowing, vendors and steam from food stalls on both sides.") },
- { id: "travel-beach-stroll", category: "Travel", aspect: "9:16", seconds: 6, prompt: clip("a traveler walking barefoot along the waterline of a white-sand beach at golden hour, gentle waves washing over their footprints.") },
+ { id: "travel-market-walk", category: "Travel", aspect: "16:9", prompt: clip("a first-person walk through a lively evening street market, lanterns glowing, vendors and steam from food stalls on both sides.") },
+ { id: "travel-beach-stroll", category: "Travel", aspect: "9:16", prompt: clip("a traveler walking barefoot along the waterline of a white-sand beach at golden hour, gentle waves washing over their footprints.") },
// City
- { id: "city-night-traffic", category: "City", aspect: "16:9", seconds: 6, prompt: clip("an elevated view of city traffic at night, headlight streams and neon reflections on wet asphalt.") },
- { id: "city-crosswalk-rush", category: "City", aspect: "16:9", seconds: 6, prompt: clip("a busy scramble crosswalk from a high angle, crowds crossing in every direction as the light changes.") },
+ { id: "city-night-traffic", category: "City", aspect: "16:9", prompt: clip("an elevated view of city traffic at night, headlight streams and neon reflections on wet asphalt.") },
+ { id: "city-crosswalk-rush", category: "City", aspect: "16:9", prompt: clip("a busy scramble crosswalk from a high angle, crowds crossing in every direction as the light changes.") },
// Technology
- { id: "tech-code-glow", category: "Technology", aspect: "16:9", seconds: 6, prompt: clip("a slow push-in on a developer working at a dual-monitor setup in a dim room, screen glow on their face, code scrolling.") },
- { id: "tech-robot-assembly", category: "Technology", aspect: "16:9", seconds: 6, prompt: clip("an industrial robot arm assembling components on a clean production line, precise repeated motion, cool white lighting.") },
+ { id: "tech-code-glow", category: "Technology", aspect: "16:9", prompt: clip("a slow push-in on a developer working at a dual-monitor setup in a dim room, screen glow on their face, code scrolling.") },
+ { id: "tech-robot-assembly", category: "Technology", aspect: "16:9", prompt: clip("an industrial robot arm assembling components on a clean production line, precise repeated motion, cool white lighting.") },
// Anime
- { id: "anime-rain-walk", category: "Anime", aspect: "9:16", seconds: 6, prompt: animeClip("a figure with a glowing umbrella walking toward the viewer down a rain-slicked neon city street at night, puddles rippling.") },
- { id: "anime-cloud-drift", category: "Anime", aspect: "16:9", seconds: 6, prompt: animeClip("towering summer clouds drifting over a green hillside town by the sea, cherry blossom petals carried on the wind.") },
+ { id: "anime-rain-walk", category: "Anime", aspect: "9:16", prompt: animeClip("a figure with a glowing umbrella walking toward the viewer down a rain-slicked neon city street at night, puddles rippling.") },
+ { id: "anime-cloud-drift", category: "Anime", aspect: "16:9", prompt: animeClip("towering summer clouds drifting over a green hillside town by the sea, cherry blossom petals carried on the wind.") },
// Animal
- { id: "animal-dog-sprint", category: "Animal", aspect: "16:9", seconds: 6, prompt: clip("a golden retriever sprinting along a beach at sunset in slow motion, sand kicking up, ears flying.") },
- { id: "animal-flock-sky", category: "Animal", aspect: "16:9", seconds: 6, prompt: clip("a flock of birds wheeling across a pastel dusk sky over still water, reflections mirroring their turns.") },
+ { id: "animal-dog-sprint", category: "Animal", aspect: "16:9", prompt: clip("a golden retriever sprinting along a beach at sunset in slow motion, sand kicking up, ears flying.") },
+ { id: "animal-flock-sky", category: "Animal", aspect: "16:9", prompt: clip("a flock of birds wheeling across a pastel dusk sky over still water, reflections mirroring their turns.") },
// Food & Drink
- { id: "food-coffee-pour", category: "Food & Drink", aspect: "16:9", seconds: 6, prompt: clip("a slow-motion pour of steamed milk into espresso forming latte art, on a marble counter, steam curling upward.") },
- { id: "food-pan-sizzle", category: "Food & Drink", aspect: "16:9", seconds: 6, prompt: clip("vegetables tossed in a sizzling wok over a high flame, embers and steam rising, close-up from the side.") },
+ { id: "food-coffee-pour", category: "Food & Drink", aspect: "16:9", prompt: clip("a slow-motion pour of steamed milk into espresso forming latte art, on a marble counter, steam curling upward.") },
+ { id: "food-pan-sizzle", category: "Food & Drink", aspect: "16:9", prompt: clip("vegetables tossed in a sizzling wok over a high flame, embers and steam rising, close-up from the side.") },
];
function makeClient(): { client: GoogleGenAI; authClient: JWT; project: string } {
@@ -167,31 +156,30 @@ function makeClient(): { client: GoogleGenAI; authClient: JWT; project: string }
return { client, authClient, project: creds.project_id };
}
-/** Renders one clip and resolves to its mp4 bytes — polls the long-running
- * operation, then reads inline bytes or downloads the signed URI. */
+/** Renders one clip and resolves to its mp4 bytes — submits a background
+ * interaction, polls it to completion, then reads inline bytes or downloads
+ * the signed URI. */
async function generateOne(client: GoogleGenAI, authClient: JWT, item: CatalogItem): Promise<Buffer> {
- let op = await client.models.generateVideos({
+ let interaction = await client.interactions.create({
model: MODEL,
- prompt: item.prompt,
- config: {
- aspectRatio: item.aspect,
- durationSeconds: item.seconds,
- resolution: "720p",
- generateAudio: true,
- // People appear across the catalog (all of Characters); the safety
- // setting is explicit.
- personGeneration: "allow_adult",
- negativePrompt: NEGATIVE_PROMPT,
- seed: seedFromId(item.id),
- },
+ input: `${item.prompt} Avoid: ${NEGATIVE_PROMPT}.`,
+ generation_config: { video_config: { task: "text_to_video" } } as never,
+ response_format: { type: "video", aspect_ratio: item.aspect } as never,
+ background: true,
});
- while (!op.done) {
+ // requires_action is a non-terminal state too (same treatment the
+ // production adapter gives it) — keep polling through it.
+ while (interaction.status === "in_progress" || interaction.status === "requires_action") {
await sleep(POLL_MS);
- op = await client.operations.getVideosOperation({ operation: op });
+ interaction = await client.interactions.get(interaction.id);
+ }
+ if (interaction.status !== "completed") {
+ const step = [...(interaction.steps ?? [])].reverse().find((st) => (st as { error?: { message?: string } }).error);
+ const message = (step as { error?: { message?: string } } | undefined)?.error?.message;
+ throw new Error(message ?? `video generation ${interaction.status}`);
}
- if (op.error) throw new Error(String(op.error.message ?? "video generation failed"));
- const video = op.response?.generatedVideos?.[0]?.video;
- if (video?.videoBytes) return Buffer.from(video.videoBytes, "base64");
+ const video = interaction.output_video;
+ if (video?.data) return Buffer.from(video.data, "base64");
if (video?.uri) {
const token = await authClient.getAccessToken();
const res = await fetch(video.uri, { headers: { Authorization: `Bearer ${token.token}` } });
@@ -201,6 +189,21 @@ async function generateOne(client: GoogleGenAI, authClient: JWT, item: CatalogIt
throw new Error("no video in response");
}
+/** The rendered file's real length: the model picks each clip's length
+ * itself, so the manifest reports what actually rendered — placement math
+ * trusts StockVideo.duration. */
+function probeDuration(id: string): number {
+ const proc = spawnSync("ffprobe", [
+ "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0",
+ path.join(OUT_DIR, `${id}.mp4`),
+ ]);
+ const sec = Number.parseFloat(proc.stdout?.toString().trim() ?? "");
+ if (proc.status !== 0 || !Number.isFinite(sec) || sec <= 0) {
+ throw new Error(`ffprobe could not read ${id}.mp4's duration`);
+ }
+ return Math.round(sec * 10) / 10;
+}
+
/** First frame of the finished mp4 as the grid thumb, via ffmpeg → sharp. */
async function writeThumb(item: CatalogItem) {
const proc = spawnSync(
@@ -277,7 +280,7 @@ async function writeManifest(done: Set<string>, tags: Map<string, string[]>) {
aspect: c.aspect,
file: `/cut-stock-video/${c.id}.mp4`,
thumb: `/cut-stock-video/${c.id}.thumb.webp`,
- duration: c.seconds,
+ duration: probeDuration(c.id),
}));
const body = `// Generated by scripts/generate-stock-videos.ts — do not edit by hand.
import type { StockVideo } from "./stock";
@@ -305,7 +308,7 @@ async function main() {
await writeFile(path.join(OUT_DIR, `${item.id}.mp4`), video);
await writeThumb(item);
done.add(item.id);
- console.log(`✓ ${item.id} (${item.aspect}, ${item.seconds}s)`);
+ console.log(`✓ ${item.id} (${item.aspect})`);
break;
} catch (e) {
if (attempt >= 2) {
diff --git a/site/src/app/api/inference/assets/refresh/route.ts b/site/src/app/api/inference/assets/refresh/route.ts
index f88d347c..d3a4888e 100644
--- a/site/src/app/api/inference/assets/refresh/route.ts
+++ b/site/src/app/api/inference/assets/refresh/route.ts
@@ -3,7 +3,6 @@ import { NextResponse } from "next/server";
import {
inferenceUsageRoutes,
recordFailedInferenceUsage,
- requireInferenceCredits,
} from "@/lib/credits/inference";
import { refreshedAssetGenerationResponse } from "@/lib/inference/assets";
import { createProviderRegistry } from "@/lib/inference/router";
@@ -30,22 +29,35 @@ export const POST = withDonkeyAuth(async (request) => {
return validationErrorResponse(parsed.error);
}
- const credits = await requireInferenceCredits({
- model: parsed.data.model,
- provider: parsed.data.provider,
- route: inferenceUsageRoutes.assetsRefresh,
- userId: request.donkey.userId,
- });
- if (!credits.ok) {
- return credits.response;
- }
-
+ // No credit gate here: the clip was billed flat at submit, so a poll does no
+ // new billable work — and gating it would strand a render the user already
+ // paid for behind a balance drained by sibling charges.
try {
const registry = createProviderRegistry();
const result = await registry.refresh(parsed.data);
- // A successful poll is free and already covered by the submit-time charge, so it writes no
- // usage event — only failed refreshes are recorded, as the diagnostic trail.
+ // An operation that finished as FAILED did no billable work — no charge, but the failure
+ // goes on the books so a dead render leaves a diagnostic trail instead of vanishing.
+ if (result.status === "failed") {
+ await recordFailedInferenceUsage({
+ clientId: client.clientId,
+ conversationId: request.donkey.conversationId,
+ errorCode: "provider_error",
+ metadata: {
+ assetKind: parsed.data.kind,
+ generationId: parsed.data.id,
+ ...(result.error !== undefined && result.error !== null
+ ? { providerError: result.error }
+ : {}),
+ },
+ model: result.model,
+ provider: result.provider,
+ requestKind: "asset_generation",
+ route: inferenceUsageRoutes.assets,
+ userId: request.donkey.userId,
+ });
+ }
+
return NextResponse.json(
refreshedAssetGenerationResponse({
generation: parsed.data,
diff --git a/site/src/app/api/inference/assets/route.ts b/site/src/app/api/inference/assets/route.ts
index e098aa96..ec95b8d1 100644
--- a/site/src/app/api/inference/assets/route.ts
+++ b/site/src/app/api/inference/assets/route.ts
@@ -98,11 +98,43 @@ export const POST = withDonkeyAuth(async (request) => {
);
}
+ // A provider can settle a generation as failed synchronously (a safety
+ // filter at submit) — that did no billable work, but the failure goes on
+ // the books so a dead render leaves a diagnostic trail.
+ if (result.status === "failed") {
+ await recordFailedInferenceUsage({
+ clientId: client.clientId,
+ conversationId: request.donkey.conversationId,
+ errorCode: "provider_error",
+ metadata: {
+ assetKind: parsed.data.kind,
+ generationId,
+ ...(result.error !== undefined && result.error !== null
+ ? { providerError: result.error }
+ : {}),
+ },
+ model: result.model,
+ provider: result.provider,
+ requestKind: "asset_generation",
+ route: inferenceUsageRoutes.assets,
+ userId: request.donkey.userId,
+ });
+ return NextResponse.json(assetGenerationResponse({ generation, result }), {
+ status: 201,
+ });
+ }
+
+ // The submit is the billable moment, for sync and async results alike: a
+ // sync completion carries its real usage, and an async render bills the
+ // flat clip price (the adapter stamps the generation-count unit) — so one
+ // submission charges exactly once by construction, and the polls that
+ // follow (assets/refresh) are free.
const recordedUsage = await recordInferenceUsage({
clientId: client.clientId,
conversationId: request.donkey.conversationId,
metadata: {
assetKind: parsed.data.kind,
+ generationId,
},
model: result.model,
provider: result.provider,
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index 6f09fbfd..73716831 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -21,13 +21,13 @@ import { refsFromDroppedFiles } from "@/cut/lib/refMedia";
import { characterPrompt, stockTitle } from "@/cut/lib/stock";
import { useEditor } from "@/cut/lib/store";
import { useLocalPref } from "@/cut/lib/uiState";
+import { useVideoGen } from "@/cut/lib/videoGen";
import {
- useVideoGen,
VIDEO_ASPECT_LABEL,
VIDEO_MODELS,
type VideoAspect,
type VideoModelOption,
-} from "@/cut/lib/videoGen";
+} from "@/cut/lib/videoModels";
import { cn } from "@/lib/utils";
import { MentionTextarea, RefChips, RefHandlePill } from "./AssetRefs";
import { DictationControl } from "./MicDictation";
@@ -39,7 +39,7 @@ import { PillSelect } from "./PillSelect";
// The generate-video panel: an always-on column in the Video tab, sitting left
// of the stock-clip browser. Clicking a stock tile loads its saved prompt here.
//
-// A visual reference (dragged in or @name-mentioned) seeds the render: Veo
+// A visual reference (dragged in or @name-mentioned) seeds the render: the model
// takes one input image, so the first reference's picture becomes the start
// frame.
@@ -48,20 +48,12 @@ const ASPECT_WORD: Record<VideoAspect, string> = {
"9:16": "Portrait",
};
-// Segmented pill group, same language as the platform switcher in PlatformPreview.
-const segGroup = "flex h-7 items-center gap-0.5 rounded-full border border-border bg-card p-0.5 shadow-xs";
-const segButton = (active: boolean) =>
- cn(
- "rounded-full px-2.5 py-[3px] text-[11px] font-medium transition-colors",
- active ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground"
- );
-
export function GenerateVideoPanel({ projectId }: { projectId: string }) {
const signedIn = useSignedIn();
const allJobs = useGenerate((s) => s.jobs);
// Panel renders only — a chat- or scene-owned job lives on its chat card.
const jobs = allJobs.filter((j) => j.projectId === projectId && j.kind === "video" && !j.chatId);
- const { prompt, refs, character, aspect, resolution } = useVideoGen();
+ const { prompt, refs, character, aspect } = useVideoGen();
const candidates = useRefCandidates();
const { active: dropActive, attachTarget, targetProps } = useAssetDrop(
(ref) => {
@@ -76,25 +68,14 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
);
const [tier, setTier] = useLocalPref<VideoModelOption["tier"]>(
"cut-gen-tier",
- "fast",
+ "omni",
(v) => VIDEO_MODELS.some((m) => m.tier === v)
);
- const [seconds, setSeconds] = useLocalPref<number>(
- "cut-gen-seconds",
- 8,
- (v) => typeof v === "number" && VIDEO_MODELS.some((m) => m.durations.includes(v))
- );
// Every knob renders from — and is clamped to — what the selected model
// supports, so a stored pick from another model can never reach the API.
const model = VIDEO_MODELS.find((m) => m.tier === tier) ?? VIDEO_MODELS[0];
- const effSeconds = model.durations.includes(seconds)
- ? seconds
- : model.durations[model.durations.length - 1];
const effAspect = model.aspects.includes(aspect) ? aspect : model.aspects[0];
- const effResolution = model.resolutions.includes(resolution)
- ? resolution
- : model.resolutions[0];
// Default the shape to the project's own orientation when the panel opens,
// same as the image panel (the user can still pick the other one).
@@ -111,10 +92,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
const composed = character?.persona ? characterPrompt(character.persona, text) : text;
const seedRefs = character ? [refFromStockVideo(character)] : all;
void useGenerate.getState().generateVideo(projectId, composed, {
- tier,
- durationSeconds: effSeconds,
aspect: effAspect,
- resolution: effResolution,
refs: seedRefs,
// The character's poster seed is the point — the same person must
// deliver the line — so free-form prompts alone get the ref rewrite.
@@ -190,7 +168,9 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
/>
</div>
- {/* Which model renders the clip — a dropdown, since the catalog grows. */}
+ {/* Which model renders the clip — a dropdown, since the catalog grows.
+ The model renders the whole clip with audio in one pass and picks
+ its own length, so aspect below is the only other knob. */}
<PillSelect
className="h-7 shrink-0"
title="Model"
@@ -198,35 +178,13 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
display={model.model}
options={VIDEO_MODELS.map((m) => ({
value: m.tier,
- label: `${m.word} · ${m.model}`,
+ // A tiered family reads "Fast · Model Fast"; a single-model
+ // entry is just its name.
+ label: m.word === m.model ? m.model : `${m.word} · ${m.model}`,
}))}
onChange={setTier}
/>
- {/* The remaining knobs follow the selected model's capabilities. */}
- <div className="flex shrink-0 items-center justify-between gap-2">
- <div className={segGroup}>
- {model.durations.map((s) => (
- <button
- key={s}
- className={segButton(effSeconds === s)}
- aria-pressed={effSeconds === s}
- onClick={() => setSeconds(s)}
- >
- {s}s
- </button>
- ))}
- </div>
- <PillSelect
- className="h-7"
- title="Resolution"
- value={effResolution}
- display={effResolution}
- options={model.resolutions.map((r) => ({ value: r, label: r }))}
- onChange={(v) => useVideoGen.getState().setResolution(v)}
- />
- </div>
-
{/* Shape, the same pill family as the image panel. */}
<PillSelect
className="h-7 shrink-0"
diff --git a/site/src/cut/lib/composeGen.ts b/site/src/cut/lib/composeGen.ts
index dd52a9e0..a087a88e 100644
--- a/site/src/cut/lib/composeGen.ts
+++ b/site/src/cut/lib/composeGen.ts
@@ -7,7 +7,7 @@ import { readRefText, refsToParts, type InlineImage } from "./refMedia";
// Reference-aware prompt composition, shared by video and image generation.
//
-// The generators read their input images literally: Veo plays its one input
+// The generators read their input images literally: the video model plays its one input
// image as the video's first frame, and the image model edits the pixels it is
// given. So a prompt that asks to *transform* a reference ("turn this into a
// korean woman") loses to the picture, and text-file references (a script,
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index a0c83eab..b5c4d080 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -9,15 +9,16 @@ import { composeGenPrompt, foldTextRefs } from "./composeGen";
import { stockAssetInDoc } from "./genvideo/docWriter";
import { hostedPost } from "./hosted";
import { enrichAsset, importFileToProject } from "./media";
-import { refsToInlineImages, visualRefs, type InlineImage } from "./refMedia";
+import { refsToInlineImages, videoSafeInline, visualRefs, type InlineImage } from "./refMedia";
import { useGenNotify } from "./genNotify";
import { useImageGen } from "./imageGen";
import { useEditor } from "./store";
import { mediaUrl, type MediaAsset } from "./types";
-import { videoModel } from "./videoGen";
+import { videoModel } from "./videoModels";
+import { walkLadder, type VideoAttempt } from "./videoLadder";
// AI generation jobs, held outside the panels so a tab switch (which unmounts
-// them) doesn't orphan a running generation — Veo renders take minutes.
+// them) doesn't orphan a running generation — video renders take minutes.
//
// Generation runs on Donkey's hosted inference routes with the user's Donkey
// sign-in and credits. The cut hosts serve the same Next app and the auth
@@ -44,6 +45,9 @@ export interface GenerateJob {
* resumed caller re-adopts exactly its own in-flight job — never another
* shot's that happens to share a prompt. */
genKey?: string;
+ /** Which ladder rung landed the render (0-based index into the attempts) —
+ * how a caller knows whether its take rode an image anchor. */
+ rung?: number;
/** The provider poll payload for an in-flight render — persisting it is what
* lets a reload re-attach to the running job instead of orphaning it. */
poll?: {
@@ -93,6 +97,23 @@ interface GenerateState {
prompt: string,
opts?: VideoGenOptions
) => { jobId: string; settled: Promise<GenerateJob> };
+ /** Kick off a video render that walks an identity ladder: ONE job spans the
+ * attempts in order, and a failed rung submits the next instead of failing
+ * the job — so a safety-blocked or rejected anchor degrades the render
+ * instead of killing it. An empty balance stops the walk (every rung would
+ * fail the same way). Both the scene pipeline's shots and chat's one-off
+ * renders run on this, so the two have identical fallback behavior. */
+ generateVideoLadder: (
+ projectId: string,
+ attempts: VideoAttempt[],
+ jobOpts?: {
+ chatId?: string;
+ genKey?: string;
+ onDone?: (asset: MediaAsset) => void;
+ /** Called as each rung starts (0-based) — progress narration. */
+ onAttempt?: (rung: number) => void;
+ }
+ ) => { jobId: string; settled: Promise<GenerateJob> };
dismiss: (id: string) => void;
/** Re-attach the poll loop of every persisted running render (reload
* recovery) — called once when the app boots. Idempotent. */
@@ -100,26 +121,23 @@ interface GenerateState {
}
export interface VideoGenOptions {
- tier?: "fast" | "high";
- durationSeconds?: number;
/** Composition shape; defaults to the project's orientation. */
aspect?: "16:9" | "9:16";
- resolution?: "720p" | "1080p";
- /** Person-safety for the render. Unset, Veo blocks person/face generation, so
- * any shot with a character fails. ALLOW_ADULT is the most any image input
- * permits (first-frame seed and reference images alike); ALLOW_ALL (needed
- * for minors) only works text-to-video. */
- personGeneration?: "DONT_ALLOW" | "ALLOW_ADULT" | "ALLOW_ALL";
- /** References of any kind — video, image, text file. Veo takes one
- * input image, so at most one picture seeds the render. */
+ /** What the render must avoid — the wrong medium's tells, letterbox bars,
+ * on-screen text. The model has no negative-prompt parameter, so the
+ * adapter folds this into the prompt as an avoid clause. */
+ negativePrompt?: string;
+ /** References of any kind — video, image, text file. The model takes one
+ * seed image, so at most one picture seeds the render as its literal
+ * opening frame. */
refs?: AssetRef[];
- /** Identity anchors (Veo 3.1 asset references, up to three): the render
+ /** Identity anchors (up to the registry's maxReferenceImages): the render
* keeps these characters/objects/scenes consistent instead of playing one
* as the first frame. Mutually exclusive with a `refs` image seed; the
* prompt rides as written (no compose rewrite). */
referenceImages?: AssetRef[];
/** Rewrite the prompt around the references before rendering (the
- * default when refs are present) — see composeGen.ts. Veo plays the
+ * default when refs are present) — see composeGen.ts. The model plays the
* input image as the literal first frame, so a prompt that transforms
* the reference must become a standalone description with the image
* dropped; the rewrite decides which. Character mode passes false — the
@@ -136,6 +154,8 @@ export interface VideoGenOptions {
genKey?: string;
}
+export type { VideoAttempt } from "./videoLadder";
+
const REFRESH_MS = 8000;
const VIDEO_DEADLINE_MS = 12 * 60_000;
@@ -248,7 +268,7 @@ const providerError = (error: unknown): string | null => {
/** Resolve a generation's prompt + input images from its refs. Runs the shared
* compose step (see composeGen.ts) unless the caller opted out; on a compose
* failure, falls back to the visual refs as-is with text-ref contents folded
- * into the prompt. `maxImages` caps what the generator accepts (Veo: 1). */
+ * into the prompt. `maxImages` caps what the generator accepts (video: 1 seed). */
async function promptAndImages(
target: "video" | "image",
prompt: string,
@@ -382,20 +402,22 @@ export const useGenerate = create<GenerateState>((set, get) => {
return true;
};
- /** Poll an in-flight Veo render to completion and land its file as a project
+ /** Poll an in-flight video render to completion and land its file as a project
* asset — the shared tail of a fresh render and a reload-resumed one. Keeps
* the job's poll payload fresh so the NEXT reload re-attaches too. */
const finishVideo = async (
jobId: string,
first: GenerationResponse,
- onDone?: (asset: MediaAsset) => void
+ onDone?: (asset: MediaAsset) => void,
+ since?: number
): Promise<void> => {
const job = get().jobs.find((j) => j.id === jobId);
if (!job) return;
let gen = first;
// A resumed render keeps its original deadline, floored so a reload near
- // the limit still gets a couple of polls before giving up.
- const deadline = Math.max(job.startedAt + VIDEO_DEADLINE_MS, Date.now() + 2 * 60_000);
+ // the limit still gets a couple of polls before giving up. A ladder rung
+ // passes its own start so a slow first rung doesn't starve the fallback.
+ const deadline = Math.max((since ?? job.startedAt) + VIDEO_DEADLINE_MS, Date.now() + 2 * 60_000);
while (gen.status === "in_progress") {
claimJobLease(jobId); // renewed every cycle; siblings back off until it staled
update(jobId, {
@@ -409,7 +431,7 @@ export const useGenerate = create<GenerateState>((set, get) => {
metadata: gen.metadata ?? {},
},
});
- if (Date.now() > deadline) throw new Error("Veo is taking too long — try again.");
+ if (Date.now() > deadline) throw new Error("The video render is taking too long — try again.");
await sleep(REFRESH_MS);
const poll = await hostedPost("/api/inference/assets/refresh", {
id: gen.id,
@@ -555,57 +577,93 @@ export const useGenerate = create<GenerateState>((set, get) => {
})();
},
- generateVideo: (projectId, prompt, opts) => {
+ generateVideo: (projectId, prompt, opts) =>
+ get().generateVideoLadder(projectId, [{ prompt, opts }], {
+ ...(opts?.chatId ? { chatId: opts.chatId } : {}),
+ ...(opts?.genKey ? { genKey: opts.genKey } : {}),
+ ...(opts?.onDone ? { onDone: opts.onDone } : {}),
+ }),
+
+ generateVideoLadder: (projectId, attempts, jobOpts) => {
+ // The job (and the landed asset's name) keeps the caller's first-rung
+ // words; only the render sees each rung's composed prompt.
const job: GenerateJob = {
id: uid(),
projectId,
kind: "video",
- prompt,
+ prompt: attempts[0]?.prompt ?? "",
startedAt: Date.now(),
status: "running",
- ...(opts?.chatId ? { chatId: opts.chatId } : {}),
- ...(opts?.genKey ? { genKey: opts.genKey } : {}),
+ ...(jobOpts?.chatId ? { chatId: jobOpts.chatId } : {}),
+ ...(jobOpts?.genKey ? { genKey: jobOpts.genKey } : {}),
};
set((s) => ({ jobs: [job, ...s.jobs] }));
claimJobLease(job.id); // this tab started it, this tab polls it
+
+ /** Compose and submit one rung's render request; resolves the provider's
+ * first response (usually in_progress) or throws the readable error. */
+ const submitRung = async ({ prompt, opts }: VideoAttempt): Promise<GenerationResponse> => {
+ // The model seeds from a single first-frame image, so at most one kept
+ // picture rides along. Identity anchors travel separately: with
+ // referenceImages set, the prompt stands as written and no seed image
+ // rides (the render takes one or the other).
+ // Every picture riding to the video model goes through videoSafeInline:
+ // it takes only JPEG/PNG, and a webp reference would fail the render
+ // after it was already billed.
+ const anchors = opts?.referenceImages?.length
+ ? await Promise.all(
+ (
+ await refsToInlineImages(
+ visualRefs(opts.referenceImages).slice(0, videoModel("omni").maxReferenceImages)
+ )
+ ).map(videoSafeInline)
+ )
+ : [];
+ const { prompt: sent, images: rawImages } = anchors.length
+ ? { prompt, images: [] as InlineImage[] }
+ : await promptAndImages("video", prompt, opts?.refs ?? [], opts?.composeRefs !== false, 1);
+ const images = await Promise.all(rawImages.map(videoSafeInline));
+ const res = await hostedPost("/api/inference/assets", {
+ kind: "video",
+ prompt: sent,
+ provider: "gemini-omni",
+ ...(anchors.length > 0
+ ? { inputs: { referenceImages: anchors } }
+ : images.length > 0
+ ? { inputs: { images } }
+ : {}),
+ parameters: {
+ aspectRatio: opts?.aspect ?? useEditor.getState().aspect,
+ ...(opts?.negativePrompt ? { negativePrompt: opts.negativePrompt } : {}),
+ },
+ });
+ if (!res.ok) throw new Error(await readError(res, "Video generation failed."));
+ return (await res.json()) as GenerationResponse;
+ };
+
const settledRun = (async () => {
try {
- // The job (and the landed asset's name) keeps the user's own words;
- // only the render sees the composed prompt. Veo seeds from a single
- // first-frame image, so at most one kept picture rides along.
- // Identity anchors travel separately: with referenceImages set, the
- // prompt stands as written and no seed image rides (Veo takes one
- // or the other).
- const tier = opts?.tier === "high" ? "high" : "fast";
- const anchors = opts?.referenceImages?.length
- ? await refsToInlineImages(
- visualRefs(opts.referenceImages).slice(0, videoModel(tier).maxReferenceImages)
- )
- : [];
- const { prompt: sent, images } = anchors.length
- ? { prompt, images: [] }
- : await promptAndImages("video", prompt, opts?.refs ?? [], opts?.composeRefs !== false, 1);
- const res = await hostedPost("/api/inference/assets", {
- kind: "video",
- prompt: sent,
- ...(anchors.length > 0
- ? { inputs: { referenceImages: anchors } }
- : images.length > 0
- ? { inputs: { images } }
- : {}),
- parameters: {
- tier,
- aspectRatio: opts?.aspect ?? useEditor.getState().aspect,
- ...(opts?.resolution ? { resolution: opts.resolution } : {}),
- ...(opts?.durationSeconds ? { durationSeconds: opts.durationSeconds } : {}),
- ...(opts?.personGeneration ? { personGeneration: opts.personGeneration } : {}),
+ const outcome = await walkLadder(
+ attempts,
+ async (attempt, rung) => {
+ jobOpts?.onAttempt?.(rung);
+ // The rung persists as the attempt starts, not when the walk
+ // settles — a reload that adopts this in-flight job must still
+ // know which rung (anchored or not) produced the take.
+ update(job.id, { rung });
+ const gen = await submitRung(attempt);
+ await finishVideo(job.id, gen, jobOpts?.onDone, Date.now());
},
- });
- if (!res.ok) throw new Error(await readError(res, "Video generation failed."));
- const gen = (await res.json()) as GenerationResponse;
- await finishVideo(job.id, gen, opts?.onDone);
- } catch (err) {
- fail(job.id, err);
+ {
+ // The next rung is a fresh submission: drop the dead rung's poll
+ // payload so a reload can't resume a render that already failed.
+ onRungFailed: () => update(job.id, { poll: undefined }),
+ // An empty balance fails every rung identically — stop there so
+ // a broke render fails fast, not once per rung.
+ fatal: (error) => error === NO_CREDITS_MESSAGE,
+ }
+ );
+ if (!outcome.ok) fail(job.id, new Error(outcome.error));
} finally {
releaseJobLease(job.id);
}
diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.ts
index 4c64df5b..37f8af20 100644
--- a/site/src/cut/lib/refMedia.ts
+++ b/site/src/cut/lib/refMedia.ts
@@ -66,10 +66,33 @@ function blobToDataUrl(blob: Blob): Promise<string> {
});
}
-async function blobToInline(blob: Blob): Promise<InlineImage> {
+/** A blob's bytes as an inline image part, mime read from the bytes. */
+export async function blobToInline(blob: Blob): Promise<InlineImage> {
return splitDataUrl(await blobToDataUrl(blob));
}
+/** Video models take input images only as JPEG or PNG — the render rejects anything
+ * else by format, killing the render after it was billed. Re-encode any other
+ * picture (webp saved off the web is the common case) to PNG; jpeg and png
+ * pass through untouched. */
+export async function videoSafeInline(img: InlineImage): Promise<InlineImage> {
+ if (img.mimeType === "image/jpeg" || img.mimeType === "image/png") return img;
+ const blob = await (await fetch(`data:${img.mimeType};base64,${img.data}`)).blob();
+ const bitmap = await createImageBitmap(blob).catch(() => null);
+ if (!bitmap) throw new Error("A reference image is in a format the video model can't read.");
+ try {
+ const canvas = document.createElement("canvas");
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("Could not convert a reference image for the video model.");
+ ctx.drawImage(bitmap, 0, 0);
+ return splitDataUrl(canvas.toDataURL("image/png"));
+ } finally {
+ bitmap.close();
+ }
+}
+
// Keeps the inline payload well under the Gemini per-request inline-data cap
// (base64 inflates by 4/3); larger audio degrades to a name-only marker.
const MAX_AUDIO_BYTES = 12 * 1024 * 1024;
diff --git a/site/src/cut/lib/stock.ts b/site/src/cut/lib/stock.ts
index 86cfca10..542a8392 100644
--- a/site/src/cut/lib/stock.ts
+++ b/site/src/cut/lib/stock.ts
@@ -23,7 +23,7 @@ export interface StockImage {
thumb: string;
}
-/** Veo renders landscape and portrait only — no square video. */
+/** Video renders landscape and portrait only — no square video. */
export type StockVideoAspect = "16:9" | "9:16";
export interface StockVideo {
@@ -60,7 +60,7 @@ export const STOCK_CATEGORIES = [
export type StockCategory = (typeof STOCK_CATEGORIES)[number];
/** Video adds a catalog-only "Characters" section: talking-head clips whose
- * prompts carry an editable spoken line (Veo generates the dialogue audio). */
+ * prompts carry an editable spoken line (the model generates the dialogue audio). */
export const STOCK_VIDEO_CATEGORIES = ["Characters", ...STOCK_CATEGORIES] as const;
export type StockVideoCategory = (typeof STOCK_VIDEO_CATEGORIES)[number];
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index e80ef6dd..73238c8a 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -680,7 +680,7 @@ export const useEditor = create<EditorState>((set, get) => {
in: srcIn,
out: srcIn + out,
// Muted: generated shots ride under the narration spine, so the clip's
- // own audio (Veo synthesizes some) must never compete with the voice.
+ // own audio (the model synthesizes some) must never compete with the voice.
muted: true,
...(speed !== undefined ? { speed } : {}),
};
diff --git a/site/src/cut/lib/videoGen.ts b/site/src/cut/lib/videoGen.ts
index 7f48de17..d0c62fe1 100644
--- a/site/src/cut/lib/videoGen.ts
+++ b/site/src/cut/lib/videoGen.ts
@@ -3,96 +3,16 @@
import { create } from "zustand";
import { addRefOnce, sameRef, type AssetRef } from "./assetRef";
import type { StockVideo } from "./stock";
+import type { VideoAspect } from "./videoModels";
// The generate-video panel's state, shared between the stock-video browser
// (which loads a stock clip's saved prompt into it on click) and the always-on
// generate panel that sits beside the browser in the Video tab.
-/** The shape the next generated clip is composed in — Veo renders landscape
- * and portrait. */
-export type VideoAspect = "16:9" | "9:16";
-
-export const VIDEO_ASPECT_LABEL: Record<VideoAspect, string> = {
- "16:9": "Landscape (16:9)",
- "9:16": "Portrait (9:16)",
-};
-
-/** Output detail the next clip renders at. */
-export type VideoResolution = "720p" | "1080p";
-
-/** A selectable video model: the tier the backend resolves to a concrete
- * model id (gemini-models.ts) plus the knobs that model supports. The
- * generate panel renders its duration/aspect/resolution controls from the
- * selected entry and clamps stored picks to it, so adding a model here is the
- * whole client-side change. */
-export interface VideoModelOption {
- tier: "fast" | "high";
- /** Segment label ("Fast") and the model name shown beside it. */
- word: string;
- model: string;
- durations: number[];
- /** Clip lengths the model renders when identity reference images ride
- * along — Veo 3.1 reference-to-video renders 8s only. */
- referenceDurations: number[];
- /** Identity reference images a render accepts alongside the prompt. */
- maxReferenceImages: number;
- aspects: VideoAspect[];
- resolutions: VideoResolution[];
-}
-
-export const VIDEO_MODELS: VideoModelOption[] = [
- {
- tier: "fast",
- word: "Fast",
- model: "Veo 3.1 Fast",
- durations: [4, 6, 8],
- referenceDurations: [8],
- maxReferenceImages: 3,
- aspects: ["16:9", "9:16"],
- resolutions: ["720p", "1080p"],
- },
- {
- tier: "high",
- word: "Best",
- model: "Veo 3.1",
- durations: [4, 6, 8],
- referenceDurations: [8],
- maxReferenceImages: 3,
- aspects: ["16:9", "9:16"],
- resolutions: ["720p", "1080p"],
- },
-];
-
-/** The registry entry for a tier — the single source of truth for what that
- * model supports. Any code that generates video (the panel, the scene pipeline)
- * reads its constraints from here, so swapping models is one edit in this file. */
-export function videoModel(tier: "fast" | "high"): VideoModelOption {
- return VIDEO_MODELS.find((m) => m.tier === tier) ?? VIDEO_MODELS[0];
-}
-
-/** Snap a desired clip length to one the model actually renders: the shortest
- * supported duration that still covers `seconds` (the caller trims down to the
- * exact need), or the model's longest. Video models render only a fixed set of
- * lengths and reject anything else, so a caller must never pass a raw duration.
- * `withReferences` reads the tighter reference-to-video set. */
-export function supportedVideoDuration(
- tier: "fast" | "high",
- seconds: number,
- opts?: { withReferences?: boolean }
-): number {
- const model = videoModel(tier);
- const durations = [...(opts?.withReferences ? model.referenceDurations : model.durations)].sort(
- (a, b) => a - b
- );
- return durations.find((d) => d >= seconds) ?? durations[durations.length - 1];
-}
-
interface VideoGenState {
prompt: string;
/** The shape the next generation is composed in. */
aspect: VideoAspect;
- /** The output detail the next generation renders at. */
- resolution: VideoResolution;
/** Visual references attached to the next generation (dragged in or picked
* via @name mentions resolved on send). */
refs: AssetRef[];
@@ -108,7 +28,6 @@ interface VideoGenState {
clearCharacter: () => void;
setPrompt: (prompt: string) => void;
setAspect: (aspect: VideoAspect) => void;
- setResolution: (resolution: VideoResolution) => void;
addRef: (ref: AssetRef) => void;
removeRef: (ref: AssetRef) => void;
}
@@ -116,7 +35,6 @@ interface VideoGenState {
export const useVideoGen = create<VideoGenState>((set) => ({
prompt: "",
aspect: "16:9",
- resolution: "720p",
refs: [],
character: null,
openWith: (prompt) => set({ prompt, refs: [], character: null }),
@@ -124,7 +42,6 @@ export const useVideoGen = create<VideoGenState>((set) => ({
clearCharacter: () => set({ character: null }),
setPrompt: (prompt) => set({ prompt }),
setAspect: (aspect) => set({ aspect }),
- setResolution: (resolution) => set({ resolution }),
addRef: (ref) => set((s) => ({ refs: addRefOnce(s.refs, ref) })),
removeRef: (ref) => set((s) => ({ refs: s.refs.filter((r) => !sameRef(r, ref)) })),
}));
diff --git a/site/src/cut/lib/videoLadder.ts b/site/src/cut/lib/videoLadder.ts
new file mode 100644
index 00000000..fa2a3075
--- /dev/null
+++ b/site/src/cut/lib/videoLadder.ts
@@ -0,0 +1,51 @@
+/**
+ * The render ladder's walk: one job tries fallback rungs in order until one
+ * lands. Pure — the store (generate.ts) supplies the submission and polling;
+ * this module owns only the policy of WHICH rung runs next, so the self-test
+ * can prove it without a browser or a credit spent.
+ */
+
+import type { VideoGenOptions } from "./generate";
+
+/** One rung of a render ladder: the prompt and options for a single hosted
+ * submission. Job-level identity (chat ownership, genKey, placement) rides
+ * the ladder call, not the rungs. */
+export interface VideoAttempt {
+ prompt: string;
+ opts?: Omit<VideoGenOptions, "onDone" | "chatId" | "genKey">;
+ /** Whether this rung runs, decided when the walk reaches it — `lastError` is
+ * the previous rung's failure (null when nothing failed yet). Lets a caller
+ * reserve a rung for specific failures, e.g. text-only only after the
+ * provider refused the image anchor. Skipped rungs cost nothing and keep
+ * the prior error. */
+ gate?: (lastError: string | null) => boolean;
+}
+
+/** Walk the rungs: run each in order, return on the first that lands. A rung
+ * whose gate declines is skipped (costing nothing, keeping the prior error);
+ * a `fatal` failure stops the walk outright — every later rung would fail the
+ * same way. `onRungFailed` fires between a failed rung and the next. */
+export async function walkLadder(
+ attempts: VideoAttempt[],
+ run: (attempt: VideoAttempt, rung: number) => Promise<void>,
+ opts?: {
+ onRungFailed?: (error: string, rung: number) => void;
+ fatal?: (error: string) => boolean;
+ }
+): Promise<{ ok: boolean; error: string; rung?: number }> {
+ let lastError = "Video generation failed.";
+ let anyFailed = false;
+ for (const [rung, attempt] of attempts.entries()) {
+ if (attempt.gate && !attempt.gate(anyFailed ? lastError : null)) continue;
+ try {
+ await run(attempt, rung);
+ return { ok: true, error: "", rung };
+ } catch (err) {
+ lastError = err instanceof Error ? err.message : String(err);
+ anyFailed = true;
+ if (opts?.fatal?.(lastError)) break;
+ opts?.onRungFailed?.(lastError, rung);
+ }
+ }
+ return { ok: false, error: lastError };
+}
diff --git a/site/src/cut/lib/videoModels.ts b/site/src/cut/lib/videoModels.ts
new file mode 100644
index 00000000..eb5fb5c0
--- /dev/null
+++ b/site/src/cut/lib/videoModels.ts
@@ -0,0 +1,48 @@
+// The video-model registry: which models render, and what each supports.
+// Pure data + lookups (no store, no browser), so the genvideo self-test can
+// exercise everything that reads constraints from here.
+
+import { geminiOmniMaxReferenceImages } from "@/lib/inference/gemini-models";
+
+/** The shape the next generated clip is composed in — landscape or portrait. */
+export type VideoAspect = "16:9" | "9:16";
+
+export const VIDEO_ASPECT_LABEL: Record<VideoAspect, string> = {
+ "16:9": "Landscape (16:9)",
+ "9:16": "Portrait (9:16)",
+};
+
+/** A selectable video model. Every render runs on the unified Omni renderer:
+ * one pass takes text plus optional seed/reference images and returns the
+ * whole clip with audio — the model picks the length (up to ~10s of 720p), so
+ * there is no duration or resolution knob. Adding a model here is the whole
+ * client-side change. */
+export type VideoTier = "omni";
+
+export interface VideoModelOption {
+ tier: VideoTier;
+ /** Segment label and the model name shown beside it (equal for a
+ * single-model entry). */
+ word: string;
+ model: string;
+ /** Identity reference images a render accepts alongside the prompt. */
+ maxReferenceImages: number;
+ aspects: VideoAspect[];
+}
+
+export const VIDEO_MODELS: VideoModelOption[] = [
+ {
+ tier: "omni",
+ word: "Omni Flash",
+ model: "Omni Flash",
+ maxReferenceImages: geminiOmniMaxReferenceImages,
+ aspects: ["16:9", "9:16"],
+ },
+];
+
+/** The registry entry for a tier — the single source of truth for what that
+ * model supports. Any code that generates video (the panel, the scene pipeline)
+ * reads its constraints from here, so swapping models is one edit in this file. */
+export function videoModel(tier: VideoTier): VideoModelOption {
+ return VIDEO_MODELS.find((m) => m.tier === tier) ?? VIDEO_MODELS[0];
+}
diff --git a/site/src/lib/credits/provider-pricing.ts b/site/src/lib/credits/provider-pricing.ts
index ff205eab..9ba9d353 100644
--- a/site/src/lib/credits/provider-pricing.ts
+++ b/site/src/lib/credits/provider-pricing.ts
@@ -8,11 +8,11 @@ import {
} from "@/lib/inference/elevenlabs-models";
import {
geminiModels,
+ geminiOmniModels,
geminiTtsModels,
- veoModels,
type GeminiModel,
+ type GeminiOmniModel,
type GeminiTtsModel,
- type VeoModel,
} from "@/lib/inference/gemini-models";
import { openaiModels, type OpenAIRunModel } from "@/lib/inference/openai-models";
import { browserUsePerStepUsd } from "@/lib/browser/pricing";
@@ -49,14 +49,14 @@ export function providerCreditPricing(
if (normalizedProvider === "gemini") {
return geminiCreditPricing(normalizedModel);
}
- // Veo video ids are hardcoded (gemini-models.ts); each is priced per clip below.
- 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);
}
+ // Omni video ids are hardcoded (gemini-models.ts); a clip bills flat at submit.
+ if (normalizedProvider === "gemini-omni") {
+ return geminiOmniCreditPricing(normalizedModel);
+ }
if (normalizedProvider === "elevenlabs") {
return elevenLabsCreditPricing(normalizedModel);
}
@@ -285,22 +285,6 @@ const geminiModelPricing: Record<GeminiModel, ProviderCreditPricing> = {
[geminiModels.proImage]: { generationCostMicros: usdWithMargin("0.134") },
};
-// Generative text/image-to-video (Veo). Model ids are hardcoded (gemini-models.ts), so each is priced
-// per clip. Veo bills per second of output; these reflect a default ~8s clip with audio (quality
-// ~$0.40/s ≈ $3.20, fast ~$0.15/s ≈ $1.20, lite ~$0.05/s ≈ $0.40), charged once at submit
-// (assets/refresh is free). A shorter/longer clip still pays the flat rate; move to
-// durationSecondCostMicros if that drifts too far. The Record is keyed by VeoModel, so adding a Veo id
-// without a price fails the build.
-const veoModelPricing: Record<VeoModel, ProviderCreditPricing> = {
- [veoModels.quality]: { generationCostMicros: usdWithMargin("3.20") },
- [veoModels.fast]: { generationCostMicros: usdWithMargin("1.20") },
- [veoModels.lite]: { generationCostMicros: usdWithMargin("0.40") },
-};
-
-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.
@@ -312,6 +296,30 @@ function geminiTtsCreditPricing(model: string): ProviderCreditPricing | undefine
return geminiTtsModelPricing[model as GeminiTtsModel];
}
+// Unified video generation (Gemini Omni Flash). The provider bills by tokens —
+// $1.50/1M input, $17.50/1M output, and a rendered second of 720p video is
+// 5,792 output tokens — but the render is async: the submit response carries no
+// token counts, and charging on the completing poll instead would let one
+// balance launch unbounded concurrent renders. So a clip charges FLAT at
+// submit (usage {generationCount: 1}): ~10s × 5,792 tokens/s × $17.5/1M ≈
+// $1.02, the model's fixed-length output. The token rates stay for the rare
+// interaction that completes synchronously with real counts. The Record is
+// keyed by GeminiOmniModel, so adding an Omni id without a price fails the build.
+const geminiOmniModelPricing: Record<GeminiOmniModel, ProviderCreditPricing> = {
+ [geminiOmniModels.flashVideo]: {
+ ...textTokenPricing({
+ model: geminiOmniModels.flashVideo,
+ input: "1.5",
+ output: "17.5",
+ }),
+ generationCostMicros: usdWithMargin("1.02"),
+ },
+};
+
+function geminiOmniCreditPricing(model: string): ProviderCreditPricing | undefined {
+ return geminiOmniModelPricing[model as GeminiOmniModel];
+}
+
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-omni-video.ts b/site/src/lib/inference/adapters/gemini-omni-video.ts
new file mode 100644
index 00000000..dc247b8d
--- /dev/null
+++ b/site/src/lib/inference/adapters/gemini-omni-video.ts
@@ -0,0 +1,323 @@
+import { GoogleGenAI } from "@google/genai";
+import type { GoogleGenAIOptions, Interactions } from "@google/genai";
+
+type Interaction = Interactions.Interaction;
+
+import {
+ geminiApiError,
+ geminiClientConfig,
+ stringValue,
+ type AdapterEnvironment,
+} from "@/lib/inference/adapters/gemini-client";
+import { providerCreditPricing } from "@/lib/credits/provider-pricing";
+import { geminiOmniMaxReferenceImages, geminiOmniModels } 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 JsonObject,
+ type StoredGenerationForProvider,
+} from "@/lib/inference/providers";
+
+// The video generation provider (Gemini Omni Flash) on the Interactions API:
+// one call takes text plus optional seed/reference images and renders a clip
+// with audio in a single pass. It submits a background interaction and the
+// caller polls refresh until it lands; the provider id keeps that refresh
+// routing separate from the synchronous image adapter. The model decides the
+// clip length (up to ~10s of 720p) — there is no duration knob to pass.
+const providerID = "gemini-omni";
+
+// Verified live against Vertex: `response_modalities` is rejected outright
+// (400), so the requested output rides response_format alone; and image output
+// is not enabled for this model, so this provider is video-only.
+export type GeminiOmniClient = Pick<GoogleGenAI, "interactions">;
+export type GeminiOmniClientFactory = (options: GoogleGenAIOptions) => GeminiOmniClient;
+
+const defaultOmniClientFactory: GeminiOmniClientFactory = (options) =>
+ new GoogleGenAI(options);
+
+export function createGeminiOmniVideoAssetProvider(
+ environment: AdapterEnvironment = process.env,
+ clientFactory: GeminiOmniClientFactory = defaultOmniClientFactory,
+): InferenceProvider {
+ const clientConfig = geminiClientConfig(environment);
+ const configured = clientConfig.configured;
+ const defaultModel = geminiOmniModels.flashVideo;
+
+ async function listModels(
+ modalities: InferenceModality[],
+ ): Promise<InferenceModel[]> {
+ if (!modalities.includes("video")) {
+ return [];
+ }
+ return [
+ {
+ id: defaultModel,
+ name: defaultModel,
+ provider: providerID,
+ inputModalities: ["text", "image"],
+ outputModalities: ["video"],
+ contextLength: null,
+ pricing: null,
+ metadata: { provider: providerID, api: "interactions" },
+ },
+ ];
+ }
+
+ function resolveModel(requested?: string): string {
+ const model = requested?.trim() || defaultModel;
+ // Fail before spending: the resolved model must have a configured price.
+ if (!providerCreditPricing(providerID, model)) {
+ throw new InferenceProviderError(
+ "No credit price is configured for the selected video model.",
+ { statusCode: 500, code: "video_model_not_priced", details: { model } },
+ );
+ }
+ return model;
+ }
+
+ async function generateAsset({
+ request,
+ }: AssetGenerationProviderRequest): Promise<AssetGenerationProviderResult> {
+ ensureConfigured(configured);
+
+ if (request.kind !== "video") {
+ throw new InferenceProviderError("Provider does not support this asset kind.", {
+ statusCode: 400,
+ code: "unsupported_asset_kind",
+ });
+ }
+
+ const model = resolveModel(request.model);
+ const basePrompt = request.prompt?.trim();
+ const inputs = toJsonObject(request.inputs ?? {});
+ const seed = firstInlineImage(inputs.images);
+ // A render takes one conditioning mode: a seed frame XOR identity
+ // references. Both at once is a caller bug — reject it rather than
+ // silently dropping the identity anchors from a billed render.
+ const references = inlineImages(inputs.referenceImages).slice(
+ 0,
+ geminiOmniMaxReferenceImages,
+ );
+ if (seed && references.length > 0) {
+ throw new InferenceProviderError(
+ "Video generation takes an input image or reference images, not both.",
+ { statusCode: 400, code: "conflicting_video_inputs" },
+ );
+ }
+ if (!basePrompt && !seed) {
+ throw new InferenceProviderError(
+ "Video generation requires a prompt or an input image.",
+ { statusCode: 400, code: "empty_video_request" },
+ );
+ }
+
+ const parameters = toJsonObject(request.parameters ?? {});
+ // The model has no negative-prompt parameter, so the bans ride the prompt
+ // itself as an avoid clause — same treatment the image model gets.
+ const negative = stringValue(parameters.negativePrompt)?.trim();
+ const prompt = [basePrompt, negative ? `Avoid: ${negative}.` : ""]
+ .filter(Boolean)
+ .join(" ");
+ const pictures = seed ? [seed] : references;
+ const input =
+ pictures.length === 0
+ ? prompt
+ : [
+ ...pictures.map((image) => ({
+ type: "image" as const,
+ data: image.data,
+ mime_type: image.mimeType as never,
+ })),
+ { type: "text" as const, text: prompt },
+ ];
+ const task = seed
+ ? "image_to_video"
+ : references.length > 0
+ ? "reference_to_video"
+ : "text_to_video";
+ const aspectRatio = stringValue(parameters.aspectRatio);
+
+ const client = clientFactory(clientConfig.options);
+ let interaction: Interaction;
+ try {
+ interaction = await client.interactions.create({
+ model,
+ input,
+ // How the pictures condition the render: a seed becomes the opening
+ // frame, references anchor identity/style across the clip.
+ generation_config: { video_config: { task } } as never,
+ response_format: {
+ type: "video",
+ ...(aspectRatio === "16:9" || aspectRatio === "9:16" ? { aspect_ratio: aspectRatio } : {}),
+ } as never,
+ background: true,
+ });
+ } catch (error) {
+ throw geminiApiError("Omni video generation failed.", error);
+ }
+
+ // Rare fast path: the interaction may already be complete on submit.
+ const settled = settledResult(interaction, interaction.id, model);
+ if (settled) {
+ return settled;
+ }
+
+ // In progress: the clip is committed, so the flat clip price bills now —
+ // generationCount is the billing unit (provider-pricing.ts), since the
+ // async submit carries no token counts and the polls that follow are free.
+ // Only the submit carries it; a refresh poll's in-progress result must not.
+ return { ...inProgressResult(interaction.id, model), usage: { generationCount: 1 } };
+ }
+
+ async function refreshAsset(
+ generation: StoredGenerationForProvider,
+ ): Promise<AssetGenerationProviderResult> {
+ ensureConfigured(configured);
+
+ const interactionId =
+ generation.providerGenerationId?.trim() ||
+ generation.providerJobId?.trim() ||
+ stringValue(generation.metadata?.interactionId);
+ if (!interactionId) {
+ return failedResult(generation.model, "No Omni interaction to poll.");
+ }
+
+ const client = clientFactory(clientConfig.options);
+ let interaction: Interaction;
+ try {
+ interaction = await client.interactions.get(interactionId);
+ } catch (error) {
+ throw geminiApiError("Polling the Omni interaction failed.", error);
+ }
+
+ return (
+ settledResult(interaction, generation.id, generation.model) ??
+ inProgressResult(interactionId, generation.model)
+ );
+ }
+
+ function inProgressResult(
+ interactionId: string,
+ model: string,
+ ): AssetGenerationProviderResult {
+ return {
+ provider: providerID,
+ model,
+ status: "in_progress",
+ providerJobId: interactionId,
+ providerGenerationId: interactionId,
+ providerPollingUrl: interactionId,
+ outputs: [],
+ metadata: { provider: providerID, api: "interactions", interactionId },
+ };
+ }
+
+ function failedResult(model: string, message: string): AssetGenerationProviderResult {
+ return {
+ provider: providerID,
+ model,
+ status: "failed",
+ outputs: [],
+ error: { message },
+ metadata: { provider: providerID, api: "interactions" },
+ };
+ }
+
+ // A completed or failed interaction mapped to a provider result; undefined
+ // while it is still running. The clip was billed flat at submit; the token
+ // counts here ride the result as diagnostics, not a charge.
+ function settledResult(
+ interaction: Interaction,
+ generationId: string,
+ model: string,
+ ): AssetGenerationProviderResult | undefined {
+ if (interaction.status === "in_progress" || interaction.status === "requires_action") {
+ return undefined;
+ }
+ const video = interaction.output_video;
+ if (interaction.status !== "completed" || !video || (!video.data && !video.uri)) {
+ return failedResult(
+ model,
+ interactionError(interaction) ?? "Omni returned no video for this request.",
+ );
+ }
+ const mimeType = video.mime_type ?? "video/mp4";
+ const output: GenerationOutputRef = {
+ id: `${generationId}-video-0`,
+ kind: "video",
+ contentType: mimeType,
+ filename: `${generationId}-0.mp4`,
+ metadata: { source: "provider-output" },
+ ...(video.data ? { dataBase64: video.data } : { url: video.uri }),
+ };
+ const usage = interaction.usage;
+ return {
+ provider: providerID,
+ model,
+ status: "completed",
+ outputs: [output],
+ usage: {
+ inputTokens: usage?.total_input_tokens ?? 0,
+ // Thought tokens bill as output; video tokens dominate either way.
+ outputTokens: (usage?.total_output_tokens ?? 0) + (usage?.total_thought_tokens ?? 0),
+ },
+ metadata: { provider: providerID, api: "interactions" },
+ };
+ }
+
+ return {
+ id: providerID,
+ configured,
+ capabilities: ["video"],
+ listModels,
+ generateAsset,
+ refreshAsset,
+ };
+}
+
+type InlineImage = { data: string; mimeType: string };
+
+// The video tools send a seed frame as inputs.images = [{ data, mimeType }]
+// and identity anchors as inputs.referenceImages.
+function firstInlineImage(list: unknown): InlineImage | undefined {
+ return inlineImages(list)[0];
+}
+
+function inlineImages(list: unknown): InlineImage[] {
+ if (!Array.isArray(list)) {
+ return [];
+ }
+ const out: InlineImage[] = [];
+ for (const item of list) {
+ if (!isJsonObject(item)) {
+ continue;
+ }
+ const data = stringValue(item.data);
+ if (!data) {
+ continue;
+ }
+ out.push({ data, mimeType: stringValue(item.mimeType) ?? "image/png" });
+ }
+ return out;
+}
+
+// A failed interaction carries its reason on the last model_output step.
+function interactionError(interaction: Interaction): string | undefined {
+ for (const step of [...(interaction.steps ?? [])].reverse()) {
+ const error = (step as unknown as JsonObject).error;
+ if (isJsonObject(error)) {
+ const message = stringValue(error.message);
+ if (message) {
+ return message;
+ }
+ }
+ }
+ return undefined;
+}
diff --git a/site/src/lib/inference/adapters/gemini-video.ts b/site/src/lib/inference/adapters/gemini-video.ts
deleted file mode 100644
index 956ca2b1..00000000
--- a/site/src/lib/inference/adapters/gemini-video.ts
+++ /dev/null
@@ -1,438 +0,0 @@
-import {
- GenerateVideosOperation,
- GoogleGenAI,
- VideoGenerationReferenceType,
-} from "@google/genai";
-import type {
- GenerateVideosConfig,
- GenerateVideosParameters,
- GoogleGenAIOptions,
-} from "@google/genai";
-
-import {
- geminiApiError,
- geminiClientConfig,
- stringValue,
- type AdapterEnvironment,
-} from "@/lib/inference/adapters/gemini-client";
-import { providerCreditPricing } from "@/lib/credits/provider-pricing";
-import { veoMaxReferenceImages, veoModels, veoTierModels } from "@/lib/inference/gemini-models";
-import { ensureConfigured } from "@/lib/inference/http";
-import { isJsonObject, toJsonObject, toJsonValue } from "@/lib/inference/json";
-import {
- InferenceProviderError,
- type AssetGenerationProviderRequest,
- type AssetGenerationProviderResult,
- type GenerationOutputRef,
- type InferenceModality,
- type InferenceModel,
- type InferenceProvider,
- type JsonObject,
- type JsonValue,
- type StoredGenerationForProvider,
-} from "@/lib/inference/providers";
-
-// Generative text/image-to-video provider (Veo). The harness reaches it through the
-// provider-neutral `video.generate` tool and the asset framework with provider unset, so the
-// registry auto-selects this provider for kind="video". Veo is a long-running operation, so unlike
-// the synchronous image adapter this submits a job and the Mac side polls refresh until it lands.
-// A DISTINCT provider id ("veo", not "gemini") keeps that refresh routing from colliding with the
-// image adapter. Adopting a newer Veo is a one-line change in gemini-models.ts, not an app change.
-const providerID = "veo";
-
-// Veo needs both `models` (submit) and `operations` (poll) on the client; the shared GeminiClient
-// type only exposes `models`, so this adapter constructs its own wider client. Injectable for tests.
-export type GeminiVideoClient = Pick<GoogleGenAI, "models" | "operations">;
-export type GeminiVideoClientFactory = (options: GoogleGenAIOptions) => GeminiVideoClient;
-
-const defaultVideoClientFactory: GeminiVideoClientFactory = (options) =>
- new GoogleGenAI(options);
-
-export function createGeminiVideoAssetProvider(
- environment: AdapterEnvironment = process.env,
- clientFactory: GeminiVideoClientFactory = defaultVideoClientFactory,
-): InferenceProvider {
- const clientConfig = geminiClientConfig(environment);
- const configured = clientConfig.configured;
-
- // Model selection lives in code: the speed/quality tier the user picks maps to a hardcoded Veo id
- // (see gemini-models.ts), so video is on by default rather than gated behind an env var. Vertex AI
- // is assumed (see geminiClientConfig).
- async function listModels(
- modalities: InferenceModality[],
- ): Promise<InferenceModel[]> {
- if (!modalities.includes("video")) {
- return [];
- }
- return Object.values(veoModels).map((id) => ({
- id,
- name: id,
- provider: providerID,
- inputModalities: ["text", "image"],
- outputModalities: ["video"],
- contextLength: null,
- pricing: null,
- metadata: { provider: providerID, api: "generateVideos" },
- }));
- }
-
- function resolveModel(requested?: string, tier?: string): string {
- const tierModel =
- veoTierModels[tier?.trim().toLowerCase() as keyof typeof veoTierModels];
- const model = requested?.trim() || tierModel || veoModels.fast;
- // Fail before spending: the resolved model must have a configured price. A hardcoded Veo id
- // always resolves; this only bites if a caller passes an unpriced model override.
- if (!providerCreditPricing(providerID, model)) {
- throw new InferenceProviderError(
- "No credit price is configured for the selected video model.",
- { statusCode: 500, code: "video_model_not_priced", details: { model } },
- );
- }
- return model;
- }
-
- async function generateAsset({
- generationId,
- request,
- }: AssetGenerationProviderRequest): Promise<AssetGenerationProviderResult> {
- ensureConfigured(configured);
-
- if (request.kind !== "video") {
- throw new InferenceProviderError("Provider does not support this asset kind.", {
- statusCode: 400,
- code: "unsupported_asset_kind",
- });
- }
-
- const requestParameters = toJsonObject(request.parameters ?? {});
- const model = resolveModel(request.model, stringValue(requestParameters.tier));
- const prompt = request.prompt?.trim();
- const inputs = toJsonObject(request.inputs ?? {});
- const image = inputImage(inputs);
- const references = referenceImages(inputs);
- if (!prompt && !image) {
- throw new InferenceProviderError(
- "Video generation requires a prompt or an input image.",
- { statusCode: 400, code: "empty_video_request" },
- );
- }
- if (references.length > 0 && image) {
- // Veo takes a first-frame seed or asset references, never both.
- throw new InferenceProviderError(
- "Video generation takes an input image or reference images, not both.",
- { statusCode: 400, code: "conflicting_video_inputs" },
- );
- }
-
- const params: GenerateVideosParameters = {
- model,
- ...(prompt ? { prompt } : {}),
- ...(image
- ? { image: { imageBytes: image.data, mimeType: image.mimeType } }
- : {}),
- config: videoConfig(requestParameters, references, image !== undefined),
- };
-
- const client = clientFactory(clientConfig.options);
- let operation: GenerateVideosOperation;
- try {
- operation = await client.models.generateVideos(params);
- } catch (error) {
- throw geminiApiError("Veo video generation failed.", error);
- }
-
- // Rare fast path: the job may already be complete on submit.
- const completed = completedOutputs(operation, generationId, model);
- if (completed) {
- return completed;
- }
- if (operation.done) {
- // Done on submit but produced no video — surface the provider's reason instead of "pending".
- throw new InferenceProviderError("Veo returned no video for this request.", {
- statusCode: 502,
- code: "empty_video_generation",
- details: { model, error: operationError(operation) ?? null },
- });
- }
-
- const operationName = operation.name?.trim();
- if (!operationName) {
- throw new InferenceProviderError("Veo did not return an operation to poll.", {
- statusCode: 502,
- code: "video_operation_missing",
- details: { model },
- });
- }
-
- // In progress: charge the flat clip price now (generationCount = 1). The assets/refresh route is
- // free, so submit time is the only billable point; hand the operation handle back for the Mac
- // side to poll via refreshAsset.
- return {
- provider: providerID,
- model,
- status: "in_progress",
- providerJobId: operationName,
- providerGenerationId: operationName,
- providerPollingUrl: operationName,
- outputs: [],
- usage: { generationCount: 1 },
- metadata: { provider: providerID, api: "generateVideos", operationName },
- };
- }
-
- async function refreshAsset(
- generation: StoredGenerationForProvider,
- ): Promise<AssetGenerationProviderResult> {
- ensureConfigured(configured);
-
- const operationName =
- generation.providerGenerationId?.trim() ||
- generation.providerJobId?.trim() ||
- stringValue(generation.metadata?.operationName);
- if (!operationName) {
- return failedResult(generation.model, {
- message: "No Veo operation handle to poll.",
- });
- }
-
- const client = clientFactory(clientConfig.options);
- // The SDK polls by calling methods on the operation instance itself, so a plain
- // `{ name }` literal is not enough — construct a real GenerateVideosOperation.
- const operationHandle = new GenerateVideosOperation();
- operationHandle.name = operationName;
- let operation: GenerateVideosOperation;
- try {
- operation = await client.operations.getVideosOperation({
- operation: operationHandle,
- });
- } catch (error) {
- throw geminiApiError("Polling the Veo operation failed.", error);
- }
-
- // No usage on completion — the flat clip price was charged at submit, and assets/refresh is free.
- const completed = completedOutputs(operation, generation.id, generation.model);
- if (completed) {
- return completed;
- }
- if (operation.done) {
- return failedResult(
- generation.model,
- operationError(operation) ?? { message: "Veo returned no video." },
- );
- }
-
- // Still running — echo in_progress (no billable usage) so the Mac side keeps polling.
- return {
- provider: providerID,
- model: generation.model,
- status: "in_progress",
- providerJobId: operationName,
- providerGenerationId: operationName,
- providerPollingUrl: operationName,
- outputs: [],
- metadata: { provider: providerID, api: "generateVideos", operationName },
- };
- }
-
- return {
- id: providerID,
- configured,
- capabilities: ["video"],
- listModels,
- generateAsset,
- refreshAsset,
- };
-}
-
-type InlineImage = { data: string; mimeType: string };
-
-// The video tool sends an optional first-frame image as inputs.images = [{ data, mimeType }] for
-// image-to-video; reuse exactly the shape the image tool sends. Only the first image is used.
-function inputImage(inputs: JsonObject | undefined): InlineImage | undefined {
- const list = inputs?.images;
- if (!Array.isArray(list)) {
- return undefined;
- }
- for (const item of list) {
- if (!isJsonObject(item)) {
- continue;
- }
- const data = stringValue(item.data);
- if (!data) {
- continue;
- }
- return { data, mimeType: stringValue(item.mimeType) ?? "image/png" };
- }
- return undefined;
-}
-
-// Veo 3.1 asset references ("ingredients"): identity anchors — characters, objects, scenes —
-// the render keeps consistent, sent as inputs.referenceImages = [{ data, mimeType }], capped at
-// the registry's veoMaxReferenceImages. Distinct from inputs.images: a reference conditions the
-// whole clip, a seed becomes frame one.
-function referenceImages(inputs: JsonObject | undefined): InlineImage[] {
- const list = inputs?.referenceImages;
- if (!Array.isArray(list)) {
- return [];
- }
- const out: InlineImage[] = [];
- for (const item of list) {
- if (!isJsonObject(item)) {
- continue;
- }
- const data = stringValue(item.data);
- if (!data) {
- continue;
- }
- out.push({ data, mimeType: stringValue(item.mimeType) ?? "image/png" });
- if (out.length === veoMaxReferenceImages) {
- break;
- }
- }
- return out;
-}
-
-// Veo knobs the tool may pass through request.parameters; audio defaults on, one video per call.
-function videoConfig(
- parameters: JsonObject | undefined,
- references: InlineImage[] = [],
- seeded = false,
-): GenerateVideosConfig {
- const config: GenerateVideosConfig = { numberOfVideos: 1, generateAudio: true };
- if (references.length > 0) {
- config.referenceImages = references.map((ref) => ({
- image: { imageBytes: ref.data, mimeType: ref.mimeType },
- referenceType: VideoGenerationReferenceType.ASSET,
- }));
- }
- if (!parameters) {
- return config;
- }
- const aspectRatio = stringValue(parameters.aspectRatio);
- if (aspectRatio) {
- config.aspectRatio = aspectRatio;
- }
- const resolution = stringValue(parameters.resolution);
- if (resolution) {
- config.resolution = resolution;
- }
- const negativePrompt = stringValue(parameters.negativePrompt);
- if (negativePrompt) {
- config.negativePrompt = negativePrompt;
- }
- const durationSeconds = numberValue(parameters.durationSeconds);
- if (durationSeconds !== undefined) {
- config.durationSeconds = durationSeconds;
- }
- const generateAudio = boolValue(parameters.generateAudio);
- if (generateAudio !== undefined) {
- config.generateAudio = generateAudio;
- }
- // Person-safety: unset, Veo blocks person/face generation (fatal for any shot
- // with a character). Callers pass DONT_ALLOW/ALLOW_ADULT/ALLOW_ALL — note Veo
- // caps any render with image inputs (first-frame seed or reference images) at
- // ALLOW_ADULT (no minors); ALLOW_ALL needs text-to-video. Clamp rather than
- // let the request 400: the reference is the caller's point, the ceiling isn't.
- let personGeneration = stringValue(parameters.personGeneration);
- if (personGeneration && (seeded || references.length > 0) && /allow[_-]?all/i.test(personGeneration)) {
- personGeneration = "ALLOW_ADULT";
- }
- if (personGeneration) {
- config.personGeneration = personGeneration as GenerateVideosConfig["personGeneration"];
- }
- return config;
-}
-
-// A completed result from a finished operation that produced video, or undefined when the operation
-// is still running or finished without any video (the caller decides how to surface those).
-function completedOutputs(
- operation: GenerateVideosOperation,
- generationId: string,
- model: string,
-): AssetGenerationProviderResult | undefined {
- if (!operation.done) {
- return undefined;
- }
- const videos = operation.response?.generatedVideos ?? [];
- const outputs: GenerationOutputRef[] = [];
- let index = 0;
- for (const generated of videos) {
- const video = generated.video;
- if (!video) {
- continue;
- }
- const mimeType = video.mimeType ?? "video/mp4";
- const filename = `${generationId}-${index}.${extensionForVideoMime(mimeType)}`;
- // Prefer inline bytes (the reliable path on Vertex with no output bucket); fall back to a URI the
- // Mac side can fetch. A gs:// URI is not directly fetchable, so inline bytes are what we expect.
- if (video.videoBytes) {
- outputs.push({
- id: `${generationId}-video-${index}`,
- kind: "video",
- dataBase64: video.videoBytes,
- contentType: mimeType,
- filename,
- metadata: { source: "provider-output" },
- });
- index += 1;
- } else if (video.uri) {
- outputs.push({
- id: `${generationId}-video-${index}`,
- kind: "video",
- url: video.uri,
- contentType: mimeType,
- filename,
- metadata: { source: "provider-output" },
- });
- index += 1;
- }
- }
- if (outputs.length === 0) {
- return undefined;
- }
- return {
- provider: providerID,
- model,
- status: "completed",
- outputs,
- metadata: { provider: providerID, api: "generateVideos" },
- };
-}
-
-function failedResult(
- model: string,
- error: JsonValue,
-): AssetGenerationProviderResult {
- return {
- provider: providerID,
- model,
- status: "failed",
- outputs: [],
- error,
- metadata: { provider: providerID, api: "generateVideos" },
- };
-}
-
-function operationError(operation: GenerateVideosOperation): JsonValue | undefined {
- return operation.error ? toJsonValue(operation.error) : undefined;
-}
-
-function numberValue(value: JsonValue | undefined): number | undefined {
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
-}
-
-function boolValue(value: JsonValue | undefined): boolean | undefined {
- return typeof value === "boolean" ? value : undefined;
-}
-
-function extensionForVideoMime(mimeType: string): string {
- switch (mimeType.toLowerCase()) {
- case "video/webm":
- return "webm";
- case "video/quicktime":
- case "video/mov":
- return "mov";
- default:
- return "mp4";
- }
-}
diff --git a/site/src/lib/inference/gemini-models.ts b/site/src/lib/inference/gemini-models.ts
index 2c30c7c7..2e44dbe6 100644
--- a/site/src/lib/inference/gemini-models.ts
+++ b/site/src/lib/inference/gemini-models.ts
@@ -21,24 +21,20 @@ export const geminiModels = {
export type GeminiModel = (typeof geminiModels)[keyof typeof geminiModels];
-// Generative text/image-to-video (Veo 3.1). Model selection lives in code, so the
-// ids are hardcoded here rather than gated behind an env var — that keeps the
-// feature on by default instead of silently dormant. Bump here when adopting a
-// newer Veo.
-export const veoModels = {
- // Best quality, slower, priciest per second.
- quality: "veo-3.1-generate-001",
- // Balanced speed/cost; the default when no tier is given.
- fast: "veo-3.1-fast-generate-001",
- // Cheapest and quickest, lower fidelity.
- lite: "veo-3.1-lite-generate-001",
+// Unified video generation (Gemini Omni Flash): one Interactions API call takes
+// text plus optional seed/reference images and renders up to ~10s of 720p video
+// with audio. The clip length is the model's call — there is no duration knob —
+// and image output is not enabled for this model. Bump here when adopting a
+// newer Omni.
+export const geminiOmniModels = {
+ flashVideo: "gemini-omni-flash-preview",
} as const;
-export type VeoModel = (typeof veoModels)[keyof typeof veoModels];
+export type GeminiOmniModel = (typeof geminiOmniModels)[keyof typeof geminiOmniModels];
-// Veo 3.1 asset references ("ingredients"): a render keeps at most this many
-// identity anchors consistent. Bump here when a newer Veo raises it.
-export const veoMaxReferenceImages = 3;
+// The most reference images an Omni render accepts; the adapter clamps and the
+// client registry (videoModels.ts) reads the same number.
+export const geminiOmniMaxReferenceImages = 3;
// 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.
@@ -48,15 +44,6 @@ export const geminiTtsModels = {
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 = {
- lite: veoModels.lite,
- fast: veoModels.fast,
- standard: veoModels.fast,
- high: veoModels.quality,
-} as const;
-
// Semantic roles map a job to the model we run for it. Prefer referencing a
// role over a bare constant so intent stays explicit at the call site.
export const geminiModelRoles = {
@@ -73,4 +60,8 @@ export const geminiModelRoles = {
visionGrounding: geminiModels.flashLite,
// Generative image editing and generation.
imageGeneration: geminiModels.proImage,
+ // Production review: the director judging rendered takes and minted frames
+ // against the plan, sheets, and benchmarks. Runs the strongest multimodal
+ // judge we serve — bump here to upgrade every review gate at once.
+ review: geminiModels.flash,
} as const;
diff --git a/site/src/lib/inference/router.ts b/site/src/lib/inference/router.ts
index 2e6fff58..f93d2179 100644
--- a/site/src/lib/inference/router.ts
+++ b/site/src/lib/inference/router.ts
@@ -2,7 +2,7 @@ import { createAudioAssetProvider } from "@/lib/inference/adapters/audio-studio"
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 { createGeminiOmniVideoAssetProvider } from "@/lib/inference/adapters/gemini-omni-video";
import { createHostedResponsesProvider } from "@/lib/inference/adapters/hosted-responses";
import {
InferenceProviderError,
@@ -219,9 +219,10 @@ export function createProviderRegistry() {
// provider serves kind="image" (gemini-computer-use lists "image" as an input modality
// but has no generateAsset, so it is never chosen for asset generation).
createGeminiImageAssetProvider(),
- // Veo serves kind="video"; its distinct provider id keeps async refresh routing from
- // colliding with the synchronous image adapter.
- createGeminiVideoAssetProvider(),
+ // Omni (Gemini Omni Flash) serves kind="video"; its distinct provider id
+ // keeps async refresh routing from colliding with the synchronous image
+ // adapter.
+ createGeminiOmniVideoAssetProvider(),
// Gemini TTS serves kind="speech" (voiceovers, subtitle read-alouds).
createGeminiSpeechAssetProvider(),
// ElevenLabs serves kind="music" (the brief-to-video music bed). It gates