Skip to content

Open source CapCut alternative.

TypeScript

feat(site): scene generation gets a dailies pass — reviewed takes, retakes with critique, reviewer-chosen trims, content-driven breakdown

David Le9cf90a04c406
diff --git a/site/scripts/genvideo-selftest.ts b/site/scripts/genvideo-selftest.ts
index a33c2458..9c9d14ca 100644
--- a/site/scripts/genvideo-selftest.ts
+++ b/site/scripts/genvideo-selftest.ts
@@ -164,6 +164,31 @@ async function run(): Promise<void> {
check("no double-import of stills (fallback holds an already-imported id)", editor.placed.length === project.shots.length);
}
+ section("dailies review — a declined take retries, the pass's window trims the placement");
+ {
+ const editor = editorWithAudio(DURATION_FRAMES);
+ const { d, studio } = deps(editor, {
+ audioNative: true,
+ reviewVerdicts: [
+ { ok: false, note: "the subject is reading, the plan wants swimming" },
+ { ok: true, fromSec: 1.5 },
+ ],
+ });
+ const project = baseProject({ audioMode: "provided", audioClipId: "audio-clip", audioAssetId: "audio-asset", durationFrames: DURATION_FRAMES });
+ const orch = new VideoOrchestrator(project, d);
+ await orch.run();
+ await orch.approveBreakdown();
+ check("run reaches done", project.phase === "done");
+ assertTiling("placed clips tile the whole audio", editor.placed, DURATION_FRAMES);
+ const videoGens = studio.calls.filter((c) => c.role === "video").length;
+ check("the declined take was regenerated", videoGens === project.shots.length + 1, `${videoGens} generations for ${project.shots.length} shots`);
+ const reviewed = studio.calls.filter((c) => c.role === "review").length;
+ check("every take was reviewed (including the retake)", reviewed === project.shots.length + 1, `${reviewed} reviews`);
+ check("the retake prompt carries the reviewer's note", studio.calls.some((c) => c.role === "video" && c.detail.includes("the plan wants swimming")));
+ check("the pass's window trims the placement", editor.placed.some((c) => c.srcInSec === 1.5));
+ check("all shots placed clean", project.shots.every((s) => s.status === "placed"));
+ }
+
// ── Entry 2: brief only → script, voice, music, video ────────────────────
section('brief only → "a video of me and my son", audio-native video');
{
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index 2da464b9..ba6fcce0 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -116,15 +116,26 @@ class Engine {
this.audioEls.clear();
}
- private videoFor(clip: VideoClip, asset: MediaAsset): MediaEl {
- let el = this.videoEls.get(clip.id);
+ /** The cached element for a clip, rebuilt when its source no longer matches —
+ * a swap keeps the clip id but repoints the asset (a shot re-render), and the
+ * old decoder would otherwise keep playing (or erroring on) the old file. */
+ private elFor(map: Map<string, MediaEl>, clipId: string, asset: MediaAsset): MediaEl {
+ let el = map.get(clipId);
+ if (el && el.getAttribute("src") !== asset.url) {
+ teardown(el);
+ el = undefined;
+ }
if (!el) {
el = makeMediaEl(asset);
- this.videoEls.set(clip.id, el);
+ map.set(clipId, el);
}
return el;
}
+ private videoFor(clip: VideoClip, asset: MediaAsset): MediaEl {
+ return this.elFor(this.videoEls, clip.id, asset);
+ }
+
/** Seek/rate/play one clip's element toward its frame at timeline time `t`,
* without touching any other element (the caller pauses stale ones). */
private prepare(span: ClipSpan, t: number, play: boolean, muted: boolean): MediaEl {
@@ -342,13 +353,10 @@ class Engine {
}
private overlayVideoFor(clip: VideoClip, asset: MediaAsset): MediaEl {
- let el = this.overlayEls.get(clip.id);
- if (!el) {
- el = makeMediaEl(asset);
- // Overlay audio is mixed on export, not previewed here.
- if (!isImageEl(el)) el.muted = true;
- this.overlayEls.set(clip.id, el);
- }
+ const had = this.overlayEls.get(clip.id);
+ const el = this.elFor(this.overlayEls, clip.id, asset);
+ // Overlay audio is mixed on export, not previewed here.
+ if (el !== had && !isImageEl(el)) el.muted = true;
return el;
}
@@ -484,6 +492,11 @@ class Engine {
const asset = s.assets.find((x) => x.id === a.assetId);
if (!asset) continue;
let el = this.audioEls.get(a.id);
+ // Same-id source swaps (a regenerated voiceover) rebuild the element.
+ if (el && el.getAttribute("src") !== asset.url) {
+ el.pause();
+ el = undefined;
+ }
if (!el) {
el = new Audio(asset.url);
el.preload = "auto";
@@ -643,9 +656,10 @@ class Engine {
const now = performance.now();
const dt = this.lastPlayNow ? Math.min(0.25, (now - this.lastPlayNow) / 1000) : 0;
let atEnd: boolean;
- if (isImageEl(el)) {
- // A still has no element clock — advance purely by wall clock and end
- // at the clip's timeline footprint.
+ if (isImageEl(el) || elErrored(el)) {
+ // A still has no element clock, and a broken source's clock never
+ // advances (steering by it would pin the playhead at the clip start) —
+ // move purely by wall clock and end at the clip's timeline footprint.
t = Math.max(span.start, Math.min(t + dt, span.start + span.len));
atEnd = t >= span.start + span.len - 0.0001;
} else {
diff --git a/site/src/cut/lib/genvideo/activity.ts b/site/src/cut/lib/genvideo/activity.ts
new file mode 100644
index 00000000..e9b729d1
--- /dev/null
+++ b/site/src/cut/lib/genvideo/activity.ts
@@ -0,0 +1,26 @@
+"use client";
+
+/**
+ * The run's live ticker — one line narrating what is happening right now,
+ * updated constantly ("Drawing pose 3/6…", "Binding 6 poses into a clip…").
+ * Adapters report fire-and-forget; whoever renders the run subscribes. Latest
+ * message wins — this is a status line, not a log. The orchestrator itself
+ * stays browser-free and narrates through its typed `activity` event instead;
+ * both streams converge in the scene store.
+ */
+
+type Listener = (message: string, projectId?: string) => void;
+const listeners = new Set<Listener>();
+
+/** `projectId` scopes the line to one run — with several projects rendering
+ * at once, a background run must not narrate over the open one's card. */
+export function reportActivity(message: string, projectId?: string): void {
+ for (const fn of listeners) fn(message, projectId);
+}
+
+export function onActivity(fn: Listener): () => void {
+ listeners.add(fn);
+ return () => {
+ listeners.delete(fn);
+ };
+}
diff --git a/site/src/cut/lib/genvideo/adapters/index.ts b/site/src/cut/lib/genvideo/adapters/index.ts
index 311a0683..f50ed3cb 100644
--- a/site/src/cut/lib/genvideo/adapters/index.ts
+++ b/site/src/cut/lib/genvideo/adapters/index.ts
@@ -13,12 +13,14 @@
* 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.
+ * no bed when no music backend is configured. `review` is the dailies check:
+ * every take is watched against its plan before it places.
*/
import type { ModelSuite } from "../capabilities";
import { makeImageRole, makeVideoRole, makeVoiceRole } from "./media";
import { makeMusicRole } from "./music";
+import { makeReviewRole } from "./review";
import { makeBreakdownRole, makeScriptRole, makeStyleRole } from "./text";
import { makeTranscribeRole } from "./transcribe";
@@ -37,5 +39,6 @@ export function realSuite(projectId: string, chatId?: string): ModelSuite {
voice: makeVoiceRole(projectId, chatId),
music: makeMusicRole(projectId, chatId),
transcribe: makeTranscribeRole(projectId),
+ review: makeReviewRole(projectId),
};
}
diff --git a/site/src/cut/lib/genvideo/adapters/review.ts b/site/src/cut/lib/genvideo/adapters/review.ts
new file mode 100644
index 00000000..f48e6de1
--- /dev/null
+++ b/site/src/cut/lib/genvideo/adapters/review.ts
@@ -0,0 +1,85 @@
+"use client";
+
+/**
+ * The dailies reviewer — a multimodal judgment role that watches a rendered
+ * take the way an editor screens footage: sampled frames of the clip ride to
+ * the hosted model with the shot's planned action and the words heard over it,
+ * and the verdict either passes the take (with the best in-point for the slot)
+ * or declines it with a note the retake prompt carries.
+ *
+ * Frames come from the same in-browser capture the visual-subtitles pipeline
+ * uses, so nothing renders server-side and the whole check is one cheap
+ * structured call.
+ */
+
+import { geminiModelRoles } from "@/lib/inference/gemini-models";
+import { hostedPost } from "../../hosted";
+import { captureVideoFrames } from "../../visualFrames";
+import { findRunAsset } from "../docWriter";
+import type { ReviewInput, ReviewRole, ReviewVerdict } from "../capabilities";
+
+const MAX_FRAMES = 8;
+/** Aim for one frame every ~1s of take. */
+const SECONDS_PER_FRAME = 1;
+
+const REVIEW_INSTRUCTIONS = `You are a film editor reviewing one rendered take against its shot plan.
+Reply with JSON only: {"ok": boolean, "note": string, "fromSec": number}
+Rules:
+- ok is whether the take shows the planned action and its subject. Judge content — the right person doing the right thing in the right place — and forgive style and small details.
+- Any rendered text is an automatic fail: captions, subtitles, speech bubbles, titles, watermarks, or readable signs — note it as "remove every trace of on-screen text". A split screen, stacked panels, or a storyboard collage is also an automatic fail: the take must be one single continuous shot.
+- Baked-in editing effects are an automatic fail: transition frames, fades to black or white, motion-blur smears, borders, or blurred letterbox bands — the picture must fill the frame edge to edge; the editor adds transitions later.
+- note, when ok is false, is one short sentence naming what is wrong, written as direction for the retake ("the boy is reading, the plan wants him swimming").
+- fromSec is where the needed window should start inside the take so its best moment lands in the window; 0 when the opening works. Stay within the take.`;
+
+function frameTimes(clipSec: number): number[] {
+ const count = Math.min(MAX_FRAMES, Math.max(3, Math.round(clipSec / SECONDS_PER_FRAME)));
+ return Array.from({ length: count }, (_, i) => ((i + 0.5) * clipSec) / count);
+}
+
+function splitDataUrl(dataUrl: string): { mimeType: string; data: string } | null {
+ const m = /^data:([^;,]+);base64,(.+)$/.exec(dataUrl);
+ return m ? { mimeType: m[1], data: m[2] } : null;
+}
+
+export function makeReviewRole(projectId: string): ReviewRole {
+ return {
+ async watch(input: ReviewInput): Promise<ReviewVerdict> {
+ // The take resolves wherever the run's project lives — store when open,
+ // persisted doc when the user switched away mid-render.
+ const asset = await findRunAsset(projectId, input.videoMediaId);
+ if (!asset || asset.type !== "video") throw new Error("No take to review.");
+ const clipSec = Math.max(0.1, asset.duration);
+ const frames = await captureVideoFrames(asset.url, frameTimes(clipSec));
+ if (frames.length === 0) throw new Error("Could not sample the take.");
+ const content: Record<string, unknown>[] = [
+ {
+ text: `Review this take, shown as frames sampled along its ${clipSec.toFixed(1)}s.
+Planned action: ${input.action || "(none written — judge against the narration)"}
+Narration heard over the shot: ${input.narration ? `"${input.narration}"` : "(none)"}
+The timeline slot needs ${input.slotSec.toFixed(1)}s of this take.`,
+ },
+ ];
+ for (const f of frames) {
+ const img = splitDataUrl(f.image);
+ if (!img) continue;
+ content.push({ text: `Frame at ${f.at.toFixed(1)}s:` });
+ content.push({ type: "input_image", dataBase64: img.data, mimeType: img.mimeType });
+ }
+ const res = await hostedPost("/api/inference/responses", {
+ donkeyProvider: "gemini",
+ model: geminiModelRoles.chat,
+ instructions: REVIEW_INSTRUCTIONS,
+ response_format: { type: "json_object" },
+ input: [{ role: "user", content }],
+ });
+ if (!res.ok) throw new Error("The review model is unavailable.");
+ const body = (await res.json()) as { output_text?: string };
+ const parsed = JSON.parse(body.output_text ?? "") as Record<string, unknown>;
+ const ok = parsed.ok !== false;
+ const note = typeof parsed.note === "string" ? parsed.note.trim() : "";
+ const rawFrom = typeof parsed.fromSec === "number" && Number.isFinite(parsed.fromSec) ? parsed.fromSec : 0;
+ const fromSec = Math.min(Math.max(0, rawFrom), Math.max(0, clipSec - input.slotSec));
+ return { ok, ...(note ? { note } : {}), ...(fromSec > 0 ? { fromSec } : {}) };
+ },
+ };
+}
diff --git a/site/src/cut/lib/genvideo/adapters/text.ts b/site/src/cut/lib/genvideo/adapters/text.ts
index 625d592b..c9a4a007 100644
--- a/site/src/cut/lib/genvideo/adapters/text.ts
+++ b/site/src/cut/lib/genvideo/adapters/text.ts
@@ -18,7 +18,7 @@ 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 { wordsInRange, type BreakdownRole, type ScriptRole, type StyleRole } from "../capabilities";
import type { ScriptBeat, ScriptPlan, TranscriptWord, VideoAsset } from "../types";
// ── the shared call ─────────────────────────────────────────────────────────
@@ -128,8 +128,12 @@ Reply with JSON only:
]}
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.
+- Each shot is 2–8 seconds and depicts the concrete subject of the words heard across it. Cut a new shot at EVERY topic the narration touches — a two-second mention gets its own two-second shot, and the setting moves with the story (school, a strawberry patch, a pool); one backdrop must never absorb several ideas.
+- Write action like a director's shot description, detailed enough to render the right moment without hearing the audio: who is on screen and their look, the specific activity mid-motion, the surroundings, and the camera's move.
+- action is what the camera sees, never editing language: no "cut to", "transition", "fade", "montage" — the editor adds those between shots later.
+- The brief, when given, is the source of truth for who speaks and who appears; the transcript is machine transcription that times the words and may mishear some — trust the brief over an odd transcription.
- framing is real camera language, varied shot to shot — wide establishing, close-up, insert of a telling detail, POV, follow shot — and action repeats the wardrobe and props that recur, so independently rendered shots still match.
+- A shot cannot be trusted to render readable text: no signs, labels, charts, lists, or lettering beyond a single short word — the viewer already hears the information in the narration.
- 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
@@ -178,11 +182,23 @@ 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:
+ const briefNote = input.brief?.trim() ? `Brief: ${input.brief.trim()}\n` : "";
+ // The shot count comes from the content: one shot per idea the words
+ // touch. Duration only bounds the physics (coverage and the 2–8s slice
+ // range); it never suggests a count.
+ const user = `Cut this ${durSec.toFixed(1)}s narration into shots covering [0, ${durSec.toFixed(1)}]. The shot count comes from the content: list the distinct ideas the transcript touches, then give each its own shot — a narration that names six things needs six shots.
+${briefNote}Timed transcript:
${timedTranscript(input.transcript)}`;
- return llmJson(BREAKDOWN_INSTRUCTIONS, user, (o) => parseShots(o, input.fps));
+ return llmJson(BREAKDOWN_INSTRUCTIONS, user, (o) => {
+ const shots = parseShots(o, input.fps);
+ if (shots === null) return null;
+ // Ground every shot in its own slice of the narration — the prompt
+ // builder carries these words into the render.
+ return shots.map((s) => ({
+ ...s,
+ audioText: wordsInRange(input.transcript, s.startFrame / input.fps, s.endFrame / input.fps),
+ }));
+ });
},
};
}
diff --git a/site/src/cut/lib/genvideo/capabilities.ts b/site/src/cut/lib/genvideo/capabilities.ts
index 5ade1d46..445e4e7a 100644
--- a/site/src/cut/lib/genvideo/capabilities.ts
+++ b/site/src/cut/lib/genvideo/capabilities.ts
@@ -25,6 +25,9 @@ export interface BreakdownInput {
transcript: TranscriptWord[];
/** Present when the run started from a brief. */
beats?: ScriptBeat[];
+ /** The user's story framing, when they gave one — the source of truth for
+ * who speaks and what the video is about; the transcript only times it. */
+ brief?: string;
durationFrames: number;
fps: number;
}
@@ -121,6 +124,31 @@ export interface TranscribeRole {
transcribe(audioMediaId: string): Promise<TranscriptWord[]>;
}
+export interface ReviewInput {
+ /** Project media id of the rendered take. */
+ videoMediaId: string;
+ /** What the plan wanted on screen. */
+ action: string;
+ /** The words heard over the shot. */
+ narration: string;
+ /** Seconds of the take the timeline slot needs. */
+ slotSec: number;
+}
+
+export interface ReviewVerdict {
+ /** Whether the take shows the planned action and subject. */
+ ok: boolean;
+ /** Why a declined take failed — carried into the retake prompt. */
+ note?: string;
+ /** Where the slot's window starts inside the take (seconds; default 0). */
+ fromSec?: number;
+}
+
+export interface ReviewRole {
+ /** Watch a rendered take against its plan — the dailies check. */
+ watch(input: ReviewInput): Promise<ReviewVerdict>;
+}
+
/** One model choice per role — what the orchestrator runs against. */
export interface ModelSuite {
/** Human label for evals and logs, e.g. "fast-video + hi-res-image". */
@@ -137,6 +165,8 @@ export interface ModelSuite {
/** Absent when `video.audioNative` — the video does its own lip-sync. */
lipSync?: LipSyncRole;
transcribe: TranscribeRole;
+ /** Absent when no reviewer is configured — takes place unwatched. */
+ review?: ReviewRole;
}
export type RoleName = keyof Omit<ModelSuite, "label">;
@@ -164,6 +194,7 @@ export function segmentByDuration(input: BreakdownInput, maxShotSec: number): Ra
return shots;
}
-function wordsInRange(words: TranscriptWord[], from: number, to: number): string {
+/** The transcript words heard across a span of seconds. */
+export function wordsInRange(words: TranscriptWord[], from: number, to: number): string {
return words.filter((w) => w.t1 > from && w.t0 < to).map((w) => w.w).join(" ");
}
diff --git a/site/src/cut/lib/genvideo/coverage.ts b/site/src/cut/lib/genvideo/coverage.ts
index 619fe9a3..d015e2e6 100644
--- a/site/src/cut/lib/genvideo/coverage.ts
+++ b/site/src/cut/lib/genvideo/coverage.ts
@@ -16,8 +16,14 @@
import type { Shot } from "./types";
-/** The video model's clip range, in seconds — shots are tuned to it. */
-export const MIN_SHOT_SEC = 4;
+/** The timeline slice range a shot may occupy, in seconds. The floor is a
+ * pacing choice, not the video model's: a narration names a new idea every
+ * couple of seconds, and each idea deserves its own shot. The model's own
+ * minimum render length lives in `supportedVideoDuration` — a short slot
+ * renders the shortest supported take and the placement trims it to the slot
+ * (the dailies review picks which window survives). The ceiling is the longest
+ * single render. */
+export const MIN_SHOT_SEC = 2;
export const MAX_SHOT_SEC = 8;
export const secToFrame = (sec: number, fps: number): number =>
diff --git a/site/src/cut/lib/genvideo/docWriter.ts b/site/src/cut/lib/genvideo/docWriter.ts
new file mode 100644
index 00000000..72d866cf
--- /dev/null
+++ b/site/src/cut/lib/genvideo/docWriter.ts
@@ -0,0 +1,141 @@
+"use client";
+
+/**
+ * Background writes to a project that is NOT open in the editor. A scene run
+ * outlives the open project: when the user switches away, its placements,
+ * assets, and plan keep landing in the project's persisted doc through this
+ * serialized read-modify-write queue, and the editor picks everything up on
+ * the next open. One promise chain per project, so concurrent shot placements
+ * never interleave a read with another write; `docWriterIdle` lets a project
+ * load wait out in-flight writes so an open never reads a half-written doc.
+ *
+ * The clip/audio placement helpers mirror the store's placeGenClip /
+ * placeGenAudio semantics exactly (fillSlot, muted shots, lanes) — the doc is
+ * just the other end of the same contract.
+ */
+
+import { apiFetch, apiJson } from "../api";
+import { storedAssets, useEditor } from "../store";
+import { mediaUrl, SPEED_MIN } from "../types";
+import type { AudioClip, MediaAsset, ProjectDoc, VideoClip } from "../types";
+import { fillSlot } from "./fillSlot";
+
+const MIN_LEN = 0.1;
+const uid = () => crypto.randomUUID().slice(0, 10);
+
+const chains = new Map<string, Promise<void>>();
+
+/** Queue one read-modify-write of a closed project's doc. Rejections reach the
+ * caller; the chain itself always continues. */
+export function withProjectDoc(
+ projectId: string,
+ mutate: (doc: ProjectDoc) => void
+): Promise<void> {
+ const prev = chains.get(projectId) ?? Promise.resolve();
+ const next = prev.then(async () => {
+ const res = await apiFetch(`/api/cut/projects/${projectId}`);
+ const doc = await apiJson<ProjectDoc>(res);
+ if (!res.ok) throw new Error(doc?.error ?? "Could not read the project.");
+ mutate(doc);
+ const put = await apiFetch(`/api/cut/projects/${projectId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(doc),
+ });
+ if (!put.ok) throw new Error("Could not save the project in the background.");
+ });
+ chains.set(projectId, next.catch(() => {}));
+ return next;
+}
+
+/** Resolves once every queued background write for the project has settled —
+ * the editor's project load awaits this so it never reads mid-write. */
+export function docWriterIdle(projectId: string): Promise<void> {
+ return (chains.get(projectId) ?? Promise.resolve()).catch(() => {});
+}
+
+/** Register a run-created asset in a closed project's doc (the open-project
+ * path stocks the store instead and autosave persists it). Idempotent. */
+export function stockAssetInDoc(projectId: string, asset: MediaAsset): Promise<void> {
+ return withProjectDoc(projectId, (doc) => {
+ if (!doc.assets.some((a) => a.id === asset.id)) {
+ doc.assets.push(storedAssets([asset])[0]);
+ }
+ });
+}
+
+/** A run's asset by id, wherever the user is: the live store when the run's
+ * project is open, its persisted doc when not. The doc projection is rebuilt
+ * into a usable runtime asset (url from the media route). */
+export async function findRunAsset(
+ projectId: string,
+ assetId: string
+): Promise<MediaAsset | undefined> {
+ const s = useEditor.getState();
+ if (s.projectId === projectId) {
+ const live = s.assets.find((a) => a.id === assetId);
+ if (live) return live;
+ }
+ const res = await apiFetch(`/api/cut/projects/${projectId}`);
+ const doc = await apiJson<ProjectDoc>(res);
+ if (!res.ok) return undefined;
+ const stored = doc.assets.find((a) => a.id === assetId);
+ return stored ? { ...stored, url: mediaUrl(projectId, stored.fileName) } : undefined;
+}
+
+/** placeGenClip against a doc: fill [startSec, endSec) exactly, muted, on
+ * track 0, honoring the reviewer's source window. Returns the new clip id. */
+export function docPlaceGenClip(
+ doc: ProjectDoc,
+ assetId: string,
+ startSec: number,
+ endSec: number,
+ srcInSec?: number
+): string | null {
+ const asset = doc.assets.find((a) => a.id === assetId);
+ if (!asset || (asset.type !== "video" && asset.type !== "image")) return null;
+ const slot = Math.max(MIN_LEN, endSec - startSec);
+ const srcIn =
+ asset.type === "video"
+ ? Math.min(Math.max(0, srcInSec ?? 0), Math.max(0, asset.duration - slot))
+ : 0;
+ const { out, speed } = fillSlot(asset.type, Math.max(MIN_LEN, asset.duration - srcIn), slot, SPEED_MIN);
+ const clip: VideoClip = {
+ id: uid(),
+ assetId,
+ track: 0,
+ start: Math.max(0, startSec),
+ in: srcIn,
+ out: srcIn + out,
+ muted: true,
+ ...(speed !== undefined ? { speed } : {}),
+ };
+ doc.clips = [...doc.clips, clip].sort((a, b) => a.start - b.start);
+ return clip.id;
+}
+
+/** placeGenAudio against a doc — voiceover or music bed, ducked, on a lane. */
+export function docPlaceGenAudio(
+ doc: ProjectDoc,
+ assetId: string,
+ startSec: number,
+ durSec: number,
+ opts?: { duck?: number; lane?: number }
+): string | null {
+ const asset = doc.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 } : {}),
+ };
+ doc.audioClips = [...doc.audioClips, clip];
+ return clip.id;
+}
diff --git a/site/src/cut/lib/genvideo/editor.ts b/site/src/cut/lib/genvideo/editor.ts
index a43db44a..ff954c9c 100644
--- a/site/src/cut/lib/genvideo/editor.ts
+++ b/site/src/cut/lib/genvideo/editor.ts
@@ -29,9 +29,16 @@ export interface EditorBridge {
importMedia(mediaId: string): Promise<string>;
/**
* Place a video clip on the video track so it exactly fills
- * [startFrame, endFrame). Returns the new timeline clip id.
+ * [startFrame, endFrame). `srcInSec` starts the clip's source window there
+ * (the reviewer's chosen moment) instead of at 0. Returns the new timeline
+ * clip id.
*/
- placeClip(mediaId: string, startFrame: number, endFrame: number): Promise<string>;
+ placeClip(
+ mediaId: string,
+ startFrame: number,
+ endFrame: number,
+ opts?: { srcInSec?: number }
+ ): Promise<string>;
/** Swap the media under an existing clip (regeneration), keeping its slot. */
replaceClipMedia(clipId: string, mediaId: string): Promise<void>;
/** Retime a clip so its footprint is exactly `durationFrames`. */
@@ -65,6 +72,7 @@ export interface PlacedClip {
mediaId: string;
startFrame: number;
endFrame: number;
+ srcInSec?: number;
transition?: { style: string; durationFrames: number };
}
@@ -88,9 +96,14 @@ export class FakeEditor implements EditorBridge {
return mediaId;
}
- async placeClip(mediaId: string, startFrame: number, endFrame: number): Promise<string> {
+ async placeClip(
+ mediaId: string,
+ startFrame: number,
+ endFrame: number,
+ opts?: { srcInSec?: number }
+ ): Promise<string> {
const clipId = `clip:${this.seq++}`;
- this.placed.push({ clipId, mediaId, startFrame, endFrame });
+ this.placed.push({ clipId, mediaId, startFrame, endFrame, ...(opts?.srcInSec ? { srcInSec: opts.srcInSec } : {}) });
return clipId;
}
diff --git a/site/src/cut/lib/genvideo/editorBridge.ts b/site/src/cut/lib/genvideo/editorBridge.ts
index a01f5d59..0e6debab 100644
--- a/site/src/cut/lib/genvideo/editorBridge.ts
+++ b/site/src/cut/lib/genvideo/editorBridge.ts
@@ -22,6 +22,7 @@
import { useEditor } from "../store";
import type { TransitionStyle } from "../types";
+import { docPlaceGenAudio, docPlaceGenClip, withProjectDoc } from "./docWriter";
import type { AudioClipInfo, EditorBridge, TimelineInfo } from "./editor";
/** The rate the plan runs at. Fixed to the export frame rate so a shot's frame
@@ -37,28 +38,52 @@ function footprintSec(c: { in: number; out: number; speed?: number }): number {
}
export class StoreEditorBridge implements EditorBridge {
+ /** The last timeline shape read while the project was open — the sync reads
+ * fall back to it when the project is closed (a background run only needs
+ * the aspect, and the plan froze its own at approval). */
+ private lastTimeline: TimelineInfo | null = null;
+
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;
+ const s = useEditor.getState();
+ return s.projectId === this.projectId && s.loaded;
+ }
+
+ /** Where this call must write: the live store when the run's project is
+ * open, its persisted doc when the user has moved on. A load in progress is
+ * waited out so a write never races the doc fetch — either it lands in the
+ * doc before the load reads it, or in the store after. */
+ private async mode(): Promise<"store" | "doc"> {
+ for (;;) {
+ const s = useEditor.getState();
+ if (s.projectId !== this.projectId) return "doc";
+ if (s.loaded) return "store";
+ await new Promise((r) => setTimeout(r, 200));
+ }
}
getTimeline(): TimelineInfo {
+ if (!this.open()) {
+ return this.lastTimeline ?? { fps: GEN_FPS, durationFrames: 0, aspect: "9:16" };
+ }
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 {
+ this.lastTimeline = {
fps: GEN_FPS,
durationFrames: Math.round(clipEnd * GEN_FPS),
aspect: s.aspect,
};
+ return this.lastTimeline;
}
getAudioClips(): AudioClipInfo[] {
+ if (!this.open()) return [];
return useEditor.getState().audioClips.map((c) => ({
clipId: c.id,
assetId: c.assetId,
@@ -73,35 +98,73 @@ export class StoreEditorBridge implements EditorBridge {
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 placeClip(
+ mediaId: string,
+ startFrame: number,
+ endFrame: number,
+ opts?: { srcInSec?: number }
+ ): Promise<string> {
+ if ((await this.mode()) === "store") {
+ const id = useEditor.getState().placeGenClip(mediaId, toSec(startFrame), toSec(endFrame), opts);
+ if (!id) throw new Error(`placeClip: no placeable asset ${mediaId}`);
+ return id;
+ }
+ let placed: string | null = null;
+ await withProjectDoc(this.projectId, (doc) => {
+ placed = docPlaceGenClip(doc, mediaId, toSec(startFrame), toSec(endFrame), opts?.srcInSec);
+ });
+ if (!placed) throw new Error(`placeClip: no placeable asset ${mediaId}`);
+ return placed;
}
async replaceClipMedia(clipId: string, mediaId: string): Promise<void> {
- if (!this.open()) return;
- useEditor.getState().updateClip(clipId, { assetId: mediaId });
+ if ((await this.mode()) === "store") {
+ useEditor.getState().updateClip(clipId, { assetId: mediaId });
+ return;
+ }
+ await withProjectDoc(this.projectId, (doc) => {
+ doc.clips = doc.clips.map((c) => (c.id === clipId ? { ...c, assetId: mediaId } : c));
+ });
}
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);
+ if ((await this.mode()) === "store") {
+ 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);
+ return;
+ }
+ await withProjectDoc(this.projectId, (doc) => {
+ doc.clips = doc.clips.map((c) => {
+ if (c.id !== clipId) return c;
+ const speed = c.speed && c.speed > 0 ? c.speed : 1;
+ return { ...c, out: c.in + toSec(durationFrames) * speed };
+ });
+ });
}
async removeClip(clipId: string): Promise<void> {
- if (!this.open()) return;
- useEditor.getState().removeClipById(clipId);
+ if ((await this.mode()) === "store") {
+ useEditor.getState().removeClipById(clipId);
+ return;
+ }
+ await withProjectDoc(this.projectId, (doc) => {
+ doc.clips = doc.clips.filter((c) => c.id !== clipId);
+ });
}
async addTransition(clipId: string, style: string, durationFrames: number): Promise<void> {
- if (!this.open()) return;
- useEditor.getState().setClipTransition(clipId, toSec(durationFrames), style as TransitionStyle);
+ if ((await this.mode()) === "store") {
+ useEditor.getState().setClipTransition(clipId, toSec(durationFrames), style as TransitionStyle);
+ return;
+ }
+ await withProjectDoc(this.projectId, (doc) => {
+ doc.clips = doc.clips.map((c) =>
+ c.id === clipId ? { ...c, transition: toSec(durationFrames), transitionStyle: style as TransitionStyle } : c
+ );
+ });
}
async placeAudio(
@@ -110,19 +173,32 @@ export class StoreEditorBridge implements EditorBridge {
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;
+ const audioOpts = {
+ ...(opts?.duck !== undefined ? { duck: opts.duck } : {}),
+ ...(opts?.lane !== undefined ? { lane: opts.lane } : {}),
+ };
+ if ((await this.mode()) === "store") {
+ const id = useEditor
+ .getState()
+ .placeGenAudio(mediaId, toSec(startFrame), toSec(durationFrames), audioOpts);
+ if (!id) throw new Error(`placeAudio: no audio asset ${mediaId}`);
+ return id;
+ }
+ let placed: string | null = null;
+ await withProjectDoc(this.projectId, (doc) => {
+ placed = docPlaceGenAudio(doc, mediaId, toSec(startFrame), toSec(durationFrames), audioOpts);
+ });
+ if (!placed) throw new Error(`placeAudio: no audio asset ${mediaId}`);
+ return placed;
}
async removeAudio(clipId: string): Promise<void> {
- if (!this.open()) return;
- useEditor.getState().removeAudioById(clipId);
+ if ((await this.mode()) === "store") {
+ useEditor.getState().removeAudioById(clipId);
+ return;
+ }
+ await withProjectDoc(this.projectId, (doc) => {
+ doc.audioClips = doc.audioClips.filter((c) => c.id !== clipId);
+ });
}
}
diff --git a/site/src/cut/lib/genvideo/fakes.ts b/site/src/cut/lib/genvideo/fakes.ts
index 0f408857..69a0234d 100644
--- a/site/src/cut/lib/genvideo/fakes.ts
+++ b/site/src/cut/lib/genvideo/fakes.ts
@@ -16,6 +16,8 @@ import {
type LipSyncInput,
type ModelSuite,
type MusicInput,
+ type ReviewInput,
+ type ReviewVerdict,
type ScriptInput,
type StyleBible,
type VideoInput,
@@ -49,6 +51,9 @@ export interface FakeStudioOptions {
/** Make the style/character-design call throw (exercises the default bible). */
failStyle?: boolean;
style?: string;
+ /** Scripted dailies verdicts, consumed in order (absent = no review role).
+ * Once the list runs dry every later take passes clean. */
+ reviewVerdicts?: ReviewVerdict[];
}
/** An in-memory studio; `.suite()` binds it to the orchestrator's roles. */
@@ -80,9 +85,16 @@ export class FakeStudio {
music: { compose: (i) => this.music(i) },
...(audioNative ? {} : { lipSync: { sync: (i: LipSyncInput) => this.lipSync(i) } }),
transcribe: { transcribe: (id: string) => this.transcribe(id) },
+ ...(this.opts.reviewVerdicts ? { review: { watch: (i: ReviewInput) => this.watch(i) } } : {}),
};
}
+ private async watch(input: ReviewInput): Promise<ReviewVerdict> {
+ const verdict = this.opts.reviewVerdicts?.shift() ?? { ok: true };
+ this.calls.push({ role: "review", detail: `${input.videoMediaId} ok=${verdict.ok}` });
+ return verdict;
+ }
+
private async writeScript(input: ScriptInput): Promise<ScriptPlan> {
const n = this.opts.scriptBeats ?? Math.max(2, Math.round((input.targetSeconds ?? 30) / 6));
const beats = Array.from({ length: n }, (_, i) => ({
@@ -125,7 +137,7 @@ export class FakeStudio {
const marker = this.opts.failVideoMarker;
if (marker && input.prompt.includes(marker))
throw new Error(`fake video failed (marker "${marker}")`);
- return this.mint("video", `${input.durationSec}s${input.audioMediaId ? " +audio" : ""}`);
+ return this.mint("video", `${input.durationSec}s${input.audioMediaId ? " +audio" : ""} ${input.prompt}`);
}
private async speak(input: VoiceInput): Promise<VoiceResult> {
diff --git a/site/src/cut/lib/genvideo/orchestrator.ts b/site/src/cut/lib/genvideo/orchestrator.ts
index b021184a..034dbf70 100644
--- a/site/src/cut/lib/genvideo/orchestrator.ts
+++ b/site/src/cut/lib/genvideo/orchestrator.ts
@@ -22,7 +22,7 @@
import { assertCoverage, frameToSec, MAX_SHOT_SEC, MIN_SHOT_SEC, repairCoverage, secToFrame, shotDurationFrames } from "./coverage";
import { fanOut } from "./pool";
import { buildPrompt, buildRefPrompt, refsForAsset, shotRefs } from "./prompt";
-import { segmentByDuration, type ModelSuite } from "./capabilities";
+import { segmentByDuration, type ModelSuite, type ReviewVerdict } from "./capabilities";
import type { EditorBridge } from "./editor";
import type { BeatVoice, RefAsset, Shot, VideoAsset, VideoEmit, VideoPhase, VideoProject } from "./types";
@@ -171,6 +171,7 @@ export class VideoOrchestrator {
frames.push(prior.durationFrames);
continue;
}
+ this.deps.emit({ type: "activity", message: `Voicing line ${bi + 1} of ${this.project.script.beats.length}…` });
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));
@@ -332,7 +333,12 @@ export class VideoOrchestrator {
private async breakdown(): Promise<void> {
if (this.project.shots.length === 0) {
this.setPhase("breakdown");
- const input = { transcript: this.project.transcript, durationFrames: this.durationFrames, fps: this.fps };
+ const input = {
+ transcript: this.project.transcript,
+ ...(this.project.brief ? { brief: this.project.brief } : {}),
+ durationFrames: this.durationFrames,
+ fps: this.fps,
+ };
const id = (i: number) => `shot:${i}`;
let shots: Shot[];
try {
@@ -382,6 +388,7 @@ export class VideoOrchestrator {
needed,
async (asset) => {
if (this.aborted) return; // a paused run spends nothing more
+ this.deps.emit({ type: "activity", message: `Designing ${asset.name}…` });
const raw = await this.deps.suite.image.generate({
prompt: buildRefPrompt(asset, this.project.style),
refs: refsForAsset(asset, this.project),
@@ -449,26 +456,30 @@ export class VideoOrchestrator {
if (this.aborted) return;
this.updateShot(shot, { status: "generating", error: undefined });
const audio = this.audioForShot(shot);
- const prompt = buildPrompt(shot, this.project);
+ const basePrompt = buildPrompt(shot, this.project);
const refs = shotRefs(shot, this.project);
+ // The reviewer's note from a declined take — the retake prompt carries it.
+ let critique: string | undefined;
for (let attempt = 1; attempt <= VIDEO_ATTEMPTS; attempt++) {
if (this.aborted) return; // a paused run spends nothing more
shot.attempts = attempt;
+ const prompt = critique ? `${basePrompt} Note from the last take's review: ${critique}` : basePrompt;
+ const video = this.deps.suite.video;
try {
- let clip = await this.deps.suite.video.generate({
+ let clip = await video.generate({
prompt,
refs,
startKeyframe: shot.startKeyframe,
endKeyframe: shot.endKeyframe,
durationSec: frameToSec(shotDurationFrames(shot), this.fps),
aspect: this.aspect,
- ...(audio && this.deps.suite.video.audioNative
+ ...(audio && video.audioNative
? { audioMediaId: audio.mediaId, audioFromSec: audio.fromSec, audioToSec: audio.toSec }
: {}),
});
clip = await this.deps.editor.importMedia(clip);
// Lip-sync post-pass when the video model can't do it inline.
- if (audio && !this.deps.suite.video.audioNative && this.deps.suite.lipSync) {
+ if (audio && !video.audioNative && this.deps.suite.lipSync) {
this.updateShot(shot, { status: "lipsync" });
const synced = await this.deps.suite.lipSync.sync({
videoMediaId: clip,
@@ -479,12 +490,32 @@ export class VideoOrchestrator {
clip = await this.deps.editor.importMedia(synced);
shot.lipSynced = true;
}
+ // The dailies check: a reviewer watches the take against the plan.
+ // A declined take retries (the throw lands in the catch below, and the
+ // retake prompt carries the note); the last attempt places regardless —
+ // a weak take beats a frozen still. The chosen window trims the
+ // placement to the take's best moment.
+ let srcInSec: number | undefined;
+ if (this.deps.suite.review) {
+ this.updateShot(shot, { status: "reviewing" });
+ const verdict = await this.reviewTake(clip, shot);
+ if (!verdict.ok && attempt < VIDEO_ATTEMPTS) {
+ critique = verdict.note?.trim() || "the take did not show the planned action";
+ throw new Error(`Retake: ${critique}`);
+ }
+ srcInSec = verdict.fromSec;
+ }
// Swap the new clip in only now that it's ready, replacing any prior
// placement (a resume's fallback still, a regen's old clip) atomically.
await this.clearVideoPlacement(shot);
shot.lastPrompt = prompt;
shot.clip = clip;
- shot.timelineClipId = await this.deps.editor.placeClip(clip, shot.startFrame, shot.endFrame);
+ shot.timelineClipId = await this.deps.editor.placeClip(
+ clip,
+ shot.startFrame,
+ shot.endFrame,
+ srcInSec ? { srcInSec } : undefined
+ );
this.updateShot(shot, { status: "placed", error: undefined });
this.emitProgress();
return;
@@ -497,6 +528,21 @@ export class VideoOrchestrator {
this.emitProgress();
}
+ /** Watch a rendered take against its plan — best-effort: a reviewer outage
+ * never blocks placement, it just goes unwatched. */
+ private async reviewTake(clip: string, shot: Shot): Promise<ReviewVerdict> {
+ try {
+ return await this.deps.suite.review!.watch({
+ videoMediaId: clip,
+ action: shot.action,
+ narration: (shot.dialogue ?? shot.audioText).trim(),
+ slotSec: frameToSec(shotDurationFrames(shot), this.fps),
+ });
+ } catch {
+ return { ok: true };
+ }
+ }
+
/** The audio slice a shot should be spoken over. */
private audioForShot(shot: Shot): { mediaId: string; fromSec: number; toSec: number } | undefined {
if (this.project.audioMode === "generated") {
@@ -574,6 +620,7 @@ export class VideoOrchestrator {
// one that declines) just means no bed.
if (this.project.audioMode === "generated" && !this.project.musicAssetId && this.deps.suite.music) {
try {
+ this.deps.emit({ type: "activity", message: "Composing the music bed…" });
const music = await this.deps.suite.music.compose({
mood: this.project.script?.style ?? this.project.style ?? "cinematic underscore",
durationSec: frameToSec(this.durationFrames, this.fps),
diff --git a/site/src/cut/lib/genvideo/prompt.ts b/site/src/cut/lib/genvideo/prompt.ts
index 059155cd..3ab16ea8 100644
--- a/site/src/cut/lib/genvideo/prompt.ts
+++ b/site/src/cut/lib/genvideo/prompt.ts
@@ -12,11 +12,19 @@ import type { RefAsset, Shot, VideoAsset, VideoProject } from "./types";
/** The text half of a shot's generation prompt. */
export function buildPrompt(shot: Shot, project: VideoProject): string {
const parts = [shot.action.trim()];
+ // The narration grounds what the shot depicts, phrased as off-screen audio —
+ // a bare quote reads as a caption request and the model burns the words into
+ // the picture as speech bubbles and subtitle bars.
+ const spoken = (shot.dialogue ?? shot.audioText).trim();
+ if (spoken) parts.push(`The voiceover heard over this shot (audio only, never visible): ${spoken}`);
const location = findAsset(project.locations, shot.location);
if (location) parts.push(`Setting, ${location.name}.`);
else if (shot.location) parts.push(`Setting, ${shot.location}.`);
if (shot.framing) parts.push(`Framing, ${shot.framing}.`);
if (project.style) parts.push(project.style);
+ parts.push(
+ "One single continuous shot with fluid, continuous character motion throughout — smooth, natural movement, never held poses or stepped animation. Pure visual storytelling: no on-screen text of any kind — no captions, subtitles, speech bubbles, titles, signs, or lettering — and no split screens, panels, or storyboard collages. No baked-in editing effects: no transition frames, fades, motion-blur smears, borders, or blurred letterbox bands — the picture fills the frame edge to edge; cuts and transitions are added later in the editor."
+ );
return parts.filter(Boolean).join(" ").trim();
}
diff --git a/site/src/cut/lib/genvideo/registry.ts b/site/src/cut/lib/genvideo/registry.ts
index 235b1cc8..2421ea00 100644
--- a/site/src/cut/lib/genvideo/registry.ts
+++ b/site/src/cut/lib/genvideo/registry.ts
@@ -21,6 +21,7 @@ import type {
LipSyncRole,
ModelSuite,
MusicRole,
+ ReviewRole,
RoleName,
ScriptRole,
StyleRole,
@@ -58,6 +59,13 @@ class Slot<T> {
if (!chosen) throw new Error(`no model registered${id ? ` with id "${id}"` : ""} for this role`);
return chosen.make();
}
+
+ /** Resolve like `resolve`, but an empty slot is undefined — for the optional
+ * roles (a suite runs without them). */
+ maybe(id?: string): T | undefined {
+ const chosen = this.options.get(id ?? this.defaultId ?? "");
+ return chosen?.make();
+ }
}
export class ModelRegistry {
@@ -70,6 +78,7 @@ export class ModelRegistry {
readonly music = new Slot<MusicRole>();
readonly lipSync = new Slot<LipSyncRole>();
readonly transcribe = new Slot<TranscribeRole>();
+ readonly review = new Slot<ReviewRole>();
/** The models registered for one role — what a picker or an eval iterates. */
options(role: RoleName): ModelOption[] {
@@ -91,6 +100,11 @@ export class ModelRegistry {
// A lip-sync model is only needed when the video model isn't audio-native.
...(video.audioNative ? {} : { lipSync: this.lipSync.resolve(selection.lipSync) }),
transcribe: this.transcribe.resolve(selection.transcribe),
+ // Optional role — a suite runs without a reviewer (takes go unwatched).
+ ...(() => {
+ const review = this.review.maybe(selection.review);
+ return review ? { review } : {};
+ })(),
};
}
}
diff --git a/site/src/cut/lib/genvideo/types.ts b/site/src/cut/lib/genvideo/types.ts
index 381f917b..7eb27907 100644
--- a/site/src/cut/lib/genvideo/types.ts
+++ b/site/src/cut/lib/genvideo/types.ts
@@ -59,6 +59,7 @@ export type ShotStatus =
| "keyframing"
| "generating"
| "lipsync"
+ | "reviewing"
| "placed"
| "failed";
@@ -150,6 +151,9 @@ export interface VideoProject {
phase: VideoPhase;
breakdownApproved: boolean;
createdAt: number;
+ /** Epoch ms when the user approved and rendering began — the card's render
+ * clock counts from here across reloads and project switches. */
+ renderStartedAt?: number;
updatedAt: number;
}
@@ -180,6 +184,8 @@ export type VideoEvent =
| { type: "breakdown"; shots: Shot[] }
| { type: "progress"; placed: number; total: number }
| { type: "log"; message: string }
+ /** The live ticker: one line on what the run is doing right now. */
+ | { type: "activity"; message: string }
| { type: "error"; message: string };
export type VideoEmit = (event: VideoEvent) => void;
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 4afccc88..493c2e6a 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -162,7 +162,7 @@ export interface EditorState {
* [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;
+ placeGenClip: (assetId: string, startSec: number, endSec: number, opts?: { srcInSec?: 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;
@@ -646,15 +646,22 @@ export const useEditor = create<EditorState>((set, get) => {
// and the plan is never written back.
setGenvideo: (project) => set({ genvideo: project ? { ...project } : undefined }),
- placeGenClip: (assetId, startSec, endSec) => {
+ placeGenClip: (assetId, startSec, endSec, opts) => {
const asset = get().assets.find((a) => a.id === assetId);
if (!asset || (asset.type !== "video" && asset.type !== "image")) return null;
+ const slot = Math.max(MIN_LEN, endSec - startSec);
+ // The reviewer's chosen window: start the source there, clamped so the
+ // slot still fits inside the file.
+ const srcIn =
+ asset.type === "video"
+ ? Math.min(Math.max(0, opts?.srcInSec ?? 0), Math.max(0, asset.duration - slot))
+ : 0;
// 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),
+ Math.max(MIN_LEN, asset.duration - srcIn),
+ slot,
SPEED_MIN
);
const clip: VideoClip = {
@@ -662,8 +669,8 @@ export const useEditor = create<EditorState>((set, get) => {
assetId,
track: 0,
start: Math.max(0, startSec),
- in: 0,
- out,
+ in: srcIn,
+ out: srcIn + out,
// Muted: generated shots ride under the narration spine, so the clip's
// own audio (Veo synthesizes some) must never compete with the voice.
muted: true,
diff --git a/site/src/cut/lib/visualFrames.ts b/site/src/cut/lib/visualFrames.ts
index 62ab38d4..e9c41424 100644
--- a/site/src/cut/lib/visualFrames.ts
+++ b/site/src/cut/lib/visualFrames.ts
@@ -47,6 +47,43 @@ function seekTo(v: HTMLVideoElement, t: number): Promise<void> {
});
}
+/** Capture small stamped frames from one video file at the given times —
+ * the dailies-review sampler. Times land in file seconds; unreadable sources
+ * or tainted canvases yield fewer frames rather than an error. */
+export async function captureVideoFrames(url: string, times: number[]): Promise<CapturedFrame[]> {
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return [];
+ ctx.imageSmoothingQuality = "high";
+ let v: HTMLVideoElement;
+ try {
+ v = await loadVideo(url);
+ } catch {
+ return [];
+ }
+ const frames: CapturedFrame[] = [];
+ try {
+ for (const at of times) {
+ await seekTo(v, Math.max(0, Math.min(at, Math.max(0, v.duration - 0.05))));
+ if (v.readyState < 2 || !v.videoWidth) continue;
+ const w = Math.min(FRAME_W, v.videoWidth);
+ const h = Math.round((w / v.videoWidth) * v.videoHeight);
+ canvas.width = w;
+ canvas.height = h;
+ ctx.drawImage(v, 0, 0, w, h);
+ try {
+ frames.push({ at, image: canvas.toDataURL("image/jpeg", JPEG_Q) });
+ } catch {
+ // A tainted canvas (unexpected CORS setup) — skip the frame.
+ }
+ }
+ } finally {
+ v.removeAttribute("src");
+ v.load();
+ }
+ return frames;
+}
+
/** Capture timeline frames from video track 0's visible clips. */
export async function captureTimelineFrames(spans: ClipSpan[]): Promise<CapturedFrame[]> {
const visible = spans.filter((sp) => !sp.clip.hidden);