Open source CapCut alternative.
TypeScript
feat(site): brief-to-video generation live in Cut [rebuild]
David Le75dc1343dc3a
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.mdindex 167de29e..f95f8e2b 100644--- a/docs/guides/cut/ai-assistant.md+++ b/docs/guides/cut/ai-assistant.md@@ -38,7 +38,7 @@ Every knowledge surface is defined once — the catalog file ships in the engine| Surface | Size today | When it enters context || --- | --- | --- || System prompt | ~3.1K chars (~750 tokens) | Claude: replaces the Agent SDK default. Codex: prepended to the first turn (a resumed session already has it). Gemini: the instructions field, every round. |-| Tool catalog (51 tools) | ~32K chars (~8K tokens) | Claude/Codex: the MCP tool listing. Gemini: function declarations on each request. |+| Tool catalog (55 tools) | ~35K chars (~8.7K tokens) | Claude/Codex: the MCP tool listing. Gemini: function declarations on each request. || Skills library (8 docs) | ~16.5K chars (~4K tokens) total | On demand only, via the list-skills and read-skill tools. || Editor snapshot | Grows with the project; media list and subtitle cues capped at 60 each | Attached to the newest user message as `<editor_state>`, rebuilt fresh every turn. || Attachments | Metadata JSON per asset | `<attached_assets>` on the message that carried them; on the Gemini path the newest message also carries the actual payloads (frames, images, text contents). |@@ -72,6 +72,12 @@ Tool calls execute in the open tab against the same store the user is editing- **Chat owns what it makes.** Media created by chat tools is tagged with its thread and previews on a card in the conversation. Placing it on the timeline or filing it into Media or the Library transfers ownership; deleting the thread deletes whatever it still owns.- **Two tools stay server-side.** The skill list and skill reads are answered by the engine directly — no browser hop.+## Generating a whole video++Most generation tools make one asset. `generate_scene` makes a whole cut: it writes a script, voices it, breaks it into shots, and — once the user approves — renders each shot and lays them on the timeline under the narration. It is genre-agnostic; the look comes from the brief and any references. It can also animate audio the project already has (`from_audio_asset_id`), tiling shots over that spine instead of writing a script.++Because a scene renders many paid shots, the tool plans and then stops. `generate_scene` returns a shot list and waits; `approve_scene` starts the renders; `regenerate_shot` and `restyle_scene` revise afterward. The plan the user approves is the plan that renders: voicing runs after the gate and only rescales the approved shots to the real voice lengths (a line longer than one clip splits its shot). The run is browser-side like every generation here, held in a small store beside the panels (`lib/genScene.ts`) so switching tabs never orphans it; leaving the project pauses it, its persisted plan (`ProjectDoc.genvideo`) resumes on the next open, and dismissing an unrendered plan clears it. Progress shows on a card in the chat while the timeline fills on its own. The shots ride under one consistent AI voice with the video model's own audio off; this version has no talking-head lip-sync.+## Context across turnsThreads persist per project in the browser's local storage — the newest 30, titled by their first message. What a returning thread remembers depends on the provider:@@ -102,3 +108,5 @@ A hidden hermetic test provider exercises the full engine bridge — context, to## Where it livesThe shared catalog (system prompt, tools, skills), the chat route with its provider runners, the browser-tool bridge, and the stdio MCP proxy live with the engine's AI code under the site's Cut folder (`server/ai/`, `server/http/ai.ts`). The page side holds the snapshot builder (`lib/aiContext.ts`), the tool implementations (`lib/aiTools.ts`), the Gemini loop (`lib/geminiChat.ts`), the model catalog (`lib/aiModels.ts`), and the chat panel with threads and transport (`components/AiPanel.tsx`).++The brief-to-video pipeline is its own subsystem: the orchestrator, coverage invariant, and role interfaces in `lib/genvideo/`, its hosted-model adapters in `lib/genvideo/adapters/`, the browser controller in `lib/genScene.ts`, and the progress card in `components/SceneCard.tsx`.diff --git a/site/scripts/genvideo-selftest.ts b/site/scripts/genvideo-selftest.tsindex a7342398..a33c2458 100644--- a/site/scripts/genvideo-selftest.ts+++ b/site/scripts/genvideo-selftest.ts@@ -8,6 +8,7 @@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";@@ -172,9 +173,14 @@ async function run(): Promise<void> {const orch = new VideoOrchestrator(project, d);await orch.run();check("wrote a script from the brief", !!project.script && project.script.beats.length > 0);- check("every shot has a spoken line", project.shots.every((s) => !!s.dialogue && !!s.voiceAssetId));+ check("every shot has a spoken line", project.shots.every((s) => !!s.dialogue));+ // The plan is laid out on estimated lengths; no TTS runs (spends) until the+ // user approves. voiceAssetId lands only after the gate.+ check("no voice spent before approval", studio.calls.every((c) => c.role !== "voice"));+ check("shots not yet voiced at the gate", project.shots.every((s) => !s.voiceAssetId));await orch.approveBreakdown();check("run reaches done", project.phase === "done");+ check("every shot voiced after approval", project.shots.every((s) => !!s.voiceAssetId));assertTiling("placed clips tile the generated spine", editor.placed, project.durationFrames);check("one voiceover placed per beat", editor.placedAudio.filter((a) => a.kind === "voice").length === (project.beatVoices?.length ?? -1));check("a single music bed spans the whole video", editor.placedAudio.filter((a) => a.kind === "music").length === 1);@@ -251,7 +257,10 @@ async function run(): Promise<void> {const project = generatedProject();const orch = new VideoOrchestrator(project, d);await orch.run();- project.shots[1].action = `${FAIL} broken`; // this shot will fall back to a still+ // Doom a shot at the gate: the voiced rescale preserves the approved shots+ // (only their frame boundaries move), so a gate-time shot edit survives to+ // the render — exactly the plan-integrity invariant the gate promises.+ project.shots[1].action = `${FAIL} broken`; // it falls back to a stillawait orch.approveBreakdown();const failed = project.shots.find((s) => s.status === "failed")!;check("interrupted shot holds a fallback still", !!failed && !!failed.timelineClipId);@@ -330,6 +339,25 @@ async function run(): Promise<void> {}}+ // ── fillSlot — a placed shot fills its exact slot (editor-boundary tiling) ─+ section("fillSlot — generated clips tile the timeline with no gap");+ {+ const foot = (r: { out: number; speed?: number }) => r.out / (r.speed ?? 1);+ const near = (a: number, b: number) => Math.abs(a - b) < 1e-6;+ check(+ "image takes the whole slot",+ near(foot(fillSlot("image", 0, 6, 0.25)), 6) && fillSlot("image", 0, 6, 0.25).speed === undefined+ );+ check("longer video trims to the slot", near(foot(fillSlot("video", 8, 6, 0.25)), 6));+ check("shorter video stretches to fill", near(foot(fillSlot("video", 4, 6, 0.25)), 6));+ check(+ "exact video needs no speed change",+ near(foot(fillSlot("video", 6, 6, 0.25)), 6) && fillSlot("video", 6, 6, 0.25).speed === undefined+ );+ const subFloor = fillSlot("video", 1, 6, 0.25);+ check("sub-floor video clamps speed (small gap over a crawl)", subFloor.speed === 0.25 && foot(subFloor) < 6);+ }+console.log(`\n${failures === 0 ? "✓ ALL PASS" : `✗ ${failures} FAILED`}`);if (failures > 0) process.exit(1);}diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 8a9ba67d..57b936e9 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -57,6 +57,7 @@ import { signInUrl, useSignedIn } from "@/cut/lib/generate";import { streamGeminiChat } from "@/cut/lib/geminiChat";import { AI_MODELS } from "@/cut/lib/aiModels";import { saveAssetToLibrary } from "@/cut/lib/library";+import { formatDuration, useGenScene } from "@/cut/lib/genScene";import { lightboxItemFromRef, useLightbox } from "@/cut/lib/lightbox";import { refsFromDroppedFiles } from "@/cut/lib/refMedia";import { revealRef } from "@/cut/lib/refReveal";@@ -351,6 +352,10 @@ function ChatSession({// Any OS file drag over the window hints the composer as a drop target;// hovering it (dropActive below) strengthens the ring and shows the label.const fileDropHint = useEditor((s) => s.dropActive !== null);+ // A resumed run can pin the scene card with no chat messages behind it — the+ // empty-state intro/suggestions must yield to it so the two don't stack.+ const sceneProjectId = useEditor((s) => s.projectId);+ const hasSceneRun = useGenScene((s) => !!s.run && s.run.projectId === sceneProjectId);const { active: dropActive, attachTarget, targetProps } = useAssetDrop((ref) => setAttachments((prev) => addRefOnce(prev, ref)),// OS files dropped on the chat attach as references (media files import@@ -531,7 +536,7 @@ function ChatSession({className="relative flex min-h-0 flex-1 flex-col"><div ref={scrollRef} className="ai-messages min-h-0 flex-1 overflow-y-auto px-3.5 py-3">- {messages.length === 0 && (+ {messages.length === 0 && !hasSceneRun && (<div className="flex flex-col gap-3 pt-6"><p className="text-[12.5px] leading-relaxed text-muted-foreground">I can see your whole project — clips, titles, subtitles, publish@@ -798,6 +803,32 @@ function MessageCopy({ text }: { text: string }) {/** Memoized per message: a streaming turn replaces `messages` every chunk,* and only the growing message should re-render — settled ones hold whole* asset-card subtrees. */+// How long each tool call ran, tracked across this session's renders (keyed by+// tool-call id). We stamp the start the first time a call renders while still+// running and the end when it settles, so the chip can show its duration.+const toolTimes = new Map<string, { start: number; end?: number; sawRunning: boolean }>();+// The map lives for the page; long sessions evict the oldest settled entries+// (their chips have already captured the duration they show).+const TOOL_TIMES_CAP = 500;+function toolDuration(id: string | undefined, settled: boolean): string | null {+ if (!id) return null;+ let t = toolTimes.get(id);+ if (!t) {+ if (toolTimes.size >= TOOL_TIMES_CAP) {+ for (const key of toolTimes.keys()) {+ if (toolTimes.size < TOOL_TIMES_CAP) break;+ if (toolTimes.get(key)?.end !== undefined) toolTimes.delete(key);+ }+ }+ t = { start: Date.now(), sawRunning: !settled };+ toolTimes.set(id, t);+ }+ if (settled && t.end === undefined) t.end = Date.now();+ // Null for a call first seen already-done (e.g. loaded on reload): its real+ // start is unknown, so a "0:00" would lie.+ return t.sawRunning && t.end !== undefined ? formatDuration(t.end - t.start) : null;+}+const MessageView = memo(function MessageView({ message }: { message: UIMessage }) {if (message.role === "user") {const text = message.parts.map((p) => (p.type === "text" ? p.text : "")).join("");@@ -848,6 +879,7 @@ const MessageView = memo(function MessageView({ message }: { message: UIMessageconst p = part as unknown as {type: string;toolName?: string;+ toolCallId?: string;state: string;input?: unknown;output?: unknown;@@ -856,6 +888,7 @@ const MessageView = memo(function MessageView({ message }: { message: UIMessageconst name = p.toolName ?? part.type.slice(5);const failed = p.state === "output-error";const done = p.state === "output-available";+ const took = toolDuration(p.toolCallId, done || failed);return (<Fragment key={i}><details className="ai-tool group max-w-full">@@ -870,6 +903,7 @@ const MessageView = memo(function MessageView({ message }: { message: UIMessage{done && <Check className="size-3 text-emerald-600" />}{failed && <TriangleAlert className="size-3" />}{!done && !failed && <CircleDashed className="size-3 animate-spin" />}+ {took && <span className="ml-auto tabular-nums text-[10px]">{took}</span>}</summary><pre className="mt-1 max-h-40 overflow-auto rounded-md bg-muted/70 p-2 font-mono text-[10px] leading-relaxed whitespace-pre-wrap">{JSON.stringify({ input: p.input, output: p.output, error: p.errorText }, null, 2)}diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 1f3c6a0b..f4c18e21 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -188,6 +188,7 @@ export function Editor({s.notes.text !== last.notes?.text ||s.notes.publishedAt !== last.notes?.publishedAt ||s.notes.links.join("") !== (last.notes?.links ?? []).join("") ||+ s.genvideo !== (last.genvideo as unknown) ||s.projectName !== lastName;if (!changed) return;last = serializeDoc(s);diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsxindex fc317c43..997ebc49 100644--- a/site/src/cut/components/GeneratePanel.tsx+++ b/site/src/cut/components/GeneratePanel.tsx@@ -57,7 +57,8 @@ const segButton = (active: boolean) =>export function GenerateVideoPanel({ projectId }: { projectId: string }) {const signedIn = useSignedIn();const allJobs = useGenerate((s) => s.jobs);- const jobs = allJobs.filter((j) => j.projectId === projectId && j.kind === "video");+ // Panel renders only — a chat- or scene-owned job lives on its chat card.+ const jobs = allJobs.filter((j) => j.projectId === projectId && j.kind === "video" && !j.chatId);const { prompt, refs, character, aspect, resolution } = useVideoGen();const candidates = useRefCandidates();const { active: dropActive, attachTarget, targetProps } = useAssetDrop(diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxindex 2fc4aa38..385367d5 100644--- a/site/src/cut/components/ImageGenPanel.tsx+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -59,7 +59,8 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {const signedIn = useSignedIn();const candidates = useRefCandidates();const allJobs = useGenerate((s) => s.jobs);- const jobs = allJobs.filter((j) => j.kind === "image" && j.projectId === projectId);+ // Panel renders only — a chat- or scene-owned job lives on its chat card.+ const jobs = allJobs.filter((j) => j.kind === "image" && j.projectId === projectId && !j.chatId);// Select the stable `assets` reference and derive here: filtering inside the// selector returns a fresh array every store write (including usePlayback's// per-frame ticks) and would re-render the panel constantly. Newest first.diff --git a/site/src/cut/components/SceneCard.tsx b/site/src/cut/components/SceneCard.tsxnew file mode 100644index 00000000..b2193573--- /dev/null+++ b/site/src/cut/components/SceneCard.tsx@@ -0,0 +1,234 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Check, ChevronRight, CircleDashed, Clapperboard, TriangleAlert, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { formatDuration, useGenScene, type SceneRun } from "../lib/genScene";+import { GEN_FPS } from "../lib/genvideo/editorBridge";+import { useEditor } from "../lib/store";+import type { Shot, ShotStatus } from "../lib/genvideo/types";++// The brief-to-video progress card, pinned into the chat while a "generate a+// video" run is planning, waiting for approval, or rendering. The timeline fills+// on its own via the editor bridge; this is the control surface — approve the+// plan, watch shots land, redo one by clicking its chip.++const STATUS_LABEL: Record<SceneRun["status"], string> = {+ planning: "Planning",+ awaiting_approval: "Ready to render",+ generating: "Rendering",+ done: "Done",+ failed: "Failed",+};++/** Badge color by shot state: green when placed, amber when it fell back to a+ * still, blue while in flight, muted while pending. */+function shotTone(status: ShotStatus): string {+ if (status === "placed") return "border-emerald-500/30 bg-emerald-500/15 text-emerald-600";+ if (status === "failed") return "border-amber-500/30 bg-amber-500/15 text-amber-600";+ if (status === "pending") return "border-border bg-muted text-muted-foreground";+ return "border-[#0a84ff]/30 bg-[#0a84ff]/12 text-[#0a84ff]";+}++/** mm:ss for a frame count at the plan's fixed rate. */+function fmt(frames: number): string {+ return formatDuration((frames / GEN_FPS) * 1000);+}++/** The one line a plan row shows — what's on screen, else the spoken line. */+function describe(sh: Shot): string {+ return sh.action?.trim() || sh.dialogue?.trim() || sh.audioText?.trim() || "—";+}++export function SceneCard() {+ const run = useGenScene((s) => s.run);+ const projectId = useEditor((s) => s.projectId);+ const genvideo = useEditor((s) => s.genvideo);+ const loaded = useEditor((s) => s.loaded);+ const hydrated = useRef<string | null>(null);+ const [open, setOpen] = useState(true);++ // Resume a persisted run once a project has finished loading. Waiting for+ // `loaded` matters: loadProject sets projectId synchronously with+ // genvideo=undefined and fills genvideo only after the fetch, so running this+ // before load would mark the project hydrated while genvideo is still empty+ // and never resume the persisted run.+ useEffect(() => {+ if (!projectId || !loaded || hydrated.current === projectId) return;+ const cur = useGenScene.getState().run;+ if (cur && cur.projectId === projectId) {+ hydrated.current = projectId;+ return;+ }+ if (genvideo) useGenScene.getState().hydrate(projectId, genvideo);+ hydrated.current = projectId;+ }, [projectId, loaded, genvideo]);++ // The elapsed clock's "now", advanced once a second while the run works.+ // Held in state — Date.now() in render is impure — and set only from the+ // interval, so the first second shows 0:00 and a settled card renders from+ // its stamped times (a stale value clamps to zero, never shows).+ const [now, setNow] = useState<number | null>(null);+ const working = run?.status === "planning" || run?.status === "generating";+ useEffect(() => {+ if (!working) return;+ const t = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(t);+ }, [working]);++ if (!run || run.projectId !== projectId) return null;++ const inFlight = run.status === "planning" || run.status === "generating";+ const canDismiss =+ run.status === "awaiting_approval" || run.status === "done" || run.status === "failed";+ const pct = run.total ? Math.round((run.placed / run.total) * 100) : 0;+ const showProgress = run.status === "generating" || run.status === "done";+ const totalFrames = run.shots.length ? Math.max(...run.shots.map((sh) => sh.endFrame)) : 0;+ // Shots that couldn't be rendered as video and are holding a still instead.+ const stillCount = run.shots.filter((sh) => sh.status === "failed").length;+ // Elapsed clock: planning counts from the run start, rendering from approval;+ // it stops at the end. Hidden while waiting for the user at the gate.+ const clockAnchor = run.status === "planning" ? run.startedAt : run.renderStartedAt ?? run.startedAt;+ const clockEnd = inFlight ? now ?? run.startedAt : run.endedAt ?? run.startedAt;+ const elapsed = run.status === "awaiting_approval" ? null : formatDuration(clockEnd - clockAnchor);++ return (+ <div className="ai-scene-card mt-2 rounded-xl border border-border bg-card/60 p-3 text-[11.5px]">+ <div className="flex items-center gap-1.5">+ <Clapperboard className="size-3.5 text-[#0a84ff]" />+ <span className="font-semibold">Generate video</span>+ <span className="ml-auto flex items-center gap-1 text-[10.5px] text-muted-foreground">+ {inFlight && <CircleDashed className="size-3 animate-spin" />}+ {STATUS_LABEL[run.status]}+ {elapsed && <span className="tabular-nums">· {elapsed}</span>}+ </span>+ </div>++ <p className="mt-1 line-clamp-2 text-muted-foreground">{run.title}</p>++ {run.status === "planning" && (+ <p className="mt-2 text-muted-foreground">Writing the script and planning shots…</p>+ )}++ {run.shots.length > 0 && (+ <div className="mt-2">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="flex w-full items-center gap-1.5 py-0.5 text-left text-muted-foreground hover:text-foreground"+ >+ <ChevronRight+ className={`size-3 shrink-0 transition-transform ${open ? "rotate-90" : ""}`}+ />+ <span className="font-medium text-foreground">Plan</span>+ <span>+ {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} · {fmt(totalFrames)}+ </span>+ {showProgress && (+ <span className="ml-auto tabular-nums text-[10.5px]">+ {run.placed}/{run.total} placed+ </span>+ )}+ </button>++ {open && (+ <ol className="mt-1 flex flex-col gap-2">+ {run.shots.map((sh, i) => {+ // Redoable only once done — a click before then would render (and+ // bill) a shot the user never approved.+ const redoable = run.status === "done";+ return (+ <li key={sh.id}>+ <button+ type="button"+ disabled={!redoable}+ onClick={() => useGenScene.getState().regenerateShot(i + 1)}+ title={redoable ? "Click to redo this shot" : `Shot ${i + 1} — ${sh.status}`}+ className={`flex w-full items-start gap-2 rounded-md py-0.5 text-left transition-colors ${+ redoable ? "cursor-pointer hover:bg-muted/40" : "cursor-default"+ }`}+ >+ <span+ className={`mt-px grid size-4 shrink-0 place-items-center rounded-full text-[9.5px] font-medium ${shotTone(+ sh.status+ )}`}+ >+ {sh.status === "placed" ? <Check className="size-2.5" /> : i + 1}+ </span>+ <span className="min-w-0 flex-1">+ <span className="mr-1.5 tabular-nums text-muted-foreground">+ {fmt(sh.startFrame)}–{fmt(sh.endFrame)}+ </span>+ <span className="text-foreground/90">{describe(sh)}</span>+ {sh.status === "failed" && (+ <span className="mt-0.5 block text-[10px] text-amber-700">+ Couldn't animate — showing a still+ {sh.error ? `: ${sh.error}` : ""}+ {redoable ? ". Click to retry." : ""}+ </span>+ )}+ </span>+ </button>+ </li>+ );+ })}+ </ol>+ )}+ </div>+ )}++ {run.status === "generating" && (+ <div className="mt-2 h-1 overflow-hidden rounded-full bg-muted">+ <div+ className="h-full rounded-full bg-[#0a84ff] transition-all duration-500"+ style={{ width: `${pct}%` }}+ />+ </div>+ )}++ {run.error && (+ <p className="mt-2 flex items-start gap-1.5 text-amber-700">+ <TriangleAlert className="mt-px size-3 shrink-0" />+ {run.error}+ </p>+ )}++ {canDismiss && (+ <div className="mt-2.5 flex items-center gap-1.5">+ {run.status === "awaiting_approval" && (+ <Button+ size="sm"+ className="h-7 flex-1 text-[11.5px]"+ onClick={() => useGenScene.getState().approve()}+ >+ Approve & render{run.shots.length ? ` (${run.shots.length})` : ""}+ </Button>+ )}+ {run.status === "done" && stillCount === 0 && (+ <span className="flex flex-1 items-center gap-1 text-emerald-600">+ <Check className="size-3.5" /> Video ready+ </span>+ )}+ {run.status === "done" && stillCount > 0 && (+ <span className="flex flex-1 items-start gap-1 text-[10.5px] text-amber-700">+ <TriangleAlert className="mt-px size-3 shrink-0" />+ {stillCount} of {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} held a+ still — video generation failed. Click a shot to retry.+ </span>+ )}+ {canDismiss && (+ <Button+ size="sm"+ variant="ghost"+ className="h-7 text-muted-foreground"+ title="Dismiss"+ onClick={() => useGenScene.getState().dismiss()}+ >+ <X className="size-3.5" />+ </Button>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex a709f0e1..a9290895 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -4,6 +4,7 @@ import { apiFetch, apiJson } from "./api";import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";import { chatOwner, tagChatAsset } from "./chatAssets";import { useGenerate, type VideoGenOptions } from "./generate";+import { useGenScene } from "./genScene";import {addTemplateToProject,createLibraryFolder,@@ -36,8 +37,7 @@ import {mediaUrl,rectOf,regionLabel,- SPEED_MAX,- SPEED_MIN,+ SPEED_FLOOR,TRANSITION_STYLE_IDS,type AudioClip,type FontId,@@ -370,7 +370,7 @@ export async function runAiTool(patch.frame = { x: clamp(rg.x, 0, 1 - w), y: clamp(rg.y, 0, 1 - h), w, h };}if (input.fit === "fit" || input.fit === "fill") patch.fit = input.fit;- if (isNum(input.speed)) patch.speed = clamp(input.speed, SPEED_MIN, SPEED_MAX);+ if (isNum(input.speed)) patch.speed = Math.max(SPEED_FLOOR, input.speed);if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");s.updateOverlayClip(c.id, patch);const next = useEditor.getState().clips.find((x) => x.id === c.id)!;@@ -548,7 +548,9 @@ export async function runAiTool(const refs = resolveRefAssets(input.reference_asset_ids);// Captured before the render: the image files under the chat that- // asked, even if the user switches threads while it generates.+ // asked, even if the user switches threads while it generates. Ownership+ // rides the job from creation, so neither the job row nor the landed+ // asset ever touches the Image panel.const chatId = chatOwner();// Hosted image generation is synchronous and quick, so wait it out.const job = await useGenerate.getState().generateImage(projectId, prompt, {@@ -559,6 +561,7 @@ export async function runAiTool(? { resolution: input.resolution }: {}),...(refs.length > 0 ? { refs } : {}),+ ...(chatId ? { chatId } : {}),});if (job.status !== "done" || !job.assetId) {throw new ToolError(job.error ?? "Image generation failed.");@@ -566,7 +569,6 @@ export async function runAiTool(const cur = useEditor.getState();const asset = cur.assets.find((a) => a.id === job.assetId);if (!asset) throw new ToolError("The generated image did not land in the project.");- tagChatAsset(asset.id, chatId);const placed = wantsTimeline(input, "index")? addVideoTrackClip(asset.id, promptedIndex(input)): NOT_PLACED;@@ -641,6 +643,73 @@ export async function runAiTool(};}+ case "generate_scene": {+ const projectId = s.projectId;+ if (!projectId) throw new ToolError("No project open.");+ const gen = useGenerate.getState();+ const signedIn = gen.signedIn ?? (await gen.probeNow());+ if (!signedIn) throw new ToolError("Sign in to Donkey to generate a video.");+ const brief = String(input.brief ?? "").trim();+ const fromAudio =+ input.from_audio_asset_id !== undefined ? String(input.from_audio_asset_id) : undefined;+ if (!brief && !fromAudio)+ throw new ToolError("A brief is required (or from_audio_asset_id to animate existing audio).");+ if (fromAudio) {+ const asset = s.assets.find((a) => a.id === fromAudio);+ const audio = s.assets.filter((a) => a.type === "audio");+ const hint = audio.length+ ? ` The project's audio: ${audio.map((a) => `${a.id} ("${a.name}")`).join(", ")}.`+ : " This project has no audio asset — omit from_audio_asset_id to write a fresh narration instead.";+ if (!asset) throw new ToolError(`No project asset with id ${fromAudio}.${hint}`);+ if (asset.type !== "audio")+ throw new ToolError(`"${asset.name}" is ${asset.type}, not audio — from_audio_asset_id must be the audio to animate.${hint}`);+ }+ // Plan up to the shot list and stop; approve_scene starts the paid renders.+ // Tag every asset the run creates to the asking chat, so intermediates and+ // shots stay off the Media/Video/Image/Audio panels.+ const res = await useGenScene.getState().start(projectId, {+ chatId: chatOwner(),+ ...(brief ? { brief } : {}),+ ...(fromAudio ? { fromAudioAssetId: fromAudio } : {}),+ ...(isNum(input.target_seconds)+ ? { targetSeconds: clamp(Math.round(input.target_seconds), 6, 90) }+ : {}),+ ...(input.aspect === "16:9" || input.aspect === "9:16" ? { aspect: input.aspect } : {}),+ ...(typeof input.style === "string" && input.style.trim() ? { style: input.style.trim() } : {}),+ ...(Array.isArray(input.reference_asset_ids)+ ? { referenceAssetIds: input.reference_asset_ids.map(String) }+ : {}),+ });+ if (!res.started) throw new ToolError(res.message);+ return {+ planned: true,+ shots: res.shotCount,+ note: `${res.message} A plan card below lists the shots for the user, so keep your reply to one short line — don't re-describe the shots or the timing. Just ask them to confirm; when they do, call approve_scene (each shot spends credits, so don't approve on your own).`,+ };+ }++ case "approve_scene": {+ const res = useGenScene.getState().approve();+ if (!res.ok) throw new ToolError(res.message);+ return { rendering: true, note: res.message };+ }++ case "regenerate_shot": {+ if (!isNum(input.n)) throw new ToolError("n (the 1-based shot number) is required.");+ const note = typeof input.note === "string" && input.note.trim() ? input.note.trim() : undefined;+ const res = useGenScene.getState().regenerateShot(Math.round(input.n), note);+ if (!res.ok) throw new ToolError(res.message);+ return { note: res.message };+ }++ case "restyle_scene": {+ const style = String(input.style ?? "").trim();+ if (!style) throw new ToolError("style is required — the new look for the whole video.");+ const res = useGenScene.getState().restyle(style);+ if (!res.ok) throw new ToolError(res.message);+ return { note: res.message };+ }+case "stock_search": {const q = String(input.query ?? "").trim().toLowerCase();const kindIn =@@ -1144,7 +1213,7 @@ export async function runAiTool(case "set_speed": {const clip = requireItem(s.clips, input.clipId, "video clip");- if (!isNum(input.speed)) throw new ToolError("speed is required (0.25–4).");+ if (!isNum(input.speed)) throw new ToolError("speed is required (e.g. 1.5).");s.setClipSpeed(clip.id, input.speed);const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;return { id: next.id, speed: next.speed ?? 1 };@@ -1493,12 +1562,14 @@ function launchVeoJob(const addToTimeline = wantsTimeline(input, "index");const index = promptedIndex(input);// Captured now: the render must file under the chat that asked, even if- // the user switches threads before it lands.+ // the user switches threads before it lands. Ownership rides the job from+ // creation, so neither the job row nor the landed asset ever touches the+ // Video panel — including a render that errors and lands no asset.const chatId = chatOwner();const { jobId } = useGenerate.getState().generateVideo(projectId, prompt, {...opts,+ ...(chatId ? { chatId } : {}),onDone: (asset) => {- tagChatAsset(asset.id, chatId);if (addToTimeline) addVideoTrackClip(asset.id, index);},});@@ -1511,7 +1582,7 @@ function launchVeoJob("Rendering with Veo — it previews in this chat when it lands, in a minute or two" +(addToTimeline? ", and goes onto the timeline."- : ". It stays in the chat (and the Video panel's renders) until the user places it."),+ : ". It stays in the chat until the user places it."),};}diff --git a/site/src/cut/lib/bytes.ts b/site/src/cut/lib/bytes.tsnew file mode 100644index 00000000..3de50f17--- /dev/null+++ b/site/src/cut/lib/bytes.ts@@ -0,0 +1,8 @@+/** Decode a base64 string to raw bytes. Shared by the media generators (image,+ * video, speech, music) that receive provider payloads inline as base64. */+export function bytesFromBase64(b64: string): Uint8Array<ArrayBuffer> {+ const bin = atob(b64);+ const bytes = new Uint8Array(new ArrayBuffer(bin.length));+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ return bytes;+}diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsnew file mode 100644index 00000000..867548b9--- /dev/null+++ b/site/src/cut/lib/genScene.ts@@ -0,0 +1,482 @@+"use client";++import { create } from "zustand";+import { useGenerate } from "./generate";+import { realSuite } from "./genvideo/adapters";+import { GEN_FPS, StoreEditorBridge } from "./genvideo/editorBridge";+import { VideoOrchestrator } from "./genvideo/orchestrator";+import type { RefAsset, Shot, VideoEvent, VideoPhase, VideoProject } from "./genvideo/types";+import { useEditor } from "./store";+import type { Aspect } from "./types";++// Brief-to-video ("generate a video") controller. It owns one VideoOrchestrator+// per open project and runs it browser-side, exactly where generation and the+// editor store live. The orchestrator plans up to the shot breakdown and stops+// (the confirmation gate); the user approves, then the shots render and land on+// the timeline live. State persists on ProjectDoc.genvideo, so a reload resumes+// a run in flight.+//+// Held outside the panels (like useGenerate) so switching tabs never orphans a+// multi-minute render.++export type SceneStatus = "planning" | "awaiting_approval" | "generating" | "done" | "failed";++export interface SceneRun {+ projectId: string;+ mode: "generated" | "provided";+ /** What the run is about, for the card heading. */+ title: string;+ status: SceneStatus;+ phase: VideoPhase;+ shots: Shot[];+ placed: number;+ total: number;+ logs: string[];+ error?: string;+ /** When the run began (planning), for the elapsed clock. */+ startedAt: number;+ /** When rendering began (approval) — the render timer counts from here, not+ * from the idle time spent at the confirmation gate. */+ renderStartedAt?: number;+ /** When the run reached done/failed, freezing the elapsed clock. */+ endedAt?: number;+}++/** M:SS for an elapsed millisecond span. */+export function formatDuration(ms: number): string {+ const t = Math.max(0, Math.floor(ms / 1000));+ return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;+}++export interface StartSceneParams {+ brief?: string;+ fromAudioAssetId?: string;+ targetSeconds?: number;+ aspect?: Aspect;+ style?: string;+ referenceAssetIds?: string[];+ /** The chat thread that asked, so the run's media is tagged to it and stays+ * off the Media/Video/Image/Audio panels. */+ chatId?: string | null;+}++// One live orchestrator at a time (per open project). Kept out of zustand state+// so its identity churn never triggers a render; the reactive `run` mirror is.+let orchestrator: VideoOrchestrator | null = null;+/** The project the live orchestrator belongs to, for the project-switch pause. */+let orchestratorProjectId: string | null = null;++// A run pauses the moment its project stops being open: nothing may render or+// spend against a project the user has left. The persisted plan resumes via+// hydrate when the project reopens.+useEditor.subscribe((s, prev) => {+ if (s.projectId !== prev.projectId && orchestrator && orchestratorProjectId !== s.projectId) {+ orchestrator.abort();+ }+});++const LOG_CAP = 24;+const CONCURRENCY = 3; // gentle on the video model's rate limit++const uid = () => crypto.randomUUID().slice(0, 8);+const isTerminal = (s: SceneStatus) => s === "done" || s === "failed";++/** Build a persistable RefAsset list from project asset ids the user pointed at.+ * Tagged "style" so they anchor both the reference images and every shot. */+function toReferences(ids: string[] | undefined): RefAsset[] {+ if (!ids?.length) return [];+ const assets = useEditor.getState().assets;+ const out: RefAsset[] = [];+ for (const id of ids) {+ const a = assets.find((x) => x.id === id);+ if (a) out.push({ mediaId: a.id, kind: a.type, purpose: "style", name: a.name });+ }+ return out;+}++function newProject(projectId: string, params: StartSceneParams): VideoProject {+ const audio = params.fromAudioAssetId+ ? useEditor.getState().assets.find((a) => a.id === params.fromAudioAssetId && a.type === "audio")+ : undefined;+ const mode: "generated" | "provided" = audio ? "provided" : "generated";+ return {+ id: `scene-${uid()}`,+ brief: params.brief?.trim() ?? "",+ references: toReferences(params.referenceAssetIds),+ audioMode: mode,+ ...(audio ? { audioAssetId: audio.id } : {}),+ ...(params.targetSeconds ? { targetSeconds: params.targetSeconds } : {}),+ fps: GEN_FPS,+ durationFrames: audio ? Math.round(audio.duration * GEN_FPS) : 0,+ transcript: [],+ // The plan owns its shape from the start (start() applies params.aspect to+ // an empty timeline before this runs), so a background render can never+ // pick up another open project's aspect.+ aspect: useEditor.getState().aspect,+ style: params.style?.trim() ?? "",+ suiteLabel: "donkey-hosted",+ ...(params.chatId ? { chatId: params.chatId } : {}),+ characters: [],+ locations: [],+ shots: [],+ phase: mode === "generated" ? "brief" : "ingest",+ breakdownApproved: false,+ createdAt: Date.now(),+ updatedAt: 0,+ };+}++/** The run's placed timeline clip ids (video track + soundtrack). */+function runClipIds(project: VideoProject): { clipIds: string[]; audioIds: string[] } {+ const clipIds = project.shots.map((s) => s.timelineClipId).filter((x): x is string => !!x);+ const audioIds = [+ ...(project.beatVoices ?? []).map((b) => b.voiceClipId),+ project.musicClipId,+ ].filter((x): x is string => !!x);+ return { clipIds, audioIds };+}++/** Every project asset id a run created (never the user's own references). */+function runAssetIds(project: VideoProject): Set<string> {+ const ids = new Set<string>();+ for (const sh of project.shots) {+ for (const id of [sh.startKeyframe, sh.endKeyframe, sh.clip, sh.voiceAssetId]) {+ if (id) ids.add(id);+ }+ }+ for (const bv of project.beatVoices ?? []) if (bv.voiceAssetId) ids.add(bv.voiceAssetId);+ if (project.musicAssetId) ids.add(project.musicAssetId);+ for (const va of [...project.characters, ...project.locations]) {+ if (va.mediaId) ids.add(va.mediaId);+ }+ return ids;+}++/** Re-assert chat ownership over everything a run created. New renders are+ * owned from creation (the chatId rides the generate job), but a run persisted+ * before that — or one whose asset landed while its project wasn't open — can+ * leave keyframes, shots, or narration sitting in the generate panels. Run on+ * hydrate, this re-tags those assets to the run's chat thread and drops any+ * panel job rows the run left behind (an errored render never landed an asset,+ * so its row is matched by the shot prompt it rendered). */+function claimRunMedia(project: VideoProject): void {+ const chatId = project.chatId;+ if (!chatId) return;+ const ids = runAssetIds(project);+ const editor = useEditor.getState();+ for (const a of editor.assets) {+ if (ids.has(a.id) && (a.origin !== "chat" || a.chatId !== chatId)) {+ editor.updateAsset(a.id, { origin: "chat", chatId });+ }+ }+ const prompts = new Set(+ project.shots.map((sh) => sh.lastPrompt).filter((p): p is string => !!p)+ );+ for (const j of useGenerate.getState().jobs) {+ if (j.chatId) continue; // already owned — the panels never saw it+ if ((j.assetId && ids.has(j.assetId)) || prompts.has(j.prompt)) {+ useGenerate.getState().dismiss(j.id);+ }+ }+}++/** Fold an orchestrator event into the reactive run mirror. */+function applyEvent(projectId: string, e: VideoEvent): void {+ useGenScene.setState((s) => {+ if (!s.run || s.run.projectId !== projectId) return s;+ const run = { ...s.run };+ switch (e.type) {+ case "phase":+ run.phase = e.phase;+ break;+ case "breakdown":+ run.shots = e.shots;+ run.total = e.shots.length;+ break;+ case "shot:update":+ run.shots = run.shots.map((sh) => (sh.id === e.shot.id ? e.shot : sh));+ break;+ case "progress":+ run.placed = e.placed;+ run.total = e.total;+ break;+ case "log":+ run.logs = [...run.logs, e.message].slice(-LOG_CAP);+ break;+ case "error":+ run.logs = [...run.logs, e.message].slice(-LOG_CAP);+ run.error = e.message;+ break;+ }+ return { run };+ });+}++/** Map the orchestrator's persisted project phase to a card status. */+function statusFor(p: VideoProject): SceneStatus {+ if (p.phase === "failed") return "failed";+ if (p.phase === "done") return "done";+ if (p.breakdownApproved) return "generating";+ // Unapproved: at the gate only once the plan exists. A run persisted+ // mid-planning must hydrate as planning — an Approve button with no shot+ // list behind it would render paid shots through a gate nobody reviewed.+ return p.shots.length > 0 ? "awaiting_approval" : "planning";+}++function syncFromProject(): void {+ const p = orchestrator?.project;+ if (!p) return;+ const status = statusFor(p);+ useGenScene.setState((s) => {+ if (!s.run) return s;+ const terminal = status === "done" || status === "failed";+ return {+ run: {+ ...s.run,+ phase: p.phase,+ shots: p.shots,+ total: p.shots.length,+ status,+ ...(terminal ? { endedAt: Date.now() } : {}),+ },+ };+ });+ // A finished run hands its clips to the user's undo domain — from here they+ // edit (and undo) like anything else. A regeneration adopts them back first.+ if (status === "done" || status === "failed") {+ useEditor.getState().releaseGenClips();+ }+}++function fail(message: string): void {+ useGenScene.setState((s) =>+ s.run ? { run: { ...s.run, status: "failed", error: message, endedAt: Date.now() } } : s+ );+ // Failed is terminal — whatever the run placed belongs to the user now.+ useEditor.getState().releaseGenClips();+}++/** Settle handlers scoped to one orchestrator: a superseded or paused run's+ * late resolution must never touch the run mirror — by the time it settles,+ * the mirror may belong to a fresh run in another project. */+function settled(orch: VideoOrchestrator): () => void {+ return () => {+ if (orchestrator === orch && !orch.isAborted) syncFromProject();+ };+}+function failed(orch: VideoOrchestrator): (e: unknown) => void {+ return (e) => {+ if (orchestrator === orch && !orch.isAborted) {+ fail(e instanceof Error ? e.message : String(e));+ }+ };+}++function buildOrchestrator(projectId: string, project: VideoProject): VideoOrchestrator {+ return new VideoOrchestrator(project, {+ editor: new StoreEditorBridge(projectId),+ // project.chatId (persisted) owns the run's media, so tagging survives a+ // reload/resume, not just the initial turn.+ suite: realSuite(projectId, project.chatId),+ emit: (e) => applyEvent(projectId, e),+ // Persist only while this run's project is the open one — a superseded run+ // (the user switched projects) must never write its plan onto another.+ persist: (p) => {+ if (useEditor.getState().projectId !== projectId) return;+ useEditor.getState().setGenvideo(p);+ },+ concurrency: CONCURRENCY,+ });+}++interface GenSceneState {+ run: SceneRun | null;+ /** Plan a video and stop at the confirmation gate. Resolves once the shot+ * list is ready (or the run fails). */+ start: (+ projectId: string,+ params: StartSceneParams+ ) => Promise<{ started: boolean; shotCount?: number; message: string }>;+ /** Approve the shot plan — the shots render in the background from here. */+ approve: () => { ok: boolean; message: string };+ /** Redo one shot (1-based), optionally nudging it ("wider", "at night"). */+ regenerateShot: (n: number, note?: string) => { ok: boolean; message: string };+ /** Restyle the whole scene and redo every shot. */+ restyle: (style: string) => { ok: boolean; message: string };+ /** Rebuild + resume a persisted run when a project loads. */+ hydrate: (projectId: string, project: VideoProject) => void;+ dismiss: () => void;+}++export const useGenScene = create<GenSceneState>((set, get) => ({+ run: null,++ start: async (projectId, params) => {+ const cur = get().run;+ if (orchestrator && cur && cur.projectId === projectId && !isTerminal(cur.status)) {+ return { started: false, message: "A video is already being generated for this project." };+ }+ // Validate before any side effect — the aspect apply below reshapes the+ // timeline and must not run for a request that gets rejected.+ if (!params.fromAudioAssetId && !params.brief?.trim()) {+ return { started: false, message: "Tell me what the video should be about." };+ }+ // Only set the aspect on an empty timeline: reframing a project that already+ // has clips is a committing edit, and this runs before the approval gate.+ // Applied before newProject so the plan freezes the effective shape.+ const ed = useEditor.getState();+ if (params.aspect && ed.clips.length === 0 && ed.audioClips.length === 0) {+ ed.setAspect(params.aspect);+ }+ const project = newProject(projectId, params);+ if (project.audioMode === "generated" && !project.brief) {+ return { started: false, message: "Tell me what the video should be about." };+ }+ // Supersede any previous run so two orchestrators never write at once.+ orchestrator?.abort();+ const orch = buildOrchestrator(projectId, project);+ orchestrator = orch;+ orchestratorProjectId = projectId;+ set({+ run: {+ projectId,+ mode: project.audioMode,+ title: project.brief || "Animating your audio",+ status: "planning",+ phase: project.phase,+ shots: [],+ placed: 0,+ total: 0,+ logs: [],+ startedAt: Date.now(),+ },+ });+ try {+ await orch.run(); // resolves at the confirmation gate+ } catch (e) {+ const message = e instanceof Error ? e.message : String(e);+ failed(orch)(e);+ return { started: false, message };+ }+ if (orchestrator !== orch || orch.isAborted) {+ return { started: false, message: "This plan was superseded before it finished." };+ }+ syncFromProject();+ const p = orch.project;+ if (p.phase === "failed") {+ return { started: false, message: get().run?.error ?? "Planning failed." };+ }+ return {+ started: true,+ shotCount: p.shots.length,+ message: `Planned ${p.shots.length} shot${p.shots.length === 1 ? "" : "s"}. Approve to render.`,+ };+ },++ approve: () => {+ const run = get().run;+ if (!orchestrator || !run || run.status !== "awaiting_approval") {+ return { ok: false, message: "There's no video plan waiting to render." };+ }+ if (run.projectId !== useEditor.getState().projectId) {+ return { ok: false, message: "Open the plan's project to approve it." };+ }+ const orch = orchestrator;+ set({ run: { ...run, status: "generating", renderStartedAt: Date.now() } });+ orch.approveBreakdown().then(settled(orch)).catch(failed(orch));+ return { ok: true, message: "Rendering — shots land on the timeline as they finish." };+ },++ regenerateShot: (n, note) => {+ const run = get().run;+ if (!orchestrator || !run || run.status !== "done") {+ return { ok: false, message: "The scene isn't finished rendering yet — revise it once it's done." };+ }+ const orch = orchestrator;+ const id = orch.shotIdByNumber(n);+ if (!id) return { ok: false, message: `This scene has no shot ${n}.` };+ // The run takes its clips back for the redo (they were released at done),+ // so the swap stays off the undo stack until it finishes again.+ const owned = runClipIds(orch.project);+ useEditor.getState().adoptGenClips(owned.clipIds, owned.audioIds);+ set({ run: { ...run, status: "generating", renderStartedAt: Date.now() } });+ const redo = note ? orch.applyShotNote(id, note) : orch.regenerateShots([id]);+ redo.then(settled(orch)).catch(failed(orch));+ return { ok: true, message: `Redoing shot ${n}…` };+ },++ restyle: (style) => {+ const run = get().run;+ if (!orchestrator || !run || run.status !== "done") {+ return { ok: false, message: "The scene isn't finished rendering yet — restyle it once it's done." };+ }+ const orch = orchestrator;+ // The run takes its clips back for the restyle (they were released at+ // done), so the swaps stay off the undo stack until it finishes again.+ const owned = runClipIds(orch.project);+ useEditor.getState().adoptGenClips(owned.clipIds, owned.audioIds);+ set({ run: { ...run, status: "generating", renderStartedAt: Date.now() } });+ orch.changeStyle(style).then(settled(orch)).catch(failed(orch));+ return { ok: true, message: "Restyling the whole scene…" };+ },++ hydrate: (projectId, project) => {+ // Re-assert chat ownership over the run's media before anything else, so+ // even a finished run's leftovers never sit in the generate panels.+ claimRunMedia(project);+ // A finished or failed run has nothing to resume — its clips are already on+ // the timeline — so it doesn't re-surface a card on reload.+ if (project.phase === "done" || project.phase === "failed") return;+ // Rebuild the orchestrator around the persisted plan so approve/regenerate+ // keep working after a reload. Supersede any prior run first so two never+ // both write.+ orchestrator?.abort();+ const orch = buildOrchestrator(projectId, project);+ orchestrator = orch;+ orchestratorProjectId = projectId;+ // The store's gen sets reset on load; re-mark this in-flight run's already+ // placed clips as render-owned so undo/redo stay off them as it finishes.+ const owned = runClipIds(project);+ useEditor.getState().adoptGenClips(owned.clipIds, owned.audioIds);+ set({+ run: {+ projectId,+ mode: project.audioMode,+ title: project.brief || "Animating your audio",+ status: statusFor(project),+ phase: project.phase,+ shots: project.shots,+ placed: project.shots.filter((s) => s.timelineClipId).length,+ total: project.shots.length,+ logs: [],+ // The original start time isn't persisted, so a resumed run's clock+ // counts from the reload.+ startedAt: Date.now(),+ ...(statusFor(project) === "generating" ? { renderStartedAt: Date.now() } : {}),+ },+ });+ // A run interrupted mid-generation picks itself back up, and one+ // interrupted mid-planning finishes its plan (run() stops at the gate by+ // construction); only a completed plan sitting at the gate waits.+ if (project.breakdownApproved || statusFor(project) === "planning") {+ orch.run().then(settled(orch)).catch(failed(orch));+ }+ },++ dismiss: () => {+ const run = get().run;+ // Dismissing an unrendered plan abandons it: the orchestrator stops and+ // the persisted plan is cleared, so it can't resurrect on the next load. A+ // finished (or failed) run keeps its record — its media re-tags from it on+ // load and nothing re-surfaces a terminal card.+ if (run && !isTerminal(run.status)) {+ orchestrator?.abort();+ orchestrator = null;+ orchestratorProjectId = null;+ if (useEditor.getState().projectId === run.projectId) {+ useEditor.getState().setGenvideo(undefined);+ }+ }+ set({ run: null });+ },+}));diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex ee064450..b90fc40c 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -4,6 +4,7 @@ import { useEffect } from "react";import { create } from "zustand";import { apiFetch, apiJson } from "./api";import type { AssetRef } from "./assetRef";+import { bytesFromBase64 } from "./bytes";import { composeGenPrompt, foldTextRefs } from "./composeGen";import { hostedPost } from "./hosted";import { enrichAsset, importFileToProject } from "./media";@@ -31,6 +32,10 @@ export interface GenerateJob {error?: string;/** The project asset the finished generation landed as. */assetId?: string;+ /** The chat thread that launched this render, when it wasn't the panel.+ * An owned job shows on its chat card only — the Video/Image panels list+ * panel renders, so they skip it — and its asset lands chat-tagged. */+ chatId?: string;}interface GenerateState {@@ -57,6 +62,9 @@ interface GenerateState {/** Rewrite the prompt around the references before rendering (the* default when refs are present) — see composeGen.ts. */composeRefs?: boolean;+ /** The owning chat thread when chat (or a scene run) asked — stamps the+ * job and the landed asset, keeping both off the generate panels. */+ chatId?: string;}) => Promise<GenerateJob>;/** Kick off a video render. Returns the job id right away (the render@@ -75,6 +83,11 @@ export interface VideoGenOptions {/** Composition shape; defaults to the project's orientation. */aspect?: "16:9" | "9:16";resolution?: "720p" | "1080p";+ /** Person-safety for the render. Unset, Veo blocks person/face generation, so+ * any shot with a character fails. ALLOW_ADULT is the most image-to-video+ * permits; ALLOW_ALL (needed for minors) only works text-to-video (no image+ * seed). */+ personGeneration?: "DONT_ALLOW" | "ALLOW_ADULT" | "ALLOW_ALL";/** References of any kind — video, image, text file. Veo takes one* input image, so at most one picture seeds the render. */refs?: AssetRef[];@@ -89,6 +102,9 @@ export interface VideoGenOptions {* project is still open — lets the AI place the clip after a background* render it couldn't wait out (the assistant tool bridge caps at 2min). */onDone?: (asset: MediaAsset) => void;+ /** The owning chat thread when chat (or a scene run) asked — stamps the+ * job and the landed asset, keeping both off the generate panels. */+ chatId?: string;}const REFRESH_MS = 8000;@@ -209,13 +225,6 @@ async function promptAndImages(};}-function bytesFromBase64(b64: string): Uint8Array<ArrayBuffer> {- const bin = atob(b64);- const bytes = new Uint8Array(new ArrayBuffer(bin.length));- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);- return bytes;-}-/** Settled video jobs persist per browser, so a render left unplaced (a chat* card, the Video panel's renders list) survives a reload. Running jobs don't* persist: a reload kills the in-flight poll loop, so a restored one would@@ -304,7 +313,14 @@ export const useGenerate = create<GenerateState>((set, get) => {},generateImage: (projectId, prompt, opts) => {- const job: GenerateJob = { id: uid(), projectId, kind: "image", prompt, status: "running" };+ const job: GenerateJob = {+ id: uid(),+ projectId,+ kind: "image",+ prompt,+ status: "running",+ ...(opts?.chatId ? { chatId: opts.chatId } : {}),+ };set((s) => ({ jobs: [job, ...s.jobs] }));return (async () => {try {@@ -353,7 +369,15 @@ export const useGenerate = create<GenerateState>((set, get) => {throw new Error(body.error ?? "Could not add the image to the project.");}const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };- if (adopt(projectId, asset)) useGenNotify.getState().landed("image", asset.id);+ if (opts?.chatId) {+ // Chat-owned: lives on its chat card, never in the Image panel's+ // grid, and no arrival badge — the chat is already watching.+ asset.origin = "chat";+ asset.chatId = opts.chatId;+ adopt(projectId, asset);+ } else if (adopt(projectId, asset)) {+ useGenNotify.getState().landed("image", asset.id);+ }update(job.id, { status: "done", assetId: asset.id });} catch (err) {fail(job.id, err);@@ -363,7 +387,14 @@ export const useGenerate = create<GenerateState>((set, get) => {},generateVideo: (projectId, prompt, opts) => {- const job: GenerateJob = { id: uid(), projectId, kind: "video", prompt, status: "running" };+ const job: GenerateJob = {+ id: uid(),+ projectId,+ kind: "video",+ prompt,+ status: "running",+ ...(opts?.chatId ? { chatId: opts.chatId } : {}),+ };set((s) => ({ jobs: [job, ...s.jobs] }));const settledRun = (async () => {try {@@ -386,6 +417,7 @@ export const useGenerate = create<GenerateState>((set, get) => {aspectRatio: opts?.aspect ?? useEditor.getState().aspect,...(opts?.resolution ? { resolution: opts.resolution } : {}),...(opts?.durationSeconds ? { durationSeconds: opts.durationSeconds } : {}),+ ...(opts?.personGeneration ? { personGeneration: opts.personGeneration } : {}),},});if (!res.ok) throw new Error(await readError(res, "Video generation failed."));@@ -432,9 +464,16 @@ export const useGenerate = create<GenerateState>((set, get) => {const asset = await importFileToProject(projectId, file);if (!asset) throw new Error("Could not import the generated video.");asset.name = promptName(prompt);- asset.origin = "generated"; // lives in the generate panel, not Media+ if (opts?.chatId) {+ // Chat-owned: lives on its chat card, never in the Video panel's+ // renders, and no arrival badge — the chat is already watching.+ asset.origin = "chat";+ asset.chatId = opts.chatId;+ } else {+ asset.origin = "generated"; // lives in the generate panel, not Media+ }if (adopt(projectId, asset)) {- useGenNotify.getState().landed("video", asset.id);+ if (!opts?.chatId) useGenNotify.getState().landed("video", asset.id);opts?.onDone?.(asset);}update(job.id, { status: "done", assetId: asset.id });diff --git a/site/src/cut/lib/genvideo/adapters/index.ts b/site/src/cut/lib/genvideo/adapters/index.tsnew file mode 100644index 00000000..311a0683--- /dev/null+++ b/site/src/cut/lib/genvideo/adapters/index.ts@@ -0,0 +1,41 @@+"use client";++/**+ * The real model suite: every genvideo role bound to Donkey's hosted models,+ * built for one open project. This is the production counterpart to+ * `fakeRegistry()` — the orchestrator depends only on the role interfaces, so+ * swapping fakes for this is the whole wiring.+ *+ * It lives here, not in `registry.ts`, so `registry.ts` stays free of the+ * browser-only generation modules and the node self-test can keep importing the+ * fakes from it.+ *+ * No `lipSync` role: v1 has no hosted lip-sync, and `video.audioNative` is+ * false, so the orchestrator places each shot as b-roll under a separate+ * narration spine. `music` is always present but best-effort — it degrades to+ * no bed when no music backend is configured.+ */++import type { ModelSuite } from "../capabilities";+import { makeImageRole, makeVideoRole, makeVoiceRole } from "./media";+import { makeMusicRole } from "./music";+import { makeBreakdownRole, makeScriptRole, makeStyleRole } from "./text";+import { makeTranscribeRole } from "./transcribe";++/** Build the suite for one project. `chatId` is the owning chat thread — every+ * asset the run creates is tagged to it (via the adapters) so the intermediates+ * and shots stay off the Media/Video/Image/Audio panels, exactly like the+ * single-asset chat generation tools. */+export function realSuite(projectId: string, chatId?: string): ModelSuite {+ return {+ label: "donkey-hosted",+ script: makeScriptRole(),+ breakdown: makeBreakdownRole(),+ style: makeStyleRole(),+ image: makeImageRole(projectId, chatId),+ video: makeVideoRole(projectId, chatId),+ voice: makeVoiceRole(projectId, chatId),+ music: makeMusicRole(projectId, chatId),+ transcribe: makeTranscribeRole(projectId),+ };+}diff --git a/site/src/cut/lib/genvideo/adapters/media.ts b/site/src/cut/lib/genvideo/adapters/media.tsnew file mode 100644index 00000000..b52cea67--- /dev/null+++ b/site/src/cut/lib/genvideo/adapters/media.ts@@ -0,0 +1,126 @@+"use client";++/**+ * The media roles — image, video, voice — over the exact browser-side+ * generation the panels and chat already use (`useGenerate`, `tts`). Each runs+ * on the user's Donkey session and credits and lands its output as a real+ * project asset, so what these return is a placeable asset id and the editor+ * bridge's `importMedia` has nothing left to do.+ *+ * Two shaping choices matter for the assembled cut:+ * - Video is NOT audio-native here: the model can't lip-sync our narration+ * track, and every shot rides under a separate narration spine. We let the+ * model generate whatever audio it wants and handle it locally — the placed+ * 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).+ * - Shots render text-to-video with personGeneration ALLOW_ALL — no person-safety+ * ceiling, so any character animates. That rules out a first-frame image seed+ * (Veo caps a seeded render at ALLOW_ADULT and blocks faces it can't clear), so+ * look continuity rides the prompt and style bible, not a keyframe.+ * - 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.+ */++import { refFromAsset, type AssetRef } from "../../assetRef";+import { tagChatAsset } from "../../chatAssets";+import { useGenerate } from "../../generate";+import { enrichAsset } from "../../media";+import { useEditor } from "../../store";+import { DEFAULT_VOICE, synthesizeSpeech } from "../../tts";+import { supportedVideoDuration } from "../../videoGen";+import type { ImageRole, VideoRole, VoiceRole } from "../capabilities";+import type { RefAsset } from "../types";++/** Resolve the pipeline's media-id references to the project assets the+ * generators take, dropping any that are no longer in the project. */+function refsToAssetRefs(refs: RefAsset[]): AssetRef[] {+ const assets = useEditor.getState().assets;+ const out: AssetRef[] = [];+ for (const r of refs) {+ const a = assets.find((x) => x.id === r.mediaId);+ if (a) out.push(refFromAsset(a));+ }+ return out;+}++export function makeImageRole(projectId: string, chatId?: string): ImageRole {+ return {+ async generate(input) {+ const job = await useGenerate.getState().generateImage(projectId, input.prompt, {+ refs: refsToAssetRefs(input.refs),+ aspect: input.aspect,+ // The prompt is already complete (buildPrompt folds in style + setting);+ // the refs ride as identity anchors, not a prompt to rewrite.+ composeRefs: false,+ // Chat ownership rides the job from creation, so keyframes and reference+ // images never touch the Image panel — job row, tile, or badge — even+ // when the render errors or lands after the user moved on.+ ...(chatId ? { chatId } : {}),+ });+ if (job.status !== "done" || !job.assetId) {+ throw new Error(job.error || "Image generation failed.");+ }+ return job.assetId;+ },+ };+}++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) {+ // Text-to-video with personGeneration ALLOW_ALL — no person-safety ceiling,+ // so any character animates (children included). That rules out a+ // first-frame image seed: Veo caps a seeded render at ALLOW_ADULT and+ // blocks a face it can't clear, which is what froze shots to a still. Look+ // continuity rides the prompt and the style bible instead of the keyframe.+ const job = await useGenerate.getState().generateVideo(projectId, input.prompt, {+ tier: VIDEO_TIER,+ // A length the model actually renders (registry-driven); the clip is+ // trimmed to the exact slot on placement.+ durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec),+ aspect: input.aspect,+ personGeneration: "ALLOW_ALL",+ // 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 } : {}),+ }).settled;+ if (job.status !== "done" || !job.assetId) {+ throw new Error(job.error || "Video generation failed.");+ }+ return job.assetId;+ },+ };+}++export function makeVoiceRole(projectId: string, chatId?: string): VoiceRole {+ return {+ async speak(input) {+ const { asset } = await synthesizeSpeech(projectId, [{ text: input.script, at: 0 }], {+ voice: input.voice || DEFAULT_VOICE,+ ...(input.direction ? { direction: input.direction } : {}),+ name: "Narration",+ });+ // synthesizeSpeech imports the file but leaves it to the caller to stock+ // the store, so the spine placement can find the asset. Only stock it when+ // this run's project is the one open — a background run whose project the+ // user switched away from must not add its narration to another project.+ if (useEditor.getState().projectId === projectId) {+ useEditor.getState().addAsset(asset);+ // Chat-owned, so the narration never shows in the Audio panel's+ // voiceover list — it's part of the run, placed on the soundtrack.+ // Only the run's own thread id: the ambient chat context is whatever+ // thread happens to be open when a background render lands.+ if (chatId) tagChatAsset(asset.id, chatId);+ void enrichAsset(asset);+ }+ return { mediaId: asset.id, durationSec: asset.duration };+ },+ };+}diff --git a/site/src/cut/lib/genvideo/adapters/music.ts b/site/src/cut/lib/genvideo/adapters/music.tsnew file mode 100644index 00000000..a5584a15--- /dev/null+++ b/site/src/cut/lib/genvideo/adapters/music.ts@@ -0,0 +1,65 @@+"use client";++/**+ * The music bed over the hosted asset route (kind:"music"). It is intentionally+ * best-effort: with no configured music backend the route rejects and this+ * throws, which the orchestrator catches to assemble the cut with no bed. So a+ * deploy without ELEVENLABS_API_KEY still produces a video, just a silent-bed+ * one.+ */++import { bytesFromBase64 } from "../../bytes";+import { hostedPost } from "../../hosted";+import { enrichAsset, importFileToProject } from "../../media";+import { useEditor } from "../../store";+import type { MusicRole } from "../capabilities";++export function makeMusicRole(projectId: string, chatId?: string): MusicRole {+ return {+ async compose(input) {+ const res = await hostedPost("/api/inference/assets", {+ kind: "music",+ prompt: input.mood,+ parameters: { durationSeconds: Math.max(1, Math.round(input.durationSec)) },+ });+ if (!res.ok) throw new Error("Music generation is unavailable.");+ const gen = (await res.json()) as {+ status?: string;+ outputs?: { dataBase64?: string; url?: string; contentType?: string; filename?: string }[];+ };+ const out = gen.outputs?.find((o) => o.dataBase64) ?? gen.outputs?.find((o) => o.url);+ let file: File;+ if (out?.dataBase64) {+ file = new File([bytesFromBase64(out.dataBase64)], out.filename ?? "music.mp3", {+ type: out.contentType ?? "audio/mpeg",+ });+ } else if (out?.url) {+ const dl = await fetch(out.url);+ if (!dl.ok) throw new Error("Could not download the music bed.");+ file = new File([await dl.arrayBuffer()], "music.mp3", { type: out.contentType ?? "audio/mpeg" });+ } else {+ throw new Error("The provider returned no music.");+ }+ const asset = await importFileToProject(projectId, file);+ if (!asset) throw new Error("Could not import the music bed.");+ asset.name = "Music bed";+ // Chat-owned from birth so the bed never surfaces in a panel; it's placed+ // on the soundtrack as part of the run. Only the run's own thread id: the+ // ambient chat context is whatever thread is open when this lands.+ if (chatId) {+ asset.origin = "chat";+ asset.chatId = chatId;+ } else {+ asset.origin = "generated";+ }+ // Only stock the store when this run's project is the one open — a+ // background run whose project the user has since switched away from must+ // never drop its media into whatever project is now on screen.+ if (useEditor.getState().projectId === projectId) {+ useEditor.getState().addAsset(asset);+ void enrichAsset(asset);+ }+ return asset.id;+ },+ };+}diff --git a/site/src/cut/lib/genvideo/adapters/text.ts b/site/src/cut/lib/genvideo/adapters/text.tsnew file mode 100644index 00000000..cd3ccd32--- /dev/null+++ b/site/src/cut/lib/genvideo/adapters/text.ts@@ -0,0 +1,241 @@+"use client";++/**+ * The judgment roles — script, breakdown, style — as one-shot structured LLM+ * calls through Donkey's hosted Gemini (the same `/api/inference/responses`+ * json_object path prompt composition already uses). Each returns plain JSON we+ * validate in code; nothing here enforces a provider-side schema, matching how+ * the planner runs.+ *+ * The one contract that ties the three together: character and location ids.+ * The script (or breakdown) assigns stable ids — char:1, loc:1, … — and every+ * shot carries them. The style role is handed those exact ids and returns one+ * asset per id, so the reference images it designs tie back to the shots by+ * construction, not by hoping two independent calls agree.+ */++import { geminiModelRoles } from "@/lib/inference/gemini-models";+import { hostedPost } from "../../hosted";+import { NO_CREDITS_MESSAGE } from "../../generate";+import { secToFrame, type RawShot } from "../coverage";+import type { BreakdownRole, ScriptRole, StyleRole } from "../capabilities";+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. */+async function llmJson<T>(+ instructions: string,+ userText: string,+ parse: (o: Record<string, unknown>) => T | null+): 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.");+ }+ 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 {+ throw new Error("The planning model returned unreadable output.");+ }+ const out = parse(parsed);+ if (out === null) throw new Error("The planning model returned an unusable plan.");+ return out;+}++// ── coercion helpers ────────────────────────────────────────────────────────++const str = (v: unknown): string => (typeof v === "string" ? v.trim() : "");+const num = (v: unknown, fallback: number): number =>+ typeof v === "number" && Number.isFinite(v) ? v : fallback;+const idList = (v: unknown): string[] =>+ Array.isArray(v) ? v.map((x) => String(x).trim()).filter(Boolean) : [];+const distinct = (xs: string[]): string[] => Array.from(new Set(xs.filter(Boolean)));++// ── script ──────────────────────────────────────────────────────────────────++const SCRIPT_INSTRUCTIONS = `You are a short-video writer. Turn the brief into a spoken video plan.+Reply with JSON only:+{"logline": string, "style": string, "beats": [+ {"dialogue": string, "action": string, "characters": ["char:1"], "location": "loc:1", "framing": string, "approxSeconds": number}+]}+Rules:+- dialogue is the narration/spoken line for that beat (one or two sentences), action is what is shown on screen.+- Assign each recurring character a stable id "char:1", "char:2", … and each place a stable id "loc:1", "loc:2", …; every beat lists the ids it uses. A beat with no character uses [].+- Keep the whole thing near the requested length; each beat is about 4–8 seconds of narration.+- style is a short reusable look for the whole video (medium, lighting, palette, mood), described by its visual traits — never a real brand, franchise, show, or artist name, even one the brief uses (a generator rejects trademarked names).`;++function parseScript(o: Record<string, unknown>): ScriptPlan | null {+ const rawBeats = Array.isArray(o.beats) ? o.beats : [];+ const beats: ScriptBeat[] = rawBeats+ .map((b): ScriptBeat => {+ const beat = (b ?? {}) as Record<string, unknown>;+ return {+ dialogue: str(beat.dialogue),+ action: str(beat.action),+ characters: idList(beat.characters),+ location: str(beat.location) || "loc:1",+ framing: str(beat.framing) || "medium shot",+ approxSeconds: Math.max(2, Math.min(8, num(beat.approxSeconds, 6))),+ };+ })+ .filter((b) => b.dialogue || b.action);+ if (beats.length === 0) return null;+ return {+ logline: str(o.logline),+ beats,+ style: typeof o.style === "string" && o.style.trim() ? o.style.trim() : undefined,+ };+}++export function makeScriptRole(): ScriptRole {+ return {+ async write(input) {+ const targetSeconds = Math.max(6, Math.min(90, input.targetSeconds ?? 24));+ const beatCount = Math.max(2, Math.min(14, Math.round(targetSeconds / 6)));+ const refNote = input.refs.length+ ? `The user attached ${input.refs.length} reference(s); keep the story consistent with them.`+ : "";+ const user = `Write a spoken video plan for this brief. Aim for about ${targetSeconds} seconds total across roughly ${beatCount} beats.+${refNote}+Brief: ${input.brief}`;+ return llmJson(SCRIPT_INSTRUCTIONS, user, parseScript);+ },+ };+}++// ── breakdown (provided-audio mode) ─────────────────────────────────────────++const BREAKDOWN_INSTRUCTIONS = `You are a shot-list editor. Break a narration into a shot list that tiles the whole timeline.+Reply with JSON only:+{"shots": [+ {"start": number, "end": number, "action": string, "characters": ["char:1"], "location": "loc:1", "framing": string}+]}+Rules:+- start/end are SECONDS on the timeline; the shots must run in order and cover the whole duration with no gaps.+- Each shot is about 4–8 seconds and its action describes what is shown while those words are heard.+- Assign stable ids: characters "char:1"…, locations "loc:1"…, reused across shots for continuity. A shot with no character uses [].`;++/** Compact, timed transcript for the model — capped so a long narration stays+ * within a sane prompt. Words are grouped into ~2s chunks with a start stamp. */+function timedTranscript(words: TranscriptWord[]): string {+ if (words.length === 0) return "(no transcript — pace the shots evenly)";+ const lines: string[] = [];+ let chunkStart = words[0].t0;+ let buf: string[] = [];+ const flush = () => {+ if (buf.length) lines.push(`[${chunkStart.toFixed(1)}s] ${buf.join(" ")}`);+ buf = [];+ };+ for (const w of words) {+ if (buf.length && w.t0 - chunkStart >= 2) {+ flush();+ chunkStart = w.t0;+ }+ buf.push(w.w);+ if (lines.length >= 200) break;+ }+ flush();+ return lines.join("\n");+}++function parseShots(o: Record<string, unknown>, fps: number): RawShot[] | null {+ const rawShots = Array.isArray(o.shots) ? o.shots : [];+ if (rawShots.length === 0) return null;+ const shots: RawShot[] = rawShots+ .map((s): RawShot => {+ const shot = (s ?? {}) as Record<string, unknown>;+ return {+ startFrame: secToFrame(num(shot.start, 0), fps),+ endFrame: secToFrame(num(shot.end, 0), fps),+ action: str(shot.action),+ characters: idList(shot.characters),+ location: str(shot.location) || "loc:1",+ framing: str(shot.framing) || "medium shot",+ };+ })+ .filter((s) => s.endFrame > s.startFrame);+ return shots.length > 0 ? shots : null;+}++export function makeBreakdownRole(): BreakdownRole {+ return {+ async segment(input) {+ const durSec = input.durationFrames / input.fps;+ const shotCount = Math.max(1, Math.round(durSec / 6));+ const user = `A ${durSec.toFixed(1)}s narration needs about ${shotCount} shots (each 4–8s) covering [0, ${durSec.toFixed(1)}].+Timed transcript:+${timedTranscript(input.transcript)}`;+ return llmJson(BREAKDOWN_INSTRUCTIONS, user, (o) => parseShots(o, input.fps));+ },+ };+}++// ── style bible ─────────────────────────────────────────────────────────────++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}]}+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, wardrobe, colors) so it stays consistent across shots.+- 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[],+ kind: "character" | "location"+): VideoAsset[] {+ const list = Array.isArray(raw) ? (raw as Record<string, unknown>[]) : [];+ const byId = new Map(list.map((e) => [str(e.id), e]));+ return ids.map((id, i) => {+ const e = byId.get(id) ?? list[i] ?? {};+ return {+ id,+ kind,+ name: str(e.name) || (kind === "character" ? "the subject" : "the setting"),+ description: str(e.description) || (kind === "character" ? "the main subject" : "the scene"),+ };+ });+}++export function makeStyleRole(): StyleRole {+ return {+ async design(input) {+ const charIds = distinct(input.beats.flatMap((b) => b.characters ?? []));+ const locIds = distinct(input.beats.map((b) => b.location ?? "").filter(Boolean));+ const wantLocs = locIds.length ? locIds : ["loc:1"];+ 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.`+ : "";+ const user = `Design the look for this video.+Brief: ${input.brief || "(none)"}+${refNote}+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"),+ }));+ },+ };+}diff --git a/site/src/cut/lib/genvideo/adapters/transcribe.ts b/site/src/cut/lib/genvideo/adapters/transcribe.tsnew file mode 100644index 00000000..911c971d--- /dev/null+++ b/site/src/cut/lib/genvideo/adapters/transcribe.ts@@ -0,0 +1,35 @@+"use client";++/**+ * Transcription over the engine's on-device STT (Apple SpeechAnalyzer via+ * cut-stt) — the same route (and poller) the subtitle tools use. Nothing+ * leaves the machine.+ *+ * The route transcribes a rendered mix, so we hand it a one-entry spec that+ * renders just the target audio asset: provided-mode ("animate this audio")+ * then transcribes exactly the spine the shots are cut against, not whatever+ * else is on the timeline.+ */++import { runTranscription, useEditor } from "../../store";+import type { TranscribeRole } from "../capabilities";+import type { TranscriptWord } from "../types";++export function makeTranscribeRole(projectId: string): TranscribeRole {+ return {+ async transcribe(audioMediaId) {+ const asset = useEditor.getState().assets.find((a) => a.id === audioMediaId);+ if (!asset || asset.type !== "audio") throw new Error("No audio to transcribe.");+ const cues = await runTranscription(projectId, {+ duration: asset.duration,+ clips: [],+ audio: [{ file: asset.fileName, in: 0, out: asset.duration, start: 0, volume: 1 }],+ });+ // The poller yields null when the project closed mid-run. That is a+ // pause, never a result — an empty transcript here would silently plan+ // shots with no relation to the narration's words.+ if (cues === null) throw new Error("Transcription stopped — the project was closed.");+ return cues.flatMap<TranscriptWord>((c) => c.words ?? []);+ },+ };+}diff --git a/site/src/cut/lib/genvideo/capabilities.ts b/site/src/cut/lib/genvideo/capabilities.tsindex e14dc1b7..5ade1d46 100644--- a/site/src/cut/lib/genvideo/capabilities.ts+++ b/site/src/cut/lib/genvideo/capabilities.ts@@ -32,7 +32,10 @@ export interface BreakdownInput {export interface StyleInput {brief?: string;refs: RefAsset[];- beats: { dialogue: string; action: string }[];+ /** The story to design for. `characters`/`location` carry the stable ids the+ * script/breakdown assigned (char:1, loc:1, …); the style role returns one+ * asset per distinct id, so identity ties back to the shots by construction. */+ beats: { dialogue: string; action: string; characters?: string[]; location?: string }[];}export interface StyleBible {@@ -128,7 +131,9 @@ export interface ModelSuite {image: ImageRole;video: VideoRole;voice: VoiceRole;- music: MusicRole;+ /** Absent when no music backend is configured — the run assembles with no+ * bed rather than failing. */+ music?: MusicRole;/** Absent when `video.audioNative` — the video does its own lip-sync. */lipSync?: LipSyncRole;transcribe: TranscribeRole;diff --git a/site/src/cut/lib/genvideo/editorBridge.ts b/site/src/cut/lib/genvideo/editorBridge.tsnew file mode 100644index 00000000..a01f5d59--- /dev/null+++ b/site/src/cut/lib/genvideo/editorBridge.ts@@ -0,0 +1,128 @@+"use client";++/**+ * The real EditorBridge: the orchestrator's typed hands on the live Cut+ * timeline. It is the single frames↔seconds conversion boundary — the plan+ * reasons in whole frames at a fixed project rate, the editor store speaks+ * seconds, and every method here divides or multiplies by GEN_FPS exactly once.+ *+ * Placement forwards to the store's id-returning gen actions (placeGenClip /+ * placeGenAudio / removeClipById / removeAudioById), which place at an exact+ * time without sliding, mute generated shots, and never touch the user's+ * selection — so a run populates the track in the background while the user+ * keeps editing. `importMedia` is identity: the media adapters already import+ * their output into the project, so what they return is a real asset id.+ *+ * Every mutation is scoped to the run's own project: the store holds one open+ * project at a time, and a background run whose project the user has since+ * switched away from must never write to whatever project is now on screen. So+ * each method checks the open project first and no-ops (or throws, for the+ * id-returning placements) when it isn't this run's.+ */++import { useEditor } from "../store";+import type { TransitionStyle } from "../types";+import type { AudioClipInfo, EditorBridge, TimelineInfo } from "./editor";++/** The rate the plan runs at. Fixed to the export frame rate so a shot's frame+ * math lines up with the rendered file. */+export const GEN_FPS = 30;++const toSec = (frames: number) => frames / GEN_FPS;++/** Effective timeline footprint of a clip (seconds), honoring speed. */+function footprintSec(c: { in: number; out: number; speed?: number }): number {+ const src = c.out - c.in;+ return c.speed && c.speed > 0 ? src / c.speed : src;+}++export class StoreEditorBridge implements EditorBridge {+ constructor(private readonly projectId: string) {}++ /** Whether this run's project is the one currently open in the store. */+ private open(): boolean {+ return useEditor.getState().projectId === this.projectId;+ }++ getTimeline(): TimelineInfo {+ const s = useEditor.getState();+ const clipEnd = Math.max(+ 0,+ ...s.clips.map((c) => c.start + footprintSec(c)),+ ...s.audioClips.map((c) => c.start + footprintSec(c))+ );+ return {+ fps: GEN_FPS,+ durationFrames: Math.round(clipEnd * GEN_FPS),+ aspect: s.aspect,+ };+ }++ getAudioClips(): AudioClipInfo[] {+ return useEditor.getState().audioClips.map((c) => ({+ clipId: c.id,+ assetId: c.assetId,+ startFrame: Math.round(c.start * GEN_FPS),+ durationFrames: Math.round(footprintSec(c) * GEN_FPS),+ }));+ }++ async importMedia(mediaId: string): Promise<string> {+ // The media adapters import their output before returning, so the id is+ // already a project asset id — nothing to do.+ return mediaId;+ }++ async placeClip(mediaId: string, startFrame: number, endFrame: number): Promise<string> {+ if (!this.open()) throw new Error("placeClip: run's project is no longer open");+ const id = useEditor.getState().placeGenClip(mediaId, toSec(startFrame), toSec(endFrame));+ if (!id) throw new Error(`placeClip: no placeable asset ${mediaId}`);+ return id;+ }++ async replaceClipMedia(clipId: string, mediaId: string): Promise<void> {+ if (!this.open()) return;+ useEditor.getState().updateClip(clipId, { assetId: mediaId });+ }++ async retimeClip(clipId: string, durationFrames: number): Promise<void> {+ if (!this.open()) return;+ const clip = useEditor.getState().clips.find((c) => c.id === clipId);+ if (!clip) return;+ // Trim the tail so the footprint matches, at whatever speed the clip carries.+ const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;+ useEditor.getState().setClipTrim(clipId, clip.in, clip.in + toSec(durationFrames) * speed);+ }++ async removeClip(clipId: string): Promise<void> {+ if (!this.open()) return;+ useEditor.getState().removeClipById(clipId);+ }++ async addTransition(clipId: string, style: string, durationFrames: number): Promise<void> {+ if (!this.open()) return;+ useEditor.getState().setClipTransition(clipId, toSec(durationFrames), style as TransitionStyle);+ }++ async placeAudio(+ mediaId: string,+ startFrame: number,+ durationFrames: number,+ opts?: { kind?: "voice" | "music"; duck?: number; lane?: number }+ ): Promise<string> {+ if (!this.open()) throw new Error("placeAudio: run's project is no longer open");+ const id = useEditor+ .getState()+ .placeGenAudio(mediaId, toSec(startFrame), toSec(durationFrames), {+ ...(opts?.duck !== undefined ? { duck: opts.duck } : {}),+ ...(opts?.lane !== undefined ? { lane: opts.lane } : {}),+ });+ if (!id) throw new Error(`placeAudio: no audio asset ${mediaId}`);+ return id;+ }++ async removeAudio(clipId: string): Promise<void> {+ if (!this.open()) return;+ useEditor.getState().removeAudioById(clipId);+ }+}diff --git a/site/src/cut/lib/genvideo/fillSlot.ts b/site/src/cut/lib/genvideo/fillSlot.tsnew file mode 100644index 00000000..1ce044da--- /dev/null+++ b/site/src/cut/lib/genvideo/fillSlot.ts@@ -0,0 +1,28 @@+/**+ * How a generated clip fills its exact timeline slot — the editor-boundary twin+ * of the frame coverage invariant. A slot is [start, end) seconds on the track;+ * a shot must occupy exactly that, or the track opens a black gap between shots.+ *+ * - An image has no intrinsic length, so it simply takes the slot.+ * - A video longer than the slot trims its tail.+ * - A shorter video time-stretches to fill (speed < 1), floored at speedMin.+ * Below that floor — a source under `speedMin × slot` — the clip is as slow as+ * allowed and a small gap remains, which beats a frozen crawl.+ *+ * A clip's footprint is (out − in) / (speed ?? 1); this returns `out` (with+ * in = 0) and an optional `speed`, so footprint equals the slot in every case+ * except the sub-floor one. Pure and dependency-free so the self-test can assert+ * the tiling without a browser store.+ */+export function fillSlot(+ kind: "video" | "image",+ srcDuration: number,+ slotSec: number,+ speedMin: number+): { out: number; speed?: number } {+ const slot = Math.max(0.1, slotSec);+ if (kind === "image") return { out: slot };+ const src = Math.max(0.1, srcDuration);+ if (src >= slot) return { out: slot };+ return { out: src, speed: Math.max(speedMin, src / slot) };+}diff --git a/site/src/cut/lib/genvideo/orchestrator.ts b/site/src/cut/lib/genvideo/orchestrator.tsindex c2608961..b021184a 100644--- a/site/src/cut/lib/genvideo/orchestrator.ts+++ b/site/src/cut/lib/genvideo/orchestrator.ts@@ -44,12 +44,34 @@ const BACKOFF_MS = 500;const VOICE_DUCK = 0.35;export class VideoOrchestrator {- private readonly aspect: "9:16" | "16:9";/** Serializes persistence so concurrent shot updates never interleave writes. */private saveChain: Promise<void> = Promise.resolve();+ /** Set when a newer run supersedes this one (the user switched projects), so+ * in-flight work stops writing to the timeline or the persisted plan. */+ private aborted = false;- constructor(public project: VideoProject, private readonly deps: OrchestratorDeps) {- this.aspect = deps.editor.getTimeline().aspect;+ constructor(public project: VideoProject, private readonly deps: OrchestratorDeps) {}++ /** Abandon this run: later phases and the persist chain become no-ops. Called+ * before a replacement orchestrator takes over, and when the run's project+ * stops being open, so nothing renders (or spends) against a project the+ * user has left. The persisted plan resumes via hydrate. */+ abort(): void {+ this.aborted = true;+ }++ /** Whether this run was superseded or paused — late settlements check this so+ * they never touch state a newer run now owns. */+ get isAborted(): boolean {+ return this.aborted;+ }++ /** The shape every keyframe and shot renders at. Frozen on the plan (captured+ * at start, refreshed at approval — the last moment the user can set it), so+ * a background render can never pick up another open project's shape. The+ * live read only backfills a plan persisted before the field existed. */+ private get aspect(): "9:16" | "16:9" {+ return this.project.aspect ?? this.deps.editor.getTimeline().aspect;}private get fps(): number {@@ -59,28 +81,38 @@ export class VideoOrchestrator {return this.project.durationFrames;}- /** Advance the run from its current phase to the next stopping point. */+ /** Advance the run from its current phase to the next stopping point. An+ * abort landing between phases stops the walk — no later phase may render or+ * spend once the run is superseded or paused. */async run(): Promise<VideoProject> {if (this.project.phase === "failed" || this.project.phase === "done") return this.project;- await this.brief();- await this.ingest();- await this.breakdown();+ 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- await this.style();- await this.keyframes();- await this.generateAndPlaceAll();- await this.polish();+ // 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;}/** The user confirmed the shot list — continue the run. */async approveBreakdown(): Promise<VideoProject> {this.project.breakdownApproved = true;+ // The approval gate is the last moment the user can set the project shape;+ // freeze it now so every render matches, even after a project switch.+ this.project.aspect = this.deps.editor.getTimeline().aspect;await this.save();return this.run();}- // ── Phase 0: brief → script → voiced spine + music (generated mode) ───────+ // ── Phase 0: brief → script → estimated shot plan (generated mode) ────────private async brief(): Promise<void> {if (this.project.audioMode !== "generated") return;if (this.project.shots.length > 0) return; // already planned (resume)@@ -93,21 +125,175 @@ export class VideoOrchestrator {});await this.save();}+ // Lay the plan out on *estimated* beat lengths (from word count) so the+ // confirmation card exists without spending a cent on TTS. The real voiced+ // lengths replace these in voice(), after the user approves; the music bed+ // is likewise deferred to polish.+ const minF = Math.round(MIN_SHOT_SEC * this.fps);+ const frames = this.project.script.beats.map((b) =>+ Math.max(minF, secToFrame(estimateSpokenSeconds(b.dialogue), this.fps))+ );+ this.layoutBeats(+ frames,+ this.project.script.beats.map(() => undefined)+ );+ await this.save();+ }++ // ── Phase 0b: voice the spine (generated mode, after the gate) ────────────+ private async voice(): Promise<void> {+ if (this.aborted) return;+ if (this.project.audioMode !== "generated" || !this.project.script) return;+ // Idempotent across resumes: done once every beat carries its asset id AND+ // the shots have been re-laid onto the voiced spine (a later resume must+ // never rebuild shots that already rendered).+ const voices = this.project.beatVoices ?? [];+ if (+ voices.length > 0 &&+ voices.every((bv) => bv.voiceAssetId) &&+ this.project.shots.every((s) => s.voiceAssetId)+ ) {+ return;+ }+ this.setPhase("voicing");// Voice each beat to get its true length; the voice is one clip per beat,// and a beat longer than one video clip spans several shots that each- // lip-sync to their own slice — so a long line is never cut off.+ // lip-sync to their own slice — so a long line is never cut off. Each beat+ // persists as it lands, so an interruption never re-bills voiced beats.const minF = Math.round(MIN_SHOT_SEC * this.fps);+ const voiceIds: string[] = [];+ const frames: number[] = [];+ for (const [bi, beat] of this.project.script.beats.entries()) {+ if (this.aborted) return;+ const prior = voices[bi];+ if (prior?.voiceAssetId) {+ voiceIds.push(prior.voiceAssetId);+ frames.push(prior.durationFrames);+ continue;+ }+ const vo = await this.deps.suite.voice.speak({ script: beat.dialogue });+ const id = await this.deps.editor.importMedia(vo.mediaId);+ const dur = Math.max(minF, secToFrame(vo.durationSec, this.fps));+ voiceIds.push(id);+ frames.push(dur);+ if (prior) {+ prior.voiceAssetId = id;+ prior.durationFrames = dur;+ await this.save();+ }+ }+ if (this.aborted) return;+ // Move the approved shots onto the real lengths — boundaries scale within+ // each beat so no slice runs past its voice clip, but the shot list itself+ // (count, order, notes) stays exactly the plan the user approved.+ this.rescaleBeats(frames, voiceIds);+ await this.save();+ this.deps.emit({ type: "breakdown", shots: this.project.shots });+ }++ /** Scale the approved shots to the real voiced beat lengths. Each beat's+ * shots keep their relative proportions inside the beat's new span, so the+ * plan the user approved — shots, order, gate-time notes — is what renders;+ * only frame boundaries move. The one exception is physical: a voiced line+ * longer than the clip cap splits its shot into contiguous sub-shots (copies+ * carrying the same prompt fields), because one clip cannot span it. Falls+ * back to a fresh layout when there is no estimated spine to scale. */+ private rescaleBeats(beatFrames: number[], voiceIds: (string | undefined)[]): void {+ const old = this.project.beatVoices;+ if (!this.project.script || !old || old.length !== beatFrames.length) {+ this.layoutBeats(beatFrames, voiceIds);+ return;+ }+ // The estimated beat spans, from the untouched startFrames: voice() rewrites+ // each entry's durationFrames as beats land, but every startFrame (and the+ // total) stays the estimated layout until the rescale below moves the shots.+ const oldEnd = (bi: number) =>+ bi + 1 < old.length ? old[bi + 1].startFrame : this.project.durationFrames;const maxF = Math.round(MAX_SHOT_SEC * this.fps);let cursor = 0;const shots: Shot[] = [];const beatVoices: BeatVoice[] = [];- for (const beat of this.project.script.beats) {- const vo = await this.deps.suite.voice.speak({ script: beat.dialogue });- const voiceId = await this.deps.editor.importMedia(vo.mediaId);- const beatFrames = Math.max(minF, secToFrame(vo.durationSec, this.fps));+ this.project.script.beats.forEach((beat, bi) => {+ const ob = old[bi];+ const oldDur = Math.max(1, oldEnd(bi) - ob.startFrame);+ const dur = beatFrames[bi];+ const voiceId = voiceIds[bi];const beatStart = cursor;- beatVoices.push({ voiceAssetId: voiceId, startFrame: beatStart, durationFrames: beatFrames });- for (const [s, e] of splitBeat(beatStart, beatFrames, maxF)) {+ const slice = (s: number, e: number, base: Shot) => ({+ ...base,+ startFrame: s,+ endFrame: e,+ ...(voiceId ? { voiceAssetId: voiceId } : {}),+ voiceFromSec: frameToSec(s - beatStart, this.fps),+ voiceToSec: frameToSec(e - beatStart, this.fps),+ });+ let beatShots = this.project.shots.filter(+ (s) => s.startFrame >= ob.startFrame && s.startFrame < ob.startFrame + oldDur+ );+ if (beatShots.length === 0) {+ // Nothing to scale for this beat (a malformed persisted plan) — seed+ // one shot from the beat so coverage holds.+ beatShots = [+ {+ id: `shot:${bi}`,+ startFrame: beatStart,+ endFrame: beatStart + dur,+ audioText: beat.dialogue,+ dialogue: beat.dialogue,+ action: beat.action,+ characters: beat.characters,+ location: beat.location,+ framing: beat.framing,+ status: "pending",+ attempts: 0,+ },+ ];+ }+ let at = cursor;+ beatShots.forEach((shot, si) => {+ const frac = (shot.endFrame - ob.startFrame) / oldDur;+ const end =+ si === beatShots.length - 1+ ? beatStart + dur+ : Math.min(beatStart + dur, Math.max(at + 1, beatStart + Math.round(frac * dur)));+ const pieces = splitBeat(at, Math.max(1, end - at), maxF);+ pieces.forEach(([s, e], pi) => {+ shots.push(slice(s, e, pieces.length === 1 ? shot : { ...shot, id: `${shot.id}.${pi}` }));+ });+ at = end;+ });+ beatVoices.push({+ ...(voiceId ? { voiceAssetId: voiceId } : {}),+ startFrame: beatStart,+ durationFrames: dur,+ });+ cursor += dur;+ });+ this.project.durationFrames = cursor;+ this.project.shots = shots;+ this.project.beatVoices = beatVoices;+ assertCoverage(this.project.shots, this.durationFrames);+ }++ /** Lay shots + the beat spine out from per-beat frame lengths. Runs twice in+ * generated mode: brief() passes estimated lengths (no voice ids yet); voice()+ * passes the real voiced lengths and ids. */+ private layoutBeats(beatFrames: number[], voiceIds: (string | undefined)[]): void {+ if (!this.project.script) return;+ const maxF = Math.round(MAX_SHOT_SEC * this.fps);+ let cursor = 0;+ const shots: Shot[] = [];+ const beatVoices: BeatVoice[] = [];+ this.project.script.beats.forEach((beat, bi) => {+ const dur = beatFrames[bi];+ const beatStart = cursor;+ const voiceId = voiceIds[bi];+ beatVoices.push({+ ...(voiceId ? { voiceAssetId: voiceId } : {}),+ startFrame: beatStart,+ durationFrames: dur,+ });+ for (const [s, e] of splitBeat(beatStart, dur, maxF)) {shots.push({id: `shot:${shots.length}`,startFrame: s,@@ -118,25 +304,19 @@ export class VideoOrchestrator {characters: beat.characters,location: beat.location,framing: beat.framing,- voiceAssetId: voiceId,+ ...(voiceId ? { voiceAssetId: voiceId } : {}),voiceFromSec: frameToSec(s - beatStart, this.fps),voiceToSec: frameToSec(e - beatStart, this.fps),status: "pending",attempts: 0,});}- cursor += beatFrames;- }+ cursor += dur;+ });this.project.durationFrames = cursor;this.project.shots = shots;this.project.beatVoices = beatVoices;assertCoverage(this.project.shots, this.durationFrames);- const music = await this.deps.suite.music.compose({- mood: this.project.script.style ?? this.project.style ?? "cinematic underscore",- durationSec: frameToSec(cursor, this.fps),- });- this.project.musicAssetId = await this.deps.editor.importMedia(music);- await this.save();}// ── Phase A: ingest (provided mode) ──────────────────────────────────────@@ -175,7 +355,12 @@ export class VideoOrchestrator {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 })),+ 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;@@ -196,6 +381,7 @@ export class VideoOrchestrator {await fanOut(needed,async (asset) => {+ if (this.aborted) return; // a paused run spends nothing moreconst raw = await this.deps.suite.image.generate({prompt: buildRefPrompt(asset, this.project.style),refs: refsForAsset(asset, this.project),@@ -225,6 +411,7 @@ export class VideoOrchestrator {}private async makeKeyframes(shot: Shot): 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);@@ -235,6 +422,7 @@ export class VideoOrchestrator {// ── Phase E + F: generation fans out; each clip places when it lands ──────private async generateAndPlaceAll(): Promise<void> {+ if (this.aborted) return;this.setPhase("generating");await this.placeSpine();const pending = this.project.shots.filter((s) => s.status !== "placed");@@ -247,7 +435,7 @@ export class VideoOrchestrator {if (this.project.audioMode !== "generated" || !this.project.beatVoices) return;let changed = false;for (const bv of this.project.beatVoices) {- if (bv.voiceClipId) continue;+ if (bv.voiceClipId || !bv.voiceAssetId) continue;bv.voiceClipId = await this.deps.editor.placeAudio(bv.voiceAssetId, bv.startFrame, bv.durationFrames, {kind: "voice",duck: VOICE_DUCK,@@ -258,11 +446,13 @@ export class VideoOrchestrator {}private async generateAndPlace(shot: Shot): Promise<void> {+ if (this.aborted) return;this.updateShot(shot, { status: "generating", error: undefined });const audio = this.audioForShot(shot);const prompt = buildPrompt(shot, this.project);const refs = shotRefs(shot, this.project);for (let attempt = 1; attempt <= VIDEO_ATTEMPTS; attempt++) {+ if (this.aborted) return; // a paused run spends nothing moreshot.attempts = attempt;try {let clip = await this.deps.suite.video.generate({@@ -327,6 +517,7 @@ export class VideoOrchestrator {/** Hold a still for a shot whose video couldn't be made — never a black gap. */private async placeFallback(shot: Shot): Promise<void> {+ if (this.aborted) return; // a paused run neither spends nor placesconst still = await this.fallbackStill(shot);if (still) {await this.clearVideoPlacement(shot);@@ -375,7 +566,23 @@ export class VideoOrchestrator {// ── Phase H: polish ──────────────────────────────────────────────────────private async polish(): Promise<void> {+ if (this.aborted) return;this.setPhase("polish");+ // Compose the bed now — after the gate and the shots — so an unapproved plan+ // never spends on one. Generated mode only: a provided audio spine is the+ // soundtrack, so nothing is laid over it. Best-effort: no music backend (or+ // one that declines) just means no bed.+ if (this.project.audioMode === "generated" && !this.project.musicAssetId && this.deps.suite.music) {+ try {+ const music = await this.deps.suite.music.compose({+ mood: this.project.script?.style ?? this.project.style ?? "cinematic underscore",+ durationSec: frameToSec(this.durationFrames, this.fps),+ });+ this.project.musicAssetId = await this.deps.editor.importMedia(music);+ } catch {+ this.deps.emit({ type: "log", message: "No music bed this time — assembling without one." });+ }+ }if (this.project.musicAssetId) {// Idempotent: replace the prior bed instead of stacking a second one.if (this.project.musicClipId) await this.deps.editor.removeAudio(this.project.musicClipId);@@ -501,14 +708,24 @@ export class VideoOrchestrator {return this.deps.sleep ? this.deps.sleep(ms) : new Promise((r) => setTimeout(r, ms));}- /** Persist, serialized so concurrent updates never interleave writes. */+ /** Persist, serialized so concurrent updates never interleave writes. An+ * aborted run stops persisting so it can't overwrite the plan the live run+ * (or a switched-to project) now owns. */private save(): Promise<void> {+ if (this.aborted) return Promise.resolve();this.project.updatedAt = this.project.updatedAt + 1; // monotonic without Date in teststhis.saveChain = this.saveChain.then(() => this.deps.persist(this.project)).catch(() => {});return this.saveChain;}}+/** Rough spoken length of a line for planning, before the real voiceover+ * exists — ~165 words/min, floored so even a couple of words hold a beat. */+function estimateSpokenSeconds(dialogue: string): number {+ const words = dialogue.trim().split(/\s+/).filter(Boolean).length;+ 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(diff --git a/site/src/cut/lib/genvideo/registry.ts b/site/src/cut/lib/genvideo/registry.tsindex 0c659283..235b1cc8 100644--- a/site/src/cut/lib/genvideo/registry.ts+++ b/site/src/cut/lib/genvideo/registry.ts@@ -108,7 +108,9 @@ export function fakeRegistry(): ModelRegistry {r.style.register({ id: "fake", label: "Fake style", provider: "fake", make: () => base.style });r.image.register({ id: "fake", label: "Fake image", provider: "fake", make: () => base.image });r.voice.register({ id: "fake", label: "Fake voice", provider: "fake", make: () => base.voice });- r.music.register({ id: "fake", label: "Fake music", provider: "fake", make: () => base.music });+ // The fake studio always supplies a music role (ModelSuite.music is optional+ // now that a real suite can omit the bed).+ r.music.register({ id: "fake", label: "Fake music", provider: "fake", make: () => base.music! });r.transcribe.register({ id: "fake", label: "Fake transcribe", provider: "fake", make: () => base.transcribe });r.lipSync.register({id: "fake",diff --git a/site/src/cut/lib/genvideo/types.ts b/site/src/cut/lib/genvideo/types.tsindex 86081a2e..381f917b 100644--- a/site/src/cut/lib/genvideo/types.ts+++ b/site/src/cut/lib/genvideo/types.ts@@ -97,7 +97,9 @@ export interface Shot {/** One beat's voiceover placed on the soundtrack — the unit the spine is* placed in, so a video regeneration never restacks narration. */export interface BeatVoice {- voiceAssetId: string;+ /** The voiced clip's asset id. Absent while the plan is still on estimated+ * lengths (pre-approval); set once the beat is voiced. */+ voiceAssetId?: string;startFrame: number;durationFrames: number;/** The placed soundtrack clip id, once on the timeline (idempotent placement). */@@ -130,10 +132,18 @@ export interface VideoProject {durationFrames: number;/** Word-level transcript of the spine (provided mode, or generated VO). */transcript: TranscriptWord[];+ /** The shape every render matches. Captured at start and refrozen at the+ * approval gate (the last moment the user can set it), so a render that+ * finishes after a project switch can never pick up another project's shape. */+ aspect?: "9:16" | "16:9";/** Reusable style string every downstream prompt carries. */style: 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+ * tagged to the chat (kept off the Media/Video/Image/Audio panels) and a+ * resume after reload keeps tagging with the same owner. */+ chatId?: string;characters: VideoAsset[];locations: VideoAsset[];shots: Shot[];@@ -145,6 +155,7 @@ export interface VideoProject {export type VideoPhase =| "brief"+ | "voicing"| "ingest"| "breakdown"| "style"diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex cc59e361..26b1bf5c 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -21,9 +21,11 @@ import type {TransitionStyle,VideoClip,} from "./types";+import type { VideoProject } from "./genvideo/types";+import { fillSlot } from "./genvideo/fillSlot";import { apiFetch, apiJson } from "./api";import { trackLocale } from "./subtitles";-import { emptySubtitles, IMAGE_CLIP_SECONDS, isCrossStyle, MAX_SUBTITLE_LANES, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";+import { emptySubtitles, IMAGE_CLIP_SECONDS, isCrossStyle, MAX_SUBTITLE_LANES, mediaUrl, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";import { readTextStyle } from "./textStyle";import { loadUiState, saveUiState } from "./uiState";import { captureTimelineFrames } from "./visualFrames";@@ -126,6 +128,9 @@ export interface EditorState {dropActive: "media" | "other" | null;/** Whether the AI assistant panel is open (remembered across sessions). */aiOpen: boolean;+ /** In-progress or finished brief-to-video run; persisted on ProjectDoc.genvideo+ * and driven by the genScene store. Absent when no scene was generated. */+ genvideo?: VideoProject;loadProject: (id: string) => Promise<void>;setProjectName: (name: string) => void;@@ -147,6 +152,30 @@ export interface EditorState {* to that gain while it plays; `opts.lane` picks the audio track it lands* on (default: the first one). */addAudioFromAsset: (assetId: string, start?: number, opts?: { duck?: number; lane?: number }) => void;+ /** Set (or clear) the persisted brief-to-video run. Replaces the object by+ * reference so autosave detects the change. */+ setGenvideo: (project: VideoProject | undefined) => void;+ /** Brief-to-video placement: place a generated clip so it fills exactly+ * [startSec, endSec) on track 0 — exact start (no slide), muted, time-stretched+ * or trimmed to the slot — and return its id. Leaves selection untouched (the+ * run is a background process). */+ placeGenClip: (assetId: string, startSec: number, endSec: number) => string | null;+ /** Brief-to-video placement: place a generated audio clip at startSec spanning+ * up to durSec on the soundtrack (duck/lane optional), returning its id. */+ placeGenAudio: (assetId: string, startSec: number, durSec: number, opts?: { duck?: number; lane?: number }) => string | null;+ /** Remove a video clip by id (a background gen swap; leaves its slot empty). */+ removeClipById: (id: string) => void;+ /** Remove a soundtrack clip by id (background gen swap, idempotent placement). */+ removeAudioById: (id: string) => void;+ /** Re-mark a resumed run's already-placed clips as render-owned. The gen sets+ * reset on load, so hydrate re-registers the persisted plan's clip ids to keep+ * undo/redo off them while the run finishes. */+ adoptGenClips: (clipIds: string[], audioIds: string[]) => void;+ /** Hand a finished run's clips over to the user's undo domain: splice them+ * into every existing history snapshot (which excluded them while the run+ * owned them) and clear the gen sets, so post-run edits to generated clips+ * undo like any other edit. */+ releaseGenClips: () => void;addOverlay: () => void;updateClip: (id: string, patch: Partial<VideoClip>) => void;/** Set a clip's playback rate (0.25–4). A longer footprint pushes the@@ -288,6 +317,16 @@ let docSeq = 0;* beginHistoryBatch). One checkpoint is captured when it goes 0→1. */let batchDepth = 0;+/** Ids of clips a background generation run placed. Those clips are the+ * orchestrator's to manage — it swaps them idempotently and holds each shot's+ * timeline id — so the user's undo/redo must neither remove nor resurrect them.+ * They are dropped from every history snapshot and re-attached live on restore,+ * so stepping through history can't open a black gap under a running render or+ * bring back a shot the run already replaced. Transient: not persisted and+ * cleared on load, so a reopened project treats them as ordinary clips. */+const genClipIds = new Set<string>();+const genAudioIds = new Set<string>();+/** Timeline clipboard (⌘C/⌘V) — survives across projects in one session. One* entry per copied item so a multi-selection round-trips. */type ClipboardItem =@@ -367,8 +406,9 @@ export function footprints(items: (VideoClip | AudioClip)[]): { start: number; e}/** POST a transcribe spec and poll the job to completion. Returns the cues, or- * null when the user switches projects mid-run. Throws user-facing errors. */-async function runTranscription(projectId: string, spec: object): Promise<SubtitleCue[] | null> {+ * null when the user switches projects mid-run. Throws user-facing errors.+ * Shared with the brief-to-video transcribe adapter. */+export async function runTranscription(projectId: string, spec: object): Promise<SubtitleCue[] | null> {const res = await apiFetch(`/api/cut/projects/${projectId}/transcribe`, {method: "POST",headers: { "Content-Type": "application/json" },@@ -393,8 +433,10 @@ export const useEditor = create<EditorState>((set, get) => {const snapshot = (): DocSnapshot => {const { clips, audioClips, overlays, subtitles } = get();return {- clips: clips.map((c) => ({ ...c })),- audioClips: audioClips.map((c) => ({ ...c })),+ // Render-owned clips are excluded — history captures the user's timeline,+ // not the background run's placements (restoreDoc re-attaches the live ones).+ clips: clips.filter((c) => !genClipIds.has(c.id)).map((c) => ({ ...c })),+ audioClips: audioClips.filter((c) => !genAudioIds.has(c.id)).map((c) => ({ ...c })),overlays: overlays.map((o) => ({ ...o })),subtitles: {...subtitles,@@ -403,6 +445,22 @@ export const useEditor = create<EditorState>((set, get) => {};};+ /** Apply a history snapshot, re-attaching the render-owned clips it omitted so+ * an undo/redo never disturbs a background run's placements. The live gen+ * clips are read at restore time, so the set is always current. */+ const restoreDoc = (snap: DocSnapshot) => {+ const { clips, audioClips } = get();+ const genClips = clips.filter((c) => genClipIds.has(c.id));+ const genAudio = audioClips.filter((c) => genAudioIds.has(c.id));+ set({+ ...snap,+ clips: [...snap.clips, ...genClips].sort((a, b) => a.start - b.start),+ audioClips: [...snap.audioClips, ...genAudio],+ selection: null,+ multiSelection: [],+ });+ };+/** Seal the deferred checkpoint: commit it to history only if the doc* changed since it was taken; otherwise drop it and leave redo intact. */const flush = () => {@@ -424,6 +482,29 @@ export const useEditor = create<EditorState>((set, get) => {pending = { snap: snapshot(), seq: docSeq };};+ /** Remove one gen-swap placement (video or audio) by id: the clip, its+ * gen-set entry, and any selection pointing at it. No push() — the+ * orchestrator's swaps stay off the undo stack. */+ const removeGenPlacement = (id: string, kind: "clip" | "audio") => {+ const exists =+ kind === "clip"+ ? get().clips.some((c) => c.id === id)+ : get().audioClips.some((c) => c.id === id);+ if (!exists) return;+ (kind === "clip" ? genClipIds : genAudioIds).delete(id);+ set((s) => {+ const keep = (sel: Selection) => !(!!sel && sel.kind === kind && sel.id === id);+ const multiSelection = s.multiSelection.filter(keep);+ return {+ ...(kind === "clip"+ ? { clips: s.clips.filter((c) => c.id !== id) }+ : { audioClips: s.audioClips.filter((c) => c.id !== id) }),+ multiSelection,+ selection: keep(s.selection) ? s.selection : multiSelection[multiSelection.length - 1] ?? null,+ };+ });+ };+return {projectId: null,projectName: "",@@ -454,11 +535,16 @@ export const useEditor = create<EditorState>((set, get) => {exportOpen: false,dropActive: null,aiOpen: typeof window !== "undefined" && localStorage.getItem("cut-ai-open") === "1",+ genvideo: undefined,loadProject: async (id) => {history.length = 0;future.length = 0;pending = null;+ // A fresh project owns no live run — any prior run's render-owned ids are+ // stale, and the loaded clips are ordinary, fully-undoable content.+ genClipIds.clear();+ genAudioIds.clear();set({projectId: id,loaded: false,@@ -480,6 +566,7 @@ export const useEditor = create<EditorState>((set, get) => {subtitleStatus: "idle",subtitleError: null,exportOpen: false,+ genvideo: undefined,});try {const [res, ui] = await Promise.all([apiFetch(`/api/cut/projects/${id}`), loadUiState(id)]);@@ -538,6 +625,7 @@ export const useEditor = create<EditorState>((set, get) => {},subtitles: doc.subtitles ?? emptySubtitles(),subtitleStatus: (doc.subtitles?.cues.length ?? 0) > 0 ? "ready" : "idle",+ genvideo: doc.genvideo ?? undefined,loaded: true,});} catch (err) {@@ -548,6 +636,114 @@ export const useEditor = create<EditorState>((set, get) => {setProjectName: (name) => set({ projectName: name }),setSaveState: (s) => set({ saveState: s }),+ // Clone so each persist yields a fresh top-level reference: the orchestrator+ // mutates one project object in place, and autosave detects a genvideo change+ // by identity — without the clone every save after the first looks unchanged+ // and the plan is never written back.+ setGenvideo: (project) => set({ genvideo: project ? { ...project } : undefined }),++ placeGenClip: (assetId, startSec, endSec) => {+ const asset = get().assets.find((a) => a.id === assetId);+ if (!asset || (asset.type !== "video" && asset.type !== "image")) return null;+ // Fill the slot exactly so the track never opens a gap between shots —+ // fillSlot mirrors the plan's frame-coverage invariant at this boundary.+ const { out, speed } = fillSlot(+ asset.type,+ Math.max(MIN_LEN, asset.duration),+ Math.max(MIN_LEN, endSec - startSec),+ SPEED_MIN+ );+ const clip: VideoClip = {+ id: uid(),+ assetId,+ track: 0,+ start: Math.max(0, startSec),+ in: 0,+ out,+ // Muted: generated shots ride under the narration spine, so the clip's+ // own audio (Veo synthesizes some) must never compete with the voice.+ muted: true,+ ...(speed !== undefined ? { speed } : {}),+ };+ // Render-owned: no push(), and tracked so history snapshots exclude it —+ // the orchestrator manages this clip (it swaps clips idempotently), so a+ // mid-render Cmd+Z must not pull a shot out from under the run.+ genClipIds.add(clip.id);+ set((s) => ({ clips: [...s.clips, clip].sort((a, b) => a.start - b.start) }));+ return clip.id;+ },++ placeGenAudio: (assetId, startSec, durSec, opts) => {+ const asset = get().assets.find((a) => a.id === assetId);+ if (!asset || asset.type !== "audio") return null;+ const out = Math.min(asset.duration, Math.max(MIN_LEN, durSec));+ const lane = opts?.lane ?? 0;+ const clip: AudioClip = {+ id: uid(),+ assetId,+ start: Math.max(0, startSec),+ in: 0,+ out,+ volume: 1,+ ...(opts?.duck !== undefined && opts.duck < 1 ? { duck: Math.max(0, opts.duck) } : {}),+ ...(lane > 0 ? { lane } : {}),+ };+ // Render-owned: no push(), tracked so history snapshots exclude it.+ genAudioIds.add(clip.id);+ set((s) => ({ audioClips: [...s.audioClips, clip] }));+ return clip.id;+ },++ // Shared body of the two gen-swap removals: drop the clip, its gen-set+ // entry, and any selection pointing at it — with no push(), because the+ // orchestrator's swaps stay off the undo stack.+ removeClipById: (id) => removeGenPlacement(id, "clip"),++ adoptGenClips: (clipIds, audioIds) => {+ for (const id of clipIds) genClipIds.add(id);+ for (const id of audioIds) genAudioIds.add(id);+ // The invariant is exact: no history snapshot holds a gen-owned clip.+ // Re-adopting released clips (a regeneration after done) scrubs them back+ // out of existing snapshots, so the eventual release grafts exactly one+ // copy and an undo never restores a clip the run has since swapped.+ const scrub = (snap: DocSnapshot) => {+ snap.clips = snap.clips.filter((c) => !genClipIds.has(c.id));+ snap.audioClips = snap.audioClips.filter((c) => !genAudioIds.has(c.id));+ };+ for (const snap of history) scrub(snap);+ for (const snap of future) scrub(snap);+ if (pending) scrub(pending.snap);+ },++ releaseGenClips: () => {+ if (genClipIds.size === 0 && genAudioIds.size === 0) return;+ const { clips, audioClips } = get();+ const relClips = clips.filter((c) => genClipIds.has(c.id));+ const relAudio = audioClips.filter((c) => genAudioIds.has(c.id));+ // Every existing snapshot omitted these clips; splice them in at their+ // final state (matching what restoreDoc would have re-attached), so an+ // undo across the run's lifetime never drops a paid render.+ const graft = (snap: DocSnapshot) => {+ if (relClips.length > 0) {+ const have = new Set(snap.clips.map((c) => c.id));+ snap.clips = [...snap.clips, ...relClips.filter((c) => !have.has(c.id)).map((c) => ({ ...c }))].sort(+ (a, b) => a.start - b.start+ );+ }+ if (relAudio.length > 0) {+ const have = new Set(snap.audioClips.map((c) => c.id));+ snap.audioClips = [...snap.audioClips, ...relAudio.filter((c) => !have.has(c.id)).map((c) => ({ ...c }))];+ }+ };+ for (const snap of history) graft(snap);+ for (const snap of future) graft(snap);+ if (pending) graft(pending.snap);+ genClipIds.clear();+ genAudioIds.clear();+ },++ removeAudioById: (id) => removeGenPlacement(id, "audio"),+pushHistory: push,beginHistoryBatch: () => {@@ -732,7 +928,7 @@ export const useEditor = create<EditorState>((set, get) => {setClipSpeed: (id, speed) => {const clip = get().clips.find((c) => c.id === id);if (!clip) return;- const clamped = Math.max(SPEED_MIN, Math.min(SPEED_MAX, speed));+ const clamped = Math.max(SPEED_FLOOR, speed);if (Math.abs(clamped - clipSpeed(clip)) < 1e-4) return;resizeClipFootprint(clip, { speed: clamped }, Math.max(MIN_LEN, (clip.out - clip.in) / clamped));},@@ -2085,7 +2281,7 @@ export const useEditor = create<EditorState>((set, get) => {const prev = history.pop();if (!prev) return;future.push(snapshot());- set({ ...prev, selection: null, multiSelection: [] });+ restoreDoc(prev);},redo: () => {@@ -2094,7 +2290,7 @@ export const useEditor = create<EditorState>((set, get) => {if (!next) return;history.push(snapshot());if (history.length > HISTORY_CAP) history.shift();- set({ ...next, selection: null, multiSelection: [] });+ restoreDoc(next);},};});@@ -2141,6 +2337,7 @@ export function serializeDoc(s: {publish: { caption: string; tags: string; soundTitle: string; handle: string };notes: { text: string; publishedAt: string; links: string[] };subtitles: SubtitlesBlock;+ genvideo?: VideoProject;}): Partial<ProjectDoc> {return {name: s.projectName,@@ -2154,6 +2351,9 @@ export function serializeDoc(s: {subtitles: s.subtitles,publish: { ...s.publish },notes: { ...s.notes, links: [...s.notes.links] },+ // Explicit null when there is no run: absence means "keep what you have"+ // to the PUT handler, so a dismissed plan could otherwise never be cleared.+ genvideo: s.genvideo ?? null,};}diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.tsindex b6832817..0701bb65 100644--- a/site/src/cut/lib/tts.ts+++ b/site/src/cut/lib/tts.ts@@ -1,6 +1,7 @@"use client";import { geminiModels } from "@/lib/inference/gemini-models";+import { bytesFromBase64 } from "./bytes";import { useGenNotify } from "./genNotify";import { importFileToProject } from "./media";import type { MediaAsset } from "./types";@@ -247,9 +248,7 @@ async function synthesizeSegment(const out = gen.outputs?.find((o) => o.dataBase64);if (!out?.dataBase64) throw new Error("The provider returned no audio.");- const bin = atob(out.dataBase64);- const bytes = new Uint8Array(new ArrayBuffer(bin.length));- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ const bytes = bytesFromBase64(out.dataBase64);const rate = Number(out.contentType?.match(/rate=(\d+)/)?.[1]) || 24000;// Gemini TTS returns raw little-endian 16-bit mono PCM.return { samples: new Int16Array(bytes.buffer, 0, bytes.byteLength >> 1), rate };diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 7a668eca..99b52f66 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -1,4 +1,5 @@import { apiUrl } from "./api";+import type { VideoProject } from "./genvideo/types";export type AssetType = "video" | "audio" | "image";@@ -144,9 +145,11 @@ export interface VideoClip {hidden?: boolean;}-/** Speed limits — matches the Inspector control and export atempo range. */+/** Speed slider range. Typed entry and tools may go beyond it; SPEED_FLOOR is+ * the only hard bound, keeping rates positive so length math stays finite. */export const SPEED_MIN = 0.25;export const SPEED_MAX = 4;+export const SPEED_FLOOR = 0.05;/** Longest transition offered; also clamps against the clips it joins. */export const TRANSITION_MAX = 2;@@ -464,6 +467,11 @@ export interface ProjectDoc {};/** Which project folder this belongs to (null/absent = ungrouped). */folderId?: string | null;+ /** In-progress or finished brief-to-video run (genvideo). Persisted so a+ * multi-minute generation survives reload and resumes; the plan is the single+ * source of truth for the run (see lib/genvideo/types.ts). On the save wire,+ * null means "clear it" (absent means keep); at rest it is never null. */+ genvideo?: VideoProject | null;}/** A named group of projects on the home screen. */diff --git a/site/src/cut/lib/videoGen.ts b/site/src/cut/lib/videoGen.tsindex fd4ae42e..b9f20ac4 100644--- a/site/src/cut/lib/videoGen.ts+++ b/site/src/cut/lib/videoGen.ts@@ -54,6 +54,22 @@ export const VIDEO_MODELS: VideoModelOption[] = [},];+/** The registry entry for a tier — the single source of truth for what that+ * model supports. Any code that generates video (the panel, the scene pipeline)+ * reads its constraints from here, so swapping models is one edit in this file. */+export function videoModel(tier: "fast" | "high"): VideoModelOption {+ return VIDEO_MODELS.find((m) => m.tier === tier) ?? VIDEO_MODELS[0];+}++/** Snap a desired clip length to one the model actually renders: the shortest+ * supported duration that still covers `seconds` (the caller trims down to the+ * exact need), or the model's longest. Video models render only a fixed set of+ * lengths and reject anything else, so a caller must never pass a raw duration. */+export function supportedVideoDuration(tier: "fast" | "high", seconds: number): number {+ const durations = [...videoModel(tier).durations].sort((a, b) => a - b);+ return durations.find((d) => d >= seconds) ?? durations[durations.length - 1];+}+interface VideoGenState {prompt: string;/** The shape the next generation is composed in. */diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 9985b340..f48a961a 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -185,7 +185,7 @@ export const AI_TOOLS: AiToolDef[] = [h: num("Height 0..1"),}, ["x", "y", "w", "h"]),fit: { type: "string", enum: ["fit", "fill"], description: "How the video meets its region" },- speed: num("Playback rate 0.25–4"),+ speed: num("Playback rate (1 = normal, no upper limit)"),}, ["id"]),},{@@ -306,6 +306,41 @@ export const AI_TOOLS: AiToolDef[] = [index: num("Insert position on the video track (passing it implies add_to_timeline)"),}, ["character_id", "line"]),},+ {+ name: "generate_scene",+ description:+ "Generate a WHOLE short video — a narrated, multi-shot cut assembled on the timeline — from a brief, or animate audio already in the project. Use this when the user wants a complete video/scene/story (\"make me a video about…\", \"turn this into a 20-second short\"), not a single clip (that's generate_video). It writes a script, voices it, breaks it into shots, then RETURNS the shot plan and STOPS: get the user's go-ahead and call approve_scene before the shots render, because each shot spends credits. Pass from_audio_asset_id to animate an audio spine the project already has (a voiceover, recording, or song → shots tiled over it) instead of writing a new script. The look is derived from the brief and any references and can be anything — cinematic live-action, anime, documentary, product ad, cartoon; never assume a genre, let the brief decide, and describe the look by its visual traits rather than naming a real franchise, show, or artist (even one a reference resembles) — the user may not want it and the generator rejects trademarked names. Needs the user signed in to Donkey (spends credits).",+ inputSchema: obj({+ brief: str("What the video is about — the story or subject. Omit only when animating existing audio."),+ from_audio_asset_id: str("Animate this project audio asset (id from media) — shots tile over it instead of a new script"),+ target_seconds: num("Rough total length in seconds, 6–90 (default ~24)"),+ aspect: { type: "string", enum: ["9:16", "16:9"], description: "Output shape (default: the project aspect)" },+ style: str("Optional look to steer the whole video (e.g. 'moody neon, handheld'); usually left to the brief"),+ reference_asset_ids: {+ type: "array",+ items: { type: "string" },+ description: "Project image/video asset ids that anchor the look (the user's attached references)",+ },+ }),+ },+ {+ name: "approve_scene",+ description:+ "Approve the pending generate_scene shot plan and start rendering. The shots render in the background and land on the timeline as they finish. Call this only when the user confirms (\"go\", \"do it\", \"looks good\") — approving spends credits per shot.",+ inputSchema: obj({}),+ },+ {+ name: "regenerate_shot",+ description:+ "Redo one shot of the generated scene by its number (1-based), optionally nudging it (\"wider\", \"at night\", \"more energetic\"). Only valid after a scene has been generated.",+ inputSchema: obj({ n: num("Shot number, 1-based"), note: str("Optional change to apply to that shot") }, ["n"]),+ },+ {+ name: "restyle_scene",+ description:+ "Restyle the whole generated scene and redo every shot with a new look (\"make it black-and-white film noir\", \"turn it into anime\"). Only valid after a scene has been generated. Spends credits (every shot re-renders), so confirm first.",+ inputSchema: obj({ style: str("The new look for the whole video") }, ["style"]),+ },{name: "stock_search",description:@@ -526,8 +561,8 @@ export const AI_TOOLS: AiToolDef[] = [{name: "set_speed",description:- "Set a video clip's playback speed (0.25–4×). Faster shortens the clip on the timeline; slower stretches it. Later titles and captions shift to stay in sync.",- inputSchema: obj({ clipId: str("Video clip id"), speed: num("Playback rate 0.25–4 (1 = normal)") }, ["clipId", "speed"]),+ "Set a video clip's playback speed. Faster shortens the clip on the timeline; slower stretches it. Later titles and captions shift to stay in sync.",+ inputSchema: obj({ clipId: str("Video clip id"), speed: num("Playback rate (1 = normal, no upper limit)") }, ["clipId", "speed"]),},{name: "set_transition",@@ -600,7 +635,7 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim- Overlay video: a video/image asset can sit on a track above track 0 (track 1, 2… — topmost wins) or behind it (track -1…). A full-frame overlay covers everything below it; give it a layout to share the frame — top/bottom/left/right halves for a split screen, pip for a floating corner box, or a custom region rect. add_overlay_video creates one from a media asset; update_overlay_video moves/trims/regions/mutes/hides it. The user makes them by dragging media above/below track 0; they drag the region in the preview.- A clip's timeline length is (out-in)/speed; total duration runs to the last clip's end, gaps included, minus cross-style transition overlaps.- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.-- set_speed sets a clip's playback rate (0.25–4×); it changes the clip's timeline length, and later titles/captions ripple to stay in sync.+- set_speed sets a clip's playback rate; it changes the clip's timeline length, and later titles/captions ripple to stay in sync.- set_transition joins a clip into the next one (0–2s, six styles) — read the transitions-and-fades skill before styling cuts. Splitting or deleting clears the affected transition.- split_at cuts the track-0 clip under that time into two clips at the exact frame. With a soundtrack or overlay clip selected it splits that instead.- The user can multi-select (⌘/⇧-click) and delete several items at once; a hover chip on each video clip toggles its own audio.@@ -705,7 +740,7 @@ Rules:- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.- Don't transcribe a video with no speech. If the user wants captions on silent footage, use subtitles_from_visuals (it narrates what's on screen). Never invent a spoken transcript.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.-- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two.+- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two. For a whole video — a full scene or story, not one clip — generate_scene plans a narrated multi-shot cut and stops at the shot list; confirm with the user, then call approve_scene, since it renders many paid shots (regenerate_shot / restyle_scene revise it after).- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen; listen_audio plays a project audio asset; detect_silence finds dead air; capture_frame shows the one rendered frame at the playhead. The watching-and-cutting skill has the flow.`;}diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex 1fd4a2ed..5f0e824c 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -135,6 +135,10 @@ export const projectsApi = {body.notes && typeof body.notes === "object"? { ...existing.notes, ...body.notes }: existing.notes,+ // Brief-to-video run state. Persisted verbatim; a client that omits the+ // key keeps the existing plan, and null clears it (a dismissed plan) —+ // normalized to undefined so the doc at rest never stores null.+ genvideo: body.genvideo !== undefined ? body.genvideo ?? undefined : existing.genvideo,};await writeProject(id, doc);return Response.json({ ok: true, updatedAt: doc.updatedAt });@@ -249,7 +253,11 @@ export const projectsApi = {async transcribeStart(req: Request, { id }: { id: string }) {try {const body = (await req.json()) as Omit<TranscribeSpec, "projectId">;- if (!Array.isArray(body.clips) || typeof body.duration !== "number") {+ if (+ !Array.isArray(body.clips) ||+ !Array.isArray(body.audio) ||+ typeof body.duration !== "number"+ ) {return err("Bad transcribe spec.", 400);}const job = await createTranscribeJob({ ...body, projectId: id });diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.tsindex dba8567c..46a680ae 100644--- a/site/src/cut/server/transcribe.ts+++ b/site/src/cut/server/transcribe.ts@@ -181,7 +181,11 @@ export async function createTranscribeJob(spec: TranscribeSpec): Promise<Transcrasync function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {if (!(await readProject(spec.projectId))) throw new Error("Project not found.");- if (spec.clips.length === 0) throw new Error("Add a video to the timeline first.");+ // Video clips or a soundtrack clip are both valid speech sources (the render+ // below mixes either), so an audio-only cut — a voiceover with no video, or a+ // brief-to-video run transcribing its audio spine — transcribes fine.+ if (spec.clips.length === 0 && spec.audio.length === 0)+ throw new Error("Add audio or video to the timeline first.");const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-stt-"));try {@@ -244,21 +248,27 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {// with a cross-dissolve overlap by the transition length (acrossfade), the// rest concatenate. A flat concat would run longer than the timeline, so// every cue after a dissolve would land progressively late.- let aAcc = "a0";- let acc = clipDur(spec.clips[0]);- for (let j = 1; j < spec.clips.length; j++) {- const prev = spec.clips[j - 1];- const durJ = clipDur(spec.clips[j]);- const d = Math.min(prev.transition ?? 0, acc * 0.9, durJ * 0.9);- const out = `aj${j}`;- if (d > 0.01) {- filters.push(`[${aAcc}][a${j}]acrossfade=d=${num(d)}[${out}]`);- acc = acc + durJ - d;- } else {- filters.push(`[${aAcc}][a${j}]concat=n=2:v=0:a=1[${out}]`);- acc = acc + durJ;+ // Skipped entirely for an audio-only cut (no clips) — there is no clip-audio+ // chain to build, only the soundtrack, mixed below. (`spec.clips[0]` would be+ // undefined otherwise.)+ let aAcc: string | null = null;+ if (spec.clips.length > 0) {+ aAcc = "a0";+ let acc = clipDur(spec.clips[0]);+ for (let j = 1; j < spec.clips.length; j++) {+ const prev = spec.clips[j - 1];+ const durJ = clipDur(spec.clips[j]);+ const d = Math.min(prev.transition ?? 0, acc * 0.9, durJ * 0.9);+ const out = `aj${j}`;+ if (d > 0.01) {+ filters.push(`[${aAcc}][a${j}]acrossfade=d=${num(d)}[${out}]`);+ acc = acc + durJ - d;+ } else {+ filters.push(`[${aAcc}][a${j}]concat=n=2:v=0:a=1[${out}]`);+ acc = acc + durJ;+ }+ aAcc = out;}- aAcc = out;}const soundLabels: string[] = [];@@ -273,11 +283,21 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {);soundLabels.push(`snd${k}`);});- let aLabel = aAcc;- if (soundLabels.length > 0) {++ // Mix the clip chain (when present) with the soundtrack. A single source+ // needs no amix; hasSpeechSource above guarantees at least one input here.+ // duration=longest spans every input (a late soundtrack clip must not be+ // cut off — with no video clip chain, `first` would truncate the mix to the+ // earliest-finishing clip and drop later speech); the outer `-t+ // spec.duration` then trims to the timeline.+ const mixInputs = [...(aAcc ? [aAcc] : []), ...soundLabels];+ let aLabel: string;+ if (mixInputs.length <= 1) {+ aLabel = mixInputs[0];+ } else {filters.push(- [aAcc, ...soundLabels].map((l) => `[${l}]`).join("") +- `amix=inputs=${soundLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`+ mixInputs.map((l) => `[${l}]`).join("") ++ `amix=inputs=${mixInputs.length}:duration=longest:dropout_transition=0:normalize=0[amix]`);aLabel = "amix";}