Open source CapCut alternative.
TypeScript
fix(site): keep chat media owned by its thread and safe to delete
David Le8fd7d9d5b187
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 7df1ca00..f598cd49 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -1,6 +1,6 @@"use client";-import { Fragment, useEffect, useMemo, useRef, useState } from "react";+import { Fragment, memo, useEffect, useMemo, useRef, useState } from "react";import { useChat } from "@ai-sdk/react";import { DefaultChatTransport, type ChatTransport, type UIMessage } from "ai";import {@@ -38,7 +38,7 @@ import { apiFetch, engineReady } from "@/cut/lib/api";import { buildAiContext } from "@/cut/lib/aiContext";import { runAiTool } from "@/cut/lib/aiTools";import { setAssetDragData } from "@/cut/lib/assetDrag";-import { deleteChatAssets, setActiveChatThread } from "@/cut/lib/chatAssets";+import { deleteChatAssets, setActiveChatThread, threadOwnsAssets } from "@/cut/lib/chatAssets";import {addRefOnce,collectRefs,@@ -94,10 +94,15 @@ function readThreads(): ChatThread[] {}function writeThreads(list: ChatThread[]) {- // A thread falling off the end of history takes its chat-only assets with it.- for (const t of list.slice(THREAD_LIMIT)) deleteChatAssets(t.id);+ // Cap history, but retain any overflow thread that still owns chat media —+ // deleting media is an explicit act (deleting its thread), never a side+ // effect of the history cap.+ const kept = [+ ...list.slice(0, THREAD_LIMIT),+ ...list.slice(THREAD_LIMIT).filter((t) => threadOwnsAssets(t.id)),+ ];try {- localStorage.setItem(threadsKey(), JSON.stringify(list.slice(0, THREAD_LIMIT)));+ localStorage.setItem(threadsKey(), JSON.stringify(kept));} catch {// Storage full/blocked — history just won't persist.}@@ -592,6 +597,10 @@ function ChatSession({* asset, double-click to expand, drag onto the timeline, "…" menu for more* actions. */function MessageAssetCard({ asset }: { asset: AssetRef }) {+ // The reveal waits out the double-click window, so expanding doesn't also+ // jump the side panel to the asset.+ const clickTimer = useRef<number | undefined>(undefined);+ useEffect(() => () => window.clearTimeout(clickTimer.current), []);return (<div className="ai-msg-asset group relative w-16"><button@@ -605,8 +614,14 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {if (asset.scope === "project") setAssetDragData(e, asset.id);setRefDragData(e, asset);}}- onClick={() => revealRef(asset)}- onDoubleClick={() => useLightbox.getState().open(lightboxItemFromRef(asset))}+ onClick={() => {+ window.clearTimeout(clickTimer.current);+ clickTimer.current = window.setTimeout(() => revealRef(asset), 250);+ }}+ onDoubleClick={() => {+ window.clearTimeout(clickTimer.current);+ useLightbox.getState().open(lightboxItemFromRef(asset));+ }}><RefThumb item={asset} className="size-16 transition-colors group-hover:border-input" /><span className="w-full truncate text-[10px] text-muted-foreground">{asset.name}</span>@@ -694,7 +709,10 @@ function MessageCopy({ text }: { text: string }) {);}-function MessageView({ message }: { message: UIMessage }) {+/** Memoized per message: a streaming turn replaces `messages` every chunk,+ * and only the growing message should re-render — settled ones hold whole+ * asset-card subtrees. */+const MessageView = memo(function MessageView({ message }: { message: UIMessage }) {if (message.role === "user") {const text = message.parts.map((p) => (p.type === "text" ? p.text : "")).join("");// normalizeRef also reads attachments saved by older threads (pre-ref shape).@@ -786,7 +804,7 @@ function MessageView({ message }: { message: UIMessage }) {<MessageCopy text={text} /></div>);-}+});function ModelSelector({info,diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 1a85ae13..f0c2e658 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -10,7 +10,7 @@ import { useExport } from "@/cut/lib/exportStore";import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";import { enrichAsset, importFileToProject } from "@/cut/lib/media";import { backTarget, useCutBase } from "@/cut/lib/nav";-import { projectDuration, serializeDoc, useEditor } from "@/cut/lib/store";+import { projectDuration, serializeDoc, storedAssets, useEditor } from "@/cut/lib/store";import type { MediaAsset } from "@/cut/lib/types";import { AiPanel } from "./AiPanel";import { ExportDialog } from "./ExportDialog";@@ -150,6 +150,19 @@ export function Editor({};let primed = false;+ // Assets change identity on runtime enrichment (thumbs, peaks) too, so a+ // new reference compares by its stored projection: field edits like an+ // origin change ("Add to Media", chat tagging) must save, enrichment not.+ let lastAssetsRef = useEditor.getState().assets;+ let lastAssetsJson = JSON.stringify(storedAssets(lastAssetsRef));+ const assetsChanged = (assets: MediaAsset[]): boolean => {+ if (assets === lastAssetsRef) return false;+ const json = JSON.stringify(storedAssets(assets));+ const changed = json !== lastAssetsJson;+ lastAssetsRef = assets;+ lastAssetsJson = json;+ return changed;+ };const unsub = useEditor.subscribe((s) => {if (!s.loaded || s.projectId !== projectId) return;if (!primed) {@@ -158,9 +171,14 @@ export function Editor({primed = true;last = serializeDoc(s);lastName = s.projectName;+ assetsChanged(s.assets);return;}+ // Evaluated every tick (not short-circuited) so the asset baseline+ // advances even when another slice triggered this save.+ const assetsDirty = assetsChanged(s.assets);const changed =+ assetsDirty ||s.clips !== (last.clips as unknown) ||s.audioClips !== (last.audioClips as unknown) ||s.overlayClips !== (last.overlayClips as unknown) ||@@ -169,7 +187,6 @@ export function Editor({s.aspect !== last.aspect ||s.fadeIn !== (last.fadeIn ?? 0) ||s.fadeOut !== (last.fadeOut ?? 0) ||- s.assets.length !== last.assets?.length ||s.publish.caption !== last.publish?.caption ||s.publish.tags !== last.publish?.tags ||s.publish.soundTitle !== last.publish?.soundTitle ||diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex 77fa3e00..07fc8641 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -282,8 +282,12 @@ function ClipPanel({ clip }: { clip: VideoClip }) {const genAudioKey = useEditor((s) => {const sp = getClipSpans(s.clips, s.assets).find((x) => x.clip.id === clip.id);if (!sp) return "";+ // AI-voice audio regardless of where it was made: the Audio panel tags+ // voiceovers, the chat tags its own — both are voice over this clip.const voiceAssets = new Set(- s.assets.filter((a) => a.origin === "voiceover").map((a) => a.id)+ s.assets+ .filter((a) => a.origin === "voiceover" || (a.origin === "chat" && a.type === "audio"))+ .map((a) => a.id));return s.audioClips.filter((a) => {diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 50302cb0..f2b79fe2 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -3,7 +3,7 @@import { apiFetch, apiJson } from "./api";import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";import { chatOwner, tagChatAsset } from "./chatAssets";-import { useGenerate } from "./generate";+import { useGenerate, type VideoGenOptions } from "./generate";import { enrichAsset, ensurePeaks, importImage, importStockVideo } from "./media";import { characterPrompt, stockTitle } from "./stock";import { STOCK_IMAGES } from "./stockManifest";@@ -367,8 +367,10 @@ export async function runAiTool(if (!prompt) throw new ToolError("A prompt is required.");const refs = resolveRefAssets(input.reference_asset_ids);- // Hosted image generation is synchronous and quick, so wait it out and- // place the still — it lands in the panel job list either way.+ // Captured before the render: the image files under the chat that+ // asked, even if the user switches threads while it generates.+ const chatId = chatOwner();+ // Hosted image generation is synchronous and quick, so wait it out.const job = await useGenerate.getState().generateImage(projectId, prompt, {...(input.aspect === "16:9" || input.aspect === "9:16" || input.aspect === "1:1"? { aspect: input.aspect }@@ -384,8 +386,10 @@ export async function runAiTool(const cur = useEditor.getState();const asset = cur.assets.find((a) => a.id === job.assetId);if (!asset) throw new ToolError("The generated image did not land in the project.");- tagChatAsset(asset.id);- const placed = maybeAddGeneratedClip(asset.id, input);+ tagChatAsset(asset.id, chatId);+ const placed = wantsTimeline(input, "index")+ ? addGeneratedClip(asset.id, promptedIndex(input))+ : NOT_PLACED;return {assetId: asset.id,name: asset.name,@@ -411,17 +415,12 @@ export async function runAiTool(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- // don't block: start the job and place the clip when it lands.+ // 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 addToTimeline = input.add_to_timeline === true || isNum(input.index);- const promptedIndex = isNum(input.index) ? Math.round(input.index) : undefined;- // Captured now: the render must file under the chat that asked, even if- // the user switches threads before it lands.- const chatId = chatOwner();- void gen.generateVideo(projectId, prompt, {+ return launchVeoJob(projectId, prompt, input, {tier: input.tier === "high" ? "high" : "fast",durationSeconds: isNum(input.duration_seconds)? clamp(Math.round(input.duration_seconds), 4, 8)@@ -431,26 +430,7 @@ export async function runAiTool(? { resolution: input.resolution }: {}),...(refs.length > 0 ? { refs } : {}),- onDone: (asset) => {- tagChatAsset(asset.id, chatId);- if (addToTimeline)- maybeAddGeneratedClip(asset.id, { add_to_timeline: true, index: promptedIndex });- },});- // The job entry is prepended synchronously, so the newest job is this- // render; the chat follows it by id to show a live card.- const jobId = useGenerate.getState().jobs[0]?.id ?? null;- return {- kind: "video",- started: true,- jobId,- addToTimeline,- note:- "Rendering with Veo — it previews in this chat when it lands, in a minute or two" +- (addToTimeline- ? ", and goes onto the timeline."- : ". It stays in the chat (and the Video panel's renders) until the user places it."),- };}case "generate_character_video": {@@ -465,37 +445,19 @@ export async function runAiTool(const gen = useGenerate.getState();const signedIn = gen.signedIn ?? (await gen.probeNow());if (!signedIn) throw new ToolError("Sign in to Donkey to generate video.");- const addToTimeline = input.add_to_timeline === true || isNum(input.index);- const promptedIndex = isNum(input.index) ? Math.round(input.index) : undefined;- const chatId = chatOwner();- void gen.generateVideo(projectId, characterPrompt(character.persona!, line), {- 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,- onDone: (asset) => {- tagChatAsset(asset.id, chatId);- if (addToTimeline)- maybeAddGeneratedClip(asset.id, { add_to_timeline: true, index: promptedIndex });- },- });- const jobId = useGenerate.getState().jobs[0]?.id ?? null;return {- kind: "video",- started: true,- jobId,+ ...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,+ }),character: character.id,- addToTimeline,- note:- "Rendering with Veo — it previews in this chat when it lands, in a minute or two" +- (addToTimeline- ? ", and goes onto the timeline."- : ". It stays in the chat (and the Video panel's renders) until the user places it."),};}@@ -570,12 +532,14 @@ export async function runAiTool(const img = vid ? undefined : STOCK_IMAGES.find((i) => i.id === id);if (!vid && !img)throw new ToolError(`No stock item with id ${id}. Call stock_search for ids.`);+ // Captured before the import: the media files under the chat that+ // asked, even if the user switches threads while it downloads.+ const chatId = chatOwner();const asset = vid? await importStockVideo(projectId, { url: vid.file, name: stockTitle(vid.id) }): await importImage(projectId, { url: img!.file, name: stockTitle(img!.id) });- tagChatAsset(asset.id);- // An explicit start is itself the ask to place.- const addToTimeline = input.add_to_timeline === true || isNum(input.start);+ tagChatAsset(asset.id, chatId);+ const addToTimeline = wantsTimeline(input, "start");let clipId: string | null = null;if (addToTimeline) {useEditor@@ -728,8 +692,7 @@ export async function runAiTool(throw new ToolError("script is required.");const start = isNum(input.start) ? Math.max(0, input.start) : s.currentTime;const lead = input.script.trim().split(/\s+/).slice(0, 4).join(" ");- // An explicit start is itself the ask to place on the soundtrack.- const place = input.add_to_timeline === true || isNum(input.start);+ const place = wantsTimeline(input, "start");return synthesizeVoiceover([{ text: input.script, at: 0 }],`AI voice — ${lead}`,@@ -923,6 +886,9 @@ async function synthesizeVoiceover(? input.direction.trim(): undefined;const duck = isNum(input.duck) ? clamp(input.duck, 0, 1) : DUCK_DEFAULT;+ // Captured before synthesis: the audio files under the chat that asked,+ // even if the user switches threads while it renders.+ const chatId = chatOwner();const { asset, offset } = await synthesizeSpeech(projectId, segments, {voice,direction,@@ -931,7 +897,7 @@ async function synthesizeVoiceover(});const cur = useEditor.getState();cur.addAsset(asset);- tagChatAsset(asset.id);+ tagChatAsset(asset.id, chatId);void enrichAsset(asset);if (!place) {return {@@ -1013,26 +979,67 @@ function layoutPatch(layout: string): Partial<OverlayClip> {return { frame: key === "full" ? undefined : { ...L.rect }, fit: L.fit };}-/** Append a generated asset to the video track at an optional index, when the- * model passed add_to_timeline:true. By default generated media stays on its- * chat preview card until the user asks for it in the cut. Shared by- * generate_image (inline) and generate_video (on the render's completion). */-function maybeAddGeneratedClip(+/** The model asked for timeline placement — explicitly, or implicitly by+ * giving a position. Otherwise generated media stays on its chat card. */+function wantsTimeline(input: Record<string, unknown>, positionKey: "index" | "start"): boolean {+ return input.add_to_timeline === true || isNum(input[positionKey]);+}++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(assetId: string,- input: { add_to_timeline?: unknown; index?: unknown }+ index?: number): { added: boolean; clipId: string | null; index: number | null } {- // An explicit index is itself the ask to place ("make it the cover frame").- if (input.add_to_timeline !== true && !isNum(input.index))- return { added: false, clipId: null, index: null };const s = useEditor.getState();- if (!s.assets.some((a) => a.id === assetId)) return { added: false, clipId: null, index: null };+ if (!s.assets.some((a) => a.id === assetId)) return NOT_PLACED;s.addClipFromAsset(assetId); // lands at the end, selectedconst sel = useEditor.getState().selection;const clipId = sel?.kind === "clip" ? sel.id : null;const count = useEditor.getState().clips.length;- const index = isNum(input.index) ? clamp(Math.round(input.index), 0, count - 1) : count - 1;- if (clipId && index !== count - 1) s.moveClip(clipId, index);- return { added: true, clipId, index };+ const at = index === undefined ? count - 1 : clamp(Math.round(index), 0, count - 1);+ if (clipId && at !== count - 1) s.moveClip(clipId, at);+ 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(+ projectId: string,+ prompt: string,+ input: Record<string, unknown>,+ opts: Omit<VideoGenOptions, "onDone">+) {+ const addToTimeline = wantsTimeline(input, "index");+ const index = promptedIndex(input);+ // Captured now: the render must file under the chat that asked, even if+ // the user switches threads before it lands.+ const chatId = chatOwner();+ const { jobId } = useGenerate.getState().generateVideo(projectId, prompt, {+ ...opts,+ onDone: (asset) => {+ tagChatAsset(asset.id, chatId);+ if (addToTimeline) addGeneratedClip(asset.id, index);+ },+ });+ return {+ kind: "video",+ started: true,+ jobId,+ addToTimeline,+ note:+ "Rendering with Veo — it previews in this chat when it lands, in a minute or two" ++ (addToTimeline+ ? ", and goes onto the timeline."+ : ". It stays in the chat (and the Video panel's renders) until the user places it."),+ };}function titlePatch(input: Record<string, unknown>) {diff --git a/site/src/cut/lib/chatAssets.ts b/site/src/cut/lib/chatAssets.tsindex dff2d4c7..732c2868 100644--- a/site/src/cut/lib/chatAssets.ts+++ b/site/src/cut/lib/chatAssets.ts@@ -1,5 +1,7 @@"use client";+import { useGenerate } from "./generate";+import { usePreviewAudio } from "./previewAudio";import { useEditor } from "./store";// Chat-created media belongs to its thread. The files live in the project's@@ -31,8 +33,18 @@ export function tagChatAsset(assetId: string, chatId: string | null = activeChatuseEditor.getState().updateAsset(assetId, { origin: "chat", chatId });}+/** Whether a thread still owns chat media in the open project — such a thread+ * must not fall out of history silently, or its media becomes unreachable. */+export function threadOwnsAssets(threadId: string): boolean {+ return useEditor.getState().assets.some(+ (a) => a.origin === "chat" && a.chatId === threadId+ );+}+/** Delete the assets a thread still owns: origin "chat", tagged with the- * thread, and not referenced by any clip. One undo step. */+ * thread, and not referenced by any clip. Assets sit outside the undo+ * history, so this is not undoable — call it only for an explicit thread+ * deletion. */export function deleteChatAssets(threadId: string) {const s = useEditor.getState();const inUse = new Set(@@ -41,8 +53,13 @@ export function deleteChatAssets(threadId: string) {const owned = s.assets.filter((a) => a.origin === "chat" && a.chatId === threadId && !inUse.has(a.id));- if (owned.length === 0) return;- s.beginHistoryBatch();- for (const a of owned) useEditor.getState().removeAsset(a.id);- useEditor.getState().endHistoryBatch();+ for (const a of owned) {+ usePreviewAudio.getState().stop(a.url);+ useEditor.getState().removeAsset(a.id);+ // A render-history entry pointing at deleted media would show as a dead+ // row in the Video panel; it goes with the asset.+ for (const j of useGenerate.getState().jobs.filter((job) => job.assetId === a.id)) {+ useGenerate.getState().dismiss(j.id);+ }+ }}diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 246da4f2..9ea19503 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -521,6 +521,14 @@ export const useEditor = create<EditorState>((set, get) => {removeAsset: (id) => {const st = get();if (!st.assets.some((a) => a.id === id)) return;+ // An unreferenced asset is no doc edit: history snapshots don't cover+ // the asset list, so removing one must not open a checkpoint or churn+ // the clip arrays (a fresh clips reference would count as a doc change+ // and wipe the redo branch).+ if (!st.clips.some((c) => c.assetId === id) && !st.audioClips.some((c) => c.assetId === id)) {+ set((s) => ({ assets: s.assets.filter((a) => a.id !== id) }));+ return;+ }push();// Cascade removes this asset's clips; every clip is free-positioned, so// the rest of the timeline (and its annotations) stays where it is.@@ -2024,6 +2032,23 @@ useEditor.subscribe((s, prev) => {docSeq++;});+/** The asset fields persisted in project.json — the projection autosave+ * writes, and the one its change detector compares (runtime fields like+ * thumbs/peaks must not mark the doc dirty). */+export function storedAssets(assets: MediaAsset[]): StoredAsset[] {+ return assets.map(({ id, fileName, name, type, duration, width, height, origin, chatId }) => ({+ id,+ fileName,+ name,+ type,+ duration,+ ...(width !== undefined ? { width } : {}),+ ...(height !== undefined ? { height } : {}),+ ...(origin !== undefined ? { origin } : {}),+ ...(chatId !== undefined ? { chatId } : {}),+ }));+}+/** The persistable slice of the editor state, for autosave. */export function serializeDoc(s: {projectName: string;@@ -2039,22 +2064,9 @@ export function serializeDoc(s: {notes: { text: string; publishedAt: string; links: string[] };subtitles: SubtitlesBlock;}): Partial<ProjectDoc> {- const assets: StoredAsset[] = s.assets.map(- ({ id, fileName, name, type, duration, width, height, origin, chatId }) => ({- id,- fileName,- name,- type,- duration,- ...(width !== undefined ? { width } : {}),- ...(height !== undefined ? { height } : {}),- ...(origin !== undefined ? { origin } : {}),- ...(chatId !== undefined ? { chatId } : {}),- })- );return {name: s.projectName,- assets,+ assets: storedAssets(s.assets),clips: s.clips,audioClips: s.audioClips,overlayClips: s.overlayClips,