Open source CapCut alternative.
TypeScript
fix(site): a deleted thread or project cancels its in-flight renders
David Le4982ac55723a
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 1d8f09f6..51bdfcab 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -43,6 +43,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 { activeChatKey, threadsKey } from "@/cut/lib/chatThreads";import {beginChatTurn,deleteChatAssets,@@ -104,13 +105,6 @@ interface ChatThread {}const THREAD_LIMIT = 30;-// Chat history is strictly per project. The keys derive from the route's-// project id passed down as a prop — never from the editor store, whose-// projectId still points at the previously open project until loadProject-// lands, which used to leak one project's chat into another.-const threadsKey = (projectId: string) => `cut-ai-threads-${projectId}`;-// The open chat survives hiding the panel — only the + button starts a new one.-const activeChatKey = (projectId: string) => `cut-ai-active-${projectId}`;function readThreads(projectId: string): ChatThread[] {try {diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 6776888c..27efc6ca 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -44,6 +44,9 @@ import {} from "@/components/ui/dropdown-menu";import { Input } from "@/components/ui/input";import { apiFetch, apiUrl, engineLost } from "@/cut/lib/api";+import { clearProjectThreads } from "@/cut/lib/chatThreads";+import { useGenerate } from "@/cut/lib/generate";+import { useGenScene } from "@/cut/lib/genScene";import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";import { formatTime } from "@/cut/lib/time";@@ -257,8 +260,16 @@ export function ProjectsHome() {const remove = async () => {if (!deleting) return;setBusy(true);+ const id = deleting.id;try {- await apiFetch(`/api/cut/projects/${deleting.id}`, { method: "DELETE" });+ await apiFetch(`/api/cut/projects/${id}`, { method: "DELETE" });+ // The doc, media, and exports go with the folder on the server. Purge the+ // client-side residue keyed to this project so nothing survives it: a live+ // scene run, its in-flight renders, and its chat history (whose ids the+ // render-resume guard reads to keep a deleted thread's render from landing).+ useGenScene.getState().killProject(id);+ useGenerate.getState().cancelForOwner({ projectId: id });+ clearProjectThreads(id);setDeleting(null);await refresh();} finally {diff --git a/site/src/cut/lib/chatThreads.ts b/site/src/cut/lib/chatThreads.tsnew file mode 100644index 00000000..7e7db4a9--- /dev/null+++ b/site/src/cut/lib/chatThreads.ts@@ -0,0 +1,39 @@+// Chat history is per project, stored in localStorage. The keys and a couple of+// raw readers live in this leaf module (importing nothing app-specific) so both+// the AI panel — which owns the history — and the generate store — which must+// refuse to resume a render whose thread the user deleted — can reach it without+// importing each other.++// The keys derive from the route's project id, never the editor store's+// projectId (that still points at the previously open project until loadProject+// lands, which used to leak one project's chat into another).+export const threadsKey = (projectId: string) => `cut-ai-threads-${projectId}`;+// The open chat survives hiding the panel — only the + button starts a new one.+export const activeChatKey = (projectId: string) => `cut-ai-active-${projectId}`;++/** The ids of every saved thread in a project. The render-resume guard checks a+ * job's owning thread against this on boot: a chat render whose thread is gone+ * (deleted, or its whole project deleted, which clears these keys) is dismissed+ * rather than landed, so a reload can't resurrect media the user removed. */+export function readThreadIds(projectId: string): Set<string> {+ try {+ const v = JSON.parse(localStorage.getItem(threadsKey(projectId)) ?? "[]") as unknown;+ if (!Array.isArray(v)) return new Set();+ return new Set(+ v.map((t) => (t as { id?: unknown }).id).filter((x): x is string => typeof x === "string")+ );+ } catch {+ return new Set();+ }+}++/** Drop a project's chat history and active-thread pointer — called when the+ * project itself is deleted, so no stale thread or its renders survive it. */+export function clearProjectThreads(projectId: string): void {+ try {+ localStorage.removeItem(threadsKey(projectId));+ localStorage.removeItem(activeChatKey(projectId));+ } catch {+ // Storage blocked — nothing to clear.+ }+}diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsindex 57f2fd24..a18edc77 100644--- a/site/src/cut/lib/genScene.ts+++ b/site/src/cut/lib/genScene.ts@@ -648,6 +648,9 @@ interface GenSceneState {/** A chat thread was deleted — every run it owned dies with it. Nothing* keeps working behind a conversation the user killed. */killThread: (chatId: string) => void;+ /** A project was deleted — abort any live run so it stops spending and can't+ * write back to a doc that no longer exists. */+ killProject: (projectId: string) => void;dismiss: () => void;}@@ -932,6 +935,10 @@ export const useGenScene = create<GenSceneState>((set, get) => ({// — a background run the boot sweep hasn't adopted — and the doc sweep// below clears their persisted plans.killedChats.add(chatId);+ // Stop the thread's in-flight video renders too: aborting the orchestrator+ // ends the scene loop, but each shot's render polls on its own in useGenerate+ // and would otherwise land its clip under the dead thread minutes later.+ useGenerate.getState().cancelForOwner({ chatId });for (const [projectId, orch] of orchestrators) {if (orch.project.chatId === chatId) killRun(projectId);}@@ -942,6 +949,19 @@ export const useGenScene = create<GenSceneState>((set, get) => ({void killPersistedThreadRuns(chatId);},+ killProject: (projectId) => {+ // The project (folder, doc, media) is being deleted: abort a live scene run+ // so it stops spending and never writes back to a doc that's gone. The+ // persisted plan needs no clearing — it dies with the project folder.+ const orch = orchestrators.get(projectId);+ if (orch) {+ orch.abort();+ orchestrators.delete(projectId);+ }+ const run = get().run;+ if (run?.projectId === projectId) set({ run: null });+ },+dismiss: () => {const run = get().run;// Dismissing an unrendered plan abandons it: the orchestrator stops anddiff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex a8d68779..761ff461 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -5,6 +5,7 @@ import { create } from "zustand";import { apiFetch, apiJson } from "./api";import type { AssetRef } from "./assetRef";import { bytesFromBase64 } from "./bytes";+import { readThreadIds } from "./chatThreads";import { composeGenPrompt, foldTextRefs } from "./composeGen";import { stockAssetInDoc } from "./genvideo/docWriter";import { cutAppBase } from "./hosts";@@ -123,6 +124,11 @@ interface GenerateState {}) => { jobId: string; settled: Promise<GenerateJob>; submitted: Promise<VideoSubmitOutcome> };dismiss: (id: string) => void;+ /** Cancel every render owned by a deleted thread or project: matching jobs are+ * dropped from the list and their in-flight polls refuse to land, so a render+ * still running when the user deletes its owner can't re-add media afterward.+ * Called by thread deletion (chatId) and project deletion (projectId). */+ cancelForOwner: (owner: { chatId?: string; projectId?: string }) => void;/** Re-attach the poll loop of every persisted running render (reload* recovery) — called once when the app boots. Idempotent. */resumeRunningJobs: () => void;@@ -384,6 +390,11 @@ export const useGenerate = create<GenerateState>((set, get) => {// tab, or the session cookie can land a beat after this page loads.let probing: Promise<boolean> | null = null;+ // Jobs whose owner (thread or project) was deleted mid-render. Their poll loop+ // checks this before landing anything, so a render that finishes after its+ // owner is gone drops its result instead of re-adding orphaned media.+ const cancelledJobs = new Set<string>();+const update = (id: string, patch: Partial<GenerateJob>) => {set((s) => ({ jobs: s.jobs.map((j) => (j.id === id ? { ...j, ...patch } : j)) }));persistJobs(get().jobs);@@ -422,11 +433,16 @@ export const useGenerate = create<GenerateState>((set, get) => {const job = get().jobs.find((j) => j.id === jobId);if (!job) return;let gen = first;+ // The render is abandoned once its owner is deleted: cancelForOwner drops the+ // job from the list, so a vanished job (or one flagged mid-render) means stop+ // polling and land nothing — the media it would have added is unwanted.+ const aborted = () => cancelledJobs.has(jobId) || !get().jobs.some((j) => j.id === jobId);// A resumed render keeps its original deadline, floored so a reload near// the limit still gets a couple of polls before giving up. A ladder rung// passes its own start so a slow first rung doesn't starve the fallback.const deadline = Math.max((since ?? job.startedAt) + VIDEO_DEADLINE_MS, Date.now() + 2 * 60_000);while (gen.status === "in_progress") {+ if (aborted()) return;claimJobLease(jobId); // renewed every cycle; siblings back off until it staledupdate(jobId, {poll: {@@ -457,6 +473,9 @@ export const useGenerate = create<GenerateState>((set, get) => {if (gen.status !== "completed") {throw new Error(providerError(gen.error) ?? "Video generation failed.");}+ // Owner deleted while the render finished: skip the import entirely so no+ // file is even written for media nobody will ever see.+ if (aborted()) return;const out = gen.outputs.find((o) => o.dataBase64) ?? gen.outputs.find((o) => o.url);const fileName = `ai-${promptSlug(job.prompt)}.mp4`;@@ -477,6 +496,15 @@ export const useGenerate = create<GenerateState>((set, get) => {const asset = await importFileToProject(job.projectId, file);if (!asset) throw new Error("Could not import the generated video.");+ // The owner may have been deleted during the import (the file write is a+ // round trip): drop the file we just wrote rather than leave it orphaned.+ if (aborted()) {+ void apiFetch(+ `/api/cut/projects/${job.projectId}/media/${encodeURIComponent(asset.fileName)}`,+ { method: "DELETE" }+ ).catch(() => {});+ return;+ }asset.name = promptName(job.prompt);applyOwnership(asset, job.chatId);if (adopt(job.projectId, asset)) {@@ -573,6 +601,15 @@ export const useGenerate = create<GenerateState>((set, get) => {throw new Error(body.error ?? "Could not add the image to the project.");}const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };+ // Owner deleted while the image rendered (cancelForOwner dropped the+ // job): drop the baked file instead of adopting orphaned media.+ if (cancelledJobs.has(job.id) || !get().jobs.some((j) => j.id === job.id)) {+ void apiFetch(+ `/api/cut/projects/${projectId}/media/${encodeURIComponent(body.fileName)}`,+ { method: "DELETE" }+ ).catch(() => {});+ return settled(job.id, job);+ }applyOwnership(asset, opts?.chatId);if (adopt(projectId, asset) && !opts?.chatId) {useGenNotify.getState().landed("image", asset.id);@@ -706,9 +743,43 @@ export const useGenerate = create<GenerateState>((set, get) => {return { jobId: job.id, settled: settledRun, submitted };},+ cancelForOwner: (owner) => {+ const match = (j: GenerateJob) =>+ (owner.chatId !== undefined && j.chatId === owner.chatId) ||+ (owner.projectId !== undefined && j.projectId === owner.projectId);+ const victims = get().jobs.filter(match);+ if (victims.length === 0) return;+ // Flag the running ones so their poll loop lands nothing (finishVideo reads+ // cancelledJobs), then drop every matching job — running or settled, its+ // card belonged to the owner the user just deleted.+ for (const j of victims) {+ cancelledJobs.add(j.id);+ releaseJobLease(j.id);+ }+ set((s) => ({ jobs: s.jobs.filter((j) => !match(j)) }));+ persistJobs(get().jobs);+ },+resumeRunningJobs: () => {const stored = new Map(readPersistedJobs().map((j) => [j.id, j]));+ // Read each project's surviving thread ids once per sweep.+ const threadCache = new Map<string, Set<string>>();+ const threadIds = (projectId: string) => {+ let ids = threadCache.get(projectId);+ if (!ids) {+ ids = readThreadIds(projectId);+ threadCache.set(projectId, ids);+ }+ return ids;+ };for (const j of get().jobs) {+ // A render whose owning thread no longer exists — the thread was deleted,+ // or its whole project was (which clears the project's threads) — must+ // never land: drop it so a reload can't resurrect media the user removed.+ if (j.chatId && !threadIds(j.projectId).has(j.chatId)) {+ get().dismiss(j.id);+ continue;+ }if (j.kind !== "video" || j.status !== "running" || !j.poll || settlements.has(j.id)) continue;// Storage is the cross-tab truth: a sibling tab may have settled this// render already — adopt its outcome instead of re-polling (and