Open source CapCut alternative.
TypeScript
feat(site): chat mentions timeline clips and steers revisions by clip scope [rebuild]
David Le0e4a605bb80f
diff --git a/site/scripts/eval-cut-chat.ts b/site/scripts/eval-cut-chat.tsindex e4a33066..e3b09e9d 100644--- a/site/scripts/eval-cut-chat.ts+++ b/site/scripts/eval-cut-chat.ts@@ -21,7 +21,7 @@ import { mkdtempSync, readFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { geminiModelRoles } from "../src/lib/inference/gemini-models";-import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "../src/cut/server/ai/catalog";+import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "../src/cut/server/ai/catalog";import {parseTurnIntent,TURN_INTENT_PROMPT,@@ -168,6 +168,9 @@ const EDITOR_STATE = {view: { pxPerSec: 60, timelineH: 260, exportDialogOpen: false },};+/** A user-imported narration file for the scene-production cases. */+const NARRATION_ASSET = { id: "a-au1", name: "narration.mp3", type: "audio", duration: 24 };+const VOICE_REF = {scope: "project",id: VOICE_ASSET.id,@@ -198,6 +201,67 @@ const FILLER_STATE = {},};+/** The base snapshot plus the narration import — the scene cases' spine. */+const AUDIO_STATE = {+ ...EDITOR_STATE,+ media: [...EDITOR_STATE.media, NARRATION_ASSET],+};++/** A finished scene run's timeline: three generated takes, each clip carrying+ * its plan shot number (sceneShot), the narration as the spine. */+const sceneClip = (n: number, start: number, len: number) => ({+ index: n - 1,+ id: `sc-${n}`,+ asset: `shot ${n} take.mp4`,+ start,+ len,+ in: 0,+ out: len,+ sourceDuration: 10,+ muted: true,+ framing: "fit",+ speed: 1,+ sceneShot: n,+});+const SCENE_DONE_STATE = {+ ...EDITOR_STATE,+ media: [+ ...EDITOR_STATE.media,+ NARRATION_ASSET,+ { id: "t-1", name: "shot 1 take.mp4", type: "video", duration: 10, origin: "generated" },+ { id: "t-2", name: "shot 2 take.mp4", type: "video", duration: 10, origin: "generated" },+ { id: "t-3", name: "shot 3 take.mp4", type: "video", duration: 10, origin: "generated" },+ ],+ videoTrack: [sceneClip(1, 0, 3), sceneClip(2, 3, 3), sceneClip(3, 6, 3)],+ soundtrack: [{ id: "au-n", asset: NARRATION_ASSET.name, start: 0, len: 9, in: 0, out: 9, volume: 1 }],+};++/** The clip mention refs the composer attaches for "@c1"/"@c2". */+const CLIP_REFS = [+ { scope: "clip", id: "sc-1", name: "clip 1", kind: "video", url: "file:sc-1", duration: 3, handle: "c1" },+ { scope: "clip", id: "sc-2", name: "clip 2", kind: "video", url: "file:sc-2", duration: 3, handle: "c2" },+];++/** What generate_scene returns after planning (mirrors aiTools' note). */+const SCENE_PLANNED = {+ planned: true,+ shots: 5,+ note: "Planned 5 shots over the audio. A plan card below lists the shots for the user, so keep your reply to one short line — don't re-describe the shots or the timing. Just ask them to confirm; when they do, call approve_scene (each shot spends credits, so don't approve on your own).",+};++/** Scene-case interceptor: asserts on generate_scene's arguments and fails+ * the case if the model self-approves the plan. */+function makeSceneSim(check: (args: Record<string, unknown>) => void) {+ return () => (name: string, args: Record<string, unknown>): unknown => {+ if (name === "generate_scene") {+ check(args);+ return SCENE_PLANNED;+ }+ if (name === "approve_scene") throw new Error("approve_scene before the user confirmed");+ return undefined;+ };+}+/** A composer turn as geminiChat's inputFromMessages builds it (keep the* envelope text in sync with geminiChat.ts). */function userTurn(@@ -211,9 +275,7 @@ function userTurn(let full = text;const extra: Item[] = [];const refs = [...(opts?.attachAudio ? [VOICE_REF] : []), ...(opts?.attachRefs ?? [])];- if (refs.length > 0) {- full += `\n\n<attached_assets>\nThe user attached these assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "library" and "stock" assets live outside it until imported; "file" assets came straight from the user's computer and exist only on this message:\n${JSON.stringify(refs)}\n</attached_assets>`;- }+ full += attachedAssetsBlock(refs);if (opts?.attachAudio) {extra.push({ text: `Attached audio "${VOICE_REF.name}":` });extra.push({ type: "input_audio", ...opts.attachAudio });@@ -525,7 +587,7 @@ function cases(audio: { dataBase64: string; mimeType: string }): EvalCase[] {jobId: "job-dogs",addToTimeline: false,note:- "Rendering with Veo — it previews in this chat when it lands, in a minute or two. It stays in the chat until the user places it.",+ "Rendering — it previews in this chat when it lands, in a minute or two. It stays in the chat until the user places it.",},},},@@ -585,6 +647,115 @@ function cases(audio: { dataBase64: string; mimeType: string }): EvalCase[] {},},},+ {+ // A cartoon ask over project audio is one generate_scene plan: the+ // audio rides as the spine, the plan waits for the user's go-ahead,+ // and a 9:16 project takes 9:16 shots.+ name: "cartoon-from-audio-plans-scene",+ input: () => [+ userTurn("turn my narration audio into a smooth 2D cartoon", { state: AUDIO_STATE }),+ ],+ reply: /shot|plan|confirm|approv|cartoon|scene/i,+ requiredTools: ["generate_scene"],+ state: AUDIO_STATE,+ simulate: makeSceneSim((args) => {+ if (String(args.from_audio_asset_id ?? "") !== NARRATION_ASSET.id)+ throw new Error(+ `generate_scene must animate ${NARRATION_ASSET.id}, got ${JSON.stringify(args.from_audio_asset_id)}`+ );+ if (args.aspect !== undefined && args.aspect !== "9:16")+ throw new Error(+ `generate_scene aspect must match the 9:16 project, got ${JSON.stringify(args.aspect)}`+ );+ }),+ },+ {+ // Foreign source audio: the speech language rides audio_language so the+ // on-device recognizer matches, and the audio still spines the cut.+ name: "cartoon-korean-audio-passes-language",+ input: () => [+ userTurn("my narration audio is in Korean — turn it into a smooth 2D cartoon", {+ state: AUDIO_STATE,+ }),+ ],+ reply: /shot|plan|confirm|approv|cartoon|scene|korean/i,+ requiredTools: ["generate_scene"],+ state: AUDIO_STATE,+ simulate: makeSceneSim((args) => {+ if (String(args.from_audio_asset_id ?? "") !== NARRATION_ASSET.id)+ throw new Error("generate_scene must animate the narration audio");+ if (!/^ko(-|$)/i.test(String(args.audio_language ?? "")))+ throw new Error(+ `audio_language must name Korean, got ${JSON.stringify(args.audio_language)}`+ );+ }),+ },+ {+ // A style image attached to the ask anchors the scene's look: its asset+ // id must ride reference_asset_ids into the plan.+ name: "cartoon-style-reference-anchors-look",+ input: () => [+ userTurn("make a cartoon episode from my narration audio in the style of this picture", {+ state: AUDIO_STATE,+ attachRefs: [PHOTO_REFS[0]],+ }),+ ],+ reply: /shot|plan|confirm|approv|cartoon|scene|style/i,+ requiredTools: ["generate_scene"],+ state: AUDIO_STATE,+ simulate: makeSceneSim((args) => {+ const refs = Array.isArray(args.reference_asset_ids)+ ? args.reference_asset_ids.map(String)+ : [];+ if (!refs.includes(PHOTO_ASSETS[0].id))+ throw new Error(+ `reference_asset_ids must carry ${PHOTO_ASSETS[0].id}, got ${JSON.stringify(args.reference_asset_ids)}`+ );+ }),+ },+ {+ // A "how would you" cartoon question is a chat deliverable: approach in+ // words, the scene pipeline untouched (generate_scene would violate).+ name: "cartoon-question-stays-in-chat",+ input: () => [+ userTurn("how would you turn my narration audio into a 2D cartoon?", {+ state: AUDIO_STATE,+ }),+ ],+ reply: /cartoon|scene|shot|animate|style|narration/i,+ state: AUDIO_STATE,+ },+ {+ // Timeline mentions: "@c1 and @c2 are too similar" must map through the+ // clip attachments to videoTrack's sceneShot numbers and revise those+ // exact shots — regenerate_shot with the complaint riding as the note,+ // never a fresh generate_video/generate_scene.+ name: "clip-mentions-redo-their-shots",+ input: () => [+ userTurn(+ "clip 1 and clip 2 are too similar and they don't match the audio. fix them",+ { attachRefs: CLIP_REFS, state: SCENE_DONE_STATE }+ ),+ ],+ reply: /shot|redo|regenerat/i,+ requiredTools: ["regenerate_shot"],+ state: SCENE_DONE_STATE,+ simulate: () => {+ const redone = new Set<number>();+ return (name, args) => {+ if (name === "regenerate_shot") {+ const n = Number(args.n);+ if (n !== 1 && n !== 2) throw new Error(`regenerate_shot ${n} — the mentions were shots 1 and 2`);+ if (!String(args.note ?? "").trim()) throw new Error("regenerate_shot without the user's note");+ redone.add(n);+ return { ok: true, message: `Redoing shot ${n}…` };+ }+ if (name === "generate_video" || name === "generate_scene" || name === "restyle_scene")+ throw new Error(`${name} called — a clip complaint revises its shot, not a new render`);+ return undefined;+ };+ },+ },];}diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsxindex 1aaaf274..8751c914 100644--- a/site/src/cut/components/AssetRefs.tsx+++ b/site/src/cut/components/AssetRefs.tsx@@ -388,17 +388,37 @@ export function MentionTextarea({const backdropRef = useRef<HTMLDivElement>(null);const [caret, setCaret] = useState(0);const [dismissed, setDismissed] = useState<number | null>(null);- const [sel, setSel] = useState(0);+ // The row highlight, remembered with the query it was chosen for — see+ // `sel` below.+ const [selState, setSelState] = useState<{ q?: string; i: number }>({ i: 0 });const mention = useMemo(() => mentionAtCaret(value, caret), [value, caret]);const matches = useMemo(() => {if (!mention || dismissed === mention.start) return [];const q = mention.query.toLowerCase();+ // Best match first, not list order: a typed handle prefix ("c" → c1, c2)+ // beats a name prefix, which beats a substring hit anywhere in the name —+ // otherwise short queries drown the handles in incidental name matches.+ // Ranked once per candidate (the list spans the full stock catalogs and+ // this runs per keystroke), then sorted on the cached rank.+ const rank = (c: AssetRef) => {+ if (c.handle?.startsWith(q)) return 0;+ const name = c.name.toLowerCase();+ return name.startsWith(q) ? 1 : name.includes(q) ? 2 : 3;+ };return candidates- .filter((c) => c.name.toLowerCase().includes(q) || c.handle?.startsWith(q))- .slice(0, 8);+ .map((c) => ({ c, r: rank(c) }))+ .filter((x) => x.r < 3)+ .sort((a, b) => a.r - b.r)+ .slice(0, 8)+ .map((x) => x.c);}, [mention, dismissed, candidates]);const open = matches.length > 0;+ // Each keystroke re-ranks the list, so a highlight chosen under a previous+ // query derives back to the best (first) match instead of holding a stale+ // arrow/hover position.+ const sel = selState.q === mention?.query ? selState.i : 0;+ const setSel = (i: number) => setSelState({ q: mention?.query, i });const selIndex = Math.min(sel, matches.length - 1);const syncCaret = () => {diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 1c8994ef..5e38fc45 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -871,6 +871,7 @@ export function Timeline() {key={span.clip.id}span={span}prevOverlap={spans[i - 1]?.transitionOut ?? 0}+ mention={`@c${i + 1}`}pps={pps}selected={selKeys.has(`clip:${span.clip.id}`)}drag={laneDrag?.kind === "clip" && laneDrag.id === span.clip.id ? laneDrag : null}@@ -1391,6 +1392,7 @@ function Playhead({function ClipView({span,prevOverlap,+ mention,pps,selected,drag,@@ -1407,6 +1409,9 @@ function ClipView({* seconds — the room the incoming transition block claims on this clip's* left. This clip's own `span.transitionOut` claims the right. */prevOverlap: number;+ /** The clip's chat mention token ("@c2"), shown on hover so the user can+ * point the assistant at this exact segment. */+ mention: string;pps: number;selected: boolean;/** This clip's live drag when it is the one being carried (ghost mode). */@@ -1515,10 +1520,14 @@ function ClipView({// glance, not just from the thin border.<div className="pointer-events-none absolute inset-0 z-[1] bg-[#0a84ff]/25" />)}- {drag && (+ {drag ? (<span className="tl-dur-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white">{(Math.round(span.len * 10) / 10).toFixed(1)}s</span>+ ) : (+ <span className="tl-mention-chip pointer-events-none absolute top-1 left-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] text-white opacity-0 transition-opacity group-hover:opacity-100">+ {mention}+ </span>)}{asset.type === "video" && (<MuteChipdiff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex b723b6c9..01d59628 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -39,6 +39,13 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {const duration = totalDuration(s.clips);const assetById = new Map(s.assets.map((a) => [a.id, a]));const subtitleTracks = subtitleLaneCount(s.subtitles);+ // Scene-run lineage: which plan shot (1-based, what regenerate_shot takes)+ // placed each clip, so "fix this clip" maps straight to a shot revision.+ const shotByClip = new Map(+ (s.genvideo?.shots ?? []).flatMap((sh, i) =>+ sh.timelineClipId ? [[sh.timelineClipId, { n: i + 1, still: sh.status === "failed" }] as const] : []+ )+ );const selection = (() => {if (!s.selection) return null;@@ -113,6 +120,13 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {muted: sp.clip.muted,framing: sp.clip.fit ?? "fit",speed: r(sp.clip.speed ?? 1),+ // The generated scene shot this clip came from — sceneShot is the+ // 1-based number regenerate_shot takes; heldStill marks a render that+ // fell back to its keyframe.+ ...(() => {+ const sh = shotByClip.get(sp.clip.id);+ return sh ? { sceneShot: sh.n, ...(sh.still ? { sceneShotHeldStill: true } : {}) } : {};+ })(),// Track 0 is free-positioned: empty stretches play black....(() => {const prevEnd = index === 0 ? 0 : spans[index - 1].start + spans[index - 1].len;diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 1a2218f0..560c540b 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -3,8 +3,9 @@import { apiFetch, apiJson } from "./api";import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";import { chatOwner, tagChatAsset } from "./chatAssets";-import { useGenerate, type VideoGenOptions } from "./generate";+import { useGenerate, type VideoAttempt, type VideoGenOptions } from "./generate";import { useGenScene } from "./genScene";+import { anchorRefused } from "./genvideo/shotAttempts";import {addTemplateToProject,createLibraryFolder,@@ -608,34 +609,39 @@ export async function runAiTool(const signedIn = gen.signedIn ?? (await gen.probeNow());if (!signedIn) throw new ToolError("Sign in to Donkey to generate video.");- // Veo renders can outrun the assistant tool bridge's 2-minute cap, so+ // Video renders can outrun the assistant tool bridge's 2-minute cap, so// don't block: start the job and let its completion place the clip.const refs =input.reference_asset_id === undefined? []: resolveRefAssets([input.reference_asset_id]);- const veoOpts: Omit<VideoGenOptions, "onDone"> = {- tier: input.tier === "high" ? "high" : "fast",- durationSeconds: isNum(input.duration_seconds)- ? clamp(Math.round(input.duration_seconds), 4, 8)- : undefined,+ // The model renders the whole clip with audio in one pass and picks its+ // own length (up to ~10s) — aspect is the only knob.+ const baseOpts: Omit<VideoGenOptions, "onDone"> = {...(input.aspect === "16:9" || input.aspect === "9:16" ? { aspect: input.aspect } : {}),- ...(input.resolution === "720p" || input.resolution === "1080p"- ? { resolution: input.resolution }- : {}),};+ // A one-off render walks the same identity ladder as a scene shot:+ // seed image first (the strongest anchor), the picture as an identity+ // reference second, text-only last — so a safety-blocked anchor+ // degrades the render instead of killing it. The text rung is gated+ // exactly like a scene shot's: it runs only when the provider refused+ // the image anchor itself. An ordinary failure (timeout, 5xx) must+ // fail the job — a render that never saw the user's picture is not a+ // success to show them.+ const asReference = (anchor: AssetRef): VideoAttempt => ({+ prompt,+ opts: { ...baseOpts, referenceImages: [anchor] },+ });+ const textOnly: VideoAttempt = { prompt, opts: { ...baseOpts }, gate: anchorRefused };// "Animate this image": the referenced frame is the product, so it seeds- // the render untouched — no image-model redesign in between.+ // the render untouched — no image-model redesign in between, and no+ // text-only rung (a render without the image isn't what was asked).if (refs.length > 0 && input.animate_reference === true) {return {- ...launchVeoJob(projectId, prompt, input, {- ...veoOpts,- refs: [refs[0]],- composeRefs: false,- // The most Veo permits with an image input; the seed carries the- // subject, so a person-safety downgrade beats losing it.- personGeneration: "ALLOW_ADULT",- }),+ ...launchVideoJob(projectId, input, [+ { prompt, opts: { ...baseOpts, refs: [refs[0]], composeRefs: false } },+ asReference(refs[0]),+ ]),note:"Animating the referenced image as the literal opening frame — the clip previews in this chat when it lands, in a minute or two.",};@@ -661,24 +667,24 @@ export async function runAiTool(: undefined;if (stillAsset) {return {- ...launchVeoJob(projectId, prompt, input, {- ...veoOpts,- refs: [refFromAsset(stillAsset)],- composeRefs: false,- // The most Veo permits with an image input; the seed carries- // the subject, so a person-safety downgrade beats losing it.- personGeneration: "ALLOW_ADULT",- }),+ ...launchVideoJob(projectId, input, [+ { prompt, opts: { ...baseOpts, refs: [refFromAsset(stillAsset)], composeRefs: false } },+ asReference(refs[0]),+ textOnly,+ ]),stillAssetId: stillAsset.id,note:"Designed the opening frame from the reference first (the image card above the render), then started the video from that exact frame — it previews in this chat when it lands, in a minute or two.",};}+ return launchVideoJob(projectId, input, [+ { prompt, opts: { ...baseOpts, refs } },+ asReference(refs[0]),+ textOnly,+ ]);}- return launchVeoJob(projectId, prompt, input, {- ...veoOpts,- ...(refs.length > 0 ? { refs } : {}),- });+ // No reference: text is the whole request, so the single rung runs ungated.+ return launchVideoJob(projectId, input, [{ prompt, opts: { ...baseOpts } }]);}case "generate_character_video": {@@ -694,17 +700,19 @@ export async function runAiTool(const signedIn = gen.signedIn ?? (await gen.probeNow());if (!signedIn) throw new ToolError("Sign in to Donkey to generate video.");return {- ...launchVeoJob(projectId, characterPrompt(character.persona!, line), input, {- tier: input.tier === "high" ? "high" : "fast",- durationSeconds: isNum(input.duration_seconds)- ? clamp(Math.round(input.duration_seconds), 4, 8)- : undefined,- aspect: character.aspect,- // The character's own clip seeds the render so the same person- // delivers the line — composing would swap the face, so it rides raw.- refs: [refFromStockVideo(character)],- composeRefs: false,- }),+ ...launchVideoJob(projectId, input, [+ {+ prompt: characterPrompt(character.persona!, line),+ opts: {+ aspect: character.aspect,+ // The character's own clip seeds the render so the same person+ // delivers the line — composing would swap the face, so it rides+ // raw, and there is no weaker rung: another anchor is another face.+ refs: [refFromStockVideo(character)],+ composeRefs: false,+ },+ },+ ]),character: character.id,};}@@ -729,6 +737,11 @@ export async function runAiTool(if (!asset) throw new ToolError(`No project asset with id ${fromAudio}.${hint}`);if (asset.type !== "audio")throw new ToolError(`"${asset.name}" is ${asset.type}, not audio — from_audio_asset_id must be the audio to animate.${hint}`);+ // The scene transcriber keys its recognizer off asset.language; a+ // mismatched recognizer turns foreign speech into garbage the plan+ // then depicts.+ const lang = typeof input.audio_language === "string" ? input.audio_language.trim() : "";+ if (lang) s.updateAsset(fromAudio, { language: lang });}// Plan up to the shot list and stop; approve_scene starts the paid renders.// Tag every asset the run creates to the asking chat, so intermediates and@@ -760,6 +773,12 @@ export async function runAiTool(return { rendering: true, note: res.message };}+ case "cancel_scene": {+ const res = useGenScene.getState().cancel();+ if (!res.ok) throw new ToolError(res.message);+ return { stopped: true, note: res.message };+ }+case "regenerate_shot": {if (!isNum(input.n)) throw new ToolError("n (the 1-based shot number) is required.");const note = typeof input.note === "string" && input.note.trim() ? input.note.trim() : undefined;@@ -1615,15 +1634,14 @@ function addVideoTrackClip(return { added: true, clipId, index: at };}-/** Start a Veo render — the shared shape of generate_video and- * generate_character_video: the job previews as a live chat card, the landed- * asset files under the asking chat, and it goes onto the timeline only when- * the model asked. Returns the tool output. */-function launchVeoJob(+/** Start a video render — the shared shape of generate_video and+ * generate_character_video: one job (and one chat card) spans the ladder's+ * fallback rungs, the landed asset files under the asking chat, and it goes+ * onto the timeline only when the model asked. Returns the tool output. */+function launchVideoJob(projectId: string,- prompt: string,input: Record<string, unknown>,- opts: Omit<VideoGenOptions, "onDone">+ attempts: VideoAttempt[]) {const addToTimeline = wantsTimeline(input, "index");const index = promptedIndex(input);@@ -1632,8 +1650,7 @@ function launchVeoJob(// creation, so neither the job row nor the landed asset ever touches the// Video panel — including a render that errors and lands no asset.const chatId = chatOwner();- const { jobId } = useGenerate.getState().generateVideo(projectId, prompt, {- ...opts,+ const { jobId } = useGenerate.getState().generateVideoLadder(projectId, attempts, {...(chatId ? { chatId } : {}),onDone: (asset) => {if (addToTimeline) addVideoTrackClip(asset.id, index);@@ -1645,7 +1662,7 @@ function launchVeoJob(jobId,addToTimeline,note:- "Rendering with Veo — it previews in this chat when it lands, in a minute or two" ++ "Rendering — it previews in this chat when it lands, in a minute or two" +(addToTimeline? ", and goes onto the timeline.": ". It stays in the chat until the user places it."),diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex 1dc7839a..33d99027 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -6,7 +6,7 @@ import { fetchLibrary, libraryMediaUrl, type LibraryAsset } from "./library";import type { StockImage, StockVideo } from "./stock";import { STOCK_IMAGES } from "./stockManifest";import { STOCK_VIDEOS } from "./stockVideoManifest";-import { useEditor } from "./store";+import { getClipSpans, useEditor } from "./store";import type { MediaAsset } from "./types";// One reference model for every piece of media in the app. A ref names an@@ -26,8 +26,11 @@ import type { MediaAsset } from "./types";// resolves tokens back to refs on send./** "file" marks a transient ref made from a desktop drop (a text file riding a- * composer) — it lives only in the composer's state, never in a catalog. */-export type AssetRefScope = "project" | "library" | "stock" | "file";+ * composer) — it lives only in the composer's state, never in a catalog.+ * "clip" names a clip on the timeline's video track (id = the clip id, url =+ * its source media), so chat can talk about segments of the cut, not just+ * assets. */+export type AssetRefScope = "project" | "library" | "stock" | "file" | "clip";export type AssetRefKind = "video" | "audio" | "image" | "text";export interface AssetRef {@@ -313,22 +316,49 @@ let libraryLoad: Promise<LibraryAsset[]> | null = null;/** The open project's media as refs with their session handles, assigned in* media order — `v1` videos, `i1` generated stills, `a1` audio — so a prompt* can say `@v2` instead of the full name. Handles are derived, never stored:- * anything that shows one resolves it from the current asset list. */+ * anything that shows one resolves it from the current asset list.+ * Chat-owned assets (origin "chat") are a run's internals — character sheets,+ * keyframes, takes — visible nowhere the user works, so they don't become+ * candidates; a take placed on the timeline is reachable as its clip (@c2). */export function projectRefs(assets: MediaAsset[]): AssetRef[] {const counters = { v: 0, i: 0, a: 0 };- return assets.map((a) => {- const prefix = a.type === "image" ? "i" : a.type === "video" ? "v" : "a";- counters[prefix] += 1;- return { ...refFromAsset(a), handle: `${prefix}${counters[prefix]}` };- });+ return assets+ .filter((a) => a.origin !== "chat")+ .map((a) => {+ const prefix = a.type === "image" ? "i" : a.type === "video" ? "v" : "a";+ counters[prefix] += 1;+ return { ...refFromAsset(a), handle: `${prefix}${counters[prefix]}` };+ });+}++/** The timeline's video-track clips as refs — `c1`, `c2`… in timeline order —+ * so a prompt can point at a segment of the cut ("@c2 doesn't match the+ * audio"). Handles are derived from the current order, never stored; the+ * timeline shows each clip's token on hover. */+export function clipRefs(+ clips: Parameters<typeof getClipSpans>[0],+ assets: MediaAsset[]+): AssetRef[] {+ return getClipSpans(clips, assets).map((sp, i) => ({+ scope: "clip",+ id: sp.clip.id,+ name: `clip ${i + 1}`,+ kind: sp.asset.type === "image" ? "image" : "video",+ url: sp.asset.url,+ duration: sp.len,+ handle: `c${i + 1}`,+ }));}-/** Everything referenceable right now, in resolution order: the open project's- * media, then the shared library, then the stock catalog. Names are unique- * within the list (first scope wins) so a mention resolves to one asset.- * Library items mention by name; stock ids are already short (`@nature-dunes`). */+/** Everything referenceable right now, in resolution order: the timeline's+ * clips first (what's in front of the user — a bare `@` leads with the cut),+ * then the open project's media, the shared library, and the stock catalog.+ * Names are unique within the list (first scope wins) so a mention resolves+ * to one asset. Library items mention by name; stock ids are already short+ * (`@nature-dunes`). */export function useRefCandidates(): AssetRef[] {const assets = useEditor((s) => s.assets);+ const clips = useEditor((s) => s.clips);const [lib, setLib] = useState<LibraryAsset[]>(libraryCache ?? []);useEffect(() => {@@ -347,6 +377,7 @@ export function useRefCandidates(): AssetRef[] {const seen = new Set<string>();const out: AssetRef[] = [];for (const ref of [+ ...clipRefs(clips, assets),...project,...lib.map(refFromLibrary),...STOCK_IMAGES.map(refFromStock),@@ -358,7 +389,7 @@ export function useRefCandidates(): AssetRef[] {out.push(ref);}return out;- }, [assets, lib]);+ }, [assets, clips, lib]);}/** The prompt token for an asset name: `@name`, quoted when it has spaces. */diff --git a/site/src/cut/lib/geminiChat.ts b/site/src/cut/lib/geminiChat.tsindex b0b08250..c5e4f864 100644--- a/site/src/cut/lib/geminiChat.ts+++ b/site/src/cut/lib/geminiChat.ts@@ -2,7 +2,7 @@import type { UIMessage, UIMessageChunk } from "ai";import { geminiModelRoles } from "@/lib/inference/gemini-models";-import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "@/cut/server/ai/catalog";+import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "@/cut/server/ai/catalog";import { buildAiContext } from "./aiContext";import { runAiTool } from "./aiTools";import { normalizeRef } from "./assetRef";@@ -168,7 +168,7 @@ async function inputFromMessages(messages: UIMessage[]): Promise<Item[]> {if (m.role === "user") {const meta = (m.metadata as { attachments?: unknown[] } | undefined)?.attachments;if (Array.isArray(meta) && meta.length > 0) {- text += `\n\n<attached_assets>\nThe user attached these assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "library" and "stock" assets live outside it until imported; "file" assets came straight from the user's computer and exist only on this message:\n${JSON.stringify(meta)}\n</attached_assets>`;+ text += attachedAssetsBlock(meta);if (m === lastUser) {// Best-effort: a ref that no longer resolves (deleted asset, stale// object URL) degrades this turn to metadata-only instead of failing.diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 424606d5..99187797 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -287,13 +287,10 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_video",description:- "Generate an AI video clip from a text prompt (Donkey's hosted Veo model) — the default for any video ask: \"generate/make a video of/about X\" means ONE clip from this tool, even though it sounds whole. Reach for generate_scene only when they name a narrated multi-shot production (a story, episode, or narrated short). When the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the video. reference_asset_id anchors the render on one project image or video: by default the tool first designs the opening frame from it with the image model (that still previews in this chat), then animates that exact frame — so tell the user it designs the frame, then renders. When the user wants the referenced image itself brought to life (\"animate this image/picture\"), pass animate_reference:true — the image becomes the literal first frame, unchanged, and the prompt describes only the motion. The render takes a minute or two and the tool RETURNS as soon as it's started — the clip previews as a live card in this chat when it finishes. Pass add_to_timeline:true (or an index) only when they asked for it in the cut; otherwise the user drags it in from the card. Needs the user signed in to Donkey (spends their credits).",+ "Generate an AI video clip from a text prompt (Donkey's hosted video model: one pass, audio included, 720p, up to ~10s — the model picks the length) — the default for any video ask: \"generate/make a video of/about X\" means ONE clip from this tool, even though it sounds whole. Reach for generate_scene only when they name a narrated multi-shot production (a story, episode, or narrated short). When the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the video. reference_asset_id anchors the render on one project image or video: by default the tool first designs the opening frame from it with the image model (that still previews in this chat), then animates that exact frame — so tell the user it designs the frame, then renders. When the user wants the referenced image itself brought to life (\"animate this image/picture\"), pass animate_reference:true — the image becomes the literal first frame, unchanged, and the prompt describes only the motion. A safety-blocked or rejected anchor degrades the render on its own (identity reference, then text-only — the same ladder scene shots walk), so never resubmit a failed render with weaker inputs yourself. The render takes a minute or two and the tool RETURNS as soon as it's started — the clip previews as a live card in this chat when it finishes. Pass add_to_timeline:true (or an index) only when they asked for it in the cut; otherwise the user drags it in from the card. Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({prompt: str("The shot to generate — describe motion, subject, and mood"),- tier: { type: "string", enum: ["fast", "high"], description: "fast = quicker/cheaper (default), high = best quality" },- duration_seconds: num("Clip length 4–8 seconds (default 8)"),aspect: { type: "string", enum: ["16:9", "9:16"], description: "Clip shape (default: the project aspect)" },- resolution: { type: "string", enum: ["720p", "1080p"], description: "Output detail (default 720p)" },reference_asset_id: str("One project asset id (image or video) the clip's opening frame is designed from"),animate_reference: bool("The referenced image IS the opening frame: animate it directly, unchanged, skipping the frame-design step (use when the user says to animate that image)"),add_to_timeline: bool("Insert the clip on the video track when it lands (default false — it stays on its chat card until the user asks)"),@@ -303,12 +300,10 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_character_video",description:- "Generate a UGC-style selfie clip of a stock talking character speaking a line you write (Donkey's hosted Veo model). Pick a character id from stock_search kind:\"character\" — each has a persona and look; the same person then delivers the line to camera. Like generate_video this RETURNS IMMEDIATELY and the clip previews in this chat a minute or two later; add_to_timeline:true places it when it lands. Needs the user signed in to Donkey (spends their credits).",+ "Generate a UGC-style selfie clip of a stock talking character speaking a line you write (Donkey's hosted video model). Pick a character id from stock_search kind:\"character\" — each has a persona and look; the same person then delivers the line to camera. Like generate_video this RETURNS IMMEDIATELY and the clip previews in this chat a minute or two later; add_to_timeline:true places it when it lands. Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({character_id: str("Talking-character id from stock_search"),line: str("What the character says, spoken to camera"),- tier: { type: "string", enum: ["fast", "high"], description: "fast = quicker/cheaper (default), high = best quality" },- duration_seconds: num("Clip length 4–8 seconds (default 8)"),add_to_timeline: bool("Insert the clip on the video track when it lands (default false — it stays on its chat card until the user asks)"),index: num("Insert position on the video track (passing it implies add_to_timeline)"),}, ["character_id", "line"]),@@ -316,10 +311,11 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_scene",description:- "Generate a narrated, multi-shot cut assembled on the timeline — script, voiceover, and several shots — from a brief, or animate audio already in the project. Use this only when the user names that kind of production (\"tell a story about…\", \"turn this into a narrated 20-second short\", \"an episode\"); a plain \"generate/make a video of/about X\" is a single clip — generate_video, not this. It writes a script, voices it, breaks it into shots, then RETURNS the shot plan and STOPS: get the user's go-ahead and call approve_scene before the shots render, because each shot spends credits. Pass from_audio_asset_id to animate an audio spine the project already has (a voiceover, recording, or song → shots tiled over it) instead of writing a new script. The look is derived from the brief and any references and can be anything — cinematic live-action, anime, documentary, product ad, cartoon; never assume a genre, let the brief decide, and describe the look by its visual traits rather than naming a real franchise, show, or artist (even one a reference resembles) — the user may not want it and the generator rejects trademarked names. Needs the user signed in to Donkey (spends credits).",+ "Generate a narrated, multi-shot cut assembled on the timeline — script, voiceover, and several shots — from a brief, or animate audio already in the project. Use this only when the user names that kind of production (\"tell a story about…\", \"turn this into a narrated 20-second short\", \"an episode\"); a plain \"generate/make a video of/about X\" is a single clip — generate_video, not this. It writes a script, voices it, breaks it into shots, then RETURNS the shot plan and STOPS: get the user's go-ahead and call approve_scene before the shots render, because each shot spends credits. Pass from_audio_asset_id to animate an audio spine the project already has (a voiceover, recording, or song → shots tiled over it) instead of writing a new script. Read the scene-productions skill before your first call — it covers the brief and look, references, aspect, and the from-audio flow. Needs the user signed in to Donkey (spends credits).",inputSchema: obj({brief: str("What the video is about — the story or subject. Omit only when animating existing audio."),from_audio_asset_id: str("Animate this project audio asset (id from media) — shots tile over it instead of a new script"),+ audio_language: str("BCP-47 language of the from_audio asset's speech (e.g. ko-KR). REQUIRED with from_audio_asset_id whenever the speech is not English — the on-device transcriber picks its recognizer from it, and the wrong recognizer garbles every shot planned over the audio"),target_seconds: num("Rough total length in seconds, 6–90 (default ~24)"),aspect: { type: "string", enum: ["9:16", "16:9"], description: "Output shape (default: the project aspect)" },style: str("Optional look to steer the whole video (e.g. 'moody neon, handheld'); usually left to the brief"),@@ -336,10 +332,16 @@ export const AI_TOOLS: AiToolDef[] = ["Approve the pending generate_scene shot plan and start rendering. The shots render in the background and land on the timeline as they finish. Call this only when the user confirms (\"go\", \"do it\", \"looks good\") — approving spends credits per shot.",inputSchema: obj({}),},+ {+ name: "cancel_scene",+ description:+ "Stop the scene generation running in this project — planning or rendering halts immediately and the plan is discarded. Clips already placed stay on the timeline; credits already spent are not refunded. Call it when the user wants the run stopped, or to clear the way for a new generate_scene.",+ inputSchema: obj({}),+ },{name: "regenerate_shot",description:- "Redo one shot of the generated scene by its number (1-based), optionally nudging it (\"wider\", \"at night\", \"more energetic\"). Only valid after a scene has been generated.",+ "Redo one shot of the generated scene by its number (1-based), optionally nudging it (\"wider\", \"at night\", \"more energetic\"). It swaps the shot's clip on the timeline by itself — never delete the clip first. Only valid after a scene has been generated.",inputSchema: obj({ n: num("Shot number, 1-based"), note: str("Optional change to apply to that shot") }, ["n"]),},{@@ -437,7 +439,7 @@ export const AI_TOOLS: AiToolDef[] = [{name: "subtitles_generate",description:- "Transcribe the cut on-device (Apple speech) and create subtitle captions on a subtitle track (the active one unless `track` says otherwise; other tracks keep their captions). Runs in the background; returns when finished. If no speech is found, no subtitles are added.",+ "Transcribe the cut on-device (Apple speech) and create subtitle captions on a subtitle track (the active one unless `track` says otherwise; other tracks keep their captions) — it WRITES captions the user sees, so call it only when they asked for subtitles; to just hear what an audio asset says, listen_audio. Runs in the background; returns when finished. If no speech is found, no subtitles are added.",inputSchema: obj({locale: str("Speech language as BCP-47 like en-US (default: the track's language)"),track: num("Subtitle track to write, 0-based (default: the active track)"),@@ -446,7 +448,7 @@ export const AI_TOOLS: AiToolDef[] = [{name: "captions_generate",description:- "Transcribe (if needed) then rewrite one subtitle track's captions into punchy social-video captions — short lines that fit inside the video frame (they may wrap onto two lines but never overflow), a few emoji, a curiosity-hook opener. style: clean | hook | punchy (default hook). Cue timings are preserved.",+ "Transcribe (if needed) then REWRITE one subtitle track's captions into punchy social-video captions — short lines that fit inside the video frame (they may wrap onto two lines but never overflow), a few emoji, a curiosity-hook opener. style: clean | hook | punchy (default hook). Cue timings are preserved. It replaces the track's existing text wholesale — for a targeted edit (removing filler words, fixing one line), edit the cues with update_cue instead.",inputSchema: obj({style: str("Caption style: clean, hook, or punchy"),track: num("Subtitle track to rewrite, 0-based (default: the active track)"),@@ -713,10 +715,18 @@ Two ways to get footage the user doesn't have: bundled stock (local, free) and hStock: stock_search browses the bundled catalogs — footage clips and images in 8 categories plus ~20 UGC talking characters — matching prompts, categories, and tags. stock_add imports an item into the project as a chat card; add_to_timeline:true (or a start) also drops it on the timeline when the user asked. In the UI these live in the Video and Image tabs beside the generators; clicking a stock tile seeds the generate panel with its prompt.Generation:- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: project aspect) and 1K/2K/4K. The still previews in the chat; placed (add_to_timeline:true or an index) it rides video track 0 as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.-- generate_video(prompt, tier?, duration_seconds?, aspect?, resolution?, reference_asset_id?, add_to_timeline?, index?): a hosted Veo model renders a 4–8s clip with audio. tier "fast" (default) is quicker/cheaper, "high" is best quality. With reference_asset_id it stages: the image model designs the opening frame from the reference first (that still previews in the chat), then Veo animates that exact frame. The render takes a minute or two, so the tool returns once it's started and the clip previews in the chat when it finishes (on the timeline only when asked) — tell the user it's rendering. Don't call it again for the same shot while one is in flight.+- generate_video(prompt, aspect?, reference_asset_id?, add_to_timeline?, index?): the hosted video model renders a short clip with audio in one pass — 720p, up to ~10s, the model picks the length (no duration knob; the user trims the clip on the timeline). With reference_asset_id it stages: the image model designs the opening frame from the reference first (that still previews in the chat), then the video model animates that exact frame. The render takes a minute or two, so the tool returns once it's started and the clip previews in the chat when it finishes (on the timeline only when asked) — tell the user it's rendering. Don't call it again for the same shot while one is in flight.- generate_character_video(character_id, line, …): a stock talking character delivers a line to camera, same async render as generate_video. Characters come from stock_search kind:"character" — each has a persona; you write the line (chat deliverable rules apply: asked for "a script", write it in chat first).References: users attach images/clips to their message or the generate panels; project asset ids (see \`media\` in editor_state, including attachments — OS drops become project assets) pass through reference_asset_ids / reference_asset_id. Images draw from any number of references; video stages one reference into a designed opening frame and animates it. When the user says "use this clip/image", pass the reference — don't just describe it in the prompt.-If generation fails with a sign-in or credits message, relay that plainly — it needs the user signed in to Donkey with credits; it is not a local fallback. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out.`,+If generation fails with a sign-in or credits message, relay that plainly — generation needs a Donkey sign-in with credits. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out. A narrated multi-shot production is generate_scene — read the scene-productions skill before planning one, especially from an audio file or in a named style.`,++ "scene-productions": `# Scene productions (generate_scene)+generate_scene plans a narrated multi-shot cut; approve_scene renders it. Planning is free; every shot render spends credits, so present the plan card and wait for the user's go-ahead — never approve on your own. Per shot, the pipeline already guarantees: smooth continuous motion (no stop-motion or held poses), zero on-screen text, character consistency via a style bible plus reference sheets, gapless non-overlapping placement of shots/voice/music, shot audio muted under the audio spine, and a reviewer that retakes failed renders.+Aspect: every shot renders at the plan's aspect, frozen from the project when approved. Check project.aspect first; when the user wants a specific format, set_aspect BEFORE approve_scene. A 9:16 project takes 9:16 shots — pass aspect to a generation tool only to match the project. Changing aspect after approval re-renders nothing.+Look: the user's style reference is the strongest anchor — pass attached images/clips as reference_asset_ids; they anchor the style bible and every shot. A reference contributes the LOOK; when the user wants its pictured character or place in the video itself, say that in the brief — otherwise the pipeline designs a fresh cast in the reference's technique. The brief describes the same look in plain visual traits so words and image agree; with no reference, build the trait wording from the ask (a simple children's cartoon → "flat hand-drawn 2D animation, clean thick outlines, simple rounded characters, soft colors, gentle fluid motion"). Describe any show, franchise, or artist by traits — the generator rejects trademarked names. Name recurring wardrobe and props in the brief so independently rendered shots match.+From an audio file (the audio rides the timeline as the spine): listen_audio first and extract every fact — who speaks, who appears, each topic in order. Then generate_scene with from_audio_asset_id PLUS a brief carrying those facts; the brief outranks transcript mishears. Speech in another language: write the brief's facts in English and pass audio_language so the on-device transcriber uses the right recognizer. Long silence or music in the source becomes filler shots — suggest trimming first (detect_silence); shots tile the full asset length, so warn on long files (many paid shots).+Scope: deliver exactly what was asked — no subtitle tracks, titles, or extra music on top (brief mode lays its own soft music bed; from-audio mode adds none). One scene run at a time — cancel_scene stops the active one when the user wants it gone or replaced.+After renders land: spot-check with capture_frame or watch_video (aspect, style, motion). The user may point at clips by @ token ("@c2 doesn't match the audio") — the clip attachment's id maps to videoTrack in editor_state, whose sceneShot is the n regenerate_shot takes; carry their complaint as its note, and check the audio itself with listen_audio on the spine asset (subtitles_generate would write a caption track nobody asked for). A shot that failed all its takes holds a still — repair it ONLY with regenerate_shot n (it re-runs the shot's identity ladder and swaps the clip in place); deleting the still or rendering a replacement with generate_video orphans the shot and loses the run's identity anchors and review. A whole-look change is restyle_scene: every shot re-renders, so confirm first. Undo removes clips; spent credits stay spent.`,"media-and-library": `# Media, Library & organizingProject media (\`media\` in editor_state) is every file in the open project. The Media panel shows the user's own imports — assets with no origin tag; created media (origin generated, voiceover, stock, chat, freeze, recording) lives where it was made until filed away.@@ -745,10 +755,22 @@ Rules:- Edits are undoable (unlimited undo), so prefer doing over asking; only ask when the request is genuinely ambiguous. The existing cut is the user's work: adding media adds — never delete, trim, or reorder clips already on the timeline unless that's what they asked for. Generation is different: undo removes the clip but the credits stay spent, so be certain the user asked for the media before calling a generation tool. Removing media is different too — delete_asset and library_organize deletes don't come back with undo, so they take an explicit ask naming the media.- Times are seconds. The frame is the project's aspect: 1080×1920 (9:16) or 1920×1080 (16:9) — see project.aspect in editor_state.- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.-- 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.+- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and never invent a spoken transcript.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the shot list — confirm with the user, then call approve_scene, since it renders many paid shots (regenerate_shot / restyle_scene revise it after).- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen; listen_audio plays a project audio asset; detect_silence finds dead air; capture_frame shows the one rendered frame at the playhead. The watching-and-cutting skill has the flow.`;}export const AI_SKILL_INDEX = Object.keys(AI_SKILLS);++/** The <attached_assets> block a user turn carries when it has attachment+ * refs. One builder serves hosted chat, the engine chat, and the eval mirror,+ * so the doctrine — especially the clip-scope steering — can never drift+ * between them. Empty when there is nothing attached. */+export function attachedAssetsBlock(refs: unknown[]): string {+ if (refs.length === 0) return "";+ const clipHint = refs.some((r) => (r as { scope?: string }).scope === "clip")+ ? '\nA "clip" attachment means the user is pointing at that segment of the cut: diagnose with read-only looks (watch_video, listen_audio — never subtitles_generate, which writes captions), then revise the clip in place — regenerate_shot for its sceneShot, edit tools otherwise — without deleting it.'+ : "";+ return `\n\n<attached_assets>\nThe user attached these assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "clip" assets are clips on the timeline's video track — the id matches videoTrack in editor_state (a scene-run clip carries its sceneShot number there); "library" and "stock" assets live outside the project until imported; "file" assets came straight from the user's computer and exist only on this message:\n${JSON.stringify(refs)}${clipHint}\n</attached_assets>`;+}diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.tsindex 61495118..ee936557 100644--- a/site/src/cut/server/http/ai.ts+++ b/site/src/cut/server/http/ai.ts@@ -13,7 +13,7 @@ import {} from "../ai/bridge";import { rewriteCaptions, translateCaptions } from "../ai/captions";import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";-import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "../ai/catalog";+import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "../ai/catalog";interface ChatBody {messages: UIMessage[];@@ -339,10 +339,7 @@ export const aiApi = {const sessionKey = crypto.randomUUID();const userText = lastUserText(body.messages);const attachments = lastUserAttachments(body.messages);- const attachBlock = attachments.length- ? `\n\n<attached_assets>\nThe user attached these media assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "library" and "stock" assets live outside it until imported:\n${JSON.stringify(attachments)}\n</attached_assets>`- : "";- const prompt = `${userText}${attachBlock}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;+ const prompt = `${userText}${attachedAssetsBlock(attachments)}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;const stream = createUIMessageStream({execute: async ({ writer }) => {