Open source CapCut alternative.
TypeScript
feat(site): a replica is built in colour and checked against its source [rebuild]
David Le9b4fbe001da5
diff --git a/site/src/clients/chatgpt/server/catalog.ts b/site/src/clients/chatgpt/server/catalog.tsindex 83d0c95c..d3d1dfe8 100644--- a/site/src/clients/chatgpt/server/catalog.ts+++ b/site/src/clients/chatgpt/server/catalog.ts@@ -42,6 +42,7 @@ export const unknownCommandNames = (names: string[]): string[] => names.filter((export const READ_COMMANDS = new Set(["watch_video","capture_frame",+ "compare_to_source","listen_audio","detect_silence","detect_beats",diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex 3902f0b5..c89f2e44 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -118,6 +118,27 @@ export const AI_PANEL_TOOLS = [to: num("Source end s (default: the clip's out, else the source's end)"),}),},+ {+ name: "compare_to_source",+ description:+ "Check the cut against the thing it was built from: renders your frame at each moment and reads the source's frame at the moment it stands for, handing both back side by side in one picture. This is how a replica is verified — watching the source tells you what it does, and this tells you whether what you made does it too. Pass `times` as timeline seconds, or as {at, source} pairs when the cut sits at a different second than the source does. Up to 4 moments a call; check, fix what is off, call again.",+ inputSchema: obj(+ {+ asset_id: str("Project asset id of the source the cut was built from"),+ times: {+ type: "array",+ description: "Moments to check — a timeline second, or {at, source} when the two clocks differ",+ items: {+ anyOf: [+ { type: "number" },+ obj({ at: num("Timeline second"), source: num("The second of the source it stands for") }, ["at"]),+ ],+ },+ },+ },+ ["asset_id", "times"]+ ),+ },{name: "find_highlights",description:diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.tsindex 7b5dd77e..d4a70152 100644--- a/site/src/cut/components/Inspector.tools.ts+++ b/site/src/cut/components/Inspector.tools.ts@@ -248,8 +248,12 @@ export const INSPECTOR_TOOLS = [{name: "detach_audio",description:- "Detach Audio: lift a clip's sound onto the soundtrack track (mutes the clip) so it can be edited independently. Select the clip first or pass its id.",- inputSchema: obj({ clipId: str("Video clip id (optional if one is selected)") }),+ "Detach Audio: lift a clip's sound onto the soundtrack track (mutes the clip) so it can be edited independently. Select the clip first or pass its id. Pass assetId instead to put a source's whole track on the soundtrack with none of its picture placed — how a cut blocked out as empty shots carries the reference's sound.",+ inputSchema: obj({+ clipId: str("Video clip id (optional if one is selected)"),+ assetId: str("Project asset id — its whole audio track lands on the soundtrack, no clip placed"),+ start: num("Timeline start s for an assetId detach (default 0)"),+ }),},{name: "set_framing",diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex c4aec825..9e59d1e7 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -78,6 +78,7 @@ import {penClosed,restingMaskFrame,} from "@donkeycut/effects-kit";+import { BLOCK_COLOR } from "@/cut/lib/blockSource";import { clipLen, clipWindow, maxClipFade, useEditor, type EditorState } from "@/cut/lib/store";import { PANEL_GLOBAL, usePanelState, useRememberedScroll } from "@/cut/lib/panelState";import { usePreviewTime } from "@/cut/lib/playhead";@@ -1195,6 +1196,23 @@ function ClipPanel({ clip }: { clip: VideoClip }) {time={formatTime(speedLen)}onRename={(name) => updateClip(clip.id, { name })}/>+ {asset?.block && (+ // A blocked-out shot's whole picture is its colour, so that is the+ // one thing there is to set on it by hand.+ <Row label="Color">+ <ColorField+ value={asset.block.color || BLOCK_COLOR}+ label="Block color"+ onBegin={() => useEditor.getState().pushHistory()}+ onLive={(c) =>+ useEditor.getState().updateAsset(asset.id, { block: { ...asset.block!, color: c } })+ }+ onCommit={(c) =>+ useEditor.getState().updateAsset(asset.id, { block: { ...asset.block!, color: c } })+ }+ />+ </Row>+ )}<Row label="Trim"><ScrubValuelabel="Trim start"diff --git a/site/src/cut/components/Timeline.tools.ts b/site/src/cut/components/Timeline.tools.tsindex 7261bb22..5c50a908 100644--- a/site/src/cut/components/Timeline.tools.ts+++ b/site/src/cut/components/Timeline.tools.ts@@ -65,7 +65,7 @@ export const TIMELINE_TOOLS = [{name: "add_clip",description:- "Put a project asset on the timeline, the same way the user dragging it in would: a video or image lands on video track 0 (at `start`, inserted at `index`, or appended at the end; a taken spot slides it right), audio lands on the soundtrack (at `start`, default the playhead). Asset ids come from `media` in editor_state — imports, attachments, and chat media alike. Call it only when the user asked for the media in the cut (\"add my beach photo\", \"stitch these into a movie\"); otherwise media stays on its card or panel for them to drag. Pass `blocks` instead of an asset to lay out a cut whose footage does not exist yet: one block per shot on track 0, each the length that shot runs, labelled with what belongs there. That is how a video you watched becomes a timeline — the cuts land at their real times, titles and sound go on top, and the person fills each block later. Blocks own no file and store nothing; footage dropped on one takes its place and its length, and replace_item does the same from here. Pass `spans` to cut several stretches of one source into one run of clips — the moments of a talk worth keeping, in order, with everything between them left out. `reference_asset_id` names the source the shots were copied from: what is being copied does not play in the copy, so the tools stop placing it once it is named.",+ "Put a project asset on the timeline, the same way the user dragging it in would: a video or image lands on video track 0 (at `start`, inserted at `index`, or appended at the end; a taken spot slides it right), audio lands on the soundtrack (at `start`, default the playhead). Asset ids come from `media` in editor_state — imports, attachments, and chat media alike. Call it only when the user asked for the media in the cut (\"add my beach photo\", \"stitch these into a movie\"); otherwise media stays on its card or panel for them to drag. Pass `blocks` instead of an asset to lay out a cut whose footage does not exist yet: one block per shot on track 0, each the length that shot runs, labelled with what belongs there. That is how a video you watched becomes a timeline — the cuts land at their real times, titles and sound go on top, and the person fills each block later. Blocks own no file and store nothing; footage dropped on one takes its place and its length, and replace_item does the same from here. Pass `spans` to cut one source into a run of clips — the moments of a talk worth keeping, with everything between them left out, or a video cut at its own shot boundaries when its picture is what plays.",inputSchema: obj({asset_id: str("Project asset id from `media` in editor_state"),blocks: {@@ -74,7 +74,8 @@ export const TIMELINE_TOOLS = [items: obj({seconds: num("How long this shot runs on the timeline"),- label: str("What belongs in this shot — shown on the block and on its timeline chip"),+ label: str("What the person puts here. It names the slot on its timeline chip; the frame itself is the flat colour"),+ color: str("The shot's backdrop as #rrggbb, so the slot carries the look it sits in"),},["seconds"]),@@ -82,10 +83,9 @@ export const TIMELINE_TOOLS = [spans: {type: "array",description:- "Stretches of this source, in SOURCE seconds — one clip each, in order, with the material between them left out. This is how several moments of one video become one cut.",+ "Stretches of this source, in SOURCE seconds — one clip each, in order. Gapped spans keep the moments and drop the rest; spans that meet cut the source at those boundaries.",items: obj({ from: num("Source start s"), to: num("Source end s") }, ["from", "to"]),},- reference_asset_id: str("Blocks only: the source these shots were copied from"),lane: { type: "integer", minimum: 0, description: "Audio assets only: soundtrack lane, default 0. Put music on lane 1 to overlap narration on lane 0." },start: num("Timeline start s"),index: num("Insert position on video track 0 (video/image only; 0 = first)"),@@ -319,7 +319,7 @@ export const TIMELINE_TOOLS = [{name: "replace_item",description:- "Replace what an item plays, keeping the item: a video clip (including a blocked-out shot) keeps its place and its length and plays the asset you name instead, trimmed from that source's head; a soundtrack clip keeps its slot; a sticker shows the new image. This is how a block becomes the person's own footage (\"put the kitchen clip in shot 3\"), and how any clip swaps its source without moving what comes after. A block left playing nothing goes with it. The source a cut was copied from is not a fill for its own blocks.",+ "Replace what an item plays, keeping the item: a video clip (including a blocked-out shot) keeps its place and its length and plays the asset you name instead, trimmed from that source's head; a soundtrack clip keeps its slot; a sticker shows the new image. This is how a block becomes the person's own footage (\"put the kitchen clip in shot 3\"), and how any clip swaps its source without moving what comes after. A block left playing nothing goes with it.",inputSchema: obj({id: str("The item to refill — a video clip, a soundtrack clip, or a sticker"),diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 3142feb8..635b581c 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -4506,6 +4506,8 @@ function filmstripFrames(view?: { lo: number; hi: number }): FilmTile[] {if (!asset) return [];+ // A blocked-out shot has no frames to tile: the strip paints its colour.+ if (asset.block) return [];// Before the pre-sampled strip exists — a fresh import, a library clip// dropped a moment ago — the clip still has a frame in hand: the one read// for its left edge. Standing that in as a one-thumb strip paints the wholediff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 0a374178..92db3281 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -468,6 +468,10 @@ function describeState(out: r(sp.clip.out),// A still has no source length; report its placed length instead of 0.sourceDuration: r(sp.asset.type === "image" ? sp.len : sp.asset.duration),+ // A blocked-out shot holds a slot and draws a flat colour — there is no+ // picture here yet, and its label lives on the chip. Without this the+ // label reads as a clip's name and a shell of a cut looks finished.+ ...(sp.asset.block ? { emptyShot: true } : {}),muted: sp.clip.muted,...(sp.clip.hidden ? { hidden: true } : {}),// The clip's own equalizer/compressor/limiter, set throughdiff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 6650ac5f..0eb3e2f3 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -121,6 +121,7 @@ import {importStockAudio,importStockVideo,importUrlMedia,+ composeComparison,composeSheets,makeStillFrame,renderAudioSpanWav,@@ -157,7 +158,8 @@ import { isSoundPresetTemplate, listSoundPresets, saveSoundPreset } from "./sounimport { isStylePresetTemplate } from "./stylePresets";import { applyOverlayPatchSettled, clipLen, track0Clips, laneGapAt, getClipSpans, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";import { playheadAt } from "./playhead";-import { renderProjectFrame } from "./exportRender";+import { renderProjectFrame, renderProjectFrames } from "./exportRender";+import { framesAt } from "./mediaRead";import { renderStageFrame, storeStageStill } from "./stageFrame";import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";import { buildAiContext, describeDoc, hiddenFromChat, placedAssetIds } from "./aiContext";@@ -404,6 +406,9 @@ const CAPTURE_LONG_SIDE = 640;* undo step, and a whole feature's worth of them in a single step is not* something anyone can step back through; a caller with more comes back. */const MAX_BLOCKS = 40;+// Each moment is two frames drawn and one picture composed; a handful at a+// time keeps the call inside the bridge's deadline and the reply readable.+const MAX_COMPARE = 4;const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);@@ -465,7 +470,6 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {if (!assetId) throw new ToolError("Pass asset_id.");const stickerAsset = s.assets.find((a) => a.id === assetId);if (stickerAsset?.type !== "image") throw new ToolError(`No image asset with id ${assetId}.`);- refuseReference(stickerAsset);if (isNum(input.start)) s.seek(input.start);s.addSticker({ assetId, ...(isLottieAsset(stickerAsset) ? { lottie: true } : {}), ...aimedLane(input) });const sel = useEditor.getState().selection;@@ -878,6 +882,112 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {return { image: await rasterCanvasToDataUrl(canvas, "image/jpeg", 0.75), at };},+ compare_to_source: async (s, input) => {+ // Building from a reference and looking at the reference are separate+ // acts, and until they are put in one picture nothing checks the first+ // against the second. This renders the cut at a moment, reads the source+ // at the moment it stands for, and hands back the two side by side.+ const asset = requireItem(s.assets, input.asset_id, "project asset");+ if (asset.type === "audio")+ throw new ToolError(`"${asset.name}" is audio — listen_audio hears it, and a frame is a picture.`);+ // Without a length every moment clamps to 0 and the comparison hands+ // back the same opening frame under four different stamps.+ if (!(asset.duration > 0))+ throw new ToolError(`"${asset.name}" has no length yet — its import is still being read. Try again in a moment.`);+ const raw = Array.isArray(input.times) ? input.times : [];+ const moments = raw+ .map((x) => {+ const rec = (x ?? {}) as Record<string, unknown>;+ const at = isNum(x) ? (x as number) : isNum(rec.at) ? (rec.at as number) : NaN;+ const sourceAt = isNum(rec.source) ? (rec.source as number) : at;+ return { at, sourceAt };+ })+ .filter((m) => Number.isFinite(m.at) && Number.isFinite(m.sourceAt));+ if (moments.length === 0)+ throw new ToolError("Pass times: [seconds] — the moments of the cut to check, or [{at, source}] when the cut sits at a different second than the source does.");+ if (moments.length > MAX_COMPARE)+ throw new ToolError(`That is ${moments.length} moments — ${MAX_COMPARE} is the most one call reads. Check these, fix what is off, then call again for the rest.`);+ const total = totalDuration(s.clips);+ const frame = frameOf(s.aspect);+ const k = CAPTURE_LONG_SIDE / Math.max(frame.w, frame.h);+ const size = { width: Math.round(frame.w * k), height: Math.round(frame.h * k) };+ // The source keeps its own aspect: a height alone lets a widescreen+ // reference stay widescreen beside a vertical cut, which is half of what+ // the comparison is for. Asking for both dimensions squashes it.+ const sourceSize = { height: size.height };+ const wanted = moments.map((m) => ({+ at: clamp(m.at, 0, Math.max(0, total - 0.001)),+ sourceAt: clamp(m.sourceAt, 0, Math.max(0, asset.duration - 0.001)),+ }));+ // One decode pass over the source, in play order, however the moments+ // were asked for.+ const order = wanted.map((_, i) => i).sort((a, b) => wanted[a].sourceAt - wanted[b].sourceAt);+ const refs = new Map<number, string>();+ if (asset.type === "image") {+ const still = await makeStillFrame(asset.url, "read").catch((e) => {+ throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`);+ });+ for (const i of order) refs.set(i, still.frames[0].image);+ } else {+ let seen = 0;+ try {+ for await (const c of framesAt(+ asset.url,+ order.map((i) => wanted[i].sourceAt),+ sourceSize+ )) {+ const i = order[seen++];+ if (c) refs.set(i, await rasterCanvasToDataUrl(c.canvas, "image/jpeg", 0.82));+ }+ } catch (e) {+ throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`);+ }+ }+ for (let i = 0; i < wanted.length; i++)+ if (!refs.has(i)) throw new ToolError(`Could not read "${asset.name}" at ${round2(wanted[i].sourceAt)}s.`);+ // One prepared painter for every moment: preparing stamps every title+ // and may bring up the segmenter, and the document does not change+ // between them.+ const pairs: { t: number; sourceAt: number; source: string; cut: string }[] = [];+ await renderProjectFrames(+ {+ aspect: s.aspect,+ assets: s.assets,+ clips: s.clips,+ audioClips: s.audioClips,+ overlays: s.overlays,+ subtitles: s.subtitles,+ background: s.background,+ },+ wanted.map((m) => m.at),+ size,+ (a) => a.url,+ async (canvas, at) => {+ const i = pairs.length;+ pairs.push({+ t: round2(at),+ sourceAt: round2(wanted[i].sourceAt),+ source: refs.get(i)!,+ cut: await rasterCanvasToDataUrl(canvas, "image/jpeg", 0.82),+ });+ }+ ).catch((e) => {+ throw new ToolError(e instanceof Error ? e.message : "Could not draw the cut's frame.");+ });+ const images = await composeComparison(pairs).catch((e) => {+ throw new ToolError(e instanceof Error ? e.message : "Could not compose the comparison.");+ });+ return {+ images,+ checked: pairs.map((p) => ({ at: p.t, source: p.sourceAt })),+ // The same shape every look returns, so a record opened by a+ // comparison knows what the other senses may ask of this source.+ source: sourceRef(asset),+ note:+ "Source on the left, your cut on the right, one picture per moment. Name what differs — colour, the words and their face, where a thing sits, its size, what is moving and how far along it is — then fix it with the tools and check again. A moment that matches needs no edit.",+ };+ },+watch_video: async (s, input) => {// A look at a reference project's footage decides a mapping and writes// nothing: no note owed, no frame map kept, no sweep started.@@ -1583,7 +1693,6 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {const asset = requireItem(s.assets, input.asset_id, "project asset");if (asset.type !== "video" && asset.type !== "image")throw new ToolError("Only video or image assets can sit on a video track.");- refuseReference(asset);const start = isNum(input.start) ? Math.max(0, input.start) : playheadAt();// Tracks stack bottom-up from track 0; overlays live on 1+. A stale// negative (the old behind-track model) clamps to the first layer.@@ -2081,8 +2190,21 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {},detach_audio: (s, input) => {+ // A cut blocked out as empty shots has no clip of the reference to lift+ // from, and its sound is what the cuts were timed to; naming the asset+ // puts that whole track on the soundtrack with nothing else placed.+ if (input.assetId) {+ const asset = requireItem(s.assets, input.assetId, "project asset");+ if (asset.type === "image" || assetIsSilent(asset))+ throw new ToolError(`"${asset.name}" carries no audio.`);+ const start = isNum(input.start) ? Math.max(0, input.start) : 0;+ s.addAudioFromAsset(asset.id, start);+ void ensurePeaks(asset);+ const sel = useEditor.getState().selection;+ return { audioClipId: sel?.kind === "audio" ? sel.id : null };+ }const id = input.clipId ? String(input.clipId) : s.selection?.kind === "clip" ? s.selection.id : null;- if (!id) throw new ToolError("Pass clipId or select a video clip first.");+ if (!id) throw new ToolError("Pass clipId, assetId, or select a video clip first.");const clip = requireItem(s.clips, id, "video clip");if (clip.muted) throw new ToolError("That clip's audio is muted — nothing to detach.");s.select({ kind: "clip", id: clip.id });@@ -2727,7 +2849,6 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {replace_item: (s, input) => {const id = typeof input.id === "string" ? input.id : "";const asset = requireItem(s.assets, input.asset_id, "project asset");- refuseReference(asset);const clip = s.clips.find((c) => c.id === id);if (clip) {if (asset.type !== "video" && asset.type !== "image")@@ -4623,6 +4744,7 @@ export const MEDIA_RUNTIME_TOOLS: ReadonlySet<string> = new Set(["detect_beats","refine_speech_cuts","capture_frame",+ "compare_to_source","render_preview","freeze_frame","create_sticker",@@ -5417,6 +5539,17 @@ function audioLaneInput(value: unknown): number {return value;}+/** A colour the model passed, as the document stores it. A value that is not+ * a colour is named: silently falling back paints a shot the reference never+ * had while the reply says the backdrop landed. */+function hexColor(raw: unknown, what: string): string {+ const v = typeof raw === "string" ? raw.trim() : "";+ const short = /^#([0-9a-fA-F]{3})$/.exec(v);+ if (short) return `#${[...short[1]].map((c) => c + c).join("")}`;+ if (/^#[0-9a-fA-F]{6}$/.test(v)) return v;+ throw new ToolError(`${what} has to be a hex colour like #ff5a00 or #f50 — got ${JSON.stringify(raw)}.`);+}+/** Lay out shots that have no footage yet: one block per shot on track 0,* each the length that shot runs, in one undo step. The blocks own no files,* so this writes nothing to storage — and each one is an ordinary clip, so it@@ -5427,6 +5560,9 @@ function placeBlocks(s: Editor, raw: unknown[], input: Record<string, unknown>).map((x) => ({seconds: isNum(x.seconds) ? clamp(x.seconds, 0.2, 600) : 0,label: typeof x.label === "string" ? x.label.trim() : "",+ // The shot's own backdrop, so a cut waiting on its footage still shows+ // the look it is standing in for.+ ...(x.color === undefined || x.color === null ? {} : { color: hexColor(x.color, "A block's color") }),})).filter((x) => x.seconds > 0);if (shots.length === 0)@@ -5435,17 +5571,11 @@ function placeBlocks(s: Editor, raw: unknown[], input: Record<string, unknown>)throw new ToolError(`That is ${shots.length} shots — ${MAX_BLOCKS} is the most one call lays down. Lay the first stretch and call again for the rest.`);- const reference =- typeof input.reference_asset_id === "string" && input.reference_asset_id- ? requireItem(s.assets, input.reference_asset_id, "project asset")- : null;const frame = frameOf(s.aspect);const made: { clipId: string; assetId: string; start: number; seconds: number; label: string }[] = [];let at = isNum(input.start) ? Math.max(0, input.start) : undefined;useEditor.getState().beginHistoryBatch();try {- // What the shots are copied from does not play in the copy.- if (reference) useEditor.getState().updateAsset(reference.id, { reference: true });for (const [i, shot] of shots.entries()) {const asset = blockAsset(shot, i, frame);const cur = useEditor.getState();@@ -5476,16 +5606,6 @@ function placeBlocks(s: Editor, raw: unknown[], input: Record<string, unknown>)};}-/** A reference is what the cut is copied from, so it never plays in it: the- * blocks standing in for its shots are waiting on the person's own footage.- * Their hands can still place it — this holds the assistant's tools. */-function refuseReference(asset: MediaAsset): void {- if (!asset.reference) return;- throw new ToolError(- `"${asset.name}" is the reference this cut is blocked out from, so it does not go in the cut. Fill a block with the person's own footage (replace_item), or leave it standing.`- );-}-/** Several stretches of one source laid down in order, each trimmed to itself* — a clip assembled from moments that were never next to each other, with* everything between them left out. Placement and trimming both ride the@@ -5496,7 +5616,6 @@ function placeAssetSpans(spans: { from: number; to: number }[],input: Record<string, unknown>) {- refuseReference(asset);if (asset.type === "audio") throw new ToolError("spans cut a video source — audio lands whole.");if (asset.type === "image") throw new ToolError("An image has no time axis to cut spans out of.");const dur = asset.duration > 0 ? asset.duration : Infinity;@@ -5547,7 +5666,6 @@ function placeAssetSpans(}function placeAssetOnTimeline(asset: MediaAsset, input: Record<string, unknown>) {- refuseReference(asset);const s = useEditor.getState();const start = isNum(input.start) ? Math.max(0, input.start) : undefined;if (asset.type === "audio") {diff --git a/site/src/cut/lib/blockSource.ts b/site/src/cut/lib/blockSource.tsindex 8a645d56..4f5dbf9b 100644--- a/site/src/cut/lib/blockSource.ts+++ b/site/src/cut/lib/blockSource.ts@@ -1,18 +1,20 @@-import { wrapTextToRoom } from "@donkeycut/effects-kit";import { createRasterCanvas, type RasterSurface } from "./raster";import type { MediaAsset, StoredAsset } from "./types";// A block is a shot with nothing in it yet: a source that holds a slot on the-// timeline and draws itself — a filled rect carrying the label of whatever-// belongs there. It owns no file, so blocking out a cut writes nothing to-// storage and decodes nothing; the picture is painted once, at whatever size-// asks for it, and cached by the reader that asked. A clip playing a block-// cuts, trims, moves and takes a transition like any other clip, and the day-// the footage arrives it replaces the block in place.+// timeline and draws itself as the colour that shot sits on. It owns no file,+// so blocking out a cut writes nothing to storage and decodes nothing; the+// picture is painted once, at whatever size asks for it, and cached by the+// reader that asked. A clip playing a block cuts, trims, moves and takes a+// transition like any other clip, and the day the footage arrives it replaces+// the block in place.+//+// Nothing is written in the frame. The label says what the person brings and+// belongs to them — it rides the timeline chip and the editor state — so a+// blocked-out cut previews and exports as the look it is standing in for,+// never as a caption describing itself.export const BLOCK_COLOR = "#161A22";-const LABEL_COLOR = "#E9EDF5";-const STROKE_COLOR = "#2E3644";/** The source a shot stands on until its footage exists. It takes the* project's own frame, so a block fills the picture the way the footage that@@ -43,7 +45,7 @@ export function blockAsset(/** Paint a block at this size. Both frame readers — the preview's and the* export's — call this in place of fetching and decoding a still. */export function drawBlock(- asset: Pick<StoredAsset, "block" | "name">,+ asset: Pick<StoredAsset, "block">,width: number,height: number): RasterSurface {@@ -52,25 +54,7 @@ export function drawBlock(const canvas = createRasterCanvas(w, h);const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;if (!ctx) return canvas;- const short = Math.min(w, h);ctx.fillStyle = asset.block?.color || BLOCK_COLOR;ctx.fillRect(0, 0, w, h);-- const inset = Math.round(short * 0.05);- ctx.strokeStyle = STROKE_COLOR;- ctx.lineWidth = Math.max(2, Math.round(short * 0.006));- ctx.strokeRect(inset, inset, w - inset * 2, h - inset * 2);-- const label = asset.block?.label?.trim() || asset.name || "";- if (!label) return canvas;- const size = Math.round(short * 0.062);- ctx.font = `600 ${size}px system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif`;- ctx.fillStyle = LABEL_COLOR;- ctx.textAlign = "center";- ctx.textBaseline = "middle";- const lines = wrapTextToRoom(label, w - inset * 4, (line) => ctx.measureText(line).width).split("\n").slice(0, 4);- const step = size * 1.3;- const top = h / 2 - ((lines.length - 1) * step) / 2;- lines.forEach((line, i) => ctx.fillText(line, w / 2, top + i * step));return canvas;}diff --git a/site/src/cut/lib/blockoutReference.test.ts b/site/src/cut/lib/blockoutReference.test.tsindex eae637aa..ff1575ec 100644--- a/site/src/cut/lib/blockoutReference.test.ts+++ b/site/src/cut/lib/blockoutReference.test.ts@@ -2,9 +2,9 @@ import { beforeEach, expect, test } from "bun:test";import { runAiTool } from "./aiTools";import { storedAssets, useEditor } from "./store";-// A cut blocked out from a reference must not end up playing that reference.-// The mark rides the asset, so the refusal holds for every tool that places-// media, whatever the model was reaching for when it tried.+// Blocks hold a watched video's shots until footage arrives. What fills them+// is the ask's to decide — the person's own footage, or the source the cut was+// blocked out from — so no tool here refuses a source.beforeEach(() => {useEditor.setState({@@ -13,50 +13,43 @@ beforeEach(() => {transitions: [],audioClips: [],assets: [- { id: "ref", fileName: "ref.mp4", name: "Reference", type: "video", duration: 60, url: "", reference: true },+ { id: "ref", fileName: "ref.mp4", name: "Reference", type: "video", duration: 60, url: "" },{ id: "mine", fileName: "mine.mp4", name: "My shot", type: "video", duration: 12, url: "" },- { id: "still", fileName: "ref.png", name: "Reference still", type: "image", duration: 0, url: "", reference: true },+ { id: "still", fileName: "ref.png", name: "Reference still", type: "image", duration: 0, url: "" },],});});-const message = async (p: Promise<unknown>) =>- p.then(() => "", (e: unknown) => (e instanceof Error ? e.message : String(e)));--test("the assistant cannot put the reference in the cut it is copied from", async () => {- const error = await message(runAiTool("add_clip", { asset_id: "ref" }));- expect(error).toContain("reference this cut is blocked out from");- expect(useEditor.getState().clips).toHaveLength(0);-});--test("the reference cannot fill a block either", async () => {- await runAiTool("add_clip", { asset_id: "mine", start: 0 });- const clip = useEditor.getState().clips[0]!;- const error = await message(runAiTool("replace_item", { id: clip.id, asset_id: "ref" }));- expect(error).toContain("reference this cut is blocked out from");- expect(useEditor.getState().clips[0]!.assetId).toBe("mine");-});-test("the person's own footage still goes down", async () => {await runAiTool("add_clip", { asset_id: "mine", start: 0 });expect(useEditor.getState().clips.map((c) => c.assetId)).toEqual(["mine"]);});-test("an unmarked source is nobody's reference", async () => {- useEditor.getState().updateAsset("ref", { reference: undefined });- await runAiTool("add_clip", { asset_id: "ref", start: 0 });- expect(useEditor.getState().clips.map((c) => c.assetId)).toEqual(["ref"]);+test("the watched source can play in the cut blocked out from it", async () => {+ await runAiTool("add_clip", { blocks: [{ seconds: 4 }, { seconds: 3 }] });+ const [first, second] = useEditor.getState().clips;+ await runAiTool("replace_item", { id: first!.id, asset_id: "ref" });+ await runAiTool("replace_item", { id: second!.id, asset_id: "mine" });+ expect(useEditor.getState().clips.map((c) => c.assetId)).toEqual(["ref", "mine"]);+});++test("spans cut a source at its own shot boundaries", async () => {+ const out = (await runAiTool("add_clip", {+ asset_id: "ref",+ spans: [{ from: 0, to: 4 }, { from: 4, to: 9.5 }, { from: 9.5, to: 12 }],+ })) as { clips: { start: number; len: number }[] };+ expect(out.clips.map((c) => c.len)).toEqual([4, 5.5, 2.5]);+ expect(out.clips.map((c) => c.start)).toEqual([0, 4, 9.5]);+ expect(useEditor.getState().clips.every((c) => c.assetId === "ref")).toBe(true);});test("a run of blocks lays a cut out end to end, storing nothing", async () => {- useEditor.getState().updateAsset("ref", { reference: undefined });const out = (await runAiTool("add_clip", {blocks: [{ seconds: 4, label: "wide of the kitchen" },{ seconds: 2.5, label: "hands only" },{ seconds: 6 },],- reference_asset_id: "ref",})) as { placed: { start: number; seconds: number; label: string }[] };expect(out.placed.map((p) => [p.start, p.seconds])).toEqual([[0, 4], [4, 2.5], [6.5, 6]]);@@ -71,12 +64,9 @@ test("a run of blocks lays a cut out end to end, storing nothing", async () => {const made = state.assets.filter((a) => a.block !== undefined);expect(made).toHaveLength(3);expect(made.every((a) => a.url === "" && a.fileName === "")).toBe(true);- // Naming the source makes it the reference, so the tools stop placing it.- expect(state.assets.find((a) => a.id === "ref")!.reference).toBe(true);});test("the whole blockout is one undo step", async () => {- useEditor.getState().updateAsset("ref", { reference: undefined });await runAiTool("add_clip", {blocks: [{ seconds: 3 }, { seconds: 3 }, { seconds: 3 }],});@@ -98,7 +88,6 @@ test("footage takes a block's place and its length", async () => {});test("a blockout survives the save", () => {- useEditor.getState().updateAsset("ref", { reference: true });useEditor.setState({assets: [...useEditor.getState().assets,@@ -115,29 +104,16 @@ test("a blockout survives the save", () => {],});const saved = storedAssets(useEditor.getState().assets);- // Without these two the blockout comes back as an image with no file: the- // shot draws nothing, footage dropped on it inserts beside it instead of- // filling it, and the reference is placeable again.+ // Without this the blockout comes back as an image with no file: the shot+ // draws nothing, and footage dropped on it inserts beside it instead of+ // filling it.expect(saved.find((a) => a.id === "b1")?.block).toEqual({ label: "wide of the kitchen" });- expect(saved.find((a) => a.id === "ref")?.reference).toBe(true);-});--test("the reference is refused on every door, not just track 0", async () => {- for (const call of [- runAiTool("add_overlay_video", { asset_id: "ref", track: 1 }),- runAiTool("add_sticker", { asset_id: "still" }),- ]) {- expect(await message(call)).toContain("reference this cut is blocked out from");- }- expect(useEditor.getState().clips).toHaveLength(0);- expect(useEditor.getState().overlays).toHaveLength(0);});test("a swap drops coverage painted for the source it replaces", async () => {await runAiTool("add_clip", { asset_id: "mine", start: 0 });const clip = useEditor.getState().clips[0]!;useEditor.getState().updateClip(clip.id, { mask: { kind: "rect", x: 0, y: 0, w: 0.5, h: 0.5 } });- useEditor.getState().updateAsset("ref", { reference: undefined });await runAiTool("replace_item", { id: clip.id, asset_id: "ref" });expect(useEditor.getState().clips[0]!.mask).toBeUndefined();});@@ -170,3 +146,33 @@ test("a sticker's swap carries how it plays", async () => {await runAiTool("replace_item", { id: sticker.id, asset_id: "anim" });expect((useEditor.getState().overlays[0] as { lottie?: boolean }).lottie).toBe(true);});++test("a block owns no address and no strip of its own", async () => {+ await runAiTool("add_clip", { blocks: [{ seconds: 4, label: "your photo", color: "#F26722" }] });+ const block = useEditor.getState().assets.find((a) => a.block)!;+ // Nothing to fetch: a url built from an empty file name aims the strip, the+ // preview and the export at a route with no file on the end of it.+ expect(block.url).toBe("");+ expect(block.fileName).toBe("");+ expect(block.thumbs).toBeUndefined();+ // The shot carries the backdrop it stands in for.+ expect(block.block).toEqual({ label: "your photo", color: "#F26722" });+});++test("a block's colour has to be a colour, and says so rather than falling back", async () => {+ // A silent fallback paints a shot the reference never had while the reply+ // reports the backdrop landed.+ const error = await runAiTool("add_clip", {+ blocks: [{ seconds: 2, label: "your photo", color: "orange-ish" }],+ }).then(() => "", (e: unknown) => (e instanceof Error ? e.message : String(e)));+ expect(error).toContain("hex colour");+ expect(useEditor.getState().assets.some((a) => a.block)).toBe(false);+});++test("shorthand is a colour too", async () => {+ await runAiTool("add_clip", { blocks: [{ seconds: 2, label: "your photo", color: "#f50" }] });+ expect(useEditor.getState().assets.find((a) => a.block)!.block).toEqual({+ label: "your photo",+ color: "#ff5500",+ });+});diff --git a/site/src/cut/lib/compareToSource.test.ts b/site/src/cut/lib/compareToSource.test.tsnew file mode 100644index 00000000..66d1b527--- /dev/null+++ b/site/src/cut/lib/compareToSource.test.ts@@ -0,0 +1,127 @@+import { beforeEach, expect, mock, test } from "bun:test";+import { setRasterFactory, type RasterSurface } from "./raster";+import { useEditor } from "./store";++// A surface that records nothing and draws nothing: this pins the shape of the+// reads and the result, and the pixels themselves are the render path's own+// tests. Every call the draw code makes answers.+const stubContext = new Proxy(+ {+ canvas: null as unknown,+ measureText: () => ({ width: 10, actualBoundingBoxAscent: 8, actualBoundingBoxDescent: 2 }),+ createLinearGradient: () => ({ addColorStop() {} }),+ getImageData: (_x: number, _y: number, w: number, h: number) => ({+ data: new Uint8ClampedArray(Math.max(1, w * h * 4)),+ width: w,+ height: h,+ }),+ } as Record<string, unknown>,+ {+ get: (target, prop) =>+ prop in target ? target[prop as string] : typeof prop === "string" ? () => undefined : undefined,+ set: (target, prop, value) => ((target[prop as string] = value), true),+ }+);++const stubCanvas = (w: number, h: number): RasterSurface =>+ ({ width: Math.max(1, w), height: Math.max(1, h), getContext: () => stubContext }) as unknown as RasterSurface;++setRasterFactory({+ createCanvas: stubCanvas,+ decodeImage: async () => ({ source: {} as CanvasImageSource, width: 90, height: 160 }),+ canvasToBlob: async () => new Blob([new Uint8Array([1, 2, 3])], { type: "image/jpeg" }),+});++// Checking a replica against its source reads two pictures per moment, so what+// it accepts is worth pinning: the moments it is given, the ones it turns away+// before drawing anything, and the shape of the read it makes of the source.++const media = await import("./mediaRead");++/** Every time the source was asked for frames, and at what size. */+const reads: { times: number[]; size: unknown }[] = [];++async function* framesAt(_src: string | Blob, times: number[], size?: unknown) {+ reads.push({ times: [...times], size });+ for (let i = 0; i < times.length; i++) yield { canvas: stubCanvas(90, 160), timestamp: 0, duration: 0 } as never;+}++mock.module("./mediaRead", () => ({ ...media, framesAt }));++const { runAiTool } = await import("./aiTools");++beforeEach(() => {+ reads.length = 0;+ useEditor.setState({+ clips: [{ id: "c1", assetId: "block", track: 0, start: 0, in: 0, out: 10, muted: false }],+ overlays: [],+ transitions: [],+ audioClips: [],+ assets: [+ { id: "ref", fileName: "ref.mp4", name: "Reference", type: "video", duration: 33.17, url: "" },+ { id: "unread", fileName: "unread.mp4", name: "Still importing", type: "video", duration: 0, url: "" },+ { id: "song", fileName: "song.mp3", name: "Song", type: "audio", duration: 33, url: "" },+ {+ id: "block",+ fileName: "",+ name: "Shot 1",+ type: "image",+ duration: 10,+ url: "",+ origin: "block",+ block: { label: "Shot 1", color: "#FF5A00" },+ },+ ],+ });+});++const message = async (p: Promise<unknown>) =>+ p.then(() => "", (e: unknown) => (e instanceof Error ? e.message : String(e)));++test("a moment is required, because there is nothing to compare without one", async () => {+ expect(await message(runAiTool("compare_to_source", { asset_id: "ref", times: [] }))).toContain("Pass times");+});++test("more moments than one call reads are turned away with what to do instead", async () => {+ const error = await message(+ runAiTool("compare_to_source", { asset_id: "ref", times: [1, 2, 3, 4, 5] })+ );+ expect(error).toContain("4 is the most one call reads");+});++test("a sound has no frame to hold up", async () => {+ expect(await message(runAiTool("compare_to_source", { asset_id: "song", times: [1] }))).toContain("listen_audio");+});++test("an unknown source says so before anything is drawn", async () => {+ expect(await message(runAiTool("compare_to_source", { asset_id: "nope", times: [1] }))).toContain("nope");+});++test("a source with no length yet is turned away, because every moment would clamp to 0", async () => {+ expect(await message(runAiTool("compare_to_source", { asset_id: "unread", times: [1, 8] }))).toContain("no length yet");+});++test("a comparison comes back as pictures, one per moment", async () => {+ const out = (await runAiTool("compare_to_source", {+ asset_id: "ref",+ times: [1, { at: 5, source: 20 }],+ })) as { images: string[]; checked: { at: number; source: number }[]; source: { sound: string } };+ expect(out.checked).toEqual([+ { at: 1, source: 1 },+ { at: 5, source: 20 },+ ]);+ expect(out.images).toHaveLength(2);+ for (const sheet of out.images) expect(sheet.startsWith("data:image/")).toBe(true);+ // The record every look returns, so a comparison does not erase what the+ // ear already knows about this source.+ expect(out.source.sound).toBeDefined();+});++test("the source is read in one pass, in play order, at a height that keeps its own shape", async () => {+ await runAiTool("compare_to_source", { asset_id: "ref", times: [{ at: 1, source: 20 }, { at: 5, source: 3 }] });+ expect(reads).toHaveLength(1);+ expect(reads[0].times).toEqual([3, 20]);+ // Both dimensions would squash a widescreen reference into a vertical cut's+ // frame — and mediabunny's sink refuses the pair outright.+ expect(Object.keys(reads[0].size as object)).toEqual(["height"]);+});diff --git a/site/src/cut/lib/devHooks.ts b/site/src/cut/lib/devHooks.tsindex 4983ba12..2149e2be 100644--- a/site/src/cut/lib/devHooks.ts+++ b/site/src/cut/lib/devHooks.ts@@ -7,7 +7,7 @@* the editor root; a no-op in production builds.*/-import { renderProjectToMp4 } from "./exportRender";+import { renderProjectFrame, renderProjectToMp4 } from "./exportRender";import { useExports } from "./exportStore";import { useGenerate } from "./generate";import { useGenScene } from "./genScene";@@ -44,6 +44,10 @@ export function installDevHooks(): void {// The export eval renders a doc through the tab's own pipeline and reads// the bytes back out.renderProjectToMp4,+ // One composited frame, the same one an export writes. The preview canvas+ // cannot be read back — it is a worker's surface — so this is how a check+ // sees what the cut actually draws at a moment.+ renderProjectFrame,projectDuration,// The export eval starts a real export through the store, the way the// dialog does, and watches the dock's feed for the file.diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.tsindex dc6d90fc..1088d8e8 100644--- a/site/src/cut/lib/exportRender.ts+++ b/site/src/cut/lib/exportRender.ts@@ -1483,6 +1483,31 @@ export class FramePainter {* clips, transitions, effects, elements, captions, the project fade. The* canvas comes off the raster seam, so this answers on a page and in a job.*/+/** Several frames of one unchanging document, from one prepared painter.+ * Preparing stamps every title, decodes every backdrop still and may bring up+ * the subject segmenter, so a call that wants four moments pays for that pass+ * once. Each frame is handed to `each` before the next overwrites the canvas.+ */+export async function renderProjectFrames(+ doc: ExportDoc,+ times: number[],+ size: { width: number; height: number },+ resolve: (asset: MediaAsset) => string,+ each: (canvas: RasterSurface, at: number) => Promise<void>+): Promise<void> {+ const canvas = createRasterCanvas(size.width, size.height);+ const painter = new FramePainter(doc, canvas, resolve);+ try {+ await painter.prepare();+ for (const at of times) {+ await painter.drawAt(at);+ await each(canvas, at);+ }+ } finally {+ painter.dispose();+ }+}+export async function renderProjectFrame(doc: ExportDoc,at: number,diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 8069241e..d860c2dc 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -1752,6 +1752,55 @@ export async function composeSheets(return sheets;}+/**+ * One moment of a replica beside the thing it copies: the source's frame on+ * the left, the cut's own frame on the right, both stamped with the second+ * they are read at.+ *+ * The pairing is the point. Two images handed over separately are two things+ * to hold in mind at once; side by side in one picture, a colour that drifted,+ * a card sitting too low or a move that peaks early is simply visible. Nothing+ * here measures the difference — a reference is often a recording of another+ * app, where a pixel comparison reads the chrome around the picture as the+ * picture — so the composite is made for an eye to judge and the judging is+ * left to whoever is looking.+ */+export async function composeComparison(+ pairs: { t: number; sourceAt: number; source: string; cut: string }[]+): Promise<string[]> {+ const out: string[] = [];+ for (const pair of pairs) {+ const [a, b] = await Promise.all([+ decodeRasterImageUrl(pair.source),+ decodeRasterImageUrl(pair.cut),+ ]);+ if (!a || !b) throw new Error("Bad frame image.");+ // Both frames stand at one height, so the eye compares like with like+ // whatever the source's own shape is.+ const h = Math.max(a.height, b.height);+ const aw = Math.round((a.width / a.height) * h);+ const bw = Math.round((b.width / b.height) * h);+ const size = Math.max(13, Math.round(h / 22));+ const bar = size + 10;+ const w = SHEET_GAP * 3 + aw + bw;+ const canvas = createRasterCanvas(w, h + bar + SHEET_GAP * 2);+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) throw new Error("No 2d context.");+ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ ctx.imageSmoothingQuality = "high";+ ctx.drawImage(a.source, SHEET_GAP, SHEET_GAP + bar, aw, h);+ ctx.drawImage(b.source, SHEET_GAP * 2 + aw, SHEET_GAP + bar, bw, h);+ ctx.font = `bold ${size}px ui-monospace, monospace`;+ ctx.textBaseline = "top";+ ctx.fillStyle = "#fff";+ ctx.fillText(`SOURCE ${round2(pair.sourceAt)}s`, SHEET_GAP, SHEET_GAP);+ ctx.fillText(`YOUR CUT ${round2(pair.t)}s`, SHEET_GAP * 2 + aw, SHEET_GAP);+ out.push(await rasterCanvasToDataUrl(canvas, "image/jpeg", 0.82));+ }+ return out;+}+// Filmstrip generation that failed, by asset id — session state, never doc// state. The clip box reads it to swap the loading pulse for a still// placeholder; each new enrich attempt (imports fire one, and every project@@ -1931,6 +1980,9 @@ async function* idleFramesAt(* `src` overrides where the frames are read from — an import still uploading* has the bytes in the browser already, so it need not wait or re-download. */export async function enrichAsset(asset: MediaAsset, src = asset.url) {+ // A block paints itself at whatever size asks, so there is no file to probe+ // and no still to stand in as its strip.+ if (asset.block) return;if (enrichInFlight.has(asset.id)) return;enrichInFlight.add(asset.id);const held = importedBytes.get(asset.id);diff --git a/site/src/cut/lib/pi/mutationLedger.ts b/site/src/cut/lib/pi/mutationLedger.tsindex cdbf1d43..f0da9801 100644--- a/site/src/cut/lib/pi/mutationLedger.ts+++ b/site/src/cut/lib/pi/mutationLedger.ts@@ -12,11 +12,13 @@ const READ_ONLY = new Set(["read_skill","request_tools","capture_frame",+ "compare_to_source","watch_video","note_source","detect_silence","find_filler","detect_beats",+ "find_highlights","listen_audio","measure_level","read_color_stats",diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 48d555aa..8eb3b4ec 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -2605,7 +2605,10 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {addAudioFromAsset: (assetId, start, opts) => {const asset = get().assets.find((a) => a.id === assetId);- if (!asset || asset.type !== "audio") return;+ // A video's own track plays on the soundtrack the same way a sound file+ // does — it is what detaching a clip's audio leaves behind — so a cut+ // laid out as empty shots can still carry the reference's sound.+ if (!asset || asset.type === "image" || assetIsSilent(asset)) return;push();// Within its lane the clip slides to the next free slot at or after the// target so it never lands on top of an existing sound.@@ -4891,7 +4894,7 @@ export const docOverlays = (() => {export function storedAssets(assets: MediaAsset[]): StoredAsset[] {return assets.filter((a) => !tabOnlyUpload(a))- .map(({ id, fileName, name, type, duration, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts, copiedFrom, block, reference }) => ({+ .map(({ id, fileName, name, type, duration, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts, copiedFrom, block }) => ({id,fileName,name,@@ -4909,7 +4912,6 @@ export function storedAssets(assets: MediaAsset[]): StoredAsset[] {...(sceneCuts !== undefined ? { sceneCuts } : {}),...(copiedFrom !== undefined ? { copiedFrom } : {}),...(block !== undefined ? { block } : {}),- ...(reference !== undefined ? { reference } : {}),}));}diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 9142dcee..8fb8364a 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -256,11 +256,6 @@ export interface StoredAsset {* blockSource.ts. Replacing it with real footage is an ordinary item* replace; the clip keeps its place and its length. */block?: { label: string; color?: string };- /** The source a blocked-out cut was copied from. Set when a blockout- * names it, and it keeps the assistant's own tools from putting- * the thing being copied into the copy: the blocks hold those slots until- * the person's footage arrives. The person's own drag is never refused. */- reference?: true;}/** A folder in the Media panel's Project Files view — a flat, project-local@@ -1690,9 +1685,16 @@ export interface ProjectSummary {* cloud project's bytes at the local engine, or the reverse, and the asset* would carry that wrong address for as long as it lives. */export const mediaUrl = (projectId: string, fileName: string, backend?: CutBackend) =>- (backend ?? getBackend()).url(- `/api/cut/projects/${projectId}/media/${encodeURIComponent(fileName)}`- );+ // A source that owns no file — a blocked-out shot draws itself — has no+ // address, and minting one aims every reader at a route with no file on the+ // end of it. The empty string is what "nothing to fetch" looks like+ // everywhere else here, so the guard belongs at the one place addresses are+ // made rather than at each of the callers.+ fileName+ ? (backend ?? getBackend()).url(+ `/api/cut/projects/${projectId}/media/${encodeURIComponent(fileName)}`+ )+ : "";/** A filename-safe slug from a display name: lowercased, every run of* non-alphanumerics collapsed to a hyphen, trimmed and capped, with `fallback`diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 81128e73..6e55965e 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -317,18 +317,20 @@ Time math (get this right):Cutting speech well: pace is part of the message, and it is set in one place — refine_speech_cuts' \`pace\`. "Fast paced", "punchy", "tight" means pace: fast there; a calm piece means relaxed. Placing your own edges closer to the words is not a faster cut, it is a clipped one: a word's tail runs past its cue, the ear hears the truncation, and no amount of tightening reads as energy. So cut loose — up to a second of spare air on each side — and let the refine step take it back to the beat the pace asks for. Shorten a long pause to that beat rather than deleting it; speech butted directly together reads as rushed however fast the piece is meant to be. Prefer split_at + delete_item, then place_clip to close the gap (a beat of black may be wanted — ask the cut, not the tool); trim_clip only tightens a clip's edges.`,"replicating-a-video": `# Replicating a video you can watch-Someone points at a video — a file they imported, a link you brought in, a clip on their timeline — and asks for one like it. Build its skeleton out of this editor's own parts and leave the footage for them to fill in.+Someone points at a video — a file they imported, a link you brought in, a clip on their timeline — and asks for one like it. Everything on the screen gets rebuilt out of this editor's own parts: every card of type, every shape, every colour, every move, at the time it happens. The footage inside the shots is the one thing you cannot rebuild, because it is the person's to bring — so each shot stands as a block in the colour the reference has behind it, with nothing written on it.**Clipping a long source.** A talk, an interview or a stream is mostly material that only makes sense in place. find_highlights ranks its stretches from the transcript, so an hour is read for its handful of moments without watching all of it; watch_video the spans it returns before committing, since the ranking never saw the picture. add_clip \`spans\` lays a pick down — several stretches of one source as one run of clips, the material between them left out — and a two-span result is one clip whose halves were never next to each other.**Watch the whole thing first.** Every decision below comes off the record, so the record has to be complete: watch from 0 and keep going until \`unwatchedSeconds\` is 0, writing each pass into note_source before the next one. Anything over a couple of minutes gets a coarse pass end to end first (\`interval_seconds\` 15-30) to learn its shape, then a dense pass (0.5) over the stretches that carry text or cut fast. Read every card word for word — its text, its face, where it sits in the frame, when it comes and goes — because a turn later the sheets are gone and the notes are all you have. Reading type is what \`detail\` is for: the dense pass over a stretch carrying words runs at \`detail\` read, and a face or treatment you are about to name runs at original, where the frame arrives at the source's own resolution. A scan cell is a quarter of the frame's width; a small caption in one is a smudge, and a smudge read as a word is how a card ends up saying something the video never said. When the cards ARE the narration — a caption track of what the speaker is saying — the transcript already holds every word, and the close passes are for how they are set: face, weight, size, colour, placement, how many words ride a card, how it enters and leaves. Read a few of those at original and take the rest from the transcript.-**Block out the cuts.** \`sceneChanges\` are the cut times: shot 1 runs from 0 to the first, shot n from one to the next, the last to the end. add_clip with \`blocks\` lays the whole skeleton down in one call — one block per shot on track 0, each the length that shot runs, labelled with what the person has to supply ("wide of the kitchen, hands only"). Name the source in \`reference_asset_id\`. They fill a block by dropping their own footage on it — it takes the block's place and its length — or by asking you to (replace_item), so everything you build on top keeps its timing. The reference itself stays off the timeline: it is what the cut is copied from, and the blocks hold its shots' slots until the person's own footage arrives.+**Block out the cuts.** \`sceneChanges\` are the cut times: shot 1 runs from 0 to the first, shot n from one to the next, the last to the end. add_clip with \`blocks\` lays the whole skeleton down in one call — one block per shot on track 0, each the length that shot runs, \`color\` set to what the reference has behind that shot and \`label\` naming what the person drops there. The label rides the timeline chip and the editor state; the frame itself shows the colour alone, so a shot never plays a sentence describing itself. A block is filled by dropping footage on it — it takes the block's place and its length — or with replace_item, so everything you build on top keeps its timing. Cuts timed to a reference are timed to what it sounds like, so that sound belongs on the soundtrack under them: detach_audio with the reference's \`assetId\` puts its whole track there and places none of its picture. When the ask is the reference's own picture playing, add_clip \`spans\` lays its shots down instead, one span per shot at those same times.**Rebuild the text as elements.** One add_title per card — the words exactly as they read, the face from the graphics skill's font ids, size in px at 1080 wide, and x/y as the fraction of the frame it sits at (a lower-third card is around y 0.75, a centered statement 0.5). A run of lines timed one after another is add_text_sequence in one call. Match the case the reference uses; match its weight and its color against the frame behind it.**Then the motion.** set_overlay_keyframes gives each card its own pose track — where it sits, at what scale, at what second — which is how the timing lands on the reference's own frames. set_overlay_animation composes on top for the entrance, the exit, a loop, and what a line does while it holds; 0.3-0.6s reads as an entrance, and a per-letter style is what makes a card read as typed. add_shape is the rest of the graphics: bars, cards, rules, a block of color behind a line.-**Say what is skeleton.** Close by telling them what to drop in: how many shots, how long each one runs, and that the titles and timing are already built around them.`,+**Look at what you made.** Watching told you what the reference does; it does not tell you whether what you made does it too, and a build that reads right from your own notes is still a guess until you see it. compare_to_source puts the source's frame and yours side by side at the same moment, a few at a time. Run it as you build, not once at the end: the first few shots, then each stretch as you finish it — an error in the first card is in every card after it. Spread the moments over what you laid down, including the middle of a move, and read each pair for colour, the words and their face, where a thing sits, its size, and how far along a move is. A title the same colour as the block behind it, or a shape covering the thing it was meant to sit beside, reads as correct in the document and is only visible here. Fix what differs, check the moments you changed, and keep going until a pass turns up nothing.++**Say what plays.** Close by naming what fills the shots, and what you checked. A shell gets what to drop in: how many shots, how long each one runs, and that the titles and timing are built around them.`,"transitions-and-fades": `# Transitions, animations, looks & fadesRoute the ask to the right feature:@@ -581,13 +583,13 @@ Rules:- Styling is part of the ask, never a bonus. Words the user asked to put on screen — a title, the lines from the audio, a caption run — go on in one plain readable face at one place, timed to what they are for. Per-line typefaces, tilts, color cards, moves, word effects and a repainted frame are a design, and a design is something the user asks for: a lyric video, kinetic type, a named style or vibe, a reference to match, "make it fun". Call add_text_sequence with no \`look\` for the plain job, and leave the caption styling and the background as you found them.- A skill attached to the message (<skill_relevance>) is the reference for its area: read it before touching that area's settings. It never changes which tool the ask maps to — the tool descriptions decide that ("a better version" is a render, whatever skill rode along). list_skills / read_skill cover an area the attachment left out.- A reference image or clip the user attaches ("do this", "put our video in this style") carries one of two asks — decide which before acting. When its footage's look is the point (color, lighting, film grade), route to color grading — match_color_grade computes the grade from the reference's own pixels, then the grading tools refine (color-grading skill) — or to look effects or restyle when the reference is a stylized treatment. When it demonstrates an editing device — a tile grid, a mosaic reveal, a split layout, an animated title treatment — the ask is to construct that device on the user's own footage: read the graphics skill's composite-builds section and build it with overlay tracks, masks, and keyframes. Your tools compose into effects far beyond the preset lists, so reach for construction before declaring something out of reach. Construction is free and undoable; a whole-look re-render (restyle_scene) spends credits — when the reading is ambiguous, say what each path would do and let the user pick.-- "Make one like this" about a video you can watch — a file they imported, a link you brought in, a clip on the timeline — is watch it all the way through, block its cuts out with add_clip's \`blocks\`, and rebuild its titles, graphics and motion with the element tools; their own footage goes into the blocks afterwards. The replicating-a-video skill has the flow.+- A video held up as a reference — a file they imported, a link you brought in, a clip on the timeline — is watched all the way through before anything is copied from it, then rebuilt out of this editor's parts: everything on the screen, every card of type, every shape, every colour and every move, at the time it happens. The footage inside the shots is the one thing you cannot rebuild — add_clip \`blocks\` holds each shot's place in the colour behind it, for the person to fill — and when they want the reference's own picture playing, add_clip \`spans\` lays its shots down instead. What you built is a guess until you look at it beside the thing it copies: compare_to_source holds the source's frame against yours at the same moment, and what differs gets fixed and checked again. The replicating-a-video skill has the flow.- A Donkey Cut project link or share link the user gives you is a document: read it with read_project (the document is the edit — never watch a reference to learn what its document already states), decide which of this project's sources plays each of its parts from the reference's observed notes and transcripts (a reference look with watch_video's project_link where those leave it dark), then call replicate_project once — the whole edit, or only the items they asked for: a title, one clip's treatment, the music, the caption look — and tune from there. copy_project_media brings files over on their own. The replicating-a-project skill has the flow.- Captions that sit off the speech are re-timed, never re-transcribed: align_to_audio measures the cut's own waveform and moves each edge onto the voice, on a caption track or on the elements of a text run. Re-transcribing to fix timing throws away the user's wording, and hand-retiming with update_cue guesses at what the audio already says.- 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, sources you have watched or listened to carry their own transcript (media entries marked speech: "transcribed"; get_state includes the timed segments), 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 / generate_music 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. generate_music makes a music track — a vocal-free background bed by default ("add music to this video"), or a full sung song (instrumental:false); it's sung music, so a spoken narration is voiceover_generate. 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. When it lands on a card, close with a statement of where it is ("The voiceover is on the card — drag it in or tell me to place it."). 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 storyboard — the user reviews the frames (regenerate_shot redraws any before approval, no credits), then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after). Close a plan message with the approval path as a statement: "Approve it — say so or hit Approve on the card — and I'll render the shots." Tweaks before approval are theirs to name.-- 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, and write each look down with note_source — sheets are conversation-local, notes stay on the source; listen_audio plays a source's audio — an audio asset or a video/clip's own track, one stretch per call, with \`coveredTo\` and \`unheardSeconds\` saying how far it reached and what nobody has played (an ask about how a whole source sounds listens on from \`unheardFrom\` until that is 0); detect_silence finds dead air; find_highlights ranks the stretches of a long source worth clipping, from what is said over them; detect_beats reads the music's beat grid (persisted on the asset, drawn as dots on its clips, snapped to by every drag) for cutting to the music; capture_frame shows one rendered frame, at the time you pass or the playhead. The watching-and-cutting skill has the flow.+- 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, and write each look down with note_source — sheets are conversation-local, notes stay on the source; listen_audio plays a source's audio — an audio asset or a video/clip's own track, one stretch per call, with \`coveredTo\` and \`unheardSeconds\` saying how far it reached and what nobody has played (an ask about how a whole source sounds listens on from \`unheardFrom\` until that is 0); detect_silence finds dead air; find_highlights ranks the stretches of a long source worth clipping, from what is said over them; detect_beats reads the music's beat grid (persisted on the asset, drawn as dots on its clips, snapped to by every drag) for cutting to the music; capture_frame shows one rendered frame, at the time you pass or the playhead; compare_to_source puts that frame beside the source's own at the same moment, which is how work copied from something is checked against it. The watching-and-cutting skill has the flow.- End on a statement. The final sentence of every reply states what changed, what failed, or the one suggestion you're making; "let me know if", "would you like", "do you want me to", and every other trailing offer or question are banned closers. The only question that may end a reply is the single clarifying one a genuinely ambiguous or blocked ask earns.`;}@@ -623,7 +625,7 @@ export const AI_SKILL_BLURBS: Record<string, string> = {"media-and-library": "Project media versus the Media panel, filing assets, the library, organizing and templates.","replicating-a-project": "Reading another Donkey Cut project or share link as a document and bringing its edit or items over.","replicating-a-video":- "Rebuilding a video you can watch: seeing all of it, blocking its cuts out as empty shots, and remaking its titles, graphics and motion.",+ "Rebuilding a video you can watch: seeing all of it, blocking its cuts out as colour slots, remaking its titles, graphics and motion, and checking the result against it.","publish-and-export": "Publish fields for the platforms, and every export preset and axis.",};diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.tsindex f714c722..fa3556f2 100644--- a/site/src/cut/server/ai/headlessTools.ts+++ b/site/src/cut/server/ai/headlessTools.ts@@ -34,6 +34,7 @@ const PAGE_MEDIA_TOOLS: ReadonlySet<string> = new Set(["refine_speech_cuts","freeze_frame","capture_frame",+ "compare_to_source","render_preview","create_sticker","subtitles_generate",