Open source CapCut alternative.
TypeScript
feat(site): recut_scene replans a shot span; finished card is a durable record [rebuild]
David Leeeb9eacfa629
diff --git a/docs/guides/cut/brief-to-video.md b/docs/guides/cut/brief-to-video.mdindex 5fcf536a..f9a7db85 100644--- a/docs/guides/cut/brief-to-video.md+++ b/docs/guides/cut/brief-to-video.md@@ -12,7 +12,11 @@ persisted, user-approved plan — never a fresh improvisation. If a shot renderswrong, fix the plan (its description, its references, its framing) andregenerate that shot; if you're tempted to slip an extra instruction into onerender call, that knowledge belongs in the plan so every later regeneration-keeps it.+keeps it. Revisions scale with their scope: a bad take regenerates one shot, a+section that needs a different cut replans just that span (same audio, same+bible — the span can become more shots or fewer, and only those render), and a+look change rebuilds the bible and re-renders everything. A finished scene is+never replanned from scratch to change part of it.## How it worksdiff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 919643f1..aa5d13e0 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -27,7 +27,7 @@ import {import Markdown from "react-markdown";import { baseMarkdownComponents } from "./markdownComponents";import { LiveElapsed } from "./Elapsed";-import { SceneCard } from "./SceneCard";+import { SceneActivity, SceneCard } from "./SceneCard";import { useElapsed } from "@/cut/hooks/useElapsed";import { Button } from "@/components/ui/button";import {@@ -635,10 +635,20 @@ function ChatSession({{messages.map((m) => (<Fragment key={m.id}><MessageView message={m} />- {m.id === sceneAnchorId && <SceneCard threadId={threadId} />}+ {m.id === sceneAnchorId && (+ <>+ <SceneCard threadId={threadId} />+ <SceneActivity threadId={threadId} />+ </>+ )}</Fragment>))}- {sceneAnchorId === undefined && <SceneCard threadId={threadId} />}+ {sceneAnchorId === undefined && (+ <>+ <SceneCard threadId={threadId} />+ <SceneActivity threadId={threadId} />+ </>+ )}<ThreadRenders threadId={threadId} />{busy && (<div className="ai-busy mt-1 flex items-center gap-1.5 text-[11.5px] text-muted-foreground">diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsxindex 1ac746ce..858206ab 100644--- a/site/src/cut/components/Lightbox.tsx+++ b/site/src/cut/components/Lightbox.tsx@@ -116,8 +116,8 @@ export function Lightbox() {<LightboxMedia item={item} ratio={ratio} /><div className="flex min-h-0 flex-col gap-3 overflow-y-auto">- <div className="flex items-center justify-between gap-3">- <div className="min-w-0 truncate text-[15px] font-semibold tracking-tight text-white">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0 text-[15px] leading-snug font-semibold tracking-tight break-words text-white">{item.name}</div>{canAdd && (diff --git a/site/src/cut/components/SceneCard.tsx b/site/src/cut/components/SceneCard.tsxindex 079c79c5..cf998d9e 100644--- a/site/src/cut/components/SceneCard.tsx+++ b/site/src/cut/components/SceneCard.tsx@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react";import { Check, ChevronRight, CircleDashed, Clapperboard, TriangleAlert, X } from "lucide-react";import { Button } from "@/components/ui/button";import { refFromAsset } from "../lib/assetRef";+import { lightboxItemFromRef, useLightbox } from "../lib/lightbox";import { formatDuration, useGenScene, type SceneRun } from "../lib/genScene";import { NO_CREDITS_MESSAGE } from "../lib/generate";import { GEN_FPS } from "../lib/genvideo/editorBridge";@@ -47,9 +48,6 @@ function describe(sh: Shot): string {export function SceneCard({ threadId }: { threadId: string }) {const run = useGenScene((s) => s.run);const projectId = useEditor((s) => s.projectId);- // Feed thumbnails resolve against the open project's media (the run's- // assets are project assets, chat-owned).- const assets = useEditor((s) => s.assets);const [open, setOpen] = useState(true);// Resuming a persisted run is the genScene store's own subscription — it@@ -67,14 +65,6 @@ export function SceneCard({ threadId }: { threadId: string }) {return () => clearInterval(t);}, [working]);- // The activity feed follows its newest entry, like the chat itself.- const feedRef = useRef<HTMLDivElement>(null);- const feedLen = run?.feed.length ?? 0;- useEffect(() => {- const el = feedRef.current;- if (el) el.scrollTop = el.scrollHeight;- }, [feedLen]);-if (!run || run.projectId !== projectId) return null;// The card belongs to the thread that asked — a new or different chat starts// clean. A run with no owner (pre-chatId persisted plans) shows anywhere.@@ -183,33 +173,6 @@ export function SceneCard({ threadId }: { threadId: string }) {</div>)}- {run.feed.length > 0 && (- // The run's chronological record — every narrated step and every- // asset it made, thumbnails included. Nothing the run does is- // internal: this is the same story the agent would tell in chat.- <div className="mt-2">- <div className="text-[10.5px] font-medium text-muted-foreground">Activity</div>- <div ref={feedRef} className="mt-1 flex max-h-44 flex-col gap-1 overflow-y-auto">- {run.feed.map((f, i) => {- const asset = f.mediaId ? assets.find((a) => a.id === f.mediaId) : undefined;- const latest = i === run.feed.length - 1;- return (- <div key={`${f.at}-${i}`} className="flex items-center gap-2">- {asset && <RefThumb item={refFromAsset(asset)} className="size-8 shrink-0" />}- <span- className={`min-w-0 flex-1 text-[11px] text-muted-foreground ${- latest && inFlight ? "animate-pulse" : ""- }`}- >- {f.text}- </span>- </div>- );- })}- </div>- </div>- )}-{run.status === "generating" && (<div className="mt-2 h-1 overflow-hidden rounded-full bg-muted"><div@@ -294,3 +257,64 @@ export function SceneCard({ threadId }: { threadId: string }) {</div>);}++/** The run's chronological record, streamed into the chat as its own item+ * right under the scene card — every narrated step and every asset it made,+ * thumbnails included. Nothing the run does is internal: this is the same+ * story the agent would tell in chat. */+export function SceneActivity({ threadId }: { threadId: string }) {+ const run = useGenScene((s) => s.run);+ const projectId = useEditor((s) => s.projectId);+ // Feed thumbnails resolve against the open project's media (the run's+ // assets are project assets, chat-owned).+ const assets = useEditor((s) => s.assets);++ // Follow new entries only when the chat is already reading the tail —+ // never yank the user back down while they scroll through old images.+ const bottomRef = useRef<HTMLDivElement>(null);+ const feedLen = run?.feed.length ?? 0;+ useEffect(() => {+ const scroller = bottomRef.current?.closest(".ai-messages");+ if (!scroller) return;+ const gap = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;+ if (gap < 160) scroller.scrollTop = scroller.scrollHeight;+ }, [feedLen]);++ if (!run || run.projectId !== projectId) return null;+ if (run.chatId && run.chatId !== threadId) return null;+ if (run.feed.length === 0) return null;+ const inFlight = run.status === "planning" || run.status === "generating";++ return (+ <div className="ai-scene-activity mt-2 mb-3 flex flex-col gap-1.5">+ <div className="text-[10.5px] font-medium text-muted-foreground">Activity</div>+ {run.feed.map((f, i) => {+ const asset = f.mediaId ? assets.find((a) => a.id === f.mediaId) : undefined;+ const ref = asset ? refFromAsset(asset) : undefined;+ const latest = i === run.feed.length - 1;+ return (+ <div key={`${f.at}-${i}`} className="flex items-center gap-2">+ {ref && (+ <button+ type="button"+ title={`${ref.name} — click to view`}+ className="shrink-0"+ onClick={() => useLightbox.getState().open(lightboxItemFromRef(ref))}+ >+ <RefThumb item={ref} className="size-8 rounded-[4px]" />+ </button>+ )}+ <span+ className={`min-w-0 flex-1 text-[11px] text-muted-foreground ${+ latest && inFlight ? "animate-pulse" : ""+ }`}+ >+ {f.text}+ </span>+ </div>+ );+ })}+ <div ref={bottomRef} />+ </div>+ );+}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 56fe00b1..75233e9e 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -786,6 +786,18 @@ export async function runAiTool(return { note: res.message };}+ case "recut_scene": {+ if (!isNum(input.from_shot) || !isNum(input.to_shot))+ throw new ToolError("from_shot and to_shot (1-based, inclusive) are required.");+ const instruction = String(input.instruction ?? "").trim();+ if (!instruction) throw new ToolError("An instruction is required — what should this span become?");+ const res = useGenScene+ .getState()+ .recutShots(Math.round(input.from_shot), Math.round(input.to_shot), instruction);+ 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.");diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsindex fc2227b2..57f2fd24 100644--- a/site/src/cut/lib/genScene.ts+++ b/site/src/cut/lib/genScene.ts@@ -27,8 +27,13 @@ export type SceneStatus = "planning" | "awaiting_approval" | "generating" | "donexport interface SceneFeedItem {at: number;text: string;- /** Project asset this entry produced — the card shows its thumbnail. */+ /** Project asset this entry produced — the feed shows its thumbnail. */mediaId?: string;+ /** The work item this entry narrates (a sheet, a shot). A new keyed entry+ * retires the item's previous in-progress lines, so "Designing Mason…"+ * gives way to "Designed Mason" instead of both lingering. Entries with+ * media are milestones and always stay. */+ key?: string;}export interface SceneRun {@@ -269,9 +274,12 @@ function newProject(projectId: string, params: StartSceneParams): VideoProject {};}-/** The run's placed timeline clip ids (video track + soundtrack). */+/** The run's placed timeline clip ids (video track + soundtrack), including+ * clips a re-cut replaced that still hold their slots. */function runClipIds(project: VideoProject): { clipIds: string[]; audioIds: string[] } {- const clipIds = project.shots.map((s) => s.timelineClipId).filter((x): x is string => !!x);+ const clipIds = project.shots+ .flatMap((s) => [s.timelineClipId, ...(s.replacesClipIds ?? [])])+ .filter((x): x is string => !!x);const audioIds = [...(project.beatVoices ?? []).map((b) => b.voiceClipId),project.musicClipId,@@ -361,13 +369,16 @@ function applyEvent(projectId: string, e: VideoEvent): void {if (!s.run || s.run.projectId !== projectId) return s;const run = { ...s.run };// Every event becomes a feed entry (consecutive repeats collapse), so the- // chat card reads as the run's chronological record, assets included.- const note = (text: string, mediaId?: string) => {+ // chat activity reads as the run's chronological record, assets included.+ // A keyed entry retires its work item's earlier in-progress lines;+ // entries with media are milestones and always stay.+ const note = (text: string, mediaId?: string, key?: string) => {const last = run.feed[run.feed.length - 1];if (last && last.text === text && last.mediaId === mediaId) return;+ const kept = key ? run.feed.filter((f) => f.key !== key || f.mediaId) : run.feed;run.feed = [- ...run.feed,- { at: Date.now(), text, ...(mediaId ? { mediaId } : {}) },+ ...kept,+ { at: Date.now(), text, ...(mediaId ? { mediaId } : {}), ...(key ? { key } : {}) },].slice(-FEED_CAP);};switch (e.type) {@@ -389,14 +400,15 @@ function applyEvent(projectId: string, e: VideoEvent): void {run.shots = run.shots.map((sh) => (sh.id === e.shot.id ? e.shot : sh));const n = run.shots.findIndex((sh) => sh.id === e.shot.id) + 1;if (n > 0) {+ const key = `shot:${e.shot.id}`;if (e.shot.startKeyframe && prev?.startKeyframe !== e.shot.startKeyframe)- note(`Shot ${n} — opening frame designed`, e.shot.startKeyframe);+ note(`Shot ${n} — opening frame designed`, e.shot.startKeyframe, key);if (e.shot.status === "placed" && prev?.status !== "placed" && e.shot.clip)- note(`Shot ${n} — take placed on the timeline`, e.shot.clip);+ note(`Shot ${n} — take placed on the timeline`, e.shot.clip, key);if (e.shot.status === "failed" && prev?.status !== "failed")- note(`Shot ${n} — couldn't animate, holding a still`, e.shot.startKeyframe);+ note(`Shot ${n} — couldn't animate, holding a still`, e.shot.startKeyframe, key);const line = e.shot.status !== prev?.status ? shotActivity(e.shot, n) : undefined;- if (line) note(line);+ if (line) note(line, undefined, key);}break;}@@ -408,10 +420,10 @@ function applyEvent(projectId: string, e: VideoEvent): void {note(e.message);break;case "asset":- note(e.label, e.mediaId);+ note(e.label, e.mediaId, e.key);break;case "activity":- note(e.message);+ note(e.message, undefined, e.key);break;case "error":note(e.message);@@ -496,8 +508,15 @@ function mirrorRun(projectId: string, p: VideoProject): void {? { renderStartedAt: p.renderStartedAt ?? Date.now() }: {}),// A terminal run's mirror is a record, not a live surface: endedAt- // freezes the clock and stops the activity bus appending to its feed.- ...(isTerminal(statusFor(p)) ? { endedAt: Date.now() } : {}),+ // freezes the clock (at the plan's stamped end, so the elapsed shown is+ // the run's real working time) and stops the activity bus appending to+ // its feed. Plans from before end-stamping clamp to 0:00.+ ...(isTerminal(statusFor(p))+ ? {+ ...(p.renderStartedAt ? { renderStartedAt: p.renderStartedAt } : {}),+ endedAt: p.endedAt ?? p.renderStartedAt ?? Date.now(),+ }+ : {}),},});}@@ -559,27 +578,16 @@ function failed(projectId: string, orch: VideoOrchestrator): (e: unknown) => voi* project. Returns true once a live orchestrator and mirror exist. */function resumeDoneRun(): boolean {const ed = useEditor.getState();- const project = ed.genvideo;- if (!ed.projectId || !project || project.phase !== "done") return false;+ const stored = ed.genvideo;+ if (!ed.projectId || !stored || stored.phase !== "done") return false;+ // Reviving the run re-opens its card; a stale dismissal must not hide the+ // record of the work about to happen on the next load.+ const project = { ...stored, cardDismissed: undefined };+ if (stored.cardDismissed) ed.setGenvideo(project);orchestrators.get(ed.projectId)?.abort();const orch = buildOrchestrator(ed.projectId, project);orchestrators.set(ed.projectId, orch);- useGenScene.setState({- run: {- projectId: ed.projectId,- chatId: project.chatId ?? null,- mode: project.audioMode,- title: project.brief || "Animating your audio",- status: "done",- phase: project.phase,- shots: project.shots,- placed: project.shots.filter((s) => s.timelineClipId).length,- total: project.shots.length,- feed: seedFeed(project),- startedAt: Date.now(),- endedAt: Date.now(),- },- });+ mirrorRun(ed.projectId, project);return true;}@@ -619,6 +627,10 @@ interface GenSceneState {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 };+ /** Re-cut a contiguous span of shots (1-based, inclusive): replan just that+ * span against the same audio — it can become more shots or fewer — and+ * render only the new ones. The rest of the scene stays as it is. */+ recutShots: (fromN: number, toN: number, instruction: string) => { ok: boolean; message: string };/** Redo every shot holding a still in one go — the card's single retry* button after a credits top-up or a bad batch. */retryFailedShots: () => { ok: boolean; message: string };@@ -749,6 +761,35 @@ export const useGenScene = create<GenSceneState>((set, get) => ({return { ok: true, message: `Redoing shot ${n}…` };},+ recutShots: (fromN, toN, instruction) => {+ // Same reload path as regenerateShot: a finished run rebuilds on demand.+ const openId = useEditor.getState().projectId;+ if (!openId) return { ok: false, message: "Open a project first." };+ if (!orchestrators.get(openId) || !get().run) resumeDoneRun();+ const run = get().run;+ const orch = orchestrators.get(openId);+ if (!orch || !run || run.status !== "done") {+ return { ok: false, message: "The scene isn't finished rendering yet — re-cut it once it's done." };+ }+ if (toN < fromN) return { ok: false, message: "to_shot must be at or after from_shot." };+ const ids: string[] = [];+ for (let n = fromN; n <= toN; n++) {+ const id = orch.shotIdByNumber(n);+ if (!id) return { ok: false, message: `This scene has no shot ${n}.` };+ ids.push(id);+ }+ // The run takes its clips back for the re-cut (they were released at+ // done), so the replacements stay off the undo stack until it finishes.+ const owned = runClipIds(orch.project);+ useEditor.getState().adoptGenClips(owned.clipIds, owned.audioIds);+ set({ run: { ...run, status: "generating", renderStartedAt: Date.now() } });+ orch.recutShots(ids, instruction).then(settled(run.projectId, orch)).catch(failed(run.projectId, orch));+ return {+ ok: true,+ message: fromN === toN ? `Re-cutting shot ${fromN}…` : `Re-cutting shots ${fromN}–${toN}…`,+ };+ },+retryFailedShots: () => {// Same reload path as regenerateShot: a finished run rebuilds on demand.const openId = useEditor.getState().projectId;@@ -772,10 +813,14 @@ export const useGenScene = create<GenSceneState>((set, get) => ({retryRun: () => {const openId = useEditor.getState().projectId;- const plan = useEditor.getState().genvideo;- if (!openId || !plan || plan.phase !== "failed") {+ const stored = useEditor.getState().genvideo;+ if (!openId || !stored || stored.phase !== "failed") {return { ok: false, message: "No failed video run to retry here." };}+ // The retry re-opens the card; clear a stale dismissal so the revived+ // run's record survives the next load too.+ const plan = { ...stored, cardDismissed: undefined };+ if (stored.cardDismissed) useEditor.getState().setGenvideo(plan);orchestrators.get(openId)?.abort();const orch = buildOrchestrator(openId, plan);orchestrators.set(openId, orch);@@ -823,21 +868,13 @@ export const useGenScene = create<GenSceneState>((set, get) => ({// 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(projectId, 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; revision tools- // rebuild a done run on demand (resumeDoneRun). EXCEPT unfinished business,- // where hiding the card would strand its Retry button behind a reload: a- // done run holding stills, and a failed run (its paid, approved work only- // continues through the card's explicit Retry — nothing auto-resumes a- // failed plan). Mirror those back (no orchestrator, nothing spends), at- // the cost that dismissing such a card only lasts until the next load.+ // A finished or failed run has nothing to resume — its clips are already+ // on the timeline — but its card is the run's durable record, so it+ // mirrors back on every load (no orchestrator, nothing spends) until the+ // user dismisses it; the X stamps the plan so the dismissal sticks.+ // Revision tools rebuild the live run on demand (resumeDoneRun).if (project.phase === "done" || project.phase === "failed") {- if (- project.phase === "failed" ||- project.shots.some((sh) => sh.status === "failed")- ) {- mirrorRun(projectId, project);- }+ if (!project.cardDismissed) mirrorRun(projectId, project);return;}// Rebuild the orchestrator around the persisted plan so approve/regenerate@@ -908,10 +945,22 @@ export const useGenScene = create<GenSceneState>((set, get) => ({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)) killRun(run.projectId);+ // 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 — but the dismissal is stamped on the plan so the card stays+ // closed across loads (until a retry or revision revives the run).+ if (run && !isTerminal(run.status)) {+ killRun(run.projectId);+ } else if (run) {+ const ed = useEditor.getState();+ if (ed.projectId === run.projectId && ed.genvideo) {+ ed.setGenvideo({ ...ed.genvideo, cardDismissed: true });+ } else {+ void withProjectDoc(run.projectId, (doc) => {+ if (doc.genvideo) doc.genvideo = { ...doc.genvideo, cardDismissed: true };+ }).catch(() => {});+ }+ }set({ run: null });},}));diff --git a/site/src/cut/lib/genvideo/orchestrator.ts b/site/src/cut/lib/genvideo/orchestrator.tsindex a4e68cab..23d51dca 100644--- a/site/src/cut/lib/genvideo/orchestrator.ts+++ b/site/src/cut/lib/genvideo/orchestrator.ts@@ -24,7 +24,7 @@ import { fanOut } from "./pool";import { buildNegative, buildPrompt, buildRefPrompt, refsForAsset, shotRefs, styleAnchor } from "./prompt";import { segmentByDuration, type ModelSuite, type ReviewVerdict } from "./capabilities";import type { EditorBridge } from "./editor";-import type { BeatVoice, RefAsset, Shot, VideoAsset, VideoEmit, VideoPhase, VideoProject } from "./types";+import type { BeatVoice, RefAsset, Shot, TranscriptWord, VideoAsset, VideoEmit, VideoPhase, VideoProject } from "./types";export interface OrchestratorDeps {editor: EditorBridge;@@ -433,7 +433,7 @@ export class VideoOrchestrator {* anchor riding along when one exists. */private async mintSheet(asset: VideoAsset): Promise<void> {if (this.aborted) return; // a paused run spends nothing more- this.deps.emit({ type: "activity", message: `Designing ${asset.name}…` });+ this.deps.emit({ type: "activity", message: `Designing ${asset.name}…`, key: asset.id });const anchor = styleAnchor(this.project);// screenedImage holds every later sheet to the anchor (the first sheet IS// the anchor — with none minted yet the gate skips itself).@@ -442,7 +442,7 @@ export class VideoOrchestrator {[...refsForAsset(asset, this.project), ...(anchor ? [anchor] : [])],`a reference sheet of ${asset.name} — ${asset.description}`);- this.deps.emit({ type: "asset", label: `Designed ${asset.name}`, mediaId: asset.mediaId });+ this.deps.emit({ type: "asset", label: `Designed ${asset.name}`, mediaId: asset.mediaId, key: asset.id });}// ── Phase D: keyframes (cheap, run in parallel) ──────────────────────────@@ -708,6 +708,12 @@ export class VideoOrchestrator {await this.deps.editor.removeClip(shot.timelineClipId);shot.timelineClipId = undefined;}+ // Clips a re-cut left in this shot's span — the replaced footage holds the+ // slot until the fresh take arrives, then goes with it.+ if (shot.replacesClipIds?.length) {+ for (const id of shot.replacesClipIds) await this.deps.editor.removeClip(id);+ shot.replacesClipIds = undefined;+ }}// ── Phase H: polish ──────────────────────────────────────────────────────@@ -791,6 +797,200 @@ export class VideoOrchestrator {});}+ /** Re-cut a contiguous span of shots against the same audio: the segmenter+ * re-slices just that span's narration (steered by the instruction), fresh+ * shots replace the old ones between the same frame boundaries — the span+ * can become more shots or fewer — and only they render. The style, the+ * bible, and every other shot's clip stay exactly as they are; a genuinely+ * new person or place gets a bible entry and a sheet first. Each replaced+ * clip holds its slot until the first fresh shot overlapping it places. */+ async recutShots(ids: string[], instruction: string): Promise<VideoProject> {+ const list = this.project.shots;+ const first = list.findIndex((s) => s.id === ids[0]);+ const last = list.findIndex((s) => s.id === ids[ids.length - 1]);+ if (first < 0 || last < first) throw new Error("Those shots are not in this scene.");+ const span = list.slice(first, last + 1);+ const startFrame = span[0].startFrame;+ const endFrame = span[span.length - 1].endFrame;+ const spanFrames = endFrame - startFrame;+ this.deps.emit({+ type: "activity",+ message: span.length === 1 ? `Re-cutting shot ${first + 1}…` : `Re-cutting shots ${first + 1}–${last + 1}…`,+ });+ // Leave the terminal phase for the duration (persisted with the splice+ // below), so a reload mid-re-cut resumes the render through run() instead+ // of stranding pending shots behind a "done" plan.+ this.setPhase("generating");+ // The segmenter sees the span as a self-contained narration (rebased to+ // zero) plus the revision ask and the bible roster, so it reuses known+ // ids and invents one only for a genuinely new person or place.+ const roster = [...this.project.characters, ...this.project.locations]+ .map((a) => `${a.id} = ${a.name}`)+ .join("; ");+ const brief = [+ this.project.brief,+ `Revise this section: ${instruction}`,+ roster+ ? `Reuse these existing ids where they fit: ${roster}. Introduce a new char:/loc: id only for a genuinely new person or place.`+ : "",+ ]+ .filter(Boolean)+ .join("\n");+ const input = {+ transcript: this.spanWords(startFrame, endFrame),+ brief,+ durationFrames: spanFrames,+ fps: this.fps,+ };+ // Fresh ids that can never collide with surviving shots (or each other),+ // however many re-cuts the plan has been through.+ const used = new Set(list.map((s) => s.id));+ let seq = 0;+ const freshId = () => {+ let id = `shot:r${seq++}`;+ while (used.has(id)) id = `shot:r${seq++}`;+ used.add(id);+ return id;+ };+ let cut: Shot[];+ try {+ cut = repairCoverage(await this.deps.suite.breakdown.segment(input), spanFrames, this.fps, freshId);+ } catch {+ cut = repairCoverage(segmentByDuration(input, MAX_SHOT_SEC), spanFrames, this.fps, freshId);+ }+ // Back onto the timeline: absolute frames, then (generated mode) re-nested+ // into the beat spine so each fresh shot lip-syncs to its own voice slice.+ const fresh = this.nestIntoBeats(+ cut.map((s) => ({ ...s, startFrame: s.startFrame + startFrame, endFrame: s.endFrame + startFrame }))+ );+ // Every fresh shot lists each replaced clip overlapping its span; the+ // first of them to place removes it (removal is idempotent). The old+ // footage holds the span until new footage starts landing, and no two+ // clips ever overlap on the track.+ for (const old of span) {+ if (!old.timelineClipId) continue;+ const overlapping = fresh.filter(+ (s) => s.startFrame < old.endFrame && s.endFrame > old.startFrame+ );+ for (const s of overlapping.length ? overlapping : [fresh[0]]) {+ (s.replacesClipIds ??= []).push(old.timelineClipId);+ }+ }+ const addedEntities = this.adoptNewEntities(fresh);+ this.project.shots = [...list.slice(0, first), ...fresh, ...list.slice(last + 1)];+ assertCoverage(this.project.shots, this.durationFrames);+ await this.save();+ this.deps.emit({ type: "breakdown", shots: this.project.shots });+ // A new entity's sheet mints before any render seeds from it, exactly like+ // a first run's design pass.+ if (addedEntities) await this.style();+ await fanOut(+ fresh,+ async (shot) => {+ try {+ await this.makeKeyframes(shot);+ } catch {+ /* placeFallback will source a still */+ }+ await this.generateAndPlace(shot);+ },+ this.poolOpts(0)+ );+ this.setPhase("done");+ await this.save();+ return this.project;+ }++ /** The words heard across a frame span, rebased to zero — the transcript+ * slice in provided mode; in generated mode, synthesized from the script+ * beats (each beat's dialogue spread evenly over its voiced span). */+ private spanWords(startFrame: number, endFrame: number): TranscriptWord[] {+ const t0 = frameToSec(startFrame, this.fps);+ const t1 = frameToSec(endFrame, this.fps);+ if (this.project.audioMode === "provided") {+ return this.project.transcript+ .filter((w) => w.t1 > t0 && w.t0 < t1)+ .map((w) => ({ ...w, t0: w.t0 - t0, t1: w.t1 - t0 }));+ }+ const beats = this.project.script?.beats ?? [];+ const spine = this.project.beatVoices ?? [];+ const words: TranscriptWord[] = [];+ spine.forEach((bv, bi) => {+ const text = beats[bi]?.dialogue.trim();+ if (!text) return;+ const parts = text.split(/\s+/).filter(Boolean);+ const beatT0 = frameToSec(bv.startFrame, this.fps);+ const per = frameToSec(bv.durationFrames, this.fps) / parts.length;+ parts.forEach((w, wi) => {+ const wt0 = beatT0 + wi * per;+ const wt1 = wt0 + per;+ if (wt1 > t0 && wt0 < t1) words.push({ t0: wt0 - t0, t1: wt1 - t0, w });+ });+ });+ return words;+ }++ /** Split re-cut shots at beat boundaries and wire each piece to its beat's+ * voice slice (generated mode) — the spine is placed audio and must not+ * move, so the new cut nests inside it. Provided mode passes through: those+ * shots read their slice straight off the one audio asset by frame. */+ private nestIntoBeats(shots: Shot[]): Shot[] {+ const beats = this.project.beatVoices;+ if (this.project.audioMode !== "generated" || !beats?.length) return shots;+ const script = this.project.script;+ const out: Shot[] = [];+ for (const shot of shots) {+ let at = shot.startFrame;+ let piece = 0;+ while (at < shot.endFrame) {+ const bi = beats.findIndex((b) => at >= b.startFrame && at < b.startFrame + b.durationFrames);+ const beat = bi >= 0 ? beats[bi] : undefined;+ const end = Math.min(shot.endFrame, beat ? beat.startFrame + beat.durationFrames : shot.endFrame);+ out.push({+ ...shot,+ id: piece === 0 ? shot.id : `${shot.id}.${piece}`,+ startFrame: at,+ endFrame: end,+ ...(beat?.voiceAssetId+ ? {+ voiceAssetId: beat.voiceAssetId,+ voiceFromSec: frameToSec(at - beat.startFrame, this.fps),+ voiceToSec: frameToSec(end - beat.startFrame, this.fps),+ }+ : {}),+ ...(bi >= 0 && script?.beats[bi] ? { dialogue: script.beats[bi].dialogue } : {}),+ });+ piece++;+ at = end;+ }+ }+ return out;+ }++ /** Bible stubs for ids a re-cut introduced — style() then mints their+ * sheets like any first-run design. Returns whether anything was added. */+ private adoptNewEntities(shots: Shot[]): boolean {+ const known = new Set(+ [...this.project.characters, ...this.project.locations].map((a) => a.id)+ );+ let added = false;+ for (const shot of shots) {+ for (const id of shot.characters) {+ if (!id || known.has(id)) continue;+ known.add(id);+ this.project.characters.push({ id, kind: "character", name: id, description: shot.action });+ added = true;+ }+ const loc = shot.location;+ if (loc && !known.has(loc)) {+ known.add(loc);+ this.project.locations.push({ id: loc, kind: "location", name: loc, description: shot.action });+ added = true;+ }+ }+ return added;+ }+/** A style change dirties everything downstream of the style bible. */async changeStyle(style: string): Promise<VideoProject> {// The new look goes back through the art director: it realizes the pinned@@ -882,6 +1082,7 @@ export class VideoOrchestrator {private setPhase(phase: VideoPhase, note?: string): void {this.project.phase = phase;+ if (phase === "done" || phase === "failed") this.project.endedAt = Date.now();this.deps.emit({ type: "phase", phase, note });}diff --git a/site/src/cut/lib/genvideo/types.ts b/site/src/cut/lib/genvideo/types.tsindex 4e65fa43..95257849 100644--- a/site/src/cut/lib/genvideo/types.ts+++ b/site/src/cut/lib/genvideo/types.ts@@ -90,6 +90,10 @@ export interface Shot {voiceToSec?: number;clip?: string; // generated video, media asset idtimelineClipId?: string; // the clip placed on the timeline+ /** Timeline clips from shots a re-cut replaced: the old footage holds this+ * shot's span until its own take places, then goes with it. Persisted, so a+ * reload mid-re-cut still clears them. */+ replacesClipIds?: string[];lipSynced?: boolean;status: ShotStatus;attempts: number;@@ -160,6 +164,13 @@ export interface VideoProject {/** Epoch ms when the user approved and rendering began — the card's render* clock counts from here across reloads and project switches. */renderStartedAt?: number;+ /** Epoch ms when the run reached done/failed — freezes the finished card's+ * elapsed clock across reloads. */+ endedAt?: number;+ /** The user closed the finished run's chat card. A terminal run's card is+ * its durable record — it re-surfaces on every load until this is stamped;+ * reviving the run (retry, revision) clears it. */+ cardDismissed?: boolean;updatedAt: number;}@@ -191,10 +202,11 @@ export type VideoEvent =| { type: "progress"; placed: number; total: number }| { type: "log"; message: string }/** A media asset the run just made (a sheet, a frame, a take) — the chat- * card lists these chronologically with a thumbnail. */- | { type: "asset"; label: string; mediaId: string }+ * activity lists these chronologically with a thumbnail. `key` names the+ * work item, so the milestone replaces that item's in-progress line. */+ | { type: "asset"; label: string; mediaId: string; key?: string }/** The live ticker: one line on what the run is doing right now. */- | { type: "activity"; message: string }+ | { type: "activity"; message: string; key?: string }| { type: "error"; message: string };export type VideoEmit = (event: VideoEvent) => void;diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 0e1a62c8..41117bb2 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -344,6 +344,16 @@ export const AI_TOOLS: AiToolDef[] = ["Redo one shot of the generated scene by its number (1-based), optionally nudging it (\"wider\", \"at night\", \"more energetic\"). It swaps the shot's clip on the timeline by itself — never delete the clip first. 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: "recut_scene",+ description:+ "Re-cut a contiguous span of the generated scene's shots: replans just that span against the same audio — it can split into more shots or merge into fewer — keeping the style, cast, and every other shot's clip, then renders only the new shots (credits per new shot). Use it when the user wants a section restructured (\"split the last shot\", \"shots 2-3 drag, tighten them\", \"that part is missing the soccer scene\"); one shot redone as-is is regenerate_shot, a whole-look change is restyle_scene. Only valid after a scene has finished.",+ inputSchema: obj({+ from_shot: num("First shot of the span, 1-based"),+ to_shot: num("Last shot of the span, 1-based (equal to from_shot for one shot)"),+ instruction: str("What the span should become — the content to cover and how to pace it"),+ }, ["from_shot", "to_shot", "instruction"]),+ },{name: "restyle_scene",description:@@ -731,7 +741,7 @@ Aspect: every shot renders at the plan's aspect, frozen from the project when apLook: the user's style reference is the strongest anchor — pass attached images/clips as reference_asset_ids; they anchor the style bible and every shot. A reference contributes the LOOK; when the user wants its pictured character or place in the video itself, say that in the brief — otherwise the pipeline designs a fresh cast in the reference's technique. The brief describes the same look in plain visual traits so words and image agree; with no reference, build the trait wording from the ask (a simple children's cartoon → "flat hand-drawn 2D animation, clean thick outlines, simple rounded characters, soft colors, gentle fluid motion"). Describe any show, franchise, or artist by traits — the generator rejects trademarked names. Name recurring wardrobe and props in the brief so independently rendered shots match.From an audio file (the audio rides the timeline as the spine): listen_audio first and extract every fact — who speaks, who appears, each topic in order. Then generate_scene with from_audio_asset_id PLUS a brief carrying those facts; the brief outranks transcript mishears. Speech in another language: write the brief's facts in English and pass audio_language so the on-device transcriber uses the right recognizer. Long silence or music in the source becomes filler shots — suggest trimming first (detect_silence); shots tile the full asset length, so warn on long files (many paid shots).Scope: deliver exactly what was asked — no subtitle tracks, titles, or extra music on top (brief mode lays its own soft music bed; from-audio mode adds none). One scene run at a time — cancel_scene stops the active one when the user wants it gone or replaced.-After renders land: spot-check with capture_frame or watch_video (aspect, style, motion). The user may point at clips by @ token ("@c2 doesn't match the audio") — the clip attachment's id maps to videoTrack in editor_state, whose sceneShot is the n regenerate_shot takes; carry their complaint as its note, and check the audio itself with listen_audio on the spine asset (subtitles_generate would write a caption track nobody asked for). A shot that failed all its takes holds a still — repair it ONLY with regenerate_shot n (it re-runs the shot's identity ladder and swaps the clip in place); deleting the still or rendering a replacement with generate_video orphans the shot and loses the run's identity anchors and review. A whole-look change is restyle_scene: every shot re-renders, so confirm first. Undo removes clips; spent credits stay spent.`,+After renders land: spot-check with capture_frame or watch_video (aspect, style, motion). The user may point at clips by @ token ("@c2 doesn't match the audio") — the clip attachment's id maps to videoTrack in editor_state, whose sceneShot is the n regenerate_shot takes; carry their complaint as its note, and check the audio itself with listen_audio on the spine asset (subtitles_generate would write a caption track nobody asked for). A shot that failed all its takes holds a still — repair it ONLY with regenerate_shot n (it re-runs the shot's identity ladder and swaps the clip in place); deleting the still or rendering a replacement with generate_video orphans the shot and loses the run's identity anchors and review. Revisions ladder by scope, never a fresh generate_scene (that replans and re-bills the whole video): one shot redone or nudged → regenerate_shot; a section restructured — split, tightened, content added ("the last shot is missing the soccer scene") → recut_scene from_shot..to_shot with the ask as its instruction (replans just that span on the same audio, keeps the cast and every other clip, bills only the new shots, no approval gate — the user's ask is the go-ahead); a whole-look change → restyle_scene (every shot re-renders, confirm first). Undo removes clips; spent credits stay spent.`,"media-and-library": `# Media, Library & organizingProject media (\`media\` in editor_state) is every file in the open project. The Media panel shows the user's own imports — assets with no origin tag; created media (origin generated, voiceover, stock, chat, freeze, recording) lives where it was made until filed away.@@ -763,7 +773,7 @@ Rules:- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and 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 a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop 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).+- 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 a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the shot list — confirm with the user, then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / 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.`;}