Open source CapCut alternative.
TypeScript
feat(site): add_clip tool places project assets on the timeline like a drag [rebuild]
David Le459c8481c4ca
diff --git a/site/scripts/eval-cut-chat.ts b/site/scripts/eval-cut-chat.tsindex 9e236e4f..916627e6 100644--- a/site/scripts/eval-cut-chat.ts+++ b/site/scripts/eval-cut-chat.ts@@ -77,6 +77,22 @@ const VOICE_ASSET = {origin: "voiceover",};+/** Photos dropped on the chat composer: imported as plain user media (no+ * origin), referenced by the message's attachment metadata. */+const PHOTO_ASSETS = [+ { id: "a-i1", name: "dog-park.jpg", type: "image" },+ { id: "a-i2", name: "dog-beach.jpg", type: "image" },+];++const PHOTO_REFS = PHOTO_ASSETS.map((a, i) => ({+ scope: "project",+ id: a.id,+ name: a.name,+ kind: "image",+ url: `http://127.0.0.1:41417/media/${a.id}.jpg`,+ handle: `i${i + 1}`,+}));+/** Hand-built snapshot mirroring buildAiContext's shape (aiContext.ts): one* 12.5s video clip on track 0, the voiceover on the soundtrack, no captions.* Keep the keys in sync with buildAiContext when its shape changes. */@@ -95,6 +111,7 @@ const EDITOR_STATE = {media: [{ id: "a-v1", name: "beach.mp4", type: "video", duration: 20 },VOICE_ASSET,+ ...PHOTO_ASSETS,],mediaTruncated: false,videoTrack: [@@ -154,11 +171,17 @@ const VOICE_REF = {/** A composer turn as geminiChat's inputFromMessages builds it (keep the* envelope text in sync with geminiChat.ts). */-function userTurn(text: string, opts?: { attachAudio?: { dataBase64: string; mimeType: string } }): Item {+function userTurn(+ text: string,+ opts?: { attachAudio?: { dataBase64: string; mimeType: string }; attachRefs?: unknown[] }+): Item {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>`;+ }if (opts?.attachAudio) {- 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([VOICE_REF])}\n</attached_assets>`;extra.push({ text: `Attached audio "${VOICE_REF.name}":` });extra.push({ type: "input_audio", ...opts.attachAudio });}@@ -196,6 +219,32 @@ function cases(audio: { dataBase64: string; mimeType: string }): EvalCase[] {input: () => [userTurn("how long is my cut right now?")],reply: /12[.,]?5?/,},+ {+ // The "drag photos in, ask for a movie" flow: an explicit ask to put+ // attached media in the cut must reach add_clip for each photo. Styling+ // follow-ups a movie ask can reasonably trigger are stubbed too.+ name: "photos-request-places-clips",+ input: () => [+ userTurn("stitch these two photos into a short movie", { attachRefs: PHOTO_REFS }),+ ],+ reply: /photo|movie|timeline|cut/i,+ requiredTools: ["add_clip"],+ stubs: {+ add_clip: { id: "c-new", kind: "image", index: 1, start: 12.5, len: 8 },+ set_transition: { ok: true },+ set_project_fade: { ok: true },+ add_title: { ok: true },+ },+ },+ {+ // Attached media with a question stays a chat deliverable: ideas in+ // text, the photos stay off the timeline (add_clip would be a violation).+ name: "photos-question-stays-in-chat",+ input: () => [+ userTurn("what could you make with these two photos?", { attachRefs: PHOTO_REFS }),+ ],+ reply: /photo|movie|montage|slideshow|cut|idea/i,+ },{// Control: a real edit request must still act with tools — guards// against over-suppressing tool use.diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 92a02665..cbc9be09 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -277,6 +277,40 @@ export async function runAiTool(};}+ case "add_clip": {+ const asset = requireItem(s.assets, input.asset_id, "project asset");+ const start = isNum(input.start) ? Math.max(0, input.start) : undefined;+ if (asset.type === "audio") {+ s.addAudioFromAsset(asset.id, start);+ const sel = useEditor.getState().selection;+ const c =+ sel?.kind === "audio"+ ? useEditor.getState().audioClips.find((x) => x.id === sel.id)+ : undefined;+ if (!c) throw new ToolError("Could not create the soundtrack clip.");+ return { id: c.id, kind: "audio", start: round2(c.start), len: round2(c.out - c.in) };+ }+ // Video/image onto track 0: an index inserts like move_clip; a start+ // (or nothing — appended at the end) free-positions like a drop.+ let clipId: string | null;+ if (isNum(input.index)) {+ clipId = addVideoTrackClip(asset.id, Math.round(input.index)).clipId;+ } else {+ s.addClipFromAsset(asset.id, start);+ const sel = useEditor.getState().selection;+ clipId = sel?.kind === "clip" ? sel.id : null;+ }+ const c = clipId ? useEditor.getState().clips.find((x) => x.id === clipId) : undefined;+ if (!c) throw new ToolError("Could not create the clip.");+ return {+ id: c.id,+ kind: asset.type,+ index: baseClips(useEditor.getState().clips).findIndex((x) => x.id === c.id),+ start: round2(c.start),+ len: round2(c.out - c.in),+ };+ }+case "add_overlay_video": {const asset = requireItem(s.assets, input.asset_id, "project asset");if (asset.type !== "video" && asset.type !== "image")@@ -531,7 +565,7 @@ export async function runAiTool(if (!asset) throw new ToolError("The generated image did not land in the project.");tagChatAsset(asset.id, chatId);const placed = wantsTimeline(input, "index")- ? addGeneratedClip(asset.id, promptedIndex(input))+ ? addVideoTrackClip(asset.id, promptedIndex(input)): NOT_PLACED;return {assetId: asset.id,@@ -1234,9 +1268,9 @@ const NOT_PLACED = { added: false, clipId: null, index: null };const promptedIndex = (input: Record<string, unknown>): number | undefined =>isNum(input.index) ? Math.round(input.index) : undefined;-/** Append a generated asset to the video track, at `index` when given. Shared- * by generate_image (inline) and the video renders' completion. */-function addGeneratedClip(+/** Append a project asset to the video track, at `index` when given. Shared+ * by add_clip, generate_image (inline), and the video renders' completion. */+function addVideoTrackClip(assetId: string,index?: number): { added: boolean; clipId: string | null; index: number | null } {@@ -1270,7 +1304,7 @@ function launchVeoJob(...opts,onDone: (asset) => {tagChatAsset(asset.id, chatId);- if (addToTimeline) addGeneratedClip(asset.id, index);+ if (addToTimeline) addVideoTrackClip(asset.id, index);},});return {diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 4abc8a80..cd80dc0a 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -104,6 +104,16 @@ export const AI_TOOLS: AiToolDef[] = ["Move a track-0 video clip to a timeline start time (seconds). The track is free-positioned: gaps are allowed and play black. If another clip occupies that spot, the clip slides right to the next free one.",inputSchema: obj({ clipId: str("Video clip id"), start: num("Target timeline start s") }, ["clipId", "start"]),},+ {+ name: "add_clip",+ description:+ "Put a project asset on the timeline, the same way the user dragging it in would: a video or image lands on video track 0 (at `start`, inserted at `index`, or appended at the end; a taken spot slides it right), audio lands on the soundtrack (at `start`, default the playhead). Asset ids come from `media` in editor_state — imports, attachments, and chat media alike. Call it only when the user asked for the media in the cut (\"add my beach photo\", \"stitch these into a movie\"); otherwise media stays on its card or panel for them to drag.",+ inputSchema: obj({+ asset_id: str("Project asset id from `media` in editor_state"),+ start: num("Timeline start s"),+ index: num("Insert position on video track 0 (video/image only; 0 = first)"),+ }, ["asset_id"]),+ },{name: "trim_clip",description:@@ -513,6 +523,7 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim"timeline-editing": `# Timeline editing- Every track is free-positioned: items carry a start time, gaps are allowed, and a track-0 gap plays black (and silence). Deleting leaves a gap. videoTrack entries in editor_state report gapBefore where one exists.- Two ways to move a track-0 clip: place_clip sets its start (respects gaps, slides right if the spot is taken); move_clip reorders by index, opening a slot at the landing point — clips after it shift right, every other gap survives. Index-based inserts (freeze_frame, generated clips) open a slot the same way.+- add_clip puts a project asset on the timeline the way a drag does: video/image onto track 0 (a \`start\`, an \`index\` insert, or appended at the end), audio onto the soundtrack.- Overlay video: a video/image asset can sit on a track above track 0 (track 1, 2… — topmost wins) or behind it (track -1…). A full-frame overlay covers everything below it; give it a layout to share the frame — top/bottom/left/right halves for a split screen, pip for a floating corner box, or a custom region rect. add_overlay_video creates one from a media asset; update_overlay_video moves/trims/regions/mutes/hides it. The user makes them by dragging media above/below track 0; they drag the region in the preview.- A clip's timeline length is (out-in)/speed; total duration runs to the last clip's end, gaps included, minus cross-style transition overlaps.- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.@@ -611,7 +622,7 @@ Rules:- 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.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.-- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this". Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two.+- 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.- 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; detect_silence finds dead air; capture_frame shows the one rendered frame at the playhead. The watching-and-cutting skill has the flow.`;}