Skip to content

Open source CapCut alternative.

TypeScript

feat(site): watching a source leaves a written record [rebuild]

David Le8d514596716c
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index 3cd0ec23..30c08e5d 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -85,6 +85,7 @@ With a tab attached, tool calls execute in it against the same store the user is
- **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.
- **Watching leaves a map.** A watch records which moments and cut candidates a source holds, persisted on the asset so it survives the thread, and the first watch of a source starts a quiet background sweep that maps the rest. The map aims later watches; only sheets returned in the conversation count as footage the model has seen.
+- **Watching leaves a record.** Contact sheets live in one conversation and the media trim drops the oldest of them, so the model writes each look down: a note-source call stores what a span showed — quoted on-screen text, what happens, where the cuts land — against its source seconds, on the asset, saved with the project. Notes come back in the editor snapshot as `observed`, in full from get-state, and on every watch result beside the spans still undescribed. A close note supersedes the coarse one over the same ground, and a watch of a source that still owes a note is refused, which is what makes an hour-long source workable: it is surveyed coarsely, described, then re-watched densely only where the work is.
- **Media rides a byte budget.** Contact sheets, audio, and attachment payloads all replay inline, so before each call the session is trimmed to a 16MB media budget — oldest parts leave first, with a note naming the tools that fetch them again. Text, tool calls, tool results, and thought signatures always survive, and the trim runs on a copy so the stored session keeps everything.
- **A link comes back as whatever it holds.** The chat's URL import works down a ladder: the bundled downloader for anything with a stream, X's own endpoints for a post's photos or Article, and otherwise the page itself — a content extractor (Defuddle over a parsed DOM) lifts the article out as markdown and the pictures it kept come along as assets. Words with no media are a successful import, so a link the user pasted to explain something reads fine, and that text is quoted for the user beside whatever media came with it.
- **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. Each render's card state (running, landed, failed) mirrors into the project doc as it changes, so the chat shows the same outcome on machines that never ran the job.
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.ts
index 43274c61..30049302 100644
--- a/site/src/cut/components/AiPanel.tools.ts
+++ b/site/src/cut/components/AiPanel.tools.ts
@@ -19,7 +19,7 @@ export const AI_PANEL_TOOLS = [
{
name: "watch_video",
description:
- "Watch a video source with your own eyes: samples candidate frames on a dense steady floor, keeps only the ones that actually differ, and tiles them into timestamped contact-sheet images — so every cell is a distinct moment and a gap between stamps means nothing changed there. Also returns sceneChanges, hard-cut times refined to about a third of a second of the true boundary (the time is where the new shot first appears) — though a shot shorter than the sampling step can fall between candidates, so where short cuts matter, re-watch narrow with a small interval_seconds. When the clip has captions or the source's own transcript exists, a fused timeline places each kept frame inside the speech it belongs to. 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 ends where the result says it does: when truncated is true (span bound, frame cap, or time budget), continue from coveredTo — everything before it was seen, nothing after it was. Watching builds the source's frame map (moment times + cut candidates), persisted on the asset; media entries list those spans as `mapped`, and your first watch starts a quiet background sweep that maps the rest (`watching: true` while it runs). The map aims your watches — a mapped span is NOT footage you have seen; only sheets returned in this conversation are, so watch any span you need to actually look at. Read the watching-and-cutting skill before editing footage by content.",
+ "Watch a video source with your own eyes: samples candidate frames on a dense steady floor, keeps only the ones that actually differ, and tiles them into timestamped contact-sheet images — so every cell is a distinct moment and a gap between stamps means nothing changed there. Also returns sceneChanges, hard-cut times refined to about a third of a second of the true boundary (the time is where the new shot first appears) — though a shot shorter than the sampling step can fall between candidates, so where short cuts matter, re-watch narrow with a small interval_seconds. When the clip has captions or the source's own transcript exists, a fused timeline places each kept frame inside the speech it belongs to. 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 ends where the result says it does: `coveredTo` is how far you have looked and `unwatchedSeconds` is how much of the source you have NOT — everything before coveredTo was seen, nothing after it was. Continue from coveredTo until unwatchedSeconds is 0 before you describe, summarize, or reproduce the source as a whole; a `to` you chose yourself ends a call with truncated false and the rest of the video still unseen. Watching builds the source's frame map (moment times + cut candidates), persisted on the asset; media entries list those spans as `mapped`, and your first watch starts a quiet background sweep that maps the rest (`watching: true` while it runs). The map aims your watches — a mapped span is NOT footage you have seen; only sheets returned in this conversation are, so watch any span you need to actually look at. Every pass ends with note_source: the sheets are conversation-local and drop out as the chat grows, so write what this stretch showed against its source seconds and it stays on the asset for every later turn. The result carries `recorded` (what is already written about the stretch you just watched) and `unnoted` (the spans of this source nothing describes yet); watching a source that still owes a note is refused. 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"),
@@ -28,6 +28,30 @@ export const AI_PANEL_TOOLS = [
interval_seconds: num("Seconds between candidate frames, 0.5–30 (default 1; near-duplicates are dropped, so a dense default costs nothing)"),
}),
},
+ {
+ name: "note_source",
+ description:
+ "Write down what you just saw in a source, against the source seconds it covers. Contact sheets live in this conversation only and the oldest media drops out as the chat grows, so a source longer than one look is only usable if each look is recorded while it is on screen: the notes save onto the asset, ride the editor state into every later turn and every later chat, and come back in get_state and in watch_video's `recorded`. Write what a later decision needs — on-screen text word for word, what happens, how it is shot, where the cuts land — one entry per stretch you looked at. A note owns its span: re-reading 0-30s closely and noting it again replaces the coarse note that covered it. Watching a source that still has an unrecorded look behind it is refused, so note as you go.",
+ inputSchema: obj(
+ {
+ clip_id: str("Video clip id — records against that clip's source"),
+ asset_id: str("Project asset id"),
+ notes: {
+ type: "array",
+ description: "One entry per stretch you looked at, in source seconds",
+ items: obj(
+ {
+ from: num("Source start s"),
+ to: num("Source end s"),
+ text: str("What that stretch showed — quote on-screen text exactly"),
+ },
+ ["from", "to", "text"]
+ ),
+ },
+ },
+ ["notes"]
+ ),
+ },
{
name: "detect_silence",
description:
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 83024096..d0de8b4a 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -33,6 +33,32 @@ function clipEffects(clip: VideoClip) {
};
}
+/** How much written record the per-message snapshot carries before it hands
+ * the rest to get_state. */
+const NOTE_SNAPSHOT_BUDGET = 3000;
+
+/** An asset's watch notes shaped for the context: whole when they fit (and
+ * whenever the caller asked for everything), otherwise each note shortened to
+ * an even share of the budget so every span still says what it holds, with
+ * `observedText` naming where the rest is. */
+function noteFields(
+ notes: { from: number; to: number; text: string }[] | undefined,
+ full: boolean
+): Record<string, unknown> {
+ if (!notes || notes.length === 0) return {};
+ const size = notes.reduce((sum, n) => sum + n.text.length, 0);
+ if (full || size <= NOTE_SNAPSHOT_BUDGET)
+ return { observed: notes.map((n) => ({ from: r(n.from), to: r(n.to), text: n.text })) };
+ const share = Math.max(120, Math.floor(NOTE_SNAPSHOT_BUDGET / notes.length));
+ let trimmed = false;
+ const observed = notes.map((n) => {
+ if (n.text.length <= share) return { from: r(n.from), to: r(n.to), text: n.text };
+ trimmed = true;
+ return { from: r(n.from), to: r(n.to), text: `${n.text.slice(0, share).trimEnd()}…` };
+ });
+ return { observed, ...(trimmed ? { observedText: "shortened here, whole in get_state" } : {}) };
+}
+
/**
* Compact JSON snapshot of everything the assistant should know: the cut,
* the selection, what's on screen, and every user-facing setting. Sent with
@@ -61,6 +87,13 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
const ownedByOtherChat = (a: { origin?: string; chatId?: string; id: string }) =>
a.origin === "chat" && !!a.chatId && a.chatId !== chatId && !placed.has(a.id);
const visibleAssets = s.assets.filter((a) => !ownedByOtherChat(a));
+ // The cap trims the tail of a huge media list, and a source someone has
+ // watched and written up stays regardless of where it sits: the record is
+ // what later decisions are made from.
+ const shownAssets =
+ visibleAssets.length <= cueCap
+ ? visibleAssets
+ : visibleAssets.filter((a, i) => i < cueCap || (a.watch?.notes?.length ?? 0) > 0);
const spans = getClipSpans(s.clips, s.assets);
const duration = totalDuration(s.clips);
const assetById = new Map(s.assets.map((a) => [a.id, a]));
@@ -122,6 +155,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
frame: `${frameOf(s.aspect).w}x${frameOf(s.aspect).h}`,
...(s.fadeIn > 0 ? { fadeIn: r(s.fadeIn) } : {}),
...(s.fadeOut > 0 ? { fadeOut: r(s.fadeOut) } : {}),
+ background: s.background,
},
playhead: r(playheadAt()),
skimmer: skimAt() === null ? null : r(skimAt()!),
@@ -131,7 +165,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
// another chat still owns is filtered out above). `origin` marks Cut-made
// media (generated/voiceover/recording/stock/freeze); no origin = a user
// import shown in the Media panel.
- media: visibleAssets.slice(0, cueCap).map((a) => ({
+ media: shownAssets.map((a) => ({
id: a.id,
name: a.name,
type: a.type,
@@ -146,6 +180,13 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
? { mapped: a.watch.ranges.map((rg) => ({ from: r(rg.from), to: r(rg.to) })) }
: {}),
...(watchSweepActive(a.id) ? { watching: true } : {}),
+ // The written record of this source — what someone looked at these
+ // frames and wrote down (note_source). Unlike `mapped`, this IS seen
+ // footage, and it survives the contact sheets that showed it, so a
+ // source too long to hold in one conversation is decided from here.
+ // The snapshot rides every model call, so it carries the notes while
+ // they are small and hands the rest to get_state.
+ ...noteFields(a.watch?.notes, opts?.fullCues === true),
// The source's own transcript (built quietly by the sweep; no subtitle
// track involved). The snapshot carries the verdict; get_state carries
// the segments — read those for the words instead of inlining audio.
@@ -164,7 +205,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
}
: {}),
})),
- mediaTruncated: visibleAssets.length > cueCap,
+ mediaTruncated: shownAssets.length < visibleAssets.length,
// AI video renders for this project, live from the job store — what
// "rendering" claims must be grounded in. A done render names the asset
// it landed as (already in `media`); a failed one carries its error.
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 2ea63455..c324a831 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -80,7 +80,7 @@ import { buildAiContext } from "./aiContext";
import { sampleClipFrameData } from "./previewCanvas";
import { laneCues, subtitleLaneCount } from "./subtitles";
import { fuseTimeline, renderFusedTimeline } from "./watch/fuse";
-import { mergeWatch } from "./watch/merge";
+import { mergeWatch, mergeWatchNotes, uncoveredSeconds, unnotedSpans } from "./watch/merge";
import { queueWatchSweep, withSweepPaused } from "./watch/sweep";
import { synthesizeMusic } from "./audioGen";
import { composeMusicPrompt } from "./composeGen";
@@ -111,6 +111,8 @@ import {
SPEED_FLOOR,
TRANSITION_STYLE_IDS,
type AnimStyle,
+ type AssetWatch,
+ type CaptionStyleId,
type AudioClip,
type ColorGrade,
type FontId,
@@ -584,6 +586,15 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
watch_video: async (s, input) => {
const { asset, clip, speed, from, to } = resolveWatchRange(s, input);
+ // The reading of the last look comes before the next one. Without it a
+ // long source is watched into a conversation that keeps dropping the
+ // sheets, and the tail arrives with the head already gone.
+ const owed = unwritten.get(asset.id);
+ if (owed && !spanIsNoted(asset.watch, owed))
+ throw new ToolError(
+ `You watched ${round2(owed.from)}-${round2(owed.to)}s of "${asset.name}" and have not written down what it showed. ` +
+ "Those sheets leave this conversation as it grows, so record them while you can still see them: call note_source with what that stretch showed — the on-screen text word for word, what happens, how it is shot, the timings — then watch on."
+ );
if (asset.type === "audio")
throw new ToolError(`"${asset.name}" is audio — listen_audio hears it, detect_silence finds its dead air.`);
// One path for both backends: the browser decodes the source (the same
@@ -631,10 +642,19 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
}),
});
}
+ // A source with more to see owes a reading of what just went past:
+ // the next watch of it asks for this span's notes first.
+ if (body.coveredTo > from && asset.duration - body.coveredTo > 0.5)
+ unwritten.set(asset.id, { from: round2(from), to: round2(body.coveredTo) });
+ else unwritten.delete(asset.id);
// A first look queues the quiet background sweep of the rest of the
// source — metadata only, merged in as segments land.
queueWatchSweep(asset.id);
}
+ const unwatched = uncoveredSeconds(
+ useEditor.getState().assets.find((x) => x.id === asset.id)?.watch,
+ asset.duration
+ );
// Tile the kept frames 3×3 and stamp each cell's source time.
const sheets = await composeSheets(body.frames).catch(() => null);
const keptTimes = body.frames.map((f) => f.t);
@@ -673,6 +693,21 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
sceneChanges: body.sceneChanges.map(round2),
coveredTo: round2(body.coveredTo),
truncated: body.truncated,
+ // What NOBODY has looked at, anywhere in the source — the union of
+ // every watched span subtracted from its length, so a watch aimed at
+ // the middle counts the head it skipped as well as the tail it never
+ // reached. `truncated` only says whether the sampler stopped early,
+ // and a caller who passed a short `to` gets truncated: false; this is
+ // the honest number, stated in the payload and in the note.
+ unwatchedSeconds: unwatched,
+ // The written record of this source, which outlives the sheets: what
+ // was already noted about the stretch on screen now, and the spans of
+ // the source nothing has been written about yet.
+ recorded: notesIn((liveAsset ?? asset).watch, from, body.coveredTo),
+ unnoted: unnotedSpans((liveAsset ?? asset).watch, asset.duration).map((g) => ({
+ from: round2(g.from),
+ to: round2(g.to),
+ })),
source: { assetId: asset.id, name: asset.name, duration: round2(asset.duration) },
...(clip
? {
@@ -691,13 +726,53 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
"Cells read left→right then top→bottom; each stamp is SOURCE seconds. " +
"Cells are distinct moments (near-duplicates removed), so gaps between stamps mean nothing changed there. " +
"sheetFrames says why each cell was kept: global = hard cut, action = local motion, settled = new settled detail (text/UI)." +
- (body.truncated
- ? ` Coverage stopped at ${round2(body.coveredTo)}s — call again with from=${round2(body.coveredTo)} to continue.`
+ (unwatched > 0.5
+ ? ` You have seen ${round2(from)}-${round2(body.coveredTo)}s of a ${round2(asset.duration)}s source; ` +
+ `${unwatched}s of it has NOT been looked at (this call's range plus anything else already watched)` +
+ (body.truncated ? " (this call hit its budget)" : " (your own `to` ended this call)") +
+ `. Call again with from=${round2(body.coveredTo)} to continue — and do continue before describing, summarizing, or reproducing the source as a whole.`
: "") +
+ " These sheets are in this conversation only, and it drops the oldest media as it grows. Write what they showed into note_source now — text word for word, what happens, the timings — and the reading stays on the source for every later turn and every later chat." +
(sheets ? "" : " (Sheets unavailable — each image is one frame; sheetFrames lists the times.)"),
};
},
+ note_source: (s, input) => {
+ const { asset } = resolveWatchTarget(s, input);
+ const raw = Array.isArray(input.notes) ? input.notes : [];
+ const notes = raw
+ .filter((n): n is Record<string, unknown> => typeof n === "object" && n !== null)
+ .map((n) => ({
+ from: isNum(n.from) ? clamp(n.from, 0, asset.duration) : 0,
+ to: isNum(n.to) ? clamp(n.to, 0, asset.duration) : asset.duration,
+ text: typeof n.text === "string" ? n.text.trim() : "",
+ }))
+ .filter((n) => n.text.length > 0);
+ if (notes.length === 0)
+ throw new ToolError("Pass notes: [{from, to, text}] — source seconds and what that stretch showed.");
+ s.updateAsset(asset.id, { watch: mergeWatchNotes(asset.watch, notes) });
+ const cur = useEditor.getState().assets.find((a) => a.id === asset.id);
+ const owed = unwritten.get(asset.id);
+ if (owed && spanIsNoted(cur?.watch, owed)) unwritten.delete(asset.id);
+ const unnoted = unnotedSpans(cur?.watch, asset.duration);
+ return {
+ source: { assetId: asset.id, name: asset.name, duration: round2(asset.duration) },
+ notes: (cur?.watch?.notes ?? []).map((n) => ({
+ from: round2(n.from),
+ to: round2(n.to),
+ text: n.text,
+ })),
+ unnoted: unnoted.map((g) => ({ from: round2(g.from), to: round2(g.to) })),
+ note:
+ "Written onto the source: it saves with the project, rides the editor state from here on, and outlives this conversation's images." +
+ (unnoted.length > 0
+ ? ` Still undescribed: ${unnoted
+ .map((g) => `${round2(g.from)}-${round2(g.to)}s`)
+ .join(", ")}.`
+ : " The whole source is described."),
+ };
+ },
+
detect_silence: async (s, input) => {
const { projectId, asset, clip, speed, from, to } = resolveWatchRange(s, input);
if (asset.type === "image") throw new ToolError(`"${asset.name}" is an image — it has no audio.`);
@@ -2554,6 +2629,35 @@ async function synthesizeVoiceover(
/** Resolve a watch/listen target: a timeline clip (its source plus trim and
* placement) or a bare project asset. */
+/** Spans watched this session that nobody has written down yet, by asset id.
+ * Contact sheets fall out of the conversation as it grows, so the record has
+ * to be written while the frames are still on screen; a second look at the
+ * same source asks for the first look's reading before it spends a call. */
+const unwritten = new Map<string, { from: number; to: number }>();
+
+/** A span counts as written down once notes describe all but a sliver of it. */
+function spanIsNoted(watch: AssetWatch | undefined, span: { from: number; to: number }): boolean {
+ let cursor = span.from;
+ for (const n of [...(watch?.notes ?? [])].sort((a, b) => a.from - b.from)) {
+ if (n.to <= cursor) continue;
+ if (n.from > cursor + 2) break;
+ cursor = Math.max(cursor, n.to);
+ }
+ return cursor >= span.to - 2;
+}
+
+/** What has been written about a stretch of a source: the notes overlapping
+ * it, oldest span first. */
+function notesIn(
+ watch: AssetWatch | undefined,
+ from: number,
+ to: number
+): { from: number; to: number; text: string }[] {
+ return (watch?.notes ?? [])
+ .filter((n) => n.to > from && n.from < to)
+ .map((n) => ({ from: round2(n.from), to: round2(n.to), text: n.text }));
+}
+
function resolveWatchTarget(
s: ReturnType<typeof useEditor.getState>,
input: Record<string, unknown>
diff --git a/site/src/cut/lib/pi/mutationLedger.ts b/site/src/cut/lib/pi/mutationLedger.ts
index 28c49ccd..3d1229f9 100644
--- a/site/src/cut/lib/pi/mutationLedger.ts
+++ b/site/src/cut/lib/pi/mutationLedger.ts
@@ -12,6 +12,7 @@ const READ_ONLY = new Set([
"read_skill",
"capture_frame",
"watch_video",
+ "note_source",
"detect_silence",
"listen_audio",
"library_list",
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 4ec83efa..45f2740b 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -141,6 +141,11 @@ export interface AssetWatch {
frames: { t: number; via: WatchKeepReason }[];
/** Hard-cut moments among the kept frames. */
sceneChanges: number[];
+ /** What the assistant read off the source, in its own words, against the
+ * span it read it from. Contact sheets leave the conversation as it grows;
+ * these stay, so a source longer than one look can be decided from the
+ * record instead of watched again. */
+ notes?: { from: number; to: number; text: string }[];
}
/** A source's own transcript — working data for the assistant, kept apart
diff --git a/site/src/cut/lib/watch/merge.test.ts b/site/src/cut/lib/watch/merge.test.ts
index 6eaa9a8a..b332836f 100644
--- a/site/src/cut/lib/watch/merge.test.ts
+++ b/site/src/cut/lib/watch/merge.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
-import { mergeSpeech, mergeWatch, nextUncoveredSpan } from "./merge";
+import { mergeSpeech, mergeWatch, mergeWatchNotes, nextUncoveredSpan, uncoveredSeconds, unnotedSpans } from "./merge";
import type { AssetWatch } from "../types";
const frame = (t: number, via: AssetWatch["frames"][number]["via"] = "global") => ({ t, via });
@@ -106,3 +106,67 @@ describe("nextUncoveredSpan", () => {
expect(nextUncoveredSpan(mergeWatch(undefined, { from: 0, to: 600, frames: [], sceneChanges: [] }), 600, 600)).toBe(null);
});
});
+
+describe("watch notes", () => {
+ const note = (from: number, to: number, text: string) => ({ from, to, text });
+
+ test("notes land sorted and empty ones are dropped", () => {
+ const w = mergeWatchNotes(undefined, [
+ note(30, 60, "the diagram builds"),
+ note(0, 30, "opening cards"),
+ note(60, 70, " "),
+ ]);
+ expect(w.notes).toEqual([note(0, 30, "opening cards"), note(30, 60, "the diagram builds")]);
+ });
+
+ test("a closer note replaces the coarse one it covers", () => {
+ const coarse = mergeWatchNotes(undefined, [note(0, 60, "titles over b-roll")]);
+ const close = mergeWatchNotes(coarse, [
+ note(0, 30, 'card: "Yo, I got a Mil in $ idea"'),
+ note(30, 60, 'card: "Right?"'),
+ ]);
+ expect(close.notes).toEqual([
+ note(0, 30, 'card: "Yo, I got a Mil in $ idea"'),
+ note(30, 60, 'card: "Right?"'),
+ ]);
+ });
+
+ test("notes outlive a re-watch of the same span", () => {
+ const noted = mergeWatchNotes(
+ mergeWatch(undefined, { from: 0, to: 10, frames: [], sceneChanges: [] }),
+ [note(0, 10, "the hook")]
+ );
+ const again = mergeWatch(noted, { from: 0, to: 10, frames: [], sceneChanges: [] });
+ expect(again.notes).toEqual([note(0, 10, "the hook")]);
+ });
+
+ test("what is still undescribed reads off the notes", () => {
+ const w = mergeWatchNotes(undefined, [note(0, 30, "opening"), note(60, 90, "the pitch")]);
+ expect(unnotedSpans(w, 120)).toEqual([
+ { from: 30, to: 60 },
+ { from: 90, to: 120 },
+ ]);
+ expect(unnotedSpans(mergeWatchNotes(w, [note(30, 120, "the rest")]), 120)).toEqual([]);
+ });
+});
+
+describe("uncoveredSeconds", () => {
+ test("a watch aimed at the middle counts the head it skipped", () => {
+ const w = mergeWatch(undefined, { from: 120, to: 600, frames: [], sceneChanges: [] });
+ expect(uncoveredSeconds(w, 600)).toBe(120);
+ });
+
+ test("overlapping spans count once", () => {
+ const w = mergeWatch(mergeWatch(undefined, { from: 0, to: 60, frames: [], sceneChanges: [] }), {
+ from: 30,
+ to: 90,
+ frames: [],
+ sceneChanges: [],
+ });
+ expect(uncoveredSeconds(w, 100)).toBe(10);
+ });
+
+ test("nothing watched is the whole source", () => {
+ expect(uncoveredSeconds(undefined, 64.1)).toBe(64.1);
+ });
+});
diff --git a/site/src/cut/lib/watch/merge.ts b/site/src/cut/lib/watch/merge.ts
index 9b116613..27e16532 100644
--- a/site/src/cut/lib/watch/merge.ts
+++ b/site/src/cut/lib/watch/merge.ts
@@ -27,6 +27,25 @@ export function nextUncoveredSpan(
const round2 = (n: number) => Math.round(n * 100) / 100;
+/** How much of [0, duration] no watch has covered, in seconds. Coverage is
+ * the union of watched spans, so a look aimed at the middle of a source
+ * leaves the head uncovered and says so — what `coveredTo` alone cannot. */
+export function uncoveredSeconds(
+ watch: { ranges: { from: number; to: number }[] } | undefined,
+ duration: number
+): number {
+ let covered = 0;
+ let cursor = 0;
+ for (const rg of watch?.ranges ?? []) {
+ const from = Math.max(rg.from, cursor);
+ if (rg.to > from) {
+ covered += rg.to - from;
+ cursor = rg.to;
+ }
+ }
+ return Math.max(0, round2(duration - covered));
+}
+
/** Fold a new watch result into an asset's stored watch metadata. The new
* span is authoritative for what it covered: stored frames and cuts inside
* [from, to] are replaced by the new ones, spans union, and everything stays
@@ -102,5 +121,61 @@ export function mergeWatch(
if (last && rg.from <= last.to + EPS) last.to = Math.max(last.to, rg.to);
else ranges.push({ from: rg.from, to: rg.to });
}
- return { ranges, frames, sceneChanges };
+ // Notes survive a re-watch: they are what someone read off the source, not
+ // a product of this pass.
+ return { ranges, frames, sceneChanges, ...(prev?.notes?.length ? { notes: prev.notes } : {}) };
+}
+
+/** Fold written observations into an asset's watch record. A new note owns
+ * its span: stored notes that fall inside it drop, so re-reading a stretch
+ * closely supersedes the coarse pass that first described it. Everything
+ * else stays, sorted by time. */
+export function mergeWatchNotes(
+ prev: AssetWatch | undefined,
+ add: { from: number; to: number; text: string }[]
+): AssetWatch {
+ const incoming = add
+ .map((n) => ({
+ from: round2(Math.max(0, Math.min(n.from, n.to))),
+ to: round2(Math.max(n.from, n.to)),
+ text: n.text.trim(),
+ }))
+ .filter((n) => n.text.length > 0);
+ // The incoming spans, unioned: a stored note goes when the new reading
+ // covers the ground it described, whether by one note or several.
+ const union: { from: number; to: number }[] = [];
+ for (const n of [...incoming].sort((a, b) => a.from - b.from)) {
+ const last = union[union.length - 1];
+ if (last && n.from <= last.to + EPS) last.to = Math.max(last.to, n.to);
+ else union.push({ from: n.from, to: n.to });
+ }
+ const covered = (n: { from: number; to: number }) =>
+ union.some((x) => n.from >= x.from - EPS && n.to <= x.to + EPS);
+ const notes = (prev?.notes ?? [])
+ .filter((n) => !covered(n))
+ .concat(incoming)
+ .sort((a, b) => a.from - b.from || a.to - b.to);
+ return {
+ ranges: prev?.ranges ?? [],
+ frames: prev?.frames ?? [],
+ sceneChanges: prev?.sceneChanges ?? [],
+ ...(notes.length ? { notes } : {}),
+ };
+}
+
+/** The stretches of [0, duration] no note describes yet, ascending — what is
+ * left to look at and write down. Slivers under MIN_GAP_S are ignored, the
+ * same way coverage gaps are. */
+export function unnotedSpans(
+ watch: AssetWatch | undefined,
+ duration: number
+): { from: number; to: number }[] {
+ const gaps: { from: number; to: number }[] = [];
+ let cursor = 0;
+ for (const n of [...(watch?.notes ?? [])].sort((a, b) => a.from - b.from)) {
+ if (n.from - cursor >= MIN_GAP_S) gaps.push({ from: round2(cursor), to: round2(n.from) });
+ cursor = Math.max(cursor, n.to);
+ }
+ if (duration - cursor >= MIN_GAP_S) gaps.push({ from: round2(cursor), to: round2(duration) });
+ return gaps;
}
diff --git a/site/src/cut/lib/watchRecord.test.ts b/site/src/cut/lib/watchRecord.test.ts
new file mode 100644
index 00000000..5ea8286b
--- /dev/null
+++ b/site/src/cut/lib/watchRecord.test.ts
@@ -0,0 +1,117 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+import { runAiTool } from "./aiTools";
+import { buildAiContext } from "./aiContext";
+import { useEditor } from "./store";
+import type { MediaAsset } from "./types";
+
+/**
+ * The written record of a source: what note_source stores on the asset, and
+ * how the editor snapshot hands it back. It is what makes a source longer
+ * than one look usable — the contact sheets are gone by the next turn, this
+ * is not.
+ */
+
+const source: MediaAsset = {
+ id: "a1",
+ fileName: "talk.mp4",
+ name: "talk.mp4",
+ type: "video",
+ duration: 3600,
+ url: "",
+};
+
+const noteOf = (id: string) => useEditor.getState().assets.find((a) => a.id === id)?.watch?.notes;
+
+describe("note_source", () => {
+ beforeEach(() => {
+ useEditor.setState({ projectId: "p1", assets: [{ ...source }], clips: [], overlays: [] });
+ });
+
+ test("writes what was seen onto the source, in source seconds", async () => {
+ await runAiTool("note_source", {
+ asset_id: "a1",
+ notes: [
+ { from: 0, to: 300, text: 'cold open on a whiteboard; card reads "Yo, I got a Mil in $ idea"' },
+ { from: 300, to: 600, text: "the diagram builds, one arrow per beat" },
+ ],
+ });
+ expect(noteOf("a1")).toEqual([
+ { from: 0, to: 300, text: 'cold open on a whiteboard; card reads "Yo, I got a Mil in $ idea"' },
+ { from: 300, to: 600, text: "the diagram builds, one arrow per beat" },
+ ]);
+ });
+
+ test("reports what is still undescribed", async () => {
+ const out = (await runAiTool("note_source", {
+ asset_id: "a1",
+ notes: [{ from: 0, to: 600, text: "the setup" }],
+ })) as { unnoted: { from: number; to: number }[] };
+ expect(out.unnoted).toEqual([{ from: 600, to: 3600 }]);
+ });
+
+ test("a close read supersedes the coarse pass over the same ground", async () => {
+ await runAiTool("note_source", {
+ asset_id: "a1",
+ notes: [{ from: 0, to: 60, text: "titles over b-roll" }],
+ });
+ await runAiTool("note_source", {
+ asset_id: "a1",
+ notes: [
+ { from: 0, to: 30, text: 'card: "Right?"' },
+ { from: 30, to: 60, text: 'card: "Literally"' },
+ ],
+ });
+ expect(noteOf("a1")).toEqual([
+ { from: 0, to: 30, text: 'card: "Right?"' },
+ { from: 30, to: 60, text: 'card: "Literally"' },
+ ]);
+ });
+
+ test("a note with no text is refused", async () => {
+ let message = "";
+ try {
+ await runAiTool("note_source", { asset_id: "a1", notes: [{ from: 0, to: 10, text: " " }] });
+ } catch (err) {
+ message = err instanceof Error ? err.message : String(err);
+ }
+ expect(message).toContain("notes");
+ expect(noteOf("a1")).toBeUndefined();
+ });
+});
+
+describe("the snapshot carries the record", () => {
+ beforeEach(() => {
+ useEditor.setState({ projectId: "p1", assets: [{ ...source }], clips: [], overlays: [] });
+ });
+
+ test("notes ride the per-message snapshot while they are small", async () => {
+ await runAiTool("note_source", {
+ asset_id: "a1",
+ notes: [{ from: 0, to: 600, text: "the setup" }],
+ });
+ const ctx = buildAiContext() as { media: { observed?: { text?: string }[] }[] };
+ expect(ctx.media[0].observed).toEqual([{ from: 0, to: 600, text: "the setup" }]);
+ });
+
+ test("a long record keeps every span readable and points at get_state", async () => {
+ await runAiTool("note_source", {
+ asset_id: "a1",
+ notes: Array.from({ length: 12 }, (_, i) => ({
+ from: i * 300,
+ to: (i + 1) * 300,
+ text: `segment ${i}: `.padEnd(400, "x"),
+ })),
+ });
+ const snapshot = buildAiContext() as {
+ media: { observed?: { text?: string }[]; observedText?: string }[];
+ };
+ expect(snapshot.media[0].observedText).toBe("shortened here, whole in get_state");
+ expect(snapshot.media[0].observed).toHaveLength(12);
+ for (const n of snapshot.media[0].observed ?? []) {
+ expect(n.text?.length).toBeLessThan(400);
+ expect(n.text).toContain("segment");
+ }
+ const full = buildAiContext({ fullCues: true }) as { media: { observed?: { text?: string }[] }[] };
+ expect(full.media[0].observed?.[0].text).toContain("segment 0");
+ });
+});
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 9242b6fb..f107a25b 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -88,6 +88,13 @@ When a request depends on what the footage actually contains — "cut the dead a
Your eyes and ears:
- watch_video(clip_id | asset_id, from?, to?, interval_seconds?): samples the SOURCE on a dense steady floor, keeps only the frames that actually differ, and returns them as timestamped contact sheets — cells read left→right, top→bottom, each burned stamp is source seconds, and a gap between stamps means nothing changed there — plus sceneChanges, hard-cut times refined to about a third of a second of the true boundary, and — when the clip has captions or the source's transcript exists — a fused timeline placing each frame inside the speech it belongs to. Coverage ends where the result says: when truncated (span bound, frame cap, or time budget), continue from coveredTo. A shot shorter than the sampling step can fall between candidates — where short cuts matter, re-watch narrow with interval_seconds 0.5–1. Watching builds the source's frame map, persisted on the asset; each media entry's "mapped" spans list where that map exists, and the first watch or listen of a source starts a background sweep that maps the rest, transcript included ("watching": true marks it running; the spans grow as segments land). Use the map to aim your watches — a mapped span is NOT footage you have seen; only the sheets returned to you in this conversation are, so watch any span before you cut inside it.
+- note_source(clip_id | asset_id, notes: [{from, to, text}]): writes what you saw onto the source, in source seconds. The sheets are conversation-local and the oldest media drops out as the chat grows; a note is permanent — it saves with the project, comes back as \`observed\` on the media entry in every later turn and chat, and is returned to you by get_state and by watch_video's \`recorded\`. This is how a source longer than one look becomes usable.
+
+**Seeing all of it.** Every result carries \`coveredTo\` and \`unwatchedSeconds\`. A \`to\` you passed yourself ends the call with \`truncated: false\` and the rest of the source unseen — that is not coverage. Any ask about the video AS A WHOLE — "what happens in this", "summarize it", "replicate/recreate this", "match this style", "how does it end" — means watching from 0 until \`unwatchedSeconds\` reaches 0, however many calls that takes. Watching a slice and describing the whole is how you end up reporting text that isn't there and putting the opening line at the end. Aiming a watch at one span is for a question about that span. One call reaches as far as its ceilings allow: a 600s span, 150 decodes, 36 kept frames, 90s of decoding — so at \`interval_seconds\` 0.5 a call covers at most 75s of source, and far less where the picture keeps changing. A source of a minute or two is a few calls; a source of an hour is not something to grind through frame-dense from 0. There, sweep it coarse first (\`interval_seconds\` 15–30 end to end) to learn its shape, then watch the spans that matter at a dense floor.
+
+**Watch, write, decide.** Watching builds a record and the record is what you work from. Every pass ends with note_source: the span you just looked at and what it showed — on-screen text word for word, what happens, how it is shot, where the cuts land. Do it while the sheets are still on screen; the conversation drops its oldest media as it grows, and a watch nobody wrote down is a watch spent for nothing. Watching a source that still has an unrecorded look behind it is refused, so the loop is one pass, one note, next pass. The record comes back to you as \`observed\` on the media entry, in full from get_state, and as \`recorded\` and \`unnoted\` on every watch result. An hour of footage is decided from notes you can hold: sweep it coarse (\`interval_seconds\` 15–30) and note its shape, then watch the spans that matter at a dense floor and note those closely — a close note replaces the coarse one over the same span. Before you plan an edit, read \`observed\` and \`unnoted\`: a span already described needs no second look, and one still blank does.
+
+**Reading on-screen text.** Recreating a video's titles, captions or kinetic typography is a transcription job, so read every card in order with its own timing: watch the whole source at \`interval_seconds\` 0.5 (a line that builds a word at a time — "You" → "You know that building" → "is everything today" — is one card, and a 1s floor collapses or skips those steps), and write each card's text, its in/out, its color and its position into note_source as you read it — that record is what you build the cut from a turn later, when the sheets are gone. Copy the text exactly, including the lines you would have trimmed; a fragment placed as if it were a whole card ("I got half of" without "my clients from Linkedin last year") is a misquote of the user's reference. Cards frequently continue across cuts — before you decide a card is finished, check the next one for the rest of its sentence.
- 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(t?): one composited frame, at the given time in seconds or the playhead — for checking the final look. Surveying footage is watch_video's job.
@@ -227,7 +234,7 @@ Rules:
- 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; listen_audio plays a source's audio — an audio asset or a video/clip's own track; detect_silence finds dead air; 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; detect_silence finds dead air; capture_frame shows one rendered frame, at the time you pass or the playhead. 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.`;
}