Skip to content

Open source CapCut alternative.

TypeScript

feat(site): teach the cut assistant to watch footage and find silence [rebuild]

David Le1baf73a53f37
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index bfbabe31..4de61b62 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -38,14 +38,15 @@ Every knowledge surface is defined once — the catalog file ships in the engine
| Surface | Size today | When it enters context |
| --- | --- | --- |
| System prompt | ~3.1K chars (~750 tokens) | Claude: replaces the Agent SDK default. Codex: prepended to the first turn (a resumed session already has it). Gemini: the instructions field, every round. |
-| Tool catalog (49 tools) | ~30K chars (~7.5K tokens) | Claude/Codex: the MCP tool listing. Gemini: function declarations on each request. |
-| Skills library (7 docs) | ~14.5K chars (~3.6K tokens) total | On demand only, via the list-skills and read-skill tools. |
+| Tool catalog (51 tools) | ~32K chars (~8K tokens) | Claude/Codex: the MCP tool listing. Gemini: function declarations on each request. |
+| Skills library (8 docs) | ~16.5K chars (~4K tokens) total | On demand only, via the list-skills and read-skill tools. |
| Editor snapshot | Grows with the project; media list and subtitle cues capped at 60 each | Attached to the newest user message as `<editor_state>`, rebuilt fresh every turn. |
| Attachments | Metadata JSON per asset | `<attached_assets>` on the message that carried them; on the Gemini path the newest message also carries the actual payloads (frames, images, text contents). |
| Full state | Uncapped | The get-state tool — the model calls it when the snapshot is stale or truncated. |
-| The rendered frame | One 640px JPEG | The capture-frame tool, for visual judgment. |
+| The rendered frame | One 640px JPEG | The capture-frame tool, for visual judgment at the playhead. |
+| The footage itself | Up to four 3×3 contact sheets per call | The watch-video tool: the engine samples a source at scene changes plus a steady floor (ffmpeg), the page stamps each cell with its source time, and the result carries the scene-change times. Detect-silence reports dead air the same way, numbers only. |
-The system prompt is deliberately small: the voice, the deliverable rule (below), id discipline, the undo-versus-credits asymmetry, and pointers into the skills. The skills carry the deep per-area documentation — editor overview, timeline editing, transitions, titles, audio and subtitles, stock and generation, publish and export — so the always-on cost stays near 8K tokens and detail is pulled only when the model works in that area.
+The system prompt is deliberately small: the voice, the deliverable rule (below), id discipline, the undo-versus-credits asymmetry, and pointers into the skills. The skills carry the deep per-area documentation — editor overview, timeline editing, watching and cutting by content, transitions, titles, audio and subtitles, stock and generation, publish and export — so the always-on cost stays near 8.5K tokens and detail is pulled only when the model works in that area.
The snapshot is a compact JSON picture of everything user-visible: project meta, playhead, selection, every media asset with its origin tag, the video track with gaps and transitions, overlay video, soundtrack, titles, subtitle tracks with the first 60 cues, publish metadata, and view state. Numbers are rounded to two decimals and empty fields are omitted. When a list is truncated the snapshot says so, which is the model's cue to call get-state.
@@ -66,6 +67,7 @@ Tool calls execute in the open tab against the same store the user is editing
- **Readable failure, then retry.** Tools validate and clamp their inputs and throw human-readable errors ("No clip with that id — call get_state for current ids"), which return to the model as tool errors it can recover from.
- **One undo step per turn.** History batches while the assistant is busy, so ⌘Z reverts the whole turn rather than one call at a time.
- **Small results.** Tools return ids and rounded numbers, plus a short note when behavior surprised ("that spot was taken — slid right").
+- **Frames become images.** A tool result's `image`/`images` data URLs leave the JSON and reach the model as real images on every path — the engine bridge emits MCP image blocks after the data text, and the Gemini loop rides the first on the function response and the rest as image parts. Watching happens in whatever model the user is chatting with; there is no side model.
- **Async when rendering.** Video generation outruns the two-minute tool window, so those tools start the job and return immediately; the clip files under the chat that asked — the owning thread is captured at call time — and lands on the timeline only when the user asked for that.
- **Chat owns what it makes.** Media created by chat tools is tagged with its thread and previews on a card in the conversation. Placing it on the timeline or filing it into Media or the Library transfers ownership; deleting the thread deletes whatever it still owns.
- **Two tools stay server-side.** The skill list and skill reads are answered by the engine directly — no browser hop.
@@ -86,6 +88,7 @@ A thread saves one session slot per provider, so switching models mid-thread kee
| Provider turns per request (Claude) | 30 |
| Tool rounds per turn (Gemini) | 16 |
| Browser tool execution | 120s |
+| One watch-video call | 600s of source, 4 sheets (36 frames); the result says where coverage stopped |
| Snapshot caps | 60 media items, 60 cues |
| Saved threads per project | 30 |
| CLI availability probe cache | 60s |
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index f598cd49..0dec4446 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -93,6 +93,30 @@ function readThreads(): ChatThread[] {
}
}
+/** Persisted copies drop frame payloads (data URLs) from tool outputs — one
+ * watch_video result carries ~1MB of contact sheets and localStorage holds a
+ * few MB per origin. The live thread keeps its images; replayed turns only
+ * ever reuse text parts, so nothing downstream misses them. */
+function slimForStorage(list: ChatThread[]): ChatThread[] {
+ const bulky = (v: unknown) => typeof v === "string" && v.startsWith("data:image/");
+ return list.map((t) => ({
+ ...t,
+ messages: t.messages.map((m) => ({
+ ...m,
+ parts: m.parts.map((p) => {
+ const out = (p as { output?: unknown }).output;
+ if (!out || typeof out !== "object") return p;
+ const o = out as Record<string, unknown>;
+ if (!bulky(o.image) && !(Array.isArray(o.images) && o.images.some(bulky))) return p;
+ return {
+ ...p,
+ output: { ...o, image: undefined, images: undefined, imagesOmitted: true },
+ } as typeof p;
+ }),
+ })),
+ }));
+}
+
function writeThreads(list: ChatThread[]) {
// Cap history, but retain any overflow thread that still owns chat media —
// deleting media is an explicit act (deleting its thread), never a side
@@ -102,7 +126,7 @@ function writeThreads(list: ChatThread[]) {
...list.slice(THREAD_LIMIT).filter((t) => threadOwnsAssets(t.id)),
];
try {
- localStorage.setItem(threadsKey(), JSON.stringify(kept));
+ localStorage.setItem(threadsKey(), JSON.stringify(slimForStorage(kept)));
} catch {
// Storage full/blocked — history just won't persist.
}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index f2b79fe2..4d011a85 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -68,6 +68,166 @@ export async function runAiTool(
return { image: scaled.toDataURL("image/jpeg", 0.75), note: "Video frame only; titles and captions overlay this in the UI." };
}
+ case "watch_video": {
+ const projectId = s.projectId;
+ if (!projectId) throw new ToolError("No project open.");
+ const { asset, clip } = resolveWatchTarget(s, input);
+ if (asset.type === "audio")
+ throw new ToolError(`"${asset.name}" is audio — detect_silence and subtitles_generate are the listening tools.`);
+ interface WatchBody {
+ sheets: { image: string; frames: { t: number; scene?: number }[] }[];
+ layout: { grid: number; margin: number; padding: number };
+ sceneChanges: number[];
+ coveredTo: number;
+ truncated: boolean;
+ error?: string;
+ }
+ // A still is one sheet with no time axis.
+ if (asset.type === "image") {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/watch`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ file: asset.fileName, still: true }),
+ });
+ const body = await apiJson<WatchBody>(res);
+ if (!res.ok) throw new ToolError(body.error ?? "Could not read the image.");
+ return {
+ images: body.sheets.map((sh) => sh.image),
+ source: { assetId: asset.id, name: asset.name },
+ note: "A still image — one frame, no time axis.",
+ };
+ }
+ const speed = clip?.speed && clip.speed > 0 ? clip.speed : 1;
+ const dur = asset.duration > 0 ? asset.duration : Infinity;
+ const from = clamp(isNum(input.from) ? input.from : clip ? clip.in : 0, 0, dur);
+ // An unknown duration leaves `to` for the engine to probe.
+ const to = isNum(input.to)
+ ? clamp(input.to, 0, dur)
+ : clip
+ ? clip.out
+ : Number.isFinite(dur)
+ ? dur
+ : undefined;
+ if (to !== undefined && to <= from)
+ throw new ToolError("from/to describe an empty range of the source.");
+ const res = await apiFetch(`/api/cut/projects/${projectId}/watch`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ file: asset.fileName,
+ from,
+ ...(to !== undefined ? { to } : {}),
+ ...(isNum(input.interval_seconds) ? { interval: input.interval_seconds } : {}),
+ }),
+ });
+ const body = await apiJson<WatchBody>(res);
+ if (!res.ok) throw new ToolError(body.error ?? "Could not watch the video.");
+ // The engine's ffmpeg has no text renderer; the cells get their source-
+ // time stamps here on a canvas. A sheet that fails to stamp rides plain —
+ // sheetFrames stays the authority either way.
+ let stamped = true;
+ const images = await Promise.all(
+ body.sheets.map((sh) =>
+ stampSheet(sh.image, sh.frames.map((f) => f.t), body.layout).catch(() => {
+ stamped = false;
+ return sh.image;
+ })
+ )
+ );
+ return {
+ images,
+ sheetFrames: body.sheets.map((sh) => sh.frames.map((f) => round2(f.t))),
+ sceneChanges: body.sceneChanges.map(round2),
+ coveredTo: round2(body.coveredTo),
+ truncated: body.truncated,
+ source: { assetId: asset.id, name: asset.name, duration: round2(asset.duration) },
+ ...(clip
+ ? {
+ clip: {
+ id: clip.id,
+ timelineStart: round2(clip.start),
+ in: round2(clip.in),
+ out: round2(clip.out),
+ speed: round2(speed),
+ note: `timeline_t = ${round2(clip.start)} + (source_t - ${round2(clip.in)}) / ${round2(speed)}, for source_t in [${round2(clip.in)}, ${round2(clip.out)}]`,
+ },
+ }
+ : {}),
+ note:
+ "Cells read left→right then top→bottom; each stamp is SOURCE seconds." +
+ (body.truncated
+ ? ` Coverage stopped at ${round2(body.coveredTo)}s — call again with from=${round2(body.coveredTo)} to continue.`
+ : "") +
+ (stamped ? "" : " (Stamps unavailable — sheetFrames lists each cell's time.)"),
+ };
+ }
+
+ case "detect_silence": {
+ const projectId = s.projectId;
+ if (!projectId) throw new ToolError("No project open.");
+ const { asset, clip } = resolveWatchTarget(s, input);
+ if (asset.type === "image") throw new ToolError(`"${asset.name}" is an image — it has no audio.`);
+ const speed = clip?.speed && clip.speed > 0 ? clip.speed : 1;
+ const dur = asset.duration > 0 ? asset.duration : Infinity;
+ const from = clamp(isNum(input.from) ? input.from : clip ? clip.in : 0, 0, dur);
+ // An unknown duration leaves `to` for the engine to probe.
+ const to = isNum(input.to)
+ ? clamp(input.to, 0, dur)
+ : clip
+ ? clip.out
+ : Number.isFinite(dur)
+ ? dur
+ : undefined;
+ if (to !== undefined && to <= from)
+ throw new ToolError("from/to describe an empty range of the source.");
+ const res = await apiFetch(`/api/cut/projects/${projectId}/silence`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ file: asset.fileName,
+ from,
+ ...(to !== undefined ? { to } : {}),
+ ...(isNum(input.threshold_db) ? { threshold_db: input.threshold_db } : {}),
+ ...(isNum(input.min_silence) ? { min_silence: input.min_silence } : {}),
+ }),
+ });
+ interface SilenceBody {
+ silences: { start: number; end: number; duration: number }[];
+ error?: string;
+ }
+ const body = await apiJson<SilenceBody>(res);
+ if (!res.ok) throw new ToolError(body.error ?? "Could not scan for silence.");
+ // Pre-map each silence's overlap with the clip's trimmed range onto the
+ // timeline so the model cuts on ready numbers.
+ const toTimeline = (t: number) =>
+ round2(clip!.start + (clamp(t, clip!.in, clip!.out) - clip!.in) / speed);
+ return {
+ silences: body.silences.map((x) => ({
+ start: round2(x.start),
+ end: round2(x.end),
+ duration: round2(x.duration),
+ ...(clip && x.end > clip.in && x.start < clip.out
+ ? { timeline: { start: toTimeline(x.start), end: toTimeline(x.end) } }
+ : {}),
+ })),
+ source: { assetId: asset.id, name: asset.name, duration: round2(asset.duration) },
+ ...(clip
+ ? {
+ clip: {
+ id: clip.id,
+ timelineStart: round2(clip.start),
+ in: round2(clip.in),
+ out: round2(clip.out),
+ speed: round2(speed),
+ },
+ }
+ : {}),
+ ...(body.silences.length === 0
+ ? { note: "No silence at these settings — a higher threshold_db or shorter min_silence hears more." }
+ : {}),
+ };
+ }
+
case "seek": {
if (!isNum(input.t)) throw new ToolError("t (seconds) is required.");
s.seek(input.t);
@@ -926,6 +1086,71 @@ async function synthesizeVoiceover(
};
}
+/** Draw each cell's source-time stamp onto a contact sheet. The bundled
+ * ffmpeg ships without a text renderer (LGPL build, no freetype), so the
+ * stamps land here, where a canvas always can. */
+async function stampSheet(
+ image: string,
+ times: number[],
+ layout: { grid: number; margin: number; padding: number }
+): Promise<string> {
+ const img = new Image();
+ await new Promise<void>((resolve, reject) => {
+ img.onload = () => resolve();
+ img.onerror = () => reject(new Error("Bad sheet image."));
+ img.src = image;
+ });
+ const canvas = document.createElement("canvas");
+ canvas.width = img.naturalWidth;
+ canvas.height = img.naturalHeight;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("No 2d context.");
+ ctx.drawImage(img, 0, 0);
+ const { grid, margin, padding } = layout;
+ const cellW = (canvas.width - 2 * margin - (grid - 1) * padding) / grid;
+ const cellH = (canvas.height - 2 * margin - (grid - 1) * padding) / grid;
+ const size = Math.max(13, Math.round(cellH / 12));
+ ctx.font = `bold ${size}px ui-monospace, monospace`;
+ ctx.textBaseline = "bottom";
+ times.forEach((t, i) => {
+ const x = margin + (i % grid) * (cellW + padding);
+ const y = margin + Math.floor(i / grid) * (cellH + padding);
+ const label = `${round2(t)}s`;
+ const w = ctx.measureText(label).width;
+ ctx.fillStyle = "rgba(0,0,0,0.6)";
+ ctx.fillRect(x + 4, y + cellH - size - 10, w + 10, size + 8);
+ ctx.fillStyle = "#fff";
+ ctx.fillText(label, x + 9, y + cellH - 6);
+ });
+ return canvas.toDataURL("image/jpeg", 0.8);
+}
+
+/** Resolve a watch/listen target: a timeline clip (its source plus trim and
+ * placement) or a bare project asset. */
+function resolveWatchTarget(
+ s: ReturnType<typeof useEditor.getState>,
+ input: Record<string, unknown>
+): {
+ asset: MediaAsset;
+ clip: { id: string; start: number; in: number; out: number; speed?: number } | null;
+} {
+ if (input.clip_id !== undefined && input.clip_id !== null) {
+ const id = String(input.clip_id);
+ const clip =
+ s.clips.find((c) => c.id === id) ??
+ s.overlayClips.find((c) => c.id === id) ??
+ s.audioClips.find((c) => c.id === id);
+ if (!clip) throw new ToolError(`No clip with id ${id}. Call get_state for current ids.`);
+ const asset = s.assets.find((a) => a.id === clip.assetId);
+ if (!asset) throw new ToolError("That clip's media asset is missing.");
+ return { asset, clip };
+ }
+ if (input.asset_id !== undefined && input.asset_id !== null) {
+ return { asset: requireItem(s.assets, input.asset_id, "project asset"), clip: null };
+ }
+ throw new ToolError("Pass clip_id or asset_id — see videoTrack and media in the editor state.");
+}
+
function requireItem<T extends { id: string }>(pool: T[], id: unknown, label: string): T {
const item = pool.find((x) => x.id === String(id ?? ""));
if (!item) throw new ToolError(`No ${label} with id ${String(id)}. Call get_state for current ids.`);
diff --git a/site/src/cut/lib/geminiChat.ts b/site/src/cut/lib/geminiChat.ts
index 50349583..f1523543 100644
--- a/site/src/cut/lib/geminiChat.ts
+++ b/site/src/cut/lib/geminiChat.ts
@@ -101,30 +101,40 @@ async function execTool(name: string, args: Record<string, unknown>): Promise<un
return runAiTool(name, args);
}
-/** A tool result as a function_response content part. The id pairs it with its
+/** A tool result as content parts. The id pairs the function_response with its
* originating call so Gemini matches responses to calls across parallel calls.
- * Screenshots leave the JSON (a data URL inlined as text would blow the token
- * budget) and ride along as an image part instead, so the model sees the frame. */
-function functionResponsePart(name: string, output: unknown, id: string): Item {
- if (output && typeof output === "object" && "image" in output) {
- const { image, ...rest } = output as { image?: unknown };
- const match = typeof image === "string" ? /^data:([^;,]+);base64,(.+)$/.exec(image) : null;
- if (match) {
- return {
- type: "function_response",
- id,
- name,
- response: rest,
- mimeType: match[1],
- screenshotBase64: match[2],
- };
+ * Frames leave the JSON (a data URL inlined as text would blow the token
+ * budget) and ride along as image parts instead: the first on the response
+ * itself, the rest (contact sheets) as input_image parts in the same turn. */
+function functionResponseParts(name: string, output: unknown, id: string): Item[] {
+ if (output && typeof output === "object" && ("image" in output || "images" in output)) {
+ const { image, images, ...rest } = output as { image?: unknown; images?: unknown };
+ const parsed = [
+ ...(typeof image === "string" ? [image] : []),
+ ...(Array.isArray(images) ? images.filter((u): u is string => typeof u === "string") : []),
+ ]
+ .map((u) => /^data:([^;,]+);base64,(.+)$/.exec(u))
+ .filter((m): m is RegExpExecArray => m !== null);
+ if (parsed.length > 0) {
+ const [first, ...more] = parsed;
+ return [
+ {
+ type: "function_response",
+ id,
+ name,
+ response: rest,
+ mimeType: first[1],
+ screenshotBase64: first[2],
+ },
+ ...more.map((m) => ({ type: "input_image", dataBase64: m[2], mimeType: m[1] })),
+ ];
}
}
const response =
output && typeof output === "object" && !Array.isArray(output)
? output
: { result: output ?? null };
- return { type: "function_response", id, name, response };
+ return [{ type: "function_response", id, name, response }];
}
interface ResponseBody {
@@ -212,11 +222,11 @@ export function streamGeminiChat({
try {
const output = await execTool(name, args);
emit({ type: "tool-output-available", toolCallId, output: output ?? null });
- responseParts.push(functionResponsePart(name, output, toolCallId));
+ responseParts.push(...functionResponseParts(name, output, toolCallId));
} catch (err) {
const errorText = err instanceof Error ? err.message : String(err);
emit({ type: "tool-output-error", toolCallId, errorText });
- responseParts.push(functionResponsePart(name, { error: errorText }, toolCallId));
+ responseParts.push(...functionResponseParts(name, { error: errorText }, toolCallId));
}
}
input.push({ role: "assistant", content: assistantParts });
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 48d41e3c..c500ec97 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -39,9 +39,34 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "capture_frame",
description:
- "Capture what the video preview currently shows (at the playhead) as an image, so you can see the frame, titles, and captions exactly as rendered.",
+ "Capture the composited video frame the preview shows at the playhead as an image. Titles and captions are drawn over the canvas in the UI, so they don't appear here — this checks the footage, not the text.",
inputSchema: obj({}),
},
+ {
+ name: "watch_video",
+ description:
+ "Watch a video source with your own eyes: samples its frames at scene changes plus a steady floor into timestamped contact-sheet images, and returns the detected scene-change times (natural cut candidates). Pass clip_id to watch a timeline clip's source (the result includes that clip's source↔timeline time math) or asset_id for any project video or image. The stamp burned into each cell is SOURCE seconds — what trim_clip's in/out use — not timeline seconds. Coverage is capped per call: survey the whole range first, then call again with a narrow from/to and a small interval_seconds where the cut needs care; the result says where coverage stopped. Read the watching-and-cutting skill before editing footage by content.",
+ inputSchema: obj({
+ clip_id: str("Video clip id, track 0 or overlay (defaults from/to to its trimmed in/out)"),
+ asset_id: str("Project asset id (video or image) — watch the source itself"),
+ from: num("Source start s (default: the clip's in, else 0)"),
+ to: num("Source end s (default: the clip's out, else the source's end; spans at most 600s per call)"),
+ interval_seconds: num("Target seconds between sampled frames, 0.5–30 (default spreads ~32 frames across the range)"),
+ }),
+ },
+ {
+ name: "detect_silence",
+ description:
+ "Find silent stretches in a source's audio — dead air, long pauses, gaps between takes. Returns [{start,end,duration}] in SOURCE seconds, plus each one's timeline times when clip_id is passed. Cheap and image-free; pair it with the transcript's cue timings to find filler, then cut with split_at / trim_clip / delete_item.",
+ inputSchema: obj({
+ clip_id: str("Clip id — video, overlay, or soundtrack; scopes to its trimmed range and maps results to timeline seconds"),
+ asset_id: str("Project asset id (video or audio)"),
+ from: num("Source start s (default: the clip's in, else 0)"),
+ to: num("Source end s (default: the clip's out, else the source's end)"),
+ threshold_db: num("Loudness below this counts as silence, dBFS (default -30)"),
+ min_silence: num("Shortest silent stretch to report, seconds (default 0.35)"),
+ }),
+ },
{
name: "seek",
description: "Move the playhead to a time (seconds, clamped to the cut).",
@@ -501,6 +526,29 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim
- The user can copy/paste any selected segment (video, overlay video, audio, title) with ⌘C/⌘V; pastes aim for the playhead and slide right to free space.
- Zoom: set_view pxPerSec (12..800) or fit. The timeline panel height: set_view timelineH (170..600).`,
+ "watching-and-cutting": `# Watching footage & cutting by content
+When a request depends on what the footage actually contains — "cut the dead air", "clip the best moment", "remove the boring part", "split where the scene changes" — watch it first. Never guess at content you haven't seen.
+
+Your eyes and ears:
+- watch_video(clip_id | asset_id, from?, to?, interval_seconds?): samples the SOURCE at scene changes plus a steady floor and returns timestamped contact sheets — cells read left→right, top→bottom, and each burned stamp is source seconds — plus sceneChanges, the natural cut candidates. Coverage is capped per call: survey the whole range at the default interval first, then zoom into the moments that matter with a narrow from/to and interval_seconds 0.5–1. When truncated, continue from coveredTo.
+- detect_silence(clip_id | asset_id, threshold_db?, min_silence?): silent stretches in source seconds; with clip_id each also carries its timeline times.
+- capture_frame: one composited frame at the playhead — for checking the final look, not for surveying footage.
+
+The flow for "edit this for me":
+1. get_state — every clip, its trim (in/out), speed, gaps, and the other tracks.
+2. Speech? subtitles_generate first — cue timings are timeline seconds and say what is said when.
+3. watch_video each distinct source (or the ranges in question); note scene changes and what happens where.
+4. Trimming dead air: detect_silence, then cross-check cue gaps so a cut never clips a word.
+5. Execute: split_at (timeline s) to divide, delete_item to drop a segment, trim_clip (source s) to tighten edges, place_clip/move_clip to close gaps or reorder, set_speed to compress slow stretches.
+6. Verify: seek to each new cut; capture_frame when the change is visual.
+
+Time math (get this right):
+- watch_video, detect_silence, and trim_clip speak SOURCE seconds; split_at and place_clip speak TIMELINE seconds.
+- timeline_t = clip.start + (source_t − clip.in) / clip.speed, valid while source_t is inside [in, out]. Each watch result's clip block carries this formula with the real numbers filled in.
+- The same source can appear in several clips — map per clip.
+
+Cutting dead air well: leave ~0.2s of breathing room around speech; 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.`,
+
"transitions-and-fades": `# Transitions & fades
Three fade-like features exist; route the ask to the right one:
- set_transition: a styled join between one video clip and the next.
@@ -564,7 +612,7 @@ Rules:
- Don't transcribe a video with no speech. If the user wants captions on silent footage, use subtitles_from_visuals (it narrates what's on screen). Never invent a spoken transcript.
- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.
- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this". 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.
-- capture_frame shows you the actual rendered frame when visual judgment matters.`;
+- You can see and hear: watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen; detect_silence finds dead air; capture_frame shows the one rendered frame at the playhead. The watching-and-cutting skill has the flow.`;
}
export const AI_SKILL_INDEX = Object.keys(AI_SKILLS);
diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.ts
index d614d0e1..36a323e7 100644
--- a/site/src/cut/server/frames.ts
+++ b/site/src/cut/server/frames.ts
@@ -1,8 +1,9 @@
import { spawn } from "node:child_process";
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, readdir, readFile, rm, unlink } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { mediaPath } from "./projects";
+import { num, round } from "./util";
function run(cmd: string, args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
@@ -123,3 +124,260 @@ export async function makeFreezeFrame(
void rm(tmp, { recursive: true, force: true });
}
}
+
+/** Media duration in seconds via ffprobe (0 when unknown). */
+export function probeDuration(file: string): Promise<number> {
+ return new Promise((resolve) => {
+ const p = spawn("ffprobe", [
+ "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "csv=p=0",
+ file,
+ ]);
+ let out = "";
+ const timer = setTimeout(() => {
+ p.kill("SIGKILL");
+ resolve(0);
+ }, 30_000);
+ timer.unref();
+ p.stdout.on("data", (d) => (out += d));
+ p.on("close", () => {
+ clearTimeout(timer);
+ resolve(parseFloat(out) || 0);
+ });
+ p.on("error", () => {
+ clearTimeout(timer);
+ resolve(0);
+ });
+ });
+}
+
+interface CaptureRun {
+ ok: boolean;
+ timedOut: boolean;
+ stderr: string;
+}
+
+/** Run ffmpeg keeping the whole stderr — the frame/silence reports stream
+ * there. A timeout resolves instead of rejecting so callers can salvage
+ * partial output; a missing binary still maps to the install hint. */
+function runCapture(args: string[], timeoutMs: number): Promise<CaptureRun> {
+ return new Promise((resolve, reject) => {
+ const p = spawn("ffmpeg", args);
+ let err = "";
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ p.kill("SIGKILL");
+ }, timeoutMs);
+ timer.unref();
+ p.stderr.on("data", (d) => {
+ if (err.length < 2_000_000) err += d.toString();
+ });
+ p.on("error", (e) => {
+ clearTimeout(timer);
+ reject(
+ e.message.includes("ENOENT")
+ ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")
+ : e
+ );
+ });
+ p.on("close", (code) => {
+ clearTimeout(timer);
+ resolve({ ok: code === 0 && !timedOut, timedOut, stderr: err });
+ });
+ });
+}
+
+const errTail = (stderr: string) => stderr.trim().split("\n").slice(-3).join("\n");
+
+const sheetDataUrl = async (file: string) =>
+ `data:image/jpeg;base64,${(await readFile(file)).toString("base64")}`;
+
+const SHEET_GRID = 3; // cells per row and column
+const SHEET_CELL = 480; // cell long side, px
+const SHEET_GAP = 4; // tile margin and padding, px — the client stamps cells by this geometry
+const SCENE_THRESHOLD = 0.3; // ffmpeg scene-score cut point
+const WATCH_BUDGET_MS = 100_000; // all attempts together; leaves salvage room under the 120s tool cap
+
+export interface SheetFrame {
+ t: number;
+ scene?: number;
+}
+
+export interface WatchResult {
+ sheets: { image: string; frames: SheetFrame[] }[];
+ /** Cell geometry, so the client can stamp each cell with its time. */
+ layout: { grid: number; margin: number; padding: number };
+ sceneChanges: number[];
+ coveredTo: number;
+ truncated: boolean;
+}
+
+/**
+ * Sample a media file into timestamped contact sheets: frames picked at scene
+ * changes plus a steady density floor, each cell stamped with its source time,
+ * tiled 3×3. This is how the assistant watches footage — a bounded survey of
+ * what the file actually shows (maxSheets per call; callers narrow the range
+ * to see more).
+ */
+export async function makeContactSheets(
+ projectId: string,
+ sourceFile: string,
+ opts: { from: number; to: number; interval: number; maxSheets: number; still?: boolean }
+): Promise<WatchResult> {
+ const src = mediaPath(projectId, sourceFile);
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "veditor-watch-"));
+ try {
+ const dims = await probeDims(src);
+ const scale = dims.width >= dims.height ? `scale=${SHEET_CELL}:-2` : `scale=-2:${SHEET_CELL}`;
+
+ // A still is its own one-cell sheet — no sampling, no time axis.
+ if (opts.still) {
+ const out = path.join(tmp, "sheet-01.jpg");
+ const r = await runCapture(
+ ["-hide_banner", "-nostats", "-y", "-i", src, "-vf", scale, "-frames:v", "1", "-q:v", "5", out],
+ 30_000
+ );
+ if (!r.ok) throw new Error(errTail(r.stderr) || "Could not read the image.");
+ return {
+ sheets: [{ image: await sheetDataUrl(out), frames: [{ t: 0 }] }],
+ layout: { grid: 1, margin: 0, padding: 0 },
+ sceneChanges: [],
+ coveredTo: 0,
+ truncated: false,
+ };
+ }
+
+ const { from, to, interval, maxSheets } = opts;
+ const minGap = Math.max(0.4, interval / 3);
+ const graph = [
+ // First frame always; a scene cut once minGap has passed; the floor.
+ `select='isnan(prev_selected_t)+gt(scene,${SCENE_THRESHOLD})*gte(t-prev_selected_t,${num(minGap)})+gte(t-prev_selected_t,${num(interval)})'`,
+ "metadata=print",
+ scale,
+ `tile=${SHEET_GRID}x${SHEET_GRID}:padding=${SHEET_GAP}:margin=${SHEET_GAP}`,
+ ].join(",");
+ const args = (hw: boolean) => [
+ "-hide_banner", "-nostats", "-loglevel", "info", "-y",
+ ...(hw ? ["-hwaccel", "videotoolbox"] : []),
+ "-ss", num(from),
+ "-t", num(to - from),
+ "-i", src,
+ "-map", "0:v:0", "-an", "-sn", "-dn",
+ "-vf", graph,
+ "-fps_mode", "vfr",
+ "-frames:v", String(maxSheets),
+ "-q:v", "5",
+ path.join(tmp, "sheet-%02d.jpg"),
+ ];
+
+ // Hardware decode first; a source it refuses gets one software retry.
+ const deadline = Date.now() + WATCH_BUDGET_MS;
+ let run = await runCapture(args(true), WATCH_BUDGET_MS);
+ if (!run.ok && !run.timedOut && deadline - Date.now() > 5_000) {
+ for (const f of await readdir(tmp)) void unlink(path.join(tmp, f)).catch(() => {});
+ run = await runCapture(args(false), deadline - Date.now());
+ }
+
+ const files = (await readdir(tmp)).filter((f) => f.endsWith(".jpg")).sort();
+ // A timeout or a mid-run decode error may leave the last sheet half-written.
+ if (!run.ok && files.length > 0) files.pop();
+ if (files.length === 0) {
+ throw new Error(
+ run.timedOut
+ ? "Sampling timed out before the first sheet was ready — try a shorter range or a larger interval."
+ : errTail(run.stderr) || "Could not sample the video."
+ );
+ }
+
+ // metadata=print logs each selected frame ("frame:N … pts_time:T" then
+ // "lavfi.scene_score=S"); times are relative to the input seek.
+ const frames: SheetFrame[] = [];
+ for (const line of run.stderr.split("\n")) {
+ const t = /frame:\d+.*pts_time:([\d.]+)/.exec(line);
+ if (t) {
+ frames.push({ t: round(from + parseFloat(t[1])) });
+ continue;
+ }
+ const s = /lavfi\.scene_score=([\d.]+)/.exec(line);
+ if (s && frames.length > 0) frames[frames.length - 1].scene = parseFloat(s[1]);
+ }
+ const perSheet = SHEET_GRID * SHEET_GRID;
+ const kept = frames.slice(0, files.length * perSheet);
+ const sheets = await Promise.all(
+ files.map(async (f, i) => ({
+ image: await sheetDataUrl(path.join(tmp, f)),
+ frames: kept.slice(i * perSheet, (i + 1) * perSheet),
+ }))
+ );
+ const lastT = kept.length > 0 ? kept[kept.length - 1].t : from;
+ // An aborted run (timeout or error) that salvaged sheets covered only what
+ // it decoded — never claim the full range for it.
+ const truncated =
+ (!run.ok || frames.length >= maxSheets * perSheet) && lastT < to - interval;
+ return {
+ sheets,
+ layout: { grid: SHEET_GRID, margin: SHEET_GAP, padding: SHEET_GAP },
+ sceneChanges: kept.filter((f) => (f.scene ?? 0) >= SCENE_THRESHOLD).map((f) => f.t),
+ coveredTo: truncated ? lastT : to,
+ truncated,
+ };
+ } finally {
+ void rm(tmp, { recursive: true, force: true });
+ }
+}
+
+export interface SilenceRange {
+ start: number;
+ end: number;
+ duration: number;
+}
+
+/** Find silent stretches in a media file's audio (ffmpeg silencedetect).
+ * Times are absolute source seconds. */
+export async function detectSilence(
+ projectId: string,
+ sourceFile: string,
+ opts: { from: number; to: number; thresholdDb: number; minSilence: number }
+): Promise<SilenceRange[]> {
+ const { from, to, thresholdDb, minSilence } = opts;
+ const r = await runCapture(
+ [
+ "-hide_banner", "-nostats", "-loglevel", "info",
+ ...(from > 0 ? ["-ss", num(from)] : []),
+ "-t", num(to - from),
+ "-i", mediaPath(projectId, sourceFile),
+ "-vn", "-sn", "-dn",
+ "-af", `silencedetect=n=${thresholdDb}dB:d=${num(minSilence)}`,
+ "-f", "null", "-",
+ ],
+ 60_000
+ );
+ if (!r.ok) {
+ if (/does not contain any stream|matches no streams|Cannot find a matching stream/i.test(r.stderr))
+ throw new Error("This file has no audio track.");
+ throw new Error(
+ r.timedOut ? "Silence detection timed out — try a shorter range." : errTail(r.stderr)
+ );
+ }
+ const silences: SilenceRange[] = [];
+ let open: number | null = null;
+ for (const line of r.stderr.split("\n")) {
+ const s = /silence_start: (-?[\d.]+)/.exec(line);
+ if (s) {
+ open = Math.max(from, from + parseFloat(s[1]));
+ continue;
+ }
+ const e = /silence_end: (-?[\d.]+)/.exec(line);
+ if (e && open !== null) {
+ const end = Math.min(to, from + parseFloat(e[1]));
+ if (end > open) silences.push({ start: round(open), end: round(end), duration: round(end - open) });
+ open = null;
+ }
+ }
+ // Silence still open at the end of the range closes there.
+ if (open !== null && to > open)
+ silences.push({ start: round(open), end: round(to), duration: round(to - open) });
+ return silences;
+}
diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.ts
index 39bf8d88..61495118 100644
--- a/site/src/cut/server/http/ai.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -443,12 +443,31 @@ export const aiApi = {
if (result.errorText !== undefined) {
return Response.json({ ...mcpText(result.errorText), isError: true });
}
- // Screenshots come back as data URLs; hand them to the model as images.
- const out = result.output as { image?: string } | undefined;
- if (name === "capture_frame" && out?.image?.startsWith("data:image/")) {
- const [head, data] = out.image.split(",", 2);
- const mimeType = head.slice(5, head.indexOf(";"));
- return Response.json({ content: [{ type: "image", data, mimeType }] });
+ // Frames come back as data URLs in `image`/`images`; hand them to the
+ // model as MCP image blocks. The data text rides first, so a provider
+ // that can't read images still gets the numbers.
+ const out = result.output as { image?: unknown; images?: unknown } | undefined;
+ const urls = [
+ ...(typeof out?.image === "string" ? [out.image] : []),
+ ...(Array.isArray(out?.images)
+ ? out.images.filter((u): u is string => typeof u === "string")
+ : []),
+ ]
+ .filter((u) => u.startsWith("data:image/"))
+ .slice(0, 6);
+ if (urls.length > 0) {
+ const rest = Object.fromEntries(
+ Object.entries(out as Record<string, unknown>).filter(([k]) => k !== "image" && k !== "images")
+ );
+ return Response.json({
+ content: [
+ { type: "text", text: JSON.stringify(rest) },
+ ...urls.map((u) => {
+ const [head, data] = u.split(",", 2);
+ return { type: "image", data, mimeType: head.slice(5, head.indexOf(";")) };
+ }),
+ ],
+ });
}
return Response.json(mcpText(result.output ?? { ok: true }));
},
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index f3b5c3c8..f96572a7 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -1,6 +1,6 @@
import { execFile } from "node:child_process";
import type { ProjectDoc } from "@/cut/lib/types";
-import { makeFreezeFrame, probeDims } from "../frames";
+import { detectSilence, makeContactSheets, makeFreezeFrame, probeDims, probeDuration } from "../frames";
import {
createProject,
createProjectFolder,
@@ -27,6 +27,7 @@ import { exists } from "../util";
const err = (message: string, status: number) => Response.json({ error: message }, { status });
const caught = (e: unknown, fallback: string, status = 500) =>
err(e instanceof Error ? e.message : fallback, status);
+const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
/** Project CRUD, media, exports, transcription, freeze-frames. */
export const projectsApi = {
@@ -329,4 +330,71 @@ export const projectsApi = {
return caught(e, String(e));
}
},
+
+ /** Sample a media file into timestamped contact sheets (the assistant's eyes). */
+ async watch(req: Request, { id }: { id: string }) {
+ try {
+ if (!(await readProject(id))) return err("Project not found.", 404);
+ const body = (await req.json()) as {
+ file?: string;
+ from?: number;
+ to?: number;
+ interval?: number;
+ maxSheets?: number;
+ still?: boolean;
+ };
+ if (!body.file) return err("file is required.", 400);
+ if (body.still) {
+ return Response.json(
+ await makeContactSheets(id, body.file, { from: 0, to: 0, interval: 1, maxSheets: 1, still: true })
+ );
+ }
+ const from = Math.max(0, typeof body.from === "number" ? body.from : 0);
+ const wanted = typeof body.to === "number" ? body.to : await probeDuration(mediaPath(id, body.file));
+ if (typeof body.to !== "number" && wanted <= 0)
+ return err("Could not read the media duration — pass to (seconds).", 400);
+ if (!(wanted > from)) return err("from/to describe an empty range.", 400);
+ const to = Math.min(wanted, from + 600); // bound the decode per call; callers resume from coveredTo
+ const interval =
+ typeof body.interval === "number"
+ ? clamp(body.interval, 0.5, 30)
+ : clamp((to - from) / 32, 2, 30);
+ const maxSheets = clamp(Math.round(typeof body.maxSheets === "number" ? body.maxSheets : 4), 1, 4);
+ const out = await makeContactSheets(id, body.file, { from, to, interval, maxSheets });
+ // The per-call decode cap is itself truncation — the caller asked for more.
+ if (to < wanted && !out.truncated) {
+ out.truncated = true;
+ out.coveredTo = to;
+ }
+ return Response.json(out);
+ } catch (e) {
+ return caught(e, "Could not sample the video.");
+ }
+ },
+
+ /** Report silent stretches in a media file's audio. */
+ async silence(req: Request, { id }: { id: string }) {
+ try {
+ if (!(await readProject(id))) return err("Project not found.", 404);
+ const body = (await req.json()) as {
+ file?: string;
+ from?: number;
+ to?: number;
+ threshold_db?: number;
+ min_silence?: number;
+ };
+ if (!body.file) return err("file is required.", 400);
+ const from = Math.max(0, typeof body.from === "number" ? body.from : 0);
+ const to = typeof body.to === "number" ? body.to : await probeDuration(mediaPath(id, body.file));
+ if (typeof body.to !== "number" && to <= 0)
+ return err("Could not read the media duration — pass to (seconds).", 400);
+ if (!(to > from)) return err("from/to describe an empty range.", 400);
+ const thresholdDb = clamp(typeof body.threshold_db === "number" ? body.threshold_db : -30, -90, 0);
+ const minSilence = clamp(typeof body.min_silence === "number" ? body.min_silence : 0.35, 0.05, 10);
+ const silences = await detectSilence(id, body.file, { from, to, thresholdDb, minSilence });
+ return Response.json({ silences, from, to });
+ } catch (e) {
+ return caught(e, "Could not scan for silence.");
+ }
+ },
};
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
index 23deb299..dacd04c0 100644
--- a/site/src/cut/server/http/routes.ts
+++ b/site/src/cut/server/http/routes.ts
@@ -40,6 +40,8 @@ export const CUT_ROUTES: CutRoute[] = [
{ method: "GET", path: "/api/cut/projects/:id/transcribe", handler: (req, p) => projectsApi.transcribePoll(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/image", handler: (req, p) => projectsApi.importImage(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/freeze", handler: (req, p) => projectsApi.freeze(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/projects/:id/watch", handler: (req, p) => projectsApi.watch(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/projects/:id/silence", handler: (req, p) => projectsApi.silence(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/duplicate", handler: (req, p) => projectsApi.duplicate(req, { id: p.id }) },
{ method: "GET", path: "/api/cut/projects/:id/preview", handler: (req, p) => projectsApi.servePreview(req, { id: p.id }) },
{ method: "GET", path: "/api/cut/projects/:id/export-jobs", handler: (req, p) => exportApi.activeForProject(req, { id: p.id }) },