Open source CapCut alternative.
TypeScript
feat(site): scene render quality gates — identity ladder, take review, failed-run retry [rebuild]
David Lefd4374808458
diff --git a/site/scripts/eval-scene-live.ts b/site/scripts/eval-scene-live.tsnew file mode 100644index 00000000..f5e8dcce--- /dev/null+++ b/site/scripts/eval-scene-live.ts@@ -0,0 +1,270 @@+/**+ * Live scene eval: drive the REAL brief-to-video pipeline in a real (headless)+ * Chrome against the dev server, and wait for every shot to settle. This is+ * the harness for judging actual output quality — real video renders, real+ * keyframes, the real director — where the fake-model self-test proves only+ * the policy mechanics.+ *+ * Auth rides the dev-only bypass header on every page request, so the run+ * needs no session cookie (dev server only; the bypass user must exist in the+ * local DB). The page exposes its stores via window.__cutDev (devHooks.ts).+ *+ * node_modules/.bin/tsx scripts/eval-scene-live.ts --project <id> [--action retry]+ *+ * Actions:+ * retry (default) — click-equivalent of the scene card's "Retry N shots"+ * status — print the run's shot states and exit+ * watch — open the editor (an interrupted run re-adopts its+ * in-flight jobs on load) and wait until every shot settles+ */++import { chromium } from "playwright";+import { readFileSync } from "node:fs";+import path from "node:path";++/** Payload for importing a local file into the page's project. */+function filePayload(p: string): { name: string; mime: string; b64: string } {+ const ext = path.extname(p).toLowerCase();+ const mime =+ ext === ".png" ? "image/png"+ : ext === ".jpg" || ext === ".jpeg" ? "image/jpeg"+ : ext === ".webp" ? "image/webp"+ : ext === ".wav" ? "audio/wav"+ : ext === ".mp3" ? "audio/mpeg"+ : ext === ".m4a" ? "audio/mp4"+ : "application/octet-stream";+ return { name: path.basename(p), mime, b64: readFileSync(p).toString("base64") };+}++const args = process.argv.slice(2);+const arg = (name: string) => {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+};+let PROJECT = arg("--project");+const ACTION = arg("--action") ?? "retry";+const BASE = arg("--base") ?? "http://localhost:3000";+const TIMEOUT_MIN = Number(arg("--timeout") ?? 40);+if (!PROJECT && ACTION !== "fresh") {+ console.error("--project <id> is required (except --action fresh)");+ process.exit(1);+}++const projectFile = () => path.join(process.cwd(), "projects", PROJECT!, "project.json");+type ShotRow = { id: string; status: string; attempts?: number; error?: string; clip?: string; startKeyframe?: string };+function shotsOnDisk(): { phase: string; shots: ShotRow[] } {+ const doc = JSON.parse(readFileSync(projectFile(), "utf8"));+ const g = doc.genvideo ?? {};+ return { phase: g.phase ?? "?", shots: (g.shots ?? []) as ShotRow[] };+}+function printShots(tag: string): void {+ const { phase, shots } = shotsOnDisk();+ console.log(`[${tag}] phase=${phase}`);+ for (const s of shots) {+ console.log(+ ` ${s.id}: ${s.status} att=${s.attempts ?? 0} clip=${s.clip ?? "-"} ${s.error ? `err=${s.error.slice(0, 90)}` : ""}`+ );+ }+}++async function main(): Promise<void> {+ const browser = await chromium.launch({ channel: "chrome", headless: true });+ const context = await browser.newContext({+ extraHTTPHeaders: { "x-donkey-dev-auth-bypass": "1" },+ viewport: { width: 1440, height: 900 },+ });+ const page = await context.newPage();+ page.on("console", (m) => {+ if (m.type() === "error") console.log(`[console.error] ${m.text().slice(0, 200)}`);+ });+ page.on("pageerror", (e) => console.log(`[pageerror] ${String(e).slice(0, 200)}`));++ if (ACTION === "fresh") {+ const name = arg("--name") ?? `eval ${new Date().toISOString().slice(0, 16)}`;+ const res = await fetch(`${BASE}/api/cut/projects`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name }),+ });+ if (!res.ok) throw new Error(`create project failed: ${res.status}`);+ PROJECT = ((await res.json()) as { id: string }).id;+ console.log(`[fresh] created project ${PROJECT} ("${name}")`);+ }++ console.log(`[open] ${BASE}/cut/p/${PROJECT}`);+ await page.goto(`${BASE}/cut/p/${PROJECT}`, { waitUntil: "domcontentloaded", timeout: 120_000 });+ await page.waitForFunction(+ () => {+ const dev = (window as unknown as { __cutDev?: { useEditor: { getState(): { loaded: boolean } } } }).__cutDev;+ return !!dev && dev.useEditor.getState().loaded;+ },+ undefined,+ { timeout: 120_000 }+ );+ console.log("[ready] editor loaded, dev hooks installed");++ if (ACTION === "status") {+ printShots("status");+ await browser.close();+ return;+ }++ if (ACTION === "retry") {+ const res = await page.evaluate(() => {+ const dev = (window as unknown as { __cutDev: { useGenScene: { getState(): { retryFailedShots(): { ok: boolean; message: string } } } } }).__cutDev;+ return dev.useGenScene.getState().retryFailedShots();+ });+ console.log(`[retry] ok=${res.ok} — ${res.message}`);+ if (!res.ok) {+ await browser.close();+ process.exit(2);+ }+ }++ if (ACTION === "fresh") {+ const audioPath = arg("--audio");+ const refPath = arg("--ref");+ const brief = arg("--brief") ?? "";+ const lang = arg("--lang");+ if (!audioPath || !refPath) throw new Error("--audio and --ref are required for fresh");++ // Import the audio spine and the style reference exactly as a user drop+ // would: through importFileToProject, registered on the open editor.+ const importOne = async (payload: { name: string; mime: string; b64: string }, language?: string) => {+ const assetId = await page.evaluate(+ async ({ file, language, projectId }) => {+ const dev = (window as unknown as {+ __cutDev: {+ importFileToProject(id: string, f: File): Promise<{ id: string } | null>;+ enrichAsset(a: unknown): Promise<void>;+ useEditor: { getState(): { addAsset(a: unknown): void; updateAsset(id: string, patch: unknown): void } };+ };+ }).__cutDev;+ const bytes = Uint8Array.from(atob(file.b64), (c) => c.charCodeAt(0));+ const f = new File([bytes], file.name, { type: file.mime });+ const asset = await dev.importFileToProject(projectId, f);+ if (!asset) return null;+ dev.useEditor.getState().addAsset(asset);+ if (language) dev.useEditor.getState().updateAsset(asset.id, { language });+ await dev.enrichAsset(asset);+ return asset.id;+ },+ { file: payload, language: language ?? null, projectId: PROJECT! }+ );+ if (!assetId) throw new Error(`import failed for ${payload.name}`);+ return assetId as string;+ };+ const audioId = await importOne(filePayload(audioPath), lang ?? undefined);+ const refId = await importOne(filePayload(refPath));+ console.log(`[fresh] imported audio=${audioId} ref=${refId}`);++ const started = await page.evaluate(+ async ({ projectId, brief, audioId, refId }) => {+ const dev = (window as unknown as {+ __cutDev: {+ useEditor: { getState(): { setAspect(a: string): void } };+ useGenScene: {+ getState(): {+ start(+ id: string,+ params: Record<string, unknown>+ ): Promise<{ started: boolean; shotCount?: number; message: string }>;+ };+ };+ };+ }).__cutDev;+ dev.useEditor.getState().setAspect("9:16");+ return dev.useGenScene.getState().start(projectId, {+ ...(brief ? { brief } : {}),+ fromAudioAssetId: audioId,+ aspect: "9:16",+ referenceAssetIds: [refId],+ });+ },+ { projectId: PROJECT!, brief, audioId, refId }+ );+ console.log(`[fresh] planned: started=${started.started} shots=${started.shotCount ?? "?"} — ${started.message}`);+ if (!started.started) {+ await browser.close();+ process.exit(2);+ }+ const approved = await page.evaluate(() => {+ const dev = (window as unknown as { __cutDev: { useGenScene: { getState(): { approve(): { ok: boolean; message: string } } } } }).__cutDev;+ return dev.useGenScene.getState().approve();+ });+ console.log(`[fresh] approve: ok=${approved.ok} — ${approved.message}`);+ if (!approved.ok) {+ await browser.close();+ process.exit(2);+ }+ }++ // Poll until every shot settles and no render job is still in flight — the+ // pipeline runs in this page, so the page must stay open throughout.+ const waitSettled = async (deadline: number): Promise<void> => {+ let lastLine = "";+ for (;;) {+ if (Date.now() > deadline) {+ printShots("timeout");+ await browser.close();+ process.exit(3);+ }+ await new Promise((r) => setTimeout(r, 10_000));+ const live = await page.evaluate(() => {+ const dev = (window as unknown as {+ __cutDev: {+ useGenerate: { getState(): { jobs: { status: string }[] } };+ useGenScene: { getState(): { run: { status: string } | null } };+ };+ }).__cutDev;+ const jobs = dev.useGenerate.getState().jobs.filter((j) => j.status === "running").length;+ const run = dev.useGenScene.getState().run;+ return { jobs, runStatus: run?.status ?? "none" };+ });+ const { shots } = shotsOnDisk();+ const settled = shots.every((s) => s.status === "placed" || s.status === "failed");+ const line = `run=${live.runStatus} jobs=${live.jobs} shots=[${shots.map((s) => s.status).join(",")}]`;+ if (line !== lastLine) {+ console.log(`[poll] ${line}`);+ lastLine = line;+ }+ if (live.runStatus !== "generating" && live.jobs === 0 && settled) return;+ }+ };+ const deadline = Date.now() + TIMEOUT_MIN * 60_000;++ if (ACTION === "redo") {+ // Sequential per-shot redos (1-based numbers) — each waits for the run to+ // settle before the next starts, since only a done run accepts a redo.+ const ns = String(arg("--shots") ?? "")+ .split(",")+ .map((v) => Number(v.trim()))+ .filter((v) => Number.isFinite(v) && v > 0);+ if (ns.length === 0) throw new Error("--shots 1,2,… required for redo");+ const note = arg("--note");+ for (const n of ns) {+ const res = await page.evaluate(({ num, note }) => {+ const dev = (window as unknown as { __cutDev: { useGenScene: { getState(): { regenerateShot(n: number, note?: string): { ok: boolean; message: string } } } } }).__cutDev;+ return dev.useGenScene.getState().regenerateShot(num, note || undefined);+ }, { num: n, note: note ?? null });+ console.log(`[redo shot ${n}] ok=${res.ok} — ${res.message}`);+ if (!res.ok) {+ await browser.close();+ process.exit(2);+ }+ await waitSettled(deadline);+ printShots(`after shot ${n}`);+ }+ await browser.close();+ return;+ }++ await waitSettled(deadline);+ printShots("done");+ await browser.close();+}++main().catch((e) => {+ console.error(e);+ process.exit(1);+});diff --git a/site/scripts/genvideo-selftest.ts b/site/scripts/genvideo-selftest.tsindex 9c9d14ca..a1da34f0 100644--- a/site/scripts/genvideo-selftest.ts+++ b/site/scripts/genvideo-selftest.ts@@ -6,13 +6,16 @@* node_modules/.bin/bun run scripts/genvideo-selftest.ts*/+import type { AssetRef } from "../src/cut/lib/assetRef";import { assertCoverage, MAX_SHOT_SEC, MIN_SHOT_SEC, repairCoverage } from "../src/cut/lib/genvideo/coverage";import { FakeEditor, type PlacedClip } from "../src/cut/lib/genvideo/editor";import { fillSlot } from "../src/cut/lib/genvideo/fillSlot";import { fakeSuite, type FakeStudioOptions } from "../src/cut/lib/genvideo/fakes";import { fakeRegistry } from "../src/cut/lib/genvideo/registry";-import { VideoOrchestrator, type OrchestratorDeps } from "../src/cut/lib/genvideo/orchestrator";-import type { VideoEvent, VideoProject } from "../src/cut/lib/genvideo/types";+import { VIDEO_ATTEMPTS, VideoOrchestrator, type OrchestratorDeps } from "../src/cut/lib/genvideo/orchestrator";+import { anchorRefused, buildShotAttempts } from "../src/cut/lib/genvideo/shotAttempts";+import type { RefAsset, VideoEvent, VideoProject } from "../src/cut/lib/genvideo/types";+import { walkLadder } from "../src/cut/lib/videoLadder";let failures = 0;function check(name: string, cond: boolean, detail = ""): void {@@ -189,6 +192,206 @@ async function run(): Promise<void> {check("all shots placed clean", project.shots.every((s) => s.status === "placed"));}+ // ── identity policy: a moving stranger never places ──────────────────────+ // One 6s shot so verdict order is deterministic (fanOut runs shots+ // concurrently; a multi-shot project interleaves who consumes which verdict).+ const singleShot = () =>+ baseProject({ audioMode: "provided", audioClipId: "audio-clip", audioAssetId: "audio-asset", durationFrames: 6 * FPS });+ section("identity gate — a moving stranger never places");+ {+ // An identity break keeps the seed: the keyframe was gated on-model, so+ // re-animating it is the fix — the retake must ride the SAME keyframe.+ const editor = editorWithAudio(6 * FPS);+ const { d, studio } = deps(editor, {+ audioNative: true,+ reviewVerdicts: [+ { ok: false, offModel: true, note: "a different design than the sheet" },+ { ok: true },+ ],+ });+ const project = singleShot();+ const orch = new VideoOrchestrator(project, d);+ await orch.run();+ await orch.approveBreakdown();+ const takes = studio.calls.filter((c) => c.role === "video");+ check("one shot, two takes", project.shots.length === 1 && takes.length === 2, `${project.shots.length} shots, ${takes.length} takes`);+ check("the identity retake rides the same on-model seed", !!takes[0]?.keyframe && takes[0].keyframe === takes[1]?.keyframe);+ check("the passing retake placed as video", project.shots[0].status === "placed" && (project.shots[0].clip ?? "").startsWith("fake:video"));+ }+ {+ // Identity break on every attempt → the on-model keyframe still places;+ // the off-model video never does.+ const editor = editorWithAudio(6 * FPS);+ const { d, studio } = deps(editor, {+ audioNative: true,+ reviewVerdicts: Array.from({ length: VIDEO_ATTEMPTS }, () => ({ ok: false, offModel: true, note: "a different design" })),+ });+ const project = singleShot();+ const orch = new VideoOrchestrator(project, d);+ await orch.run();+ await orch.approveBreakdown();+ const shot = project.shots[0];+ const takes = studio.calls.filter((c) => c.role === "video");+ check("all attempts spent, all from the kept seed", takes.length === VIDEO_ATTEMPTS && takes.every((t) => !!t.keyframe && t.keyframe === takes[0].keyframe), `${takes.length} takes`);+ check("no off-model take placed", shot.status === "failed");+ check("the shot holds its on-model keyframe still", !!shot.startKeyframe && shot.clip === shot.startKeyframe && !!shot.timelineClipId);+ assertTiling("the still fills the slot", editor.placed, project.durationFrames);+ }+ {+ // Contrast: a non-identity flaw on the final take still places — motion+ // beats a frozen still when the character is right.+ const editor = editorWithAudio(6 * FPS);+ const { d, studio } = deps(editor, {+ audioNative: true,+ reviewVerdicts: Array.from({ length: VIDEO_ATTEMPTS }, () => ({ ok: false, note: "the action is weak" })),+ });+ const project = singleShot();+ const orch = new VideoOrchestrator(project, d);+ await orch.run();+ await orch.approveBreakdown();+ check("a weak-but-on-model final take places", project.shots[0].status === "placed" && (project.shots[0].clip ?? "").startsWith("fake:video"));+ check("all attempts were spent first", studio.calls.filter((c) => c.role === "video").length === VIDEO_ATTEMPTS);+ }++ // ── seed policy: re-mint on seed flaws, never render anchor-less ─────────+ section("seed policy — re-mint on seed flaws, restore when the mint fails");+ {+ // A seed-flaw decline mints a FRESH seed for the retake.+ const editor = editorWithAudio(6 * FPS);+ const { d, studio } = deps(editor, {+ audioNative: true,+ reviewVerdicts: [{ ok: false, note: "compose the scene upright" }, { ok: true }],+ });+ const project = singleShot();+ const orch = new VideoOrchestrator(project, d);+ await orch.run();+ await orch.approveBreakdown();+ const takes = studio.calls.filter((c) => c.role === "video");+ check("a seed-flaw retake rides a fresh seed", takes.length === 2 && !!takes[0].keyframe && !!takes[1].keyframe && takes[0].keyframe !== takes[1].keyframe);+ check("the retake placed", project.shots[0].status === "placed");+ }+ {+ // The prior seed is released only once its replacement exists: when the+ // re-mint fails (its prompt carries the critique, which is the failing+ // marker here), the retake rides the ORIGINAL keyframe — never anchor-less.+ const editor = editorWithAudio(6 * FPS);+ const { d, studio } = deps(editor, {+ audioNative: true,+ failImageMarker: "compose the scene upright",+ reviewVerdicts: [{ ok: false, note: "compose the scene upright" }, { ok: true }],+ });+ const project = singleShot();+ const orch = new VideoOrchestrator(project, d);+ await orch.run();+ await orch.approveBreakdown();+ const takes = studio.calls.filter((c) => c.role === "video");+ check("a failed re-mint restores the prior seed", takes.length === 2 && !!takes[0].keyframe && takes[0].keyframe === takes[1].keyframe);+ check("the retake placed from the restored seed", project.shots[0].status === "placed");+ }+ {+ // A refused anchor changes the identity-break policy: the stranger came+ // from WORDS (the provider blocked the seed), so re-submitting the same+ // seed re-blocks forever — the retake must mint a FRESH seed to re-roll+ // the refusal.+ const editor = editorWithAudio(6 * FPS);+ const { d, studio } = deps(editor, {+ audioNative: true,+ anchorsRefused: true,+ reviewVerdicts: [{ ok: false, offModel: true, note: "a stranger drawn from words" }, { ok: true }],+ });+ const project = singleShot();+ const orch = new VideoOrchestrator(project, d);+ await orch.run();+ await orch.approveBreakdown();+ const takes = studio.calls.filter((c) => c.role === "video");+ check("an unanchored identity break re-rolls with a fresh seed", takes.length === 2 && !!takes[0].keyframe && !!takes[1].keyframe && takes[0].keyframe !== takes[1].keyframe);+ check("the re-rolled retake placed", project.shots[0].status === "placed");+ }+ {+ // Two unanchored off-model misses mean the provider is refusing this+ // shot's seeds outright — the third re-mint must RESTAGE the seed (face+ // away from camera) instead of rolling the same composition again.+ const editor = editorWithAudio(6 * FPS);+ const { d, studio } = deps(editor, {+ audioNative: true,+ anchorsRefused: true,+ reviewVerdicts: [+ { ok: false, offModel: true, note: "a stranger" },+ { ok: false, offModel: true, note: "a stranger again" },+ { ok: true },+ ],+ });+ const project = singleShot();+ const orch = new VideoOrchestrator(project, d);+ await orch.run();+ await orch.approveBreakdown();+ const mints = studio.calls.filter((c) => c.role === "image" && c.prompt);+ check(+ "repeated refused anchors restage the seed",+ mints.some((c) => (c.prompt ?? "").includes("Restage the composition")),+ `${mints.length} mints`+ );+ check("the restaged retake placed", project.shots[0].status === "placed");+ }++ // ── the shot ladder: rung policy is data, the text rung is policy-gated ──+ section("shot ladder — the text rung opens only when the provider refuses the anchor");+ {+ const kf: AssetRef = { scope: "project", id: "kf1", name: "keyframe", kind: "image", url: "file:kf1" };+ const sheet: AssetRef = { scope: "project", id: "sheet1", name: "Mason sheet", kind: "image", url: "file:sheet1" };+ const castRefs: RefAsset[] = [+ { mediaId: "sheet1", kind: "image", purpose: "character", name: "Mason", description: "an 8-year-old boy" },+ ];+ const base = { aspect: "9:16" as const };+ const full = buildShotAttempts({+ prompt: "Mason waves.", refs: castRefs, base,+ keyframe: kf, anchors: [sheet], ridingIds: new Set(["sheet1"]),+ });+ check("three rungs, strongest first", full.length === 3 && !!full[0].opts?.refs && !!full[1].opts?.referenceImages && !full[2].opts?.refs && !full[2].opts?.referenceImages);+ check("the seed rides raw (no compose rewrite)", full[0].opts?.composeRefs === false);+ check("every rung keeps the shared base", full.every((r) => r.opts?.aspect === "9:16"));+ const gate = full[2].gate;+ check("cast text rung is gated", typeof gate === "function");+ check("the gate stays closed with no failure and on ordinary failures",+ gate?.(null) === false && gate?.("The video render is taking too long — try again.") === false && gate?.("fake video failed") === false);+ check("a person-policy refusal opens the gate",+ gate?.("The input image contains content that has been blocked by your current safety settings for person/face generation. Support codes: 17301594") === true);+ check("a format refusal opens the gate", gate?.("Unsupported image format. Expected JPEG or PNG.") === true);+ check("a filtered (empty) render opens the gate", gate?.("Omni returned no video for this request.") === true);+ const castless = buildShotAttempts({+ prompt: "an aquarium bubbles.", refs: [{ mediaId: "loc1", kind: "image", purpose: "location", name: "living room" }],+ base, keyframe: kf, anchors: [], ridingIds: new Set(),+ });+ check("a castless shot keeps an ungated text rung", castless[castless.length - 1].gate === undefined);+ const anchorless = buildShotAttempts({+ prompt: "Mason waves.", refs: castRefs, base, anchors: [], ridingIds: new Set(),+ });+ check("a cast shot with no image anchor keeps the text floor", anchorless.length === 1 && anchorless[0].gate === undefined);+ }++ // ── the ladder walk: gates and fatal stops ────────────────────────────────+ section("ladder walk — gated rungs run only on the failures they're for");+ {+ const runRungs = async (throwWith: string, gated = true) => {+ const ran: number[] = [];+ const out = await walkLadder(+ [{ prompt: "seed" }, { prompt: "text", ...(gated ? { gate: anchorRefused } : {}) }],+ async (_a, rung) => {+ ran.push(rung);+ if (rung === 0) throw new Error(throwWith);+ },+ { fatal: (e) => e === "No credits left" }+ );+ return { ran, out };+ };+ const refused = await runRungs("The input image contains content that has been blocked for person/face generation. 17301594");+ check("an anchor refusal unlocks the gated rung", refused.out.ok && refused.ran.join(",") === "0,1");+ const ordinary = await runRungs("a transient render error");+ check("an ordinary failure keeps the gated rung closed (error surfaces)", !ordinary.out.ok && ordinary.ran.join(",") === "0" && ordinary.out.error === "a transient render error");+ const broke = await runRungs("No credits left", false);+ check("a fatal failure stops the walk before ungated rungs", !broke.out.ok && broke.ran.join(",") === "0" && broke.out.error === "No credits left");+ }+// ── Entry 2: brief only → script, voice, music, video ────────────────────section('brief only → "a video of me and my son", audio-native video');{@@ -229,19 +432,24 @@ async function run(): Promise<void> {assertTiling("split-beat shots still tile", editor.placed, project.durationFrames);}- // ── findings 8, 9: style failures degrade instead of dropping anchors ────- section("style-bible failure degrades gracefully (findings 8, 9)");+ // ── the bible is the run's spine: a failed design fails the run loudly ───+ // (a stand-in look would silently corrupt every render downstream)+ section("style-bible failure fails the run loudly (finding 8, revised)");{const editor = emptyEditor();const { d } = deps(editor, { audioNative: true, failStyle: true });const project = generatedProject();const orch = new VideoOrchestrator(project, d);await orch.run();- await orch.approveBreakdown();- check("style failure still yields a character bible", project.characters.length > 0);- check("reference image minted from the default bible", project.characters.every((c) => !!c.mediaId));- check("run still completes and tiles", project.phase === "done" && tiles(editor, project.durationFrames));+ let error = "";+ await orch.approveBreakdown().catch((e: unknown) => {+ error = String(e);+ });+ check("a failed style design rejects the run", error.includes("fake style design failed"));+ check("no stand-in bible is installed", project.characters.length === 0);+ check("nothing rendered under a missing bible", project.shots.every((s) => s.status !== "placed"));}+ section("reference-sheet failure degrades gracefully (finding 9)");{const editor = emptyEditor();// Fail only the character reference sheet (its prompt carries the description).diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex b2c22c95..16995304 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -12,6 +12,7 @@ import { enrichAsset, importFileToProject } from "@/cut/lib/media";// Side-effect import: registers the brief-to-video resume subscription, so a// persisted run resumes on project load even when the AI panel never mounts.import "@/cut/lib/genScene";+import { installDevHooks } from "@/cut/lib/devHooks";import { backTarget, useCutBase } from "@/cut/lib/nav";import { projectDuration, serializeDoc, storedAssets, useEditor } from "@/cut/lib/store";import type { MediaAsset } from "@/cut/lib/types";@@ -34,6 +35,7 @@ export function Editor({from?: string | null;folder?: string | null;}) {+ useEffect(() => installDevHooks(), []);const back = backTarget(useCutBase(), from, folder);const loaded = useEditor((s) => s.loaded);const loadError = useEditor((s) => s.loadError);diff --git a/site/src/cut/lib/devHooks.ts b/site/src/cut/lib/devHooks.tsnew file mode 100644index 00000000..7f1c1062--- /dev/null+++ b/site/src/cut/lib/devHooks.ts@@ -0,0 +1,24 @@+"use client";++/**+ * Dev-only automation hooks: expose the Cut stores on window so a real-model+ * eval (a headless browser driving the actual pipeline) can start runs and+ * read progress deterministically instead of scraping the UI. Installed from+ * the editor root; a no-op in production builds.+ */++import { useGenerate } from "./generate";+import { useGenScene } from "./genScene";+import { enrichAsset, importFileToProject } from "./media";+import { useEditor } from "./store";++export function installDevHooks(): void {+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") return;+ (window as unknown as Record<string, unknown>).__cutDev = {+ useEditor,+ useGenerate,+ useGenScene,+ importFileToProject,+ enrichAsset,+ };+}diff --git a/site/src/cut/lib/genvideo/adapters/index.ts b/site/src/cut/lib/genvideo/adapters/index.tsindex f50ed3cb..cece4319 100644--- a/site/src/cut/lib/genvideo/adapters/index.ts+++ b/site/src/cut/lib/genvideo/adapters/index.ts@@ -33,7 +33,7 @@ export function realSuite(projectId: string, chatId?: string): ModelSuite {label: "donkey-hosted",script: makeScriptRole(),breakdown: makeBreakdownRole(),- style: makeStyleRole(),+ style: makeStyleRole(projectId),image: makeImageRole(projectId, chatId),video: makeVideoRole(projectId, chatId),voice: makeVoiceRole(projectId, chatId),diff --git a/site/src/cut/lib/genvideo/adapters/media.ts b/site/src/cut/lib/genvideo/adapters/media.tsindex ac68c09d..92497b2a 100644--- a/site/src/cut/lib/genvideo/adapters/media.ts+++ b/site/src/cut/lib/genvideo/adapters/media.ts@@ -14,28 +14,34 @@* clip is muted, so its audio never competes — rather than asking the model to* suppress audio (a knob many models reject, which just fails the render).* - Cast identity is anchored per shot, strongest signal first (see the ladder- * in makeVideoRole): the shot's keyframe — already rendered with the cast's- * reference images, so it IS the cast — seeds an image-to-video render; if- * that's blocked, the character/location reference images condition a- * reference-to-video render; only as a last resort does a shot fall back to- * text-only, where the cast rides the prompt alone and drifts. The seeded- * and referenced modes run at personGeneration ALLOW_ADULT (the most Veo- * permits with image inputs); text-only runs ALLOW_ALL.- * - Durations come from the video-model registry (videoGen.ts), never a literal- * here — models render only fixed clip lengths, so we ask for a supported one- * and let the editor trim it to the exact shot.+ * in shotAttempts.ts): the shot's keyframe — already rendered with the cast's+ * reference images, so it IS the cast — seeds the render as its literal+ * opening frame; if the anchor is blocked, the character/location reference+ * images condition a reference-to-video render; text-only is the last+ * resort — for a cast shot it runs only when the provider refused the image+ * anchor itself, and its take still faces the reviewer's identity gate+ * before placing. Each rung's prompt folds in the bible descriptions of+ * exactly the cast that doesn't ride that call as an image+ * (describeUnanchored), so the text-only rung renders against the full+ * written identity — the same fixed words every shot — instead of a bare+ * action line.+ * - The model picks each clip's length (up to ~10s) — there is no duration+ * knob — and always covers the shot's slot, so the editor trims the take to+ * the exact shot.*/import { refFromAsset, type AssetRef } from "../../assetRef";import { tagChatAsset } from "../../chatAssets";-import { NO_CREDITS_MESSAGE, useGenerate, videoJobSettlement, type VideoGenOptions } from "../../generate";+import { useGenerate, videoJobSettlement } from "../../generate";import { enrichAsset } from "../../media";import { useEditor } from "../../store";import { DEFAULT_VOICE, synthesizeSpeech } from "../../tts";-import { supportedVideoDuration, videoModel } from "../../videoGen";+import { videoModel } from "../../videoModels";import { reportActivity } from "../activity";import { findRunAsset, stockAssetInDoc } from "../docWriter";+import { buildShotAttempts } from "../shotAttempts";import type { ImageRole, VideoRole, VoiceRole } from "../capabilities";+import { refRoleNote } from "../prompt";import type { RefAsset } from "../types";/** Resolve the pipeline's media-id references to the project assets the@@ -55,7 +61,10 @@ async function refsToAssetRefs(projectId: string, refs: RefAsset[]): Promise<Assexport function makeImageRole(projectId: string, chatId?: string): ImageRole {return {async generate(input) {- const job = await useGenerate.getState().generateImage(projectId, input.prompt, {+ // The refs ride as bare pixels, so the prompt states each one's role —+ // sheets fix the cast, style references contribute technique only.+ const roles = refRoleNote(input.refs);+ const job = await useGenerate.getState().generateImage(projectId, roles ? `${input.prompt} ${roles}` : input.prompt, {refs: await refsToAssetRefs(projectId, input.refs),aspect: input.aspect,// The prompt is already complete (buildPrompt folds in style + setting);@@ -74,30 +83,22 @@ export function makeImageRole(projectId: string, chatId?: string): ImageRole {};}-const VIDEO_TIER = "fast" as const;-export function makeVideoRole(projectId: string, chatId?: string): VideoRole {return {// The model isn't given our narration track, so it never lip-syncs to it.audioNative: false,async generate(input) {- // The identity ladder: every rung renders the same prompt, each with a- // weaker identity anchor, and a shot takes the first rung that lands.- // Veo allows one anchor kind per render (seed OR references), caps both- // at ALLOW_ADULT, and renders reference-conditioned clips at 8s only —- // so the rungs are distinct requests, not one combined one.+ // The identity ladder: each rung renders from a weaker identity anchor,+ // its prompt growing the written identity of whatever no longer rides as+ // an image, and a shot takes the first rung that lands. A render takes+ // one anchor kind per call (seed OR references), so the rungs are+ // distinct requests, not one combined one.// The shot's stable identity, stamped on every job this render starts so// a resumed run re-adopts exactly its own in-flight take.const genKey = input.shotId ? `${projectId}:${input.shotId}` : undefined;const base = {- tier: VIDEO_TIER,aspect: input.aspect,- ...(genKey ? { genKey } : {}),- // Chat ownership rides the job from creation, so a shot never touches- // the Video panel — job row, tile, or badge — even when the render- // errors or lands after the user moved on. Once placed on the timeline- // it's protected from thread-deletion by the clip.- ...(chatId ? { chatId } : {}),+ ...(input.negativePrompt ? { negativePrompt: input.negativePrompt } : {}),};// The seed keyframe resolves wherever the run's project lives — the// store when open, the persisted doc when the user switched away.@@ -106,48 +107,37 @@ export function makeVideoRole(projectId: string, chatId?: string): VideoRole {: undefined;// Identity and place anchors only — a user style reference is a look,// not a cast member, and must never ride as an asset to keep consistent.- const anchors = (- await refsToAssetRefs(- projectId,- input.refs.filter((r) => r.purpose === "character" || r.purpose === "location")- )- ).slice(0, videoModel(VIDEO_TIER).maxReferenceImages);- const attempts: VideoGenOptions[] = [- // 1. The keyframe as the literal first frame. It was rendered from the- // cast's reference images, so it carries identity, wardrobe, setting,- // and framing in one anchor — the strongest continuity Veo offers.- ...(keyframe- ? [{- ...base,- refs: [refFromAsset(keyframe)],- composeRefs: false,- personGeneration: "ALLOW_ADULT" as const,- durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec),- }]- : []),- // 2. Reference-to-video on the cast sheets themselves — identity holds,- // composition is the model's again.- ...(anchors.length > 0- ? [{- ...base,- referenceImages: anchors,- personGeneration: "ALLOW_ADULT" as const,- durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec, {- withReferences: true,- }),- }]- : []),- // 3. Text-only, ALLOW_ALL — always renders, identity rides the prompt.- {- ...base,- personGeneration: "ALLOW_ALL" as const,- durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec),- },- ];+ // The ref↔anchor pairing survives so each rung's prompt can name exactly+ // the cast that does NOT ride that call as an image.+ const identityRefs = input.refs.filter(+ (r) => r.purpose === "character" || r.purpose === "location"+ );+ const resolved: { ref: RefAsset; anchor: AssetRef }[] = [];+ for (const r of identityRefs) {+ const a = await findRunAsset(projectId, r.mediaId);+ if (a) resolved.push({ ref: r, anchor: refFromAsset(a) });+ }+ const riding = resolved.slice(0, videoModel("omni").maxReferenceImages);+ // The rung policy — order, anchor strength, the policy-gated text rung —+ // is pure data built in shotAttempts.ts (locked by the self-test); this+ // role only resolves the assets it rides on.+ const attempts = buildShotAttempts({+ prompt: input.prompt,+ refs: input.refs,+ base,+ keyframe: keyframe ? refFromAsset(keyframe) : undefined,+ anchors: riding.map((p) => p.anchor),+ ridingIds: new Set(riding.map((p) => p.ref.mediaId)),+ });// A reload may have left this exact shot's render in flight — adopt the// resumed job's result instead of billing a second take. The match is// the shot's own identity, never the prompt text: two shots can share a// prompt and each still owns its own take.+ // Whether a landed rung rode pixels — the retake policy needs to know a+ // take held its identity by anchor or by words alone.+ const anchoredRung = (rung?: number) =>+ rung !== undefined &&+ Boolean(attempts[rung]?.opts?.refs || attempts[rung]?.opts?.referenceImages);const inFlight = genKey? useGenerate.getState()@@ -155,25 +145,30 @@ export function makeVideoRole(projectId: string, chatId?: string): VideoRole {: undefined;if (inFlight) {const settledJob = await videoJobSettlement(inFlight.id);- if (settledJob?.status === "done" && settledJob.assetId) return settledJob.assetId;- }- let lastError = "Video generation failed.";- for (const [rung, opts] of attempts.entries()) {- reportActivity(- rung === 0- ? "Animating the frame with Veo — a minute or two…"- : "That anchor failed — retrying the render with a weaker identity anchor…",- projectId- );- const job = await useGenerate.getState().generateVideo(projectId, input.prompt, opts)- .settled;- if (job.status === "done" && job.assetId) return job.assetId;- lastError = job.error || lastError;- // An empty balance fails every rung (and every orchestrator retry)- // identically — stop here so a broke run fails fast, not 9 times.- if (lastError === NO_CREDITS_MESSAGE) break;+ if (settledJob?.status === "done" && settledJob.assetId)+ return { mediaId: settledJob.assetId, anchored: anchoredRung(settledJob.rung) };}- throw new Error(lastError);+ // The ladder walk itself — one job spanning the rungs, next rung on any+ // failure, fail-fast on an empty balance — lives in generateVideoLadder,+ // shared with chat's one-off renders.+ const job = await useGenerate.getState().generateVideoLadder(projectId, attempts, {+ ...(genKey ? { genKey } : {}),+ // Chat ownership rides the job from creation, so a shot never touches+ // the Video panel — job row, tile, or badge — even when the render+ // errors or lands after the user moved on. Once placed on the timeline+ // it's protected from thread-deletion by the clip.+ ...(chatId ? { chatId } : {}),+ onAttempt: (rung) =>+ reportActivity(+ rung === 0+ ? "Animating the frame — a minute or two…"+ : "That take failed — retrying on a fallback renderer…",+ projectId+ ),+ }).settled;+ if (job.status === "done" && job.assetId)+ return { mediaId: job.assetId, anchored: anchoredRung(job.rung) };+ throw new Error(job.error || "Video generation failed.");},};}diff --git a/site/src/cut/lib/genvideo/adapters/refImages.ts b/site/src/cut/lib/genvideo/adapters/refImages.tsnew file mode 100644index 00000000..8c8c250a--- /dev/null+++ b/site/src/cut/lib/genvideo/adapters/refImages.ts@@ -0,0 +1,47 @@+"use client";++/**+ * Reference media as inline image parts for hosted-model calls. Resolution+ * goes through findRunAsset so a background run (its project closed) keeps+ * its references; anything unresolvable is skipped, never fatal — a missing+ * reference degrades the call, it doesn't block it.+ *+ * Mime derivation rides refMedia's byte-sniffing path: the engine's media+ * URLs don't promise an image Content-Type, and Vertex rejects any part+ * labelled application/octet-stream.+ */++import { blobToInline, type InlineImage } from "../../refMedia";+import { findRunAsset } from "../docWriter";+import type { RefAsset } from "../types";++export type InlineImagePart = InlineImage;++/** One image URL's bytes as a base64 part, null on any failure. */+export async function imagePart(url: string): Promise<InlineImagePart | null> {+ try {+ const res = await fetch(url);+ if (!res.ok) return null;+ return await blobToInline(await res.blob());+ } catch {+ return null;+ }+}++/** Resolve image references to inline parts, capped, order preserved. */+export async function refImageParts(+ projectId: string,+ refs: RefAsset[],+ max = 4+): Promise<InlineImagePart[]> {+ const out: InlineImagePart[] = [];+ for (const r of refs) {+ if (out.length >= max) break;+ if (r.kind !== "image") continue;+ const asset = await findRunAsset(projectId, r.mediaId);+ if (!asset) continue;+ const part = await imagePart(asset.url);+ if (part) out.push(part);+ }+ return out;+}diff --git a/site/src/cut/lib/genvideo/adapters/review.ts b/site/src/cut/lib/genvideo/adapters/review.tsindex f48e6de1..c89cd02b 100644--- a/site/src/cut/lib/genvideo/adapters/review.ts+++ b/site/src/cut/lib/genvideo/adapters/review.ts@@ -16,21 +16,38 @@ import { geminiModelRoles } from "@/lib/inference/gemini-models";import { hostedPost } from "../../hosted";import { captureVideoFrames } from "../../visualFrames";import { findRunAsset } from "../docWriter";-import type { ReviewInput, ReviewRole, ReviewVerdict } from "../capabilities";+import { imagePart } from "./refImages";+import type { FrameCheckInput, ReviewInput, ReviewRole, ReviewVerdict } from "../capabilities";const MAX_FRAMES = 8;/** Aim for one frame every ~1s of take. */const SECONDS_PER_FRAME = 1;const REVIEW_INSTRUCTIONS = `You are a film editor reviewing one rendered take against its shot plan.-Reply with JSON only: {"ok": boolean, "note": string, "fromSec": number}+Reply with JSON only: {"ok": boolean, "note": string, "offModel": boolean, "medium": string, "frameMedium": string, "fromSec": number}+- medium classifies the TAKE's rendering medium from its frames alone: "hand-drawn-2d" (ink or drawn outlines, flat or cel shading, painted texture), "3d-cgi" (specular highlights, smooth volumetric shading, ambient occlusion, plastic-like surfaces, camera depth of field), "live-action", "stop-motion", or "other". frameMedium is the same classification for the approved opening frame ("" when none is shown). Classify each independently from what you SEE.Rules:-- ok is whether the take shows the planned action and its subject. Judge content — the right person doing the right thing in the right place — and forgive style and small details.+- ok is whether the take shows the planned action and its subject. Judge content — the right person doing the right thing in the right place — and forgive small details.+- When a cast member's design sheet is shown, the take's character must read as that exact design: the same face shape, eye style, hair silhouette, and body proportions — and the sheet's outfit, except attire the planned action itself changes (a uniform, swimwear, a costume): then the new clothes are the plan's and only the character must match. A character who reads as a DIFFERENT design — rounder or sharper features, different hair, a redesigned face — is an automatic fail even if the clothing colors match: set offModel true and name the drift ("the boy is a round-faced toddler design, not the sheet's spiky-haired 8-year-old").+- Judge the MEDIUM strictly against the plan's look: a take in the wrong medium — live-action or photorealistic footage when the look is animated or illustrated, or the reverse — is an automatic fail with offModel true; note it as direction for the retake ("render as hand-drawn 2D animation, not live-action"). 3D CGI when the look is hand-drawn 2D is the wrong medium.+- When the shot's approved opening frame is shown, the take must also match its rendering technique — lineweight, shading, palette, texture. A take whose technique visibly differs from that frame is an automatic fail with offModel true; name the difference as retake direction ("match the opening frame's flat pastel rendering, not cel-shaded anime"). Within the right medium and technique, forgive stylistic detail. offModel is true ONLY for these wrong-world flaws — a wrong character design, medium, or technique; it is false for every other flaw (weak action, on-screen text, framing, editing artifacts).- Any rendered text is an automatic fail: captions, subtitles, speech bubbles, titles, watermarks, or readable signs — note it as "remove every trace of on-screen text". A split screen, stacked panels, or a storyboard collage is also an automatic fail: the take must be one single continuous shot.-- Baked-in editing effects are an automatic fail: transition frames, fades to black or white, motion-blur smears, borders, or blurred letterbox bands — the picture must fill the frame edge to edge; the editor adds transitions later.+- Baked-in editing effects are an automatic fail: transition frames, fades to black or white, motion-blur smears, borders, black bars boxing the picture (letterboxing or pillarboxing), or blurred letterbox bands — the picture must fill the frame edge to edge; the editor adds transitions later.+- A sideways take is an automatic fail: the composition must be upright for its frame — level horizon, people and gravity pointing down. A scene rendered rotated 90° to fit (walls or a pool running vertically, a subject lying sideways) fails; note it as "compose the scene upright for the vertical frame".- note, when ok is false, is one short sentence naming what is wrong, written as direction for the retake ("the boy is reading, the plan wants him swimming").- fromSec is where the needed window should start inside the take so its best moment lands in the window; 0 when the opening works. Stay within the take.`;+const IDENTITY_INSTRUCTIONS = `You compare character designs for a production.+Reply with JSON only: {"sameDesign": boolean, "drift": string}+The first image is the canonical design sheet. The frames after it show a character in a rendered shot — possibly at a distance, in motion, or seen from behind. Judge STRUCTURE, not rendering detail: head and hair silhouette, face shape and eye style when visible, body proportions, and the outfit with its exact colors — except attire the stated shot plan changes (a uniform, swimwear, a costume): that outfit is the plan's, not drift, so judge everything but the clothes. Distance or motion blur losing fine detail is fine; a DIFFERENT design is not — a rounder or simplified head, different hair silhouette, or a redesigned face means sameDesign false, as does a changed outfit the plan did not call for. Seen only from behind or far away, judge silhouette (and outfit, when the plan keeps it) — and silhouette includes head shape: a round or bean-shaped head where the sheet has an angular or spiky-haired one is a DIFFERENT design at any distance. drift, when false, is one short retake direction naming the difference ("a bean-headed chibi with dot eyes — match the sheet's spiky-haired detailed anime boy").`;++const FRAME_INSTRUCTIONS = `You are a production's art director signing off one drawn frame against the production's benchmark sheet.+Reply with JSON only: {"ok": boolean, "note": string}+Rules:+- The frame must look drawn by the same artist as the benchmark: the same medium, line weight, shading system, finish, and palette. A recurring garment or prop keeps its exact color — a shirt that reads as a different yellow than the benchmark's fails — except attire the frame's stated subject changes (a uniform, swimwear, a costume): then the new clothes are correct and only the artist's technique must match. Judge the rendering, not the composition: a different subject, pose, camera, or setting is expected and fine.+- Any split screen, stacked panels, storyboard collage, visible seam between two pictures, on-screen text, letterboxing or black bars, or sideways composition is an automatic fail.+- note, when ok is false, is one short retake direction naming the difference ("thicker outlines and a warmer, deeper yellow tee — match the benchmark's flat pastel shading").`;+function frameTimes(clipSec: number): number[] {const count = Math.min(MAX_FRAMES, Math.max(3, Math.round(clipSec / SECONDS_PER_FRAME)));return Array.from({ length: count }, (_, i) => ((i + 0.5) * clipSec) / count);@@ -43,6 +60,40 @@ function splitDataUrl(dataUrl: string): { mimeType: string; data: string } | nulexport function makeReviewRole(projectId: string): ReviewRole {return {+ async frame(input: FrameCheckInput): Promise<ReviewVerdict> {+ const [candidate, benchmark] = await Promise.all([+ findRunAsset(projectId, input.imageMediaId).then((a) => (a ? imagePart(a.url) : null)),+ findRunAsset(projectId, input.benchmarkMediaId).then((a) => (a ? imagePart(a.url) : null)),+ ]);+ // No pictures, no judgment — an unreadable frame passes rather than+ // blocking the run on the gate's own plumbing.+ if (!candidate || !benchmark) return { ok: true };+ const content: Record<string, unknown>[] = [+ {+ text: `Sign off this frame for the production.+The plan's look: ${input.style || "(none written — judge against the benchmark alone)"}+The frame should show: ${input.subject}+The benchmark sheet — the artist to match:`,+ },+ { type: "input_image", dataBase64: benchmark.data, mimeType: benchmark.mimeType },+ { text: "The frame to judge:" },+ { type: "input_image", dataBase64: candidate.data, mimeType: candidate.mimeType },+ ];+ const res = await hostedPost("/api/inference/responses", {+ donkeyProvider: "gemini",+ model: geminiModelRoles.review,+ instructions: FRAME_INSTRUCTIONS,+ response_format: { type: "json_object" },+ input: [{ role: "user", content }],+ });+ if (!res.ok) throw new Error("The review model is unavailable.");+ const body = (await res.json()) as { output_text?: string };+ const parsed = JSON.parse(body.output_text ?? "") as Record<string, unknown>;+ const ok = parsed.ok !== false;+ const note = typeof parsed.note === "string" ? parsed.note.trim() : "";+ return { ok, ...(note ? { note } : {}) };+ },+async watch(input: ReviewInput): Promise<ReviewVerdict> {// The take resolves wherever the run's project lives — store when open,// persisted doc when the user switched away mid-render.@@ -51,14 +102,45 @@ export function makeReviewRole(projectId: string): ReviewRole {const clipSec = Math.max(0.1, asset.duration);const frames = await captureVideoFrames(asset.url, frameTimes(clipSec));if (frames.length === 0) throw new Error("Could not sample the take.");+ // Each cast sheet rides both the main review and the identity check —+ // resolve and encode it once per take, not once per use.+ const sheetImages = new Map<string, Awaited<ReturnType<typeof imagePart>>>();+ const sheetImage = async (mediaId: string) => {+ if (!sheetImages.has(mediaId)) {+ const sheetAsset = await findRunAsset(projectId, mediaId);+ sheetImages.set(mediaId, sheetAsset ? await imagePart(sheetAsset.url) : null);+ }+ return sheetImages.get(mediaId) ?? null;+ };const content: Record<string, unknown>[] = [{text: `Review this take, shown as frames sampled along its ${clipSec.toFixed(1)}s.Planned action: ${input.action || "(none written — judge against the narration)"}+The plan's look: ${input.style || "(none — judge content only)"}Narration heard over the shot: ${input.narration ? `"${input.narration}"` : "(none)"}The timeline slot needs ${input.slotSec.toFixed(1)}s of this take.`,},];+ let keyframeShown = false;+ if (input.keyframeMediaId) {+ const kf = await findRunAsset(projectId, input.keyframeMediaId);+ const img = kf ? await imagePart(kf.url) : null;+ if (img) {+ content.push({ text: "The shot's approved opening frame — the production's look:" });+ content.push({ type: "input_image", dataBase64: img.data, mimeType: img.mimeType });+ keyframeShown = true;+ }+ }+ // The cast's canonical designs — identity is judged against these, not+ // the keyframe, so a take rendered without the keyframe anchor is still+ // held to the same character.+ for (const sheet of input.castSheets ?? []) {+ const img = await sheetImage(sheet.mediaId);+ if (img) {+ content.push({ text: `Design sheet for the character "${sheet.name}":` });+ content.push({ type: "input_image", dataBase64: img.data, mimeType: img.mimeType });+ }+ }for (const f of frames) {const img = splitDataUrl(f.image);if (!img) continue;@@ -67,7 +149,7 @@ The timeline slot needs ${input.slotSec.toFixed(1)}s of this take.`,}const res = await hostedPost("/api/inference/responses", {donkeyProvider: "gemini",- model: geminiModelRoles.chat,+ model: geminiModelRoles.review,instructions: REVIEW_INSTRUCTIONS,response_format: { type: "json_object" },input: [{ role: "user", content }],@@ -75,11 +157,77 @@ The timeline slot needs ${input.slotSec.toFixed(1)}s of this take.`,if (!res.ok) throw new Error("The review model is unavailable.");const body = (await res.json()) as { output_text?: string };const parsed = JSON.parse(body.output_text ?? "") as Record<string, unknown>;+ // The wrong-world check is deterministic: the judge CLASSIFIES what it+ // sees — an easier ask than remembering to fail — and code compares. A+ // take whose medium differs from the approved opening frame's never+ // passes, whatever the holistic `ok` said (a 3D-CGI take of a 2D+ // production has slipped a judge's overall judgment before).+ const MEDIA = ["hand-drawn-2d", "3d-cgi", "live-action", "stop-motion"];+ const medium = typeof parsed.medium === "string" ? parsed.medium.trim() : "";+ const frameMedium = typeof parsed.frameMedium === "string" ? parsed.frameMedium.trim() : "";+ if (keyframeShown && MEDIA.includes(medium) && MEDIA.includes(frameMedium) && medium !== frameMedium) {+ return {+ ok: false,+ offModel: true,+ note: `render as ${frameMedium} matching the opening frame's artwork, not ${medium}`,+ };+ }const ok = parsed.ok !== false;const note = typeof parsed.note === "string" ? parsed.note.trim() : "";+ const offModel = !ok && parsed.offModel === true;const rawFrom = typeof parsed.fromSec === "number" && Number.isFinite(parsed.fromSec) ? parsed.fromSec : 0;const fromSec = Math.min(Math.max(0, rawFrom), Math.max(0, clipSec - input.slotSec));- return { ok, ...(note ? { note } : {}), ...(fromSec > 0 ? { fromSec } : {}) };+ // Identity gets its own focused comparison — one sheet, a few frames,+ // one question. Buried inside the multi-rule review above, a wrong+ // design has slipped a holistic "ok" before; a dedicated call is the+ // same judge doing a far easier task.+ if (ok && input.castSheets?.length) {+ for (const sheet of input.castSheets) {+ const img = await sheetImage(sheet.mediaId);+ if (!img) continue;+ // The judge must know the plan: a wardrobe the shot itself calls+ // for (a uniform, swimwear) is not identity drift.+ const idContent: Record<string, unknown>[] = [+ {+ text: `The shot's plan (attire it names overrides the sheet's): ${+ input.action || "(none written)"+ }+The canonical design sheet for "${sheet.name}":`,+ },+ { type: "input_image", dataBase64: img.data, mimeType: img.mimeType },+ ];+ const mid = frames.filter((_, i) => i % 2 === 1).slice(0, 3);+ for (const f of mid.length ? mid : frames.slice(0, 3)) {+ const fi = splitDataUrl(f.image);+ if (!fi) continue;+ idContent.push({ text: `Shot frame at ${f.at.toFixed(1)}s:` });+ idContent.push({ type: "input_image", dataBase64: fi.data, mimeType: fi.mimeType });+ }+ const idRes = await hostedPost("/api/inference/responses", {+ donkeyProvider: "gemini",+ model: geminiModelRoles.review,+ instructions: IDENTITY_INSTRUCTIONS,+ response_format: { type: "json_object" },+ input: [{ role: "user", content: idContent }],+ });+ if (!idRes.ok) break; // best-effort: the main verdict stands+ const idBody = (await idRes.json()) as { output_text?: string };+ const idParsed = JSON.parse(idBody.output_text ?? "{}") as Record<string, unknown>;+ if (idParsed.sameDesign === false) {+ const drift =+ typeof idParsed.drift === "string" && idParsed.drift.trim()+ ? idParsed.drift.trim()+ : `the character does not match the design sheet for ${sheet.name}`;+ return { ok: false, offModel: true, note: drift };+ }+ }+ }+ return {+ ok,+ ...(note ? { note } : {}),+ ...(offModel ? { offModel } : {}),+ ...(fromSec > 0 ? { fromSec } : {}),+ };},};}diff --git a/site/src/cut/lib/genvideo/adapters/text.ts b/site/src/cut/lib/genvideo/adapters/text.tsindex c9a4a007..88543048 100644--- a/site/src/cut/lib/genvideo/adapters/text.ts+++ b/site/src/cut/lib/genvideo/adapters/text.ts@@ -19,39 +19,86 @@ import { hostedPost } from "../../hosted";import { NO_CREDITS_MESSAGE } from "../../generate";import { secToFrame, type RawShot } from "../coverage";import { wordsInRange, type BreakdownRole, type ScriptRole, type StyleRole } from "../capabilities";+import { refImageParts, type InlineImagePart } from "./refImages";import type { ScriptBeat, ScriptPlan, TranscriptWord, VideoAsset } from "../types";// ── the shared call ─────────────────────────────────────────────────────────-/** One structured JSON completion. `parse` returns null for unusable output,- * which surfaces as a throw the caller (or the orchestrator) recovers from. */+/** One structured JSON completion. `parse` returns null for unusable output.+ * Transient failures — rate limits, upstream 5xx, network blips, an+ * unparseable sample — retry before the error escapes: a plan step failing on+ * one blip poisons everything downstream of it. These are background steps,+ * so the envelope is wide enough (~30s) to ride out a real overload burst,+ * which a couple of sub-second retries cannot. Sign-in and credit errors+ * throw immediately; retrying can't fix them. */+const LLM_RETRY_DELAYS_MS = [0, 2_000, 8_000, 20_000];+async function llmJson<T>(instructions: string,userText: string,- parse: (o: Record<string, unknown>) => T | null+ parse: (o: Record<string, unknown>) => T | null,+ images: InlineImagePart[] = []): Promise<T> {- const res = await hostedPost("/api/inference/responses", {- donkeyProvider: "gemini",- model: geminiModelRoles.chat,- instructions,- response_format: { type: "json_object" },- input: [{ role: "user", content: [{ text: userText }] }],- });- if (!res.ok) {- if (res.status === 402) throw new Error(NO_CREDITS_MESSAGE);- if (res.status === 401) throw new Error("Sign in to Donkey to generate a video.");- throw new Error("The planning model is unavailable — try again.");+ let lastError = new Error("The planning model is unavailable — try again.");+ for (const delay of LLM_RETRY_DELAYS_MS) {+ if (delay > 0) await new Promise((r) => setTimeout(r, delay));+ let res: Response;+ try {+ res = await hostedPost("/api/inference/responses", {+ donkeyProvider: "gemini",+ model: geminiModelRoles.chat,+ instructions,+ response_format: { type: "json_object" },+ input: [+ {+ role: "user",+ content: [+ { text: userText },+ ...images.map((i) => ({ type: "input_image", dataBase64: i.data, mimeType: i.mimeType })),+ ],+ },+ ],+ });+ } catch {+ continue; // network blip — retry+ }+ if (!res.ok) {+ if (res.status === 402) throw new Error(NO_CREDITS_MESSAGE);+ if (res.status === 401) throw new Error("Sign in to Donkey to generate a video.");+ const reason = await providerReason(res);+ lastError = new Error(reason ?? "The planning model is unavailable — try again.");+ // Any other 4xx is deterministic — the same request fails the same way —+ // so surface the reason now instead of burning the retry envelope on it.+ if (res.status < 500 && res.status !== 408 && res.status !== 429) throw lastError;+ continue;+ }+ const body = (await res.json()) as { output_text?: string };+ let parsed: Record<string, unknown>;+ try {+ parsed = JSON.parse(body.output_text ?? "") as Record<string, unknown>;+ } catch {+ lastError = new Error("The planning model returned unreadable output.");+ continue;+ }+ const out = parse(parsed);+ if (out === null) {+ lastError = new Error("The planning model returned an unusable plan.");+ continue;+ }+ return out;}- const body = (await res.json()) as { output_text?: string };- let parsed: Record<string, unknown>;+ throw lastError;+}++/** The provider's human reason from an error body, when one rode along. */+async function providerReason(res: Response): Promise<string | null> {try {- parsed = JSON.parse(body.output_text ?? "") as Record<string, unknown>;+ const body = (await res.json()) as { message?: string; details?: { message?: string } };+ const msg = body.details?.message || body.message;+ return typeof msg === "string" && msg.trim() ? msg.trim() : null;} catch {- throw new Error("The planning model returned unreadable output.");+ return null;}- const out = parse(parsed);- if (out === null) throw new Error("The planning model returned an unusable plan.");- return out;}// ── coercion helpers ────────────────────────────────────────────────────────@@ -207,14 +254,14 @@ ${timedTranscript(input.transcript)}`;const STYLE_INSTRUCTIONS = `You are an art director. Design the visual world for a short video.Reply with JSON only:-{"style": string, "characters": [{"id": "char:1", "name": string, "description": string}], "locations": [{"id": "loc:1", "name": string, "description": string}]}+{"style": string, "negative": string, "characters": [{"id": "char:1", "name": string, "description": string}], "locations": [{"id": "loc:1", "name": string, "description": string}]}Rules:-- style is one reusable paragraph every shot carries: medium, lighting, palette, camera, mood.-- Return one entry per id you are asked to define, using those exact ids. description is a concrete visual of that subject/place — appearance, one fixed wardrobe, and the props the story repeats (a bag, a book, earphones) — so every shot renders the same person carrying the same things.+- style is one reusable paragraph every shot carries: medium, lighting, palette, camera, mood. Name the medium first and unambiguously — it is the instruction renders most often break. When reference images are attached, derive this wording from what they actually show: name their exact technique (linework, shading, color finish) so words and pixels agree. Pin the palette with precise color words ("flat marigold yellow", "warm cream skin, no gradient") — every shot is drawn independently, and only an exact name keeps a color the same across them.+- Reference images set the LOOK. A reference that is itself a character design — a turnaround sheet, or a single full-body character on a plain background — also sets a cast member's DESIGN: when the brief gives that character no appearance of its own, describe the cast member as exactly the pictured character (hair, face, eyewear, outfit, precise colors). Any other reference's people, characters, and creatures join the cast only when the brief asks for them; otherwise design the cast from the brief and describe them in the reference's technique, never as the pictured characters.+- negative is a short comma-separated list of what must never appear in this look: the wrong medium's tells. For a hand-drawn 2D look: "photorealistic rendering, live-action footage, 3D CGI, realistic skin texture, photographic lighting". For live-action: "cartoon rendering, cel shading, illustration". Tells only — subjects and story stay out.+- Return one entry per id you are asked to define, using those exact ids. description is a concrete visual of that subject/place — appearance, one fixed wardrobe, and the props the story repeats (a bag, a book, earphones) — so every shot renders the same person carrying the same things. Name each garment's and prop's color with the same precise words the style paragraph uses, and repeat those words verbatim wherever the item appears.- Never name a real brand, franchise, show, studio, or artist — not even one the brief names. A generator rejects a trademarked name, so translate any such reference into its concrete visual traits: linework, proportions, palette, shading, era. (e.g. a named 1990s TV cartoon → "hand-drawn 2D animation, thick black outlines, flat bright colors, exaggerated rounded features, yellow-toned skin, simple suburban backdrops".)`;-const DEFAULT_STYLE = "Cinematic, natural light, shallow depth of field.";-function toAssets(raw: unknown,ids: string[],@@ -233,7 +280,7 @@ function toAssets(});}-export function makeStyleRole(): StyleRole {+export function makeStyleRole(projectId: string): StyleRole {return {async design(input) {const charIds = distinct(input.beats.flatMap((b) => b.characters ?? []));@@ -242,21 +289,40 @@ export function makeStyleRole(): StyleRole {const story = input.beats.map((b, i) => `${i + 1}. ${b.action}${b.dialogue ? ` — "${b.dialogue}"` : ""}`).join("\n");- const refNote = input.refs.length- ? `The user attached ${input.refs.length} reference image(s) that fix how key subjects look; keep descriptions compatible with them.`+ // The art director sees the actual reference pixels, so the style+ // wording names the real technique instead of guessing from the brief.+ const refParts = await refImageParts(projectId, input.refs);+ const refNote = refParts.length+ ? `The user's reference image(s) are attached — they define the look.`+ : "";+ const lookNote = input.style+ ? `The user pinned this look — style must realize it (translated per the rules): ${input.style}`: "";const user = `Design the look for this video.Brief: ${input.brief || "(none)"}${refNote}+${lookNote}Story:${story}Define these characters (use these exact ids): ${charIds.join(", ") || "(none)"}Define these locations (use these exact ids): ${wantLocs.join(", ")}`;- return llmJson(STYLE_INSTRUCTIONS, user, (o) => ({- style: str(o.style) || DEFAULT_STYLE,- characters: toAssets(o.characters, charIds, "character"),- locations: toAssets(o.locations, wantLocs, "location"),- }));+ return llmJson(+ STYLE_INSTRUCTIONS,+ user,+ (o) => {+ // A bible without a style paragraph is unusable — retried, never+ // silently replaced with a stand-in look.+ const style = str(o.style);+ if (!style) return null;+ return {+ style,+ ...(str(o.negative) ? { negative: str(o.negative) } : {}),+ characters: toAssets(o.characters, charIds, "character"),+ locations: toAssets(o.locations, wantLocs, "location"),+ };+ },+ refParts+ );},};}diff --git a/site/src/cut/lib/genvideo/capabilities.ts b/site/src/cut/lib/genvideo/capabilities.tsindex 3d291c5b..7d8f9d80 100644--- a/site/src/cut/lib/genvideo/capabilities.ts+++ b/site/src/cut/lib/genvideo/capabilities.ts@@ -34,6 +34,8 @@ export interface BreakdownInput {export interface StyleInput {brief?: string;+ /** A look the user pinned up front — the bible's style must realize it. */+ style?: string;refs: RefAsset[];/** The story to design for. `characters`/`location` carry the stable ids the* script/breakdown assigned (char:1, loc:1, …); the style role returns one@@ -44,6 +46,9 @@ export interface StyleInput {export interface StyleBible {/** The reusable style string every downstream prompt carries. */style: string;+ /** What must never appear in a render of this look — the wrong medium's+ * tells (e.g. photorealistic footage in a hand-drawn cut). */+ negative?: string;characters: VideoAsset[];locations: VideoAsset[];}@@ -56,12 +61,14 @@ export interface ImageInput {export interface VideoInput {prompt: string;+ /** The model's negative prompt — the look's banned tells plus the base+ * bans every render shares. */+ negativePrompt?: string;refs: RefAsset[];/** The shot this render is for — its stable identity across reloads, so a* resumed run re-adopts its own in-flight job instead of billing a retake. */shotId?: string;startKeyframe?: string;- endKeyframe?: string;/** The audio slice this shot should be spoken over — for audio-native video. */audioMediaId?: string;audioFromSec?: number;@@ -106,9 +113,18 @@ export interface ImageRole {/** Returns the generated project media id. */generate(input: ImageInput): Promise<string>;}+export interface VideoTake {+ /** The generated project media id. */+ mediaId: string;+ /** Whether the take rode an image anchor (seed keyframe or reference+ * sheets). An unanchored take came from the text rung — identity held only+ * by words — which changes the retake policy: its identity break means the+ * provider refused the seed, so a FRESH seed re-rolls that refusal, whereas+ * an anchored stranger keeps the seed it drifted from. */+ anchored: boolean;+}export interface VideoRole {- /** Returns the generated project media id. */- generate(input: VideoInput): Promise<string>;+ generate(input: VideoInput): Promise<VideoTake>;/** True when this model lip-syncs to provided audio itself (no post-pass). */readonly audioNative: boolean;}@@ -132,6 +148,15 @@ export interface ReviewInput {videoMediaId: string;/** What the plan wanted on screen. */action: string;+ /** The plan's look — the reviewer judges the medium against it strictly. */+ style?: string;+ /** The shot's approved opening frame — the take must match its rendering+ * technique, so a weaker-rung render can't land in a different look. */+ keyframeMediaId?: string;+ /** The canonical design sheet of each cast member in the shot, by name — the+ * take's characters must read as the SAME designs, so a weaker-rung render+ * can't land a reinvented character. */+ castSheets?: { name: string; mediaId: string }[];/** The words heard over the shot. */narration: string;/** Seconds of the take the timeline slot needs. */@@ -143,13 +168,35 @@ export interface ReviewVerdict {ok: boolean;/** Why a declined take failed — carried into the retake prompt. */note?: string;+ /** A declined take that doesn't belong to this production — a character off+ * its design sheet, or the wrong medium/technique (3D or live-action in a+ * 2D production). Not a weak performance: an off-model take NEVER places,+ * even on the last attempt — the on-model keyframe still holds the slot+ * instead. The retake's seed follows the take's anchor: an anchored+ * stranger keeps the gated-on-model seed it drifted from; an unanchored one+ * means the provider refused the seed, so a fresh mint re-rolls it. */+ offModel?: boolean;/** Where the slot's window starts inside the take (seconds; default 0). */fromSec?: number;}+export interface FrameCheckInput {+ /** Project media id of the minted frame. */+ imageMediaId: string;+ /** The production's technique benchmark (the anchor sheet). */+ benchmarkMediaId: string;+ /** The plan's look. */+ style?: string;+ /** What the frame should show. */+ subject: string;+}+export interface ReviewRole {/** Watch a rendered take against its plan — the dailies check. */watch(input: ReviewInput): Promise<ReviewVerdict>;+ /** Judge one minted frame against the production's benchmark BEFORE it seeds+ * a paid render — the same-artist gate. Optional; absent means no gate. */+ frame?(input: FrameCheckInput): Promise<ReviewVerdict>;}/** One model choice per role — what the orchestrator runs against. */diff --git a/site/src/cut/lib/genvideo/coverage.ts b/site/src/cut/lib/genvideo/coverage.tsindex d015e2e6..eab834a0 100644--- a/site/src/cut/lib/genvideo/coverage.ts+++ b/site/src/cut/lib/genvideo/coverage.ts@@ -18,11 +18,10 @@ import type { Shot } from "./types";/** The timeline slice range a shot may occupy, in seconds. The floor is a* pacing choice, not the video model's: a narration names a new idea every- * couple of seconds, and each idea deserves its own shot. The model's own- * minimum render length lives in `supportedVideoDuration` — a short slot- * renders the shortest supported take and the placement trims it to the slot- * (the dailies review picks which window survives). The ceiling is the longest- * single render. */+ * couple of seconds, and each idea deserves its own shot. The model picks its+ * own render length (up to ~10s) and always covers the slot, so the placement+ * trims the take to it (the dailies review picks which window survives). The+ * ceiling keeps one slot from swallowing a whole beat. */export const MIN_SHOT_SEC = 2;export const MAX_SHOT_SEC = 8;diff --git a/site/src/cut/lib/genvideo/fakes.ts b/site/src/cut/lib/genvideo/fakes.tsindex 69a0234d..1e1ec6ff 100644--- a/site/src/cut/lib/genvideo/fakes.ts+++ b/site/src/cut/lib/genvideo/fakes.ts@@ -21,6 +21,7 @@ import {type ScriptInput,type StyleBible,type VideoInput,+ type VideoTake,type VoiceInput,type VoiceResult,} from "./capabilities";@@ -31,6 +32,12 @@ export interface FakeCall {role: string;detail: string;mediaId?: string;+ /** Video calls: which shot rendered, and from which seed keyframe — so a+ * test can prove seed-retention policies across retakes. */+ shotId?: string;+ keyframe?: string;+ /** Image/video calls: the full prompt, for asserting retake direction. */+ prompt?: string;}export interface FakeStudioOptions {@@ -48,12 +55,16 @@ export interface FakeStudioOptions {voiceSeconds?: number;/** Fail every image generation whose prompt contains this marker. */failImageMarker?: string;- /** Make the style/character-design call throw (exercises the default bible). */+ /** Make the style/character-design call throw (the run must fail loudly). */failStyle?: boolean;style?: string;/** Scripted dailies verdicts, consumed in order (absent = no review role).* Once the list runs dry every later take passes clean. */reviewVerdicts?: ReviewVerdict[];+ /** Simulate the provider refusing every image anchor: takes still render,+ * but unanchored (the real ladder's text rung) — how a person-policy block+ * on the seed looks to the orchestrator. */+ anchorsRefused?: boolean;}/** An in-memory studio; `.suite()` binds it to the orchestrator's roles. */@@ -130,14 +141,23 @@ export class FakeStudio {const marker = this.opts.failImageMarker;if (marker && input.prompt.includes(marker))throw new Error(`fake image failed (marker "${marker}")`);- return this.mint("image", input.prompt.slice(0, 40));+ const id = this.mint("image", input.prompt.slice(0, 40));+ this.calls[this.calls.length - 1].prompt = input.prompt;+ return id;}- private async video(input: VideoInput): Promise<string> {+ private async video(input: VideoInput): Promise<VideoTake> {const marker = this.opts.failVideoMarker;if (marker && input.prompt.includes(marker))throw new Error(`fake video failed (marker "${marker}")`);- return this.mint("video", `${input.durationSec}s${input.audioMediaId ? " +audio" : ""} ${input.prompt}`);+ const id = this.mint("video", `${input.durationSec}s${input.audioMediaId ? " +audio" : ""} ${input.prompt}`);+ const call = this.calls[this.calls.length - 1];+ call.shotId = input.shotId;+ call.keyframe = input.startKeyframe;+ // Anchored when an anchor exists and the provider took it; refused+ // anchors fall to the words-only render, exactly like the real ladder.+ const anchored = !this.opts.anchorsRefused && (!!input.startKeyframe || input.refs.length > 0);+ return { mediaId: id, anchored };}private async speak(input: VoiceInput): Promise<VoiceResult> {diff --git a/site/src/cut/lib/genvideo/orchestrator.ts b/site/src/cut/lib/genvideo/orchestrator.tsindex d1132e2d..a4e68cab 100644--- a/site/src/cut/lib/genvideo/orchestrator.ts+++ b/site/src/cut/lib/genvideo/orchestrator.ts@@ -21,7 +21,7 @@import { assertCoverage, frameToSec, MAX_SHOT_SEC, MIN_SHOT_SEC, repairCoverage, secToFrame, shotDurationFrames } from "./coverage";import { fanOut } from "./pool";-import { buildPrompt, buildRefPrompt, refsForAsset, shotRefs } from "./prompt";+import { buildNegative, buildPrompt, buildRefPrompt, refsForAsset, shotRefs, styleAnchor } from "./prompt";import { segmentByDuration, type ModelSuite, type ReviewVerdict } from "./capabilities";import type { EditorBridge } from "./editor";import type { BeatVoice, RefAsset, Shot, VideoAsset, VideoEmit, VideoPhase, VideoProject } from "./types";@@ -38,7 +38,11 @@ export interface OrchestratorDeps {sleep?: (ms: number) => Promise<void>;}-const VIDEO_ATTEMPTS = 3; // the first try plus two retries+// Takes per shot before the on-model still holds the slot. Generous on+// purpose: a person-policy block on the seed is per-image luck, so every+// retake re-rolls it with a fresh keyframe, and the director throws away+// off-model takes — attempts are the shot's supply of dice.+export const VIDEO_ATTEMPTS = 5;const REF_ATTEMPTS = 2; // extra retries for continuity anchorsconst BACKOFF_MS = 500;const VOICE_DUCK = 0.35;@@ -86,20 +90,49 @@ export class VideoOrchestrator {* spend once the run is superseded or paused. */async run(): Promise<VideoProject> {if (this.project.phase === "failed" || this.project.phase === "done") return this.project;- const phases = [this.brief, this.ingest, this.breakdown];- for (const phase of phases) {- if (this.aborted) return this.project;- await phase.call(this);- }- if (!this.project.breakdownApproved) return this.project; // wait for confirmation- // The spine is voiced only now, past the gate, so an unapproved plan spends- // nothing on TTS (the plan up to here runs on estimated beat lengths).- const paid = [this.voice, this.style, this.keyframes, this.generateAndPlaceAll, this.polish];- for (const phase of paid) {- if (this.aborted) return this.project;- await phase.call(this);+ return this.failLoudly(async () => {+ const phases = [this.brief, this.ingest, this.breakdown];+ for (const phase of phases) {+ if (this.aborted) return this.project;+ await phase.call(this);+ }+ if (!this.project.breakdownApproved) return this.project; // wait for confirmation+ // The spine is voiced only now, past the gate, so an unapproved plan spends+ // nothing on TTS (the plan up to here runs on estimated beat lengths).+ const paid = [this.voice, this.style, this.keyframes, this.generateAndPlaceAll, this.polish];+ for (const phase of paid) {+ if (this.aborted) return this.project;+ await phase.call(this);+ }+ return this.project;+ });+ }++ /** Run a lifecycle step; a throw becomes the run's persisted terminal+ * outcome. Without this the plan keeps its mid-render phase on disk, and the+ * next load silently resumes (and re-bills) a run the user watched die. An+ * aborted run is an interruption, not an outcome — it persists nothing. */+ private async failLoudly<T>(work: () => Promise<T>): Promise<T> {+ try {+ return await work();+ } catch (e) {+ if (!this.aborted) {+ this.setPhase("failed");+ await this.save().catch(() => {});+ }+ throw e;}- return this.project;+ }++ /** An explicit user retry of a failed run. Auto-resume paths skip a failed+ * plan (that stop is what failLoudly buys); the click re-arms it, and every+ * phase then skips whatever already landed — voiced beats, minted sheets,+ * placed shots — so only the missing work re-bills. */+ async retryFailed(): Promise<VideoProject> {+ if (this.project.phase !== "failed") return this.project;+ this.setPhase(this.project.breakdownApproved ? "voicing" : "brief");+ await this.save();+ return this.run();}/** The user confirmed the shot list — continue the run. */@@ -357,48 +390,38 @@ export class VideoOrchestrator {private async style(): Promise<void> {this.setPhase("style");if (!this.project.style || this.project.characters.length === 0) {- try {- const bible = await this.deps.suite.style.design({- brief: this.project.brief,- refs: this.project.references,- beats: this.project.shots.map((s) => ({- dialogue: s.dialogue ?? s.audioText,- action: s.action,- characters: s.characters,- location: s.location,- })),- });- this.project.style = bible.style;- this.project.characters = bible.characters;- this.project.locations = bible.locations;- } catch {- // Degrade to a default bible so identity anchors still exist — an empty- // characters list would silently drop every reference image.- if (!this.project.style) this.project.style = "Cinematic, natural light.";- if (this.project.characters.length === 0)- this.project.characters = [{ id: "char:1", kind: "character", name: "the subject", description: "the main subject, from the references" }];- if (this.project.locations.length === 0)- this.project.locations = [{ id: "loc:1", kind: "location", name: "the setting", description: "the scene" }];- }+ // The bible is the run's spine: the look every shot leads with, the+ // negative, and the cast the sheets are minted from. A failed design+ // fails the run loudly here — before any shot spends — and a resume+ // re-runs it. A stand-in bible would silently corrupt every render.+ const bible = await this.deps.suite.style.design({+ brief: this.project.brief,+ style: this.project.style || undefined,+ refs: this.project.references,+ beats: this.project.shots.map((s) => ({+ dialogue: s.dialogue ?? s.audioText,+ action: s.action,+ characters: s.characters,+ location: s.location,+ })),+ });+ this.project.style = bible.style;+ this.project.negative = bible.negative;+ this.project.characters = bible.characters;+ this.project.locations = bible.locations;await this.save();}const needed = this.referencedAssets().filter((a) => !a.mediaId);if (needed.length > 0) {- await fanOut(- needed,- async (asset) => {- if (this.aborted) return; // a paused run spends nothing more- this.deps.emit({ type: "activity", message: `Designing ${asset.name}…` });- const raw = await this.deps.suite.image.generate({- prompt: buildRefPrompt(asset, this.project.style),- refs: refsForAsset(asset, this.project),- aspect: this.aspect,- });- asset.mediaId = await this.deps.editor.importMedia(raw);- this.deps.emit({ type: "log", message: `Designed ${asset.name}.` });- },- this.poolOpts(REF_ATTEMPTS)- );+ // The anchor sheet mints alone; the rest fan out with it riding as a+ // style reference (mintSheet), so one drawing technique propagates+ // through the whole bible instead of each sheet converging on its own.+ const queue = [...needed];+ if (!styleAnchor(this.project)) {+ await fanOut([queue.shift()!], (asset) => this.mintSheet(asset), this.poolOpts(REF_ATTEMPTS));+ await this.save();+ }+ await fanOut(queue, (asset) => this.mintSheet(asset), this.poolOpts(REF_ATTEMPTS));const missing = needed.filter((a) => !a.mediaId);if (missing.length)this.deps.emit({ type: "log", message: `Couldn't design ${missing.map((a) => a.name).join(", ")} — those shots may drift.` });@@ -406,6 +429,22 @@ export class VideoOrchestrator {}}+ /** Render one character/location reference sheet, the run's technique+ * anchor riding along when one exists. */+ private async mintSheet(asset: VideoAsset): Promise<void> {+ if (this.aborted) return; // a paused run spends nothing more+ this.deps.emit({ type: "activity", message: `Designing ${asset.name}…` });+ const anchor = styleAnchor(this.project);+ // screenedImage holds every later sheet to the anchor (the first sheet IS+ // the anchor — with none minted yet the gate skips itself).+ asset.mediaId = await this.screenedImage(+ `${buildRefPrompt(asset, this.project.style)} Avoid: ${buildNegative(this.project)}.`,+ [...refsForAsset(asset, this.project), ...(anchor ? [anchor] : [])],+ `a reference sheet of ${asset.name} — ${asset.description}`+ );+ this.deps.emit({ type: "asset", label: `Designed ${asset.name}`, mediaId: asset.mediaId });+ }+// ── Phase D: keyframes (cheap, run in parallel) ──────────────────────────private async keyframes(): Promise<void> {this.setPhase("keyframes");@@ -417,13 +456,16 @@ export class VideoOrchestrator {await this.save();}- private async makeKeyframes(shot: Shot): Promise<void> {+ private async makeKeyframes(shot: Shot, note?: string): Promise<void> {if (this.aborted) return; // a paused run spends nothing morethis.updateShot(shot, { status: "keyframing" });const refs = shotRefs(shot, this.project);- const prompt = buildPrompt(shot, this.project);- shot.startKeyframe = await this.importedImage(`${prompt} Opening frame.`, refs);- if (hasMotion(shot)) shot.endKeyframe = await this.importedImage(`${prompt} Closing frame.`, refs);+ // The image model has no negative-prompt parameter, so the bans ride as+ // avoid-text — a letterboxed or off-medium keyframe seeds a bad video.+ const prompt = `${buildPrompt(shot, this.project)} Avoid: ${buildNegative(this.project)}.${+ note ? ` Note from the last take's review: ${note}` : ""+ }`;+ shot.startKeyframe = await this.screenedImage(`${prompt} Opening frame.`, refs, shot.action);this.updateShot(shot, { status: "pending" });}@@ -459,6 +501,14 @@ export class VideoOrchestrator {const refs = shotRefs(shot, this.project);// The reviewer's note from a declined take — the retake prompt carries it.let critique: string | undefined;+ // Whether the next attempt should replace the seed keyframe (set by a+ // decline whose flaw traces to the seed; identity breaks keep it).+ let remintSeed = false;+ // Off-model takes that never rode an anchor: the provider is refusing+ // this shot's seed frames outright, take after take. Past two of those,+ // fresh dice aren't enough — the seed itself needs restaging (subject at+ // a distance, face away from camera) so the anchor stops being refused.+ let unanchoredMisses = 0;for (let attempt = 1; attempt <= VIDEO_ATTEMPTS; attempt++) {if (this.aborted) return; // a paused run spends nothing moreshot.attempts = attempt;@@ -469,19 +519,41 @@ export class VideoOrchestrator {const prompt = critique ? `${basePrompt} Note from the last take's review: ${critique}` : basePrompt;const video = this.deps.suite.video;try {- let clip = await video.generate({+ // A seed-flaw decline re-mints the keyframes with the critique so the+ // retake animates a fresh frame instead of the flawed one — but the+ // prior seed is released only once its replacement exists: a failed+ // mint restores it rather than rendering anchor-less, which is how a+ // cast shot loses its character to a weaker rung.+ if (remintSeed || !shot.startKeyframe) {+ const prior = { start: shot.startKeyframe };+ shot.startKeyframe = undefined;+ remintSeed = false;+ const seedNote =+ unanchoredMisses >= 2+ ? `${critique ? `${critique} ` : ""}Restage the composition: the subject at mid-distance or seen from a three-quarter or back angle, no face near the camera, with the action still fully readable.`+ : critique;+ try {+ await this.makeKeyframes(shot, seedNote);+ } catch {+ // Restored below — a prior on-model seed beats no seed at all.+ }+ shot.startKeyframe = shot.startKeyframe ?? prior.start;+ await this.save();+ this.updateShot(shot, { status: "generating", error: undefined });+ }+ const take = await video.generate({prompt,+ negativePrompt: buildNegative(this.project),refs,shotId: shot.id,startKeyframe: shot.startKeyframe,- endKeyframe: shot.endKeyframe,durationSec: frameToSec(shotDurationFrames(shot), this.fps),aspect: this.aspect,...(audio && video.audioNative? { audioMediaId: audio.mediaId, audioFromSec: audio.fromSec, audioToSec: audio.toSec }: {}),});- clip = await this.deps.editor.importMedia(clip);+ let clip = await this.deps.editor.importMedia(take.mediaId);// Lip-sync post-pass when the video model can't do it inline.if (audio && !video.audioNative && this.deps.suite.lipSync) {this.updateShot(shot, { status: "lipsync" });@@ -496,15 +568,28 @@ export class VideoOrchestrator {}// The dailies check: a reviewer watches the take against the plan.// A declined take retries (the throw lands in the catch below, and the- // retake prompt carries the note); the last attempt places regardless —- // a weak take beats a frozen still. The chosen window trims the- // placement to the take's best moment.+ // retake prompt carries the note). On the last attempt a weak take+ // still places — motion beats a frozen still — EXCEPT an identity+ // break: a moving stranger never lands, the shot falls out of the+ // loop and holds its on-model keyframe still instead. The chosen+ // window trims the placement to the take's best moment.let srcInSec: number | undefined;if (this.deps.suite.review) {this.updateShot(shot, { status: "reviewing" });const verdict = await this.reviewTake(clip, shot);- if (!verdict.ok && attempt < VIDEO_ATTEMPTS) {+ if (!verdict.ok && (attempt < VIDEO_ATTEMPTS || verdict.offModel)) {critique = verdict.note?.trim() || "the take did not show the planned action";+ // Where the retake's seed comes from depends on where the flaw+ // came from. An identity break on an ANCHORED take keeps the+ // seed: the on-model keyframe rode the render and the model still+ // drifted — re-animating it is the fix. An identity break on an+ // UNANCHORED take means the provider refused the seed and words+ // alone drew a stranger — the seed is what's blocked, so a fresh+ // one re-rolls that refusal. Every other flaw usually traces to+ // the seed (sideways composition, wrong technique, baked text),+ // so those re-mint too, with the critique.+ remintSeed = !verdict.offModel || !take.anchored;+ if (verdict.offModel && !take.anchored) unanchoredMisses++;throw new Error(`Retake: ${critique}`);}srcInSec = verdict.fromSec;@@ -539,6 +624,14 @@ export class VideoOrchestrator {return await this.deps.suite.review!.watch({videoMediaId: clip,action: shot.action,+ style: this.project.style,+ keyframeMediaId: shot.startKeyframe,+ // Identity is judged against the canonical sheets, not the keyframe —+ // a take rendered from a weaker rung (no keyframe riding) is still+ // held to the same character designs.+ castSheets: shotRefs(shot, this.project)+ .filter((r) => r.purpose === "character")+ .map((r) => ({ name: r.name || "the character", mediaId: r.mediaId })),narration: (shot.dialogue ?? shot.audioText).trim(),slotSec: frameToSec(shotDurationFrames(shot), this.fps),});@@ -586,9 +679,12 @@ export class VideoOrchestrator {* or a neighbor's frame — so a keyframe-gen failure never leaves a hole. */private async fallbackStill(shot: Shot): Promise<string | undefined> {if (shot.startKeyframe) return shot.startKeyframe;- if (shot.endKeyframe) return shot.endKeyframe;try {- shot.startKeyframe = await this.importedImage(`${buildPrompt(shot, this.project)} Still frame.`, shotRefs(shot, this.project));+ shot.startKeyframe = await this.screenedImage(+ `${buildPrompt(shot, this.project)} Still frame.`,+ shotRefs(shot, this.project),+ shot.action+ );return shot.startKeyframe;} catch {/* fall through to holding a neighbor's frame */@@ -665,7 +761,6 @@ export class VideoOrchestrator {// clip is ready — clearing them up front would open a hole if the redo// fails. The beat voice is untouched, so narration never restacks.shot.startKeyframe = undefined;- shot.endKeyframe = undefined;shot.lipSynced = false;shot.error = undefined;shot.status = "pending";@@ -698,11 +793,34 @@ export class VideoOrchestrator {/** A style change dirties everything downstream of the style bible. */async changeStyle(style: string): Promise<VideoProject> {+ // The new look goes back through the art director: it realizes the pinned+ // style into a fresh bible (banned tells included, trademarks translated+ // to traits) and re-dresses the cast for it — wardrobe is look. Emptying+ // the cast (in memory only — style() persists the new bible when it lands)+ // is what re-runs the design; ids re-derive from the shots.+ const prior = {+ style: this.project.style,+ negative: this.project.negative,+ characters: this.project.characters,+ locations: this.project.locations,+ };this.project.style = style;- for (const a of [...this.project.characters, ...this.project.locations]) a.mediaId = undefined;- await this.save();- await this.style();- await this.regenerateShots(this.project.shots.map((s) => s.id));+ this.project.negative = undefined;+ this.project.characters = [];+ this.project.locations = [];+ try {+ await this.style();+ await this.regenerateShots(this.project.shots.map((s) => s.id));+ } catch (e) {+ // A failed redesign must not strand the project bible-less: every later+ // regenerate_shot would render with no identity anchors. The old cast+ // (or the new one, if the design landed and only the re-render failed)+ // stays in place, and the project returns to its terminal phase.+ if (this.project.characters.length === 0) Object.assign(this.project, prior);+ this.setPhase("done");+ await this.save().catch(() => {});+ throw e;+ }// Restore the terminal phase so a later resume doesn't re-run polish (which// would otherwise re-place the music bed).this.setPhase("done");@@ -730,6 +848,33 @@ export class VideoOrchestrator {return this.deps.editor.importMedia(raw);}+ /** Mint an image and hold it to the production's benchmark: the art-director+ * gate judges it against the anchor sheet before it seeds anything paid, and+ * a declined take re-mints once with the critique in the prompt. The second+ * take lands either way — the gate improves frames, it never blocks the run. */+ private async screenedImage(prompt: string, refs: RefAsset[], subject: string): Promise<string> {+ let mediaId = await this.importedImage(prompt, refs);+ const benchmark = styleAnchor(this.project)?.mediaId;+ const gate = this.deps.suite.review?.frame;+ if (!benchmark || !gate) return mediaId;+ try {+ const verdict = await gate({+ imageMediaId: mediaId,+ benchmarkMediaId: benchmark,+ style: this.project.style,+ subject,+ });+ if (!verdict.ok) {+ const note = verdict.note ?? "match the benchmark sheet exactly — same artist, same palette";+ this.deps.emit({ type: "log", message: `Redrawing an off-style frame — ${note}` });+ mediaId = await this.importedImage(`${prompt} Note from the art director: ${note}.`, refs);+ }+ } catch {+ // The gate is best-effort; a frame it couldn't judge still serves.+ }+ return mediaId;+ }+private emitProgress(): void {const placed = this.project.shots.filter((s) => s.timelineClipId).length;this.deps.emit({ type: "progress", placed, total: this.project.shots.length });@@ -777,13 +922,6 @@ function estimateSpokenSeconds(dialogue: string): number {return Math.max(1.2, (words / 165) * 60);}-/** Whether a shot has enough motion to warrant a distinct closing keyframe. */-function hasMotion(shot: Shot): boolean {- return /\b(runs?|walks?|jumps?|flies|fly|turns?|moves?|falls?|rises?|spins?|races?|drives?|dances?|zoom)/i.test(- shot.action- );-}-/** Split one beat's span into contiguous shots each no longer than `maxFrames`,* distributing the remainder so the pieces stay as even as possible. */function splitBeat(start: number, frames: number, maxFrames: number): [number, number][] {diff --git a/site/src/cut/lib/genvideo/prompt.ts b/site/src/cut/lib/genvideo/prompt.tsindex 3ab16ea8..f4799a32 100644--- a/site/src/cut/lib/genvideo/prompt.ts+++ b/site/src/cut/lib/genvideo/prompt.ts@@ -3,15 +3,23 @@** Text describes what happens; references (character and location images, plus* whatever the user brought) carry what things look like and are passed as- * media, never described here. Keeping that split clean is what holds identity- * and style continuous across shots.+ * media. That split holds whenever an image can ride — prose that fights the+ * reference pixels weakens them. When one can't (a sheet that never minted, a+ * ladder rung that takes no images), the bible's fixed description rides in+ * the text instead — the same words every shot, because on that call they are+ * the only thing holding identity.*/import type { RefAsset, Shot, VideoAsset, VideoProject } from "./types";+const sentence = (s: string) => (/[.!?]$/.test(s.trim()) ? s.trim() : `${s.trim()}.`);+/** The text half of a shot's generation prompt. */export function buildPrompt(shot: Shot, project: VideoProject): string {- const parts = [shot.action.trim()];+ // The look leads: video models weight the prompt's head, and the wrong+ // medium (live-action in an animated cut) is the costliest way a render+ // can miss.+ const parts = [project.style, shot.action.trim()];// The narration grounds what the shot depicts, phrased as off-screen audio —// a bare quote reads as a caption request and the model burns the words into// the picture as speech bubbles and subtitle bars.@@ -20,28 +28,104 @@ export function buildPrompt(shot: Shot, project: VideoProject): string {const location = findAsset(project.locations, shot.location);if (location) parts.push(`Setting, ${location.name}.`);else if (shot.location) parts.push(`Setting, ${shot.location}.`);+ // Cast or setting with no minted sheet can never ride as an image on any+ // call — the bible's wording is all that holds their identity, so it rides+ // here, in every render of the shot.+ if (location && !location.mediaId) parts.push(sentence(location.description));+ for (const id of shot.characters) {+ const asset = findAsset(project.characters, id);+ if (asset && !asset.mediaId) parts.push(sentence(`${asset.name}: ${asset.description}`));+ }if (shot.framing) parts.push(`Framing, ${shot.framing}.`);- if (project.style) parts.push(project.style);parts.push(- "One single continuous shot with fluid, continuous character motion throughout — smooth, natural movement, never held poses or stepped animation. Pure visual storytelling: no on-screen text of any kind — no captions, subtitles, speech bubbles, titles, signs, or lettering — and no split screens, panels, or storyboard collages. No baked-in editing effects: no transition frames, fades, motion-blur smears, borders, or blurred letterbox bands — the picture fills the frame edge to edge; cuts and transitions are added later in the editor."+ "One single continuous shot with fluid, continuous character motion throughout — smooth, natural movement, never held poses or stepped animation. Pure visual storytelling: no on-screen text of any kind — no captions, subtitles, speech bubbles, titles, signs, or lettering — and no split screens, panels, or storyboard collages. No baked-in editing effects: no transition frames, fades, motion-blur smears, borders, or blurred letterbox bands — the picture fills the frame edge to edge, composed upright for this frame with a level horizon; cuts and transitions are added later in the editor.");return parts.filter(Boolean).join(" ").trim();}+/** The run's technique anchor: the first minted sheet. Every later sheet and+ * keyframe renders with it riding as a style reference, so one drawing+ * technique propagates through the whole run instead of each render+ * converging on its own lineweight, shading, and palette. */+export function styleAnchor(project: VideoProject): RefAsset | undefined {+ const minted = [...project.characters, ...project.locations].find((a) => a.mediaId);+ return minted?.mediaId+ ? { mediaId: minted.mediaId, kind: "image", purpose: "style", name: minted.name }+ : undefined;+}+/** The reference media a shot's generation draws from: its characters, its- * location, and every reference the user brought (identity, style, motion). */+ * location, the run's technique anchor, and every reference the user brought+ * (identity, style, motion). */export function shotRefs(shot: Shot, project: VideoProject): RefAsset[] {const refs: RefAsset[] = [];for (const id of shot.characters) {const asset = findAsset(project.characters, id);- if (asset?.mediaId) refs.push({ mediaId: asset.mediaId, kind: "image", purpose: "character", name: asset.name });+ if (asset?.mediaId)+ refs.push({ mediaId: asset.mediaId, kind: "image", purpose: "character", name: asset.name, description: asset.description });}const location = findAsset(project.locations, shot.location);- if (location?.mediaId) refs.push({ mediaId: location.mediaId, kind: "image", purpose: "location", name: location.name });+ if (location?.mediaId)+ refs.push({ mediaId: location.mediaId, kind: "image", purpose: "location", name: location.name, description: location.description });+ const anchor = styleAnchor(project);+ if (anchor && !refs.some((r) => r.mediaId === anchor.mediaId)) refs.push(anchor);refs.push(...project.references);return refs;}+/** The role of every reference riding an IMAGE render, stated in its prompt.+ * The image model receives references as bare pixels; without this text it+ * guesses — and the commonest wrong guess is pasting a style reference's+ * subjects into the shot. Cast sheets fix appearance; style references+ * contribute technique only. */+export function refRoleNote(refs: RefAsset[]): string {+ const cast = refs+ .filter((r) => r.purpose === "character" || r.purpose === "location")+ .map((r) => r.name)+ .filter(Boolean);+ const styled = refs.some((r) => r.purpose === "style");+ const parts: string[] = [];+ if (cast.length)+ parts.push(`The attached pictures of ${cast.join(", ")} fix exactly how they look — same face, wardrobe, and build.`);+ if (styled)+ parts.push(+ "The style reference images set the drawing technique: draw as the same artist — identical linework, shading, finish, and the exact same colors (a garment's yellow stays that yellow, sampled from the reference, never a nearby shade). The people, characters, and objects pictured in them stay out of the frame unless this prompt names them."+ );+ return parts.join(" ");+}++/** What no render may show, whatever the look: the frame-integrity bans the+ * prompt states affirmatively, restated as the model's negative prompt. */+const BASE_NEGATIVE =+ "on-screen text, captions, subtitles, watermarks, letterboxing, black bars, split screen, storyboard panels, sideways or rotated composition";++/** The negative prompt a shot renders with: the base bans plus the style+ * bible's banned tells for this look (project.negative). */+export function buildNegative(project: VideoProject): string {+ return [BASE_NEGATIVE, project.negative].filter(Boolean).join(", ");+}++/** Fold the written identity of unanchored cast into one render's prompt.+ * `riding` is the mediaIds that actually ride this call as images; every+ * character/location ref outside it gets its bible description appended —+ * the same fixed words every shot, so text-only renders drift around one+ * written identity instead of a bare action line. */+export function describeUnanchored(+ prompt: string,+ refs: RefAsset[],+ riding: ReadonlySet<string>+): string {+ const lines = refs+ .filter(+ (r) =>+ (r.purpose === "character" || r.purpose === "location") &&+ r.description &&+ !riding.has(r.mediaId)+ )+ .map((r) => sentence(r.name ? `${r.name}: ${r.description}` : r.description ?? ""));+ return lines.length ? `${prompt} ${lines.join(" ")}` : prompt;+}+/** The prompt that mints one reference image for a character or location. */export function buildRefPrompt(asset: VideoAsset, style: string): string {const subject =diff --git a/site/src/cut/lib/genvideo/shotAttempts.ts b/site/src/cut/lib/genvideo/shotAttempts.tsnew file mode 100644index 00000000..d9ee6ed0--- /dev/null+++ b/site/src/cut/lib/genvideo/shotAttempts.ts@@ -0,0 +1,92 @@+"use client";++/**+ * The scene shot's identity ladder as data: which rungs a shot renders+ * through, in strength order, and when each may run. Pure — media.ts resolves+ * the assets and hands them in, so the self-test can prove the ladder policy+ * (rung order, anchor strength, the policy-gated text rung) without a browser+ * or a credit spent.+ */++import type { AssetRef } from "../assetRef";+import type { VideoAttempt } from "../videoLadder";+import type { VideoGenOptions } from "../generate";+import { describeUnanchored } from "./prompt";+import type { RefAsset } from "./types";++/** Whether a render failure means the provider refused the image anchor+ * itself — a safety policy on what the picture shows, an unreadable format —+ * rather than the render going wrong. Keyed on the provider's refusal, never+ * on what or who the content depicts. */+export function anchorRefused(err: string | null): boolean {+ // "returned no video" is a completed render whose OUTPUT was filtered — for+ // an image-anchored rung that's the safety policy refusing the content it+ // rendered, the same dead end as refusing the anchor itself.+ return err !== null && /input image|image format|person\/face|17301594|returned no video/i.test(err);+}++export interface ShotAttemptArgs {+ prompt: string;+ /** The shot's full reference set (with purposes) — cast detection and the+ * written identities of whatever doesn't ride a given rung as pixels. */+ refs: RefAsset[];+ /** Options every rung shares (aspect, negative prompt). */+ base: Omit<VideoGenOptions, "onDone" | "chatId" | "genKey">;+ /** The shot's approved opening frame, resolved — the strongest anchor. */+ keyframe?: AssetRef;+ /** Resolved identity anchors (cast/location sheets), already capped to the+ * model's reference limit. */+ anchors: AssetRef[];+ /** The media ids riding as anchors — their cast skips the written identity. */+ ridingIds: Set<string>;+}++/** Build the ladder: keyframe seed → reference-to-video → text-only. Words+ * hold a face far worse than pixels, so a cast shot's text-only rung is+ * reserved for the failures an image anchor can't survive — the provider+ * refusing the anchor itself (anchorRefused above). An ordinary render+ * failure on the last rung fails the whole attempt back to the orchestrator's+ * retake (a fresh keyframe, fresh dice); and whatever the text rung renders+ * still faces the reviewer's identity gate before it places. */+export function buildShotAttempts(a: ShotAttemptArgs): VideoAttempt[] {+ const hasCast = a.refs.some((r) => r.purpose === "character");+ const imageAnchored = Boolean(a.keyframe) || a.anchors.length > 0;+ return [+ // 1. The keyframe as the literal first frame. It was rendered from the+ // cast's reference images, so it carries identity, wardrobe, setting,+ // and framing in one anchor — the strongest continuity there is. The+ // prompt adds one clause AGREEING with those pixels: without it a model+ // can re-render the scene in its own medium (3D CGI from a hand-drawn+ // frame) instead of animating the artwork it was given.+ ...(a.keyframe+ ? [{+ prompt: `${a.prompt} The video continues this exact opening frame — keep its artwork, medium, and rendering technique unchanged.`,+ opts: {+ ...a.base,+ refs: [a.keyframe],+ composeRefs: false as const,+ },+ }]+ : []),+ // 2. Reference-to-video on the cast sheets themselves — identity holds,+ // composition is the model's again; cast beyond the reference cap is+ // described in the prompt instead.+ ...(a.anchors.length > 0+ ? [{+ prompt: describeUnanchored(a.prompt, a.refs, a.ridingIds),+ opts: {+ ...a.base,+ referenceImages: a.anchors,+ },+ }]+ : []),+ // 3. Text-only — the full written identity of every cast member rides the+ // prompt. For cast shots this rung runs only when the provider refused+ // the image anchor itself.+ {+ prompt: describeUnanchored(a.prompt, a.refs, new Set()),+ opts: { ...a.base },+ ...(hasCast && imageAnchored ? { gate: anchorRefused } : {}),+ },+ ];+}diff --git a/site/src/cut/lib/genvideo/types.ts b/site/src/cut/lib/genvideo/types.tsindex 7eb27907..4e65fa43 100644--- a/site/src/cut/lib/genvideo/types.ts+++ b/site/src/cut/lib/genvideo/types.ts@@ -25,6 +25,9 @@ export interface RefAsset {/** What this reference anchors — identity, place, look, or motion. */purpose?: "character" | "location" | "style" | "motion";name?: string;+ /** The bible's written identity, carried so a render this image can't ride+ * on (a ladder rung without it) can fold the same words into its prompt. */+ description?: string;}/** One beat of a generated script — a shot's worth of screen time. */@@ -79,7 +82,6 @@ export interface Shot {location: string; // location asset id ("" = unspecified)framing: string;startKeyframe?: string; // media asset id- endKeyframe?: string; // media asset id/** The beat voiceover this shot lip-syncs to (generated mode). The voice is* placed once per beat; a shot spans a slice of it (voiceFromSec..voiceToSec,* relative to the beat start), so a line longer than one clip is never cut. */@@ -139,6 +141,10 @@ export interface VideoProject {aspect?: "9:16" | "16:9";/** Reusable style string every downstream prompt carries. */style: string;+ /** The look's negative — what must never appear in a render (the wrong+ * medium's tells), minted with the style bible and sent as the video+ * model's negative prompt. */+ negative?: string;/** The suite label the run was produced with (for provenance and evals). */suiteLabel: string;/** The chat thread that owns this run's media, so every asset it creates is@@ -184,6 +190,9 @@ export type VideoEvent =| { type: "breakdown"; shots: Shot[] }| { type: "progress"; placed: number; total: number }| { type: "log"; message: string }+ /** A media asset the run just made (a sheet, a frame, a take) — the chat+ * card lists these chronologically with a thumbnail. */+ | { type: "asset"; label: string; mediaId: string }/** The live ticker: one line on what the run is doing right now. */| { type: "activity"; message: string }| { type: "error"; message: string };diff --git a/site/src/cut/server/serveFile.ts b/site/src/cut/server/serveFile.tsindex b7d58f20..7634f200 100644--- a/site/src/cut/server/serveFile.ts+++ b/site/src/cut/server/serveFile.ts@@ -15,6 +15,13 @@ const TYPES: Record<string, string> = {".wav": "audio/wav",".ogg": "audio/ogg",".flac": "audio/flac",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".webp": "image/webp",+ ".gif": "image/gif",+ ".avif": "image/avif",+ ".heic": "image/heic",};export function contentTypeFor(p: string) {