Skip to content

Open source CapCut alternative.

TypeScript

fix(site): carry a project's chat history with its copies

David Le8e01d66633a1
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index 15d84d72..adea7643 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -70,6 +70,7 @@ Tool calls execute in the open tab against the same store the user is editing
- **Frames become images.** A tool result's `image`/`images` data URLs leave the JSON and reach the model as real images on every path — the engine bridge emits MCP image blocks after the data text, and the Gemini loop rides the first on the function response and the rest as image parts. Watching happens in whatever model the user is chatting with; there is no side model.
- **Async when rendering.** Video generation outruns the two-minute tool window, so those tools start the job and return immediately; the clip files under the chat that asked — the owning thread is captured at call time — and lands on the timeline only when the user asked for that. Each render's card state (running, landed, failed) mirrors into the project doc as it changes, so the chat shows the same outcome on machines that never ran the job.
- **Chat owns what it makes.** Media created by chat tools is tagged with its thread and previews on a card in the conversation. Placing it on the timeline or filing it into Media or the Library transfers ownership; deleting the thread deletes whatever it still owns.
+- **Chat media is the account's storage.** It is real project media: it counts toward the cloud quota and the project's size like an import, and the thread is the only place it can be seen or deleted from. So conversations travel wherever their media travels — a project moved between the Mac and the cloud, an owner's duplicate, and a share copy with chat shared all carry the threads with the files. A copy that took the files alone would hold media nobody can find, delete, or explain, and the user would still be paying for it.
- **Two tools stay server-side.** The skill list and skill reads are answered by the engine directly — no browser hop.
## Generating a whole video
diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsx
index aa8fc8c9..f057698d 100644
--- a/site/src/cut/components/TopBar.tsx
+++ b/site/src/cut/components/TopBar.tsx
@@ -27,6 +27,7 @@ import {
import { cloudBackend } from "@/cut/lib/backend/cloud";
import { cloudUsageQueryKey, useCutMode } from "@/cut/lib/backend/hooks";
import { localBackend } from "@/cut/lib/backend/local";
+import { clearProjectThreads } from "@/cut/lib/chatThreads";
import { useWebMode } from "@/cut/lib/flags";
import { backTarget, projectHref, useCutBase } from "@/cut/lib/nav";
import { copyProjectAcross } from "@/cut/lib/projectCopy";
@@ -227,6 +228,9 @@ export function TopBar({
await localBackend
.fetch(`/api/cut/projects/${projectId}`, { method: "DELETE" })
.catch(() => {});
+ // The chat history moved with the project; the old project's copy goes
+ // with the project itself.
+ clearProjectThreads(projectId);
window.location.href = projectHref(base, newId, "projects", null);
} catch (e) {
setMoveError(
diff --git a/site/src/cut/lib/chatCloud.ts b/site/src/cut/lib/chatCloud.ts
index de59bd15..d1c1193d 100644
--- a/site/src/cut/lib/chatCloud.ts
+++ b/site/src/cut/lib/chatCloud.ts
@@ -3,15 +3,48 @@
// /projects/:id/chats routes so the history follows the account across
// devices. Threads stay opaque here — the module reads only id and updatedAt
// to merge, and ships the same slimmed payload the panel writes to storage.
-import { apiFetch, cutMode } from "./backend";
-import { threadsKey } from "./chatThreads";
+import { apiFetch, cutMode, getBackend, type CutBackend } from "./backend";
+import {
+ isStoredThread,
+ mergeThreads,
+ readProjectThreads,
+ writeProjectThreads,
+ type StoredThread,
+} from "./chatThreads";
-type ThreadRecord = { id: string; updatedAt?: number };
+const seeded = new Map<string, Promise<void>>();
-const isThread = (v: unknown): v is ThreadRecord =>
- !!v && typeof v === "object" && typeof (v as ThreadRecord).id === "string";
+/** A cloud project's threads as the server holds them. Takes its backend, so a
+ * project copy can read the residency it is copying from rather than the one
+ * the editor happens to be bound to. */
+export async function fetchCloudThreads(
+ backend: CutBackend,
+ projectId: string
+): Promise<StoredThread[]> {
+ if (backend.kind !== "cloud") return [];
+ // Throws on a failed read rather than reading as "no threads": the seed memo
+ // and a project copy both have to tell an empty history from a lost one.
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/chats`);
+ if (!res.ok) throw new Error("Could not read the project's chats.");
+ const body = (await res.json()) as unknown;
+ return Array.isArray(body) ? mergeThreads(body.filter(isStoredThread)) : [];
+}
-const seeded = new Map<string, Promise<void>>();
+/** Write one thread to a cloud project, on an explicit backend. Throws on a
+ * failed write — a copy that loses a conversation has to say so. */
+export async function putCloudThread(
+ backend: CutBackend,
+ projectId: string,
+ thread: StoredThread
+): Promise<void> {
+ if (backend.kind !== "cloud") return;
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/chats/${thread.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(thread),
+ });
+ if (!res.ok) throw new Error("Could not save a chat thread.");
+}
/** Merge the server's copy of a cloud project's threads into localStorage —
* per thread, the newer updatedAt wins. Resolves immediately for local
@@ -32,28 +65,9 @@ export function ensureCloudThreads(projectId: string): Promise<void> {
}
async function seedThreads(projectId: string): Promise<void> {
- const res = await apiFetch(`/api/cut/projects/${projectId}/chats`);
- if (!res.ok) return;
- const remote = (await res.json()) as unknown;
- if (!Array.isArray(remote)) return;
- let local: unknown[] = [];
- try {
- const v = JSON.parse(localStorage.getItem(threadsKey(projectId)) ?? "[]") as unknown;
- if (Array.isArray(v)) local = v;
- } catch {
- // Unreadable local copy — the server copy stands alone.
- }
- const byId = new Map<string, ThreadRecord>();
- for (const t of [...remote, ...local].filter(isThread)) {
- const prev = byId.get(t.id);
- if (!prev || (t.updatedAt ?? 0) >= (prev.updatedAt ?? 0)) byId.set(t.id, t);
- }
- const merged = [...byId.values()].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
- try {
- localStorage.setItem(threadsKey(projectId), JSON.stringify(merged));
- } catch {
- // Storage full/blocked — the in-memory panel still works this session.
- }
+ const remote = await fetchCloudThreads(getBackend(), projectId);
+ if (remote.length === 0) return;
+ writeProjectThreads(projectId, mergeThreads(remote, readProjectThreads(projectId)));
}
// Saves debounce per thread: while a turn streams, the panel re-saves on every
@@ -73,7 +87,7 @@ let pageHideHooked = false;
const saveKey = (projectId: string, threadId: string) => `${projectId}/${threadId}`;
-export function queueCloudThreadSave(projectId: string, thread: ThreadRecord): void {
+export function queueCloudThreadSave(projectId: string, thread: StoredThread): void {
if (cutMode() !== "cloud") return;
const key = saveKey(projectId, thread.id);
const prev = pending.get(key);
diff --git a/site/src/cut/lib/chatThreads.test.ts b/site/src/cut/lib/chatThreads.test.ts
new file mode 100644
index 00000000..eaa0bf5c
--- /dev/null
+++ b/site/src/cut/lib/chatThreads.test.ts
@@ -0,0 +1,62 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+
+import {
+ clearProjectThreads,
+ mergeThreads,
+ readProjectThreads,
+ readThreadIds,
+ threadsKey,
+ writeProjectThreads,
+} from "./chatThreads";
+
+// Bun's test runtime has no localStorage; the module reads it per call.
+const store = new Map<string, string>();
+beforeEach(() => {
+ store.clear();
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => void store.set(k, v),
+ removeItem: (k: string) => void store.delete(k),
+ };
+});
+
+describe("stored chat threads", () => {
+ test("a project's threads round trip", () => {
+ writeProjectThreads("p1", [{ id: "a", updatedAt: 2 }, { id: "b", updatedAt: 1 }]);
+ expect(readProjectThreads("p1").map((t) => t.id)).toEqual(["a", "b"]);
+ expect(readThreadIds("p1")).toEqual(new Set(["a", "b"]));
+ });
+
+ test("threads are per project, and clearing one leaves the other", () => {
+ writeProjectThreads("p1", [{ id: "a" }]);
+ writeProjectThreads("p2", [{ id: "b" }]);
+ clearProjectThreads("p1");
+ expect(readProjectThreads("p1")).toEqual([]);
+ expect(readProjectThreads("p2").map((t) => t.id)).toEqual(["b"]);
+ });
+
+ test("junk in storage reads as no threads rather than throwing", () => {
+ store.set(threadsKey("p1"), "not json");
+ expect(readProjectThreads("p1")).toEqual([]);
+ store.set(threadsKey("p1"), JSON.stringify([{ id: "a" }, 7, null, { noId: true }]));
+ expect(readProjectThreads("p1").map((t) => t.id)).toEqual(["a"]);
+ });
+});
+
+describe("mergeThreads", () => {
+ test("the newest copy of each id wins, newest first", () => {
+ const merged = mergeThreads(
+ [{ id: "a", updatedAt: 5 }, { id: "b", updatedAt: 1 }],
+ [{ id: "a", updatedAt: 9 }, { id: "c", updatedAt: 7 }]
+ );
+ expect(merged).toEqual([
+ { id: "a", updatedAt: 9 },
+ { id: "c", updatedAt: 7 },
+ { id: "b", updatedAt: 1 },
+ ]);
+ });
+
+ test("a thread with no timestamp still survives the merge", () => {
+ expect(mergeThreads([{ id: "a" }], []).map((t) => t.id)).toEqual(["a"]);
+ });
+});
diff --git a/site/src/cut/lib/chatThreads.ts b/site/src/cut/lib/chatThreads.ts
index 7e7db4a9..fc25e265 100644
--- a/site/src/cut/lib/chatThreads.ts
+++ b/site/src/cut/lib/chatThreads.ts
@@ -11,20 +11,49 @@ 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}`;
+/** A saved thread as this module handles it: an opaque record read only for its
+ * id and modified time, so history, the cloud mirror, and project copies can
+ * move threads around without knowing the panel's payload. */
+export type StoredThread = { id: string; updatedAt?: number };
+
+export const isStoredThread = (v: unknown): v is StoredThread =>
+ !!v && typeof v === "object" && typeof (v as StoredThread).id === "string";
+
+/** Every saved thread in a project, as stored. */
+export function readProjectThreads(projectId: string): StoredThread[] {
+ try {
+ const v = JSON.parse(localStorage.getItem(threadsKey(projectId)) ?? "[]") as unknown;
+ return Array.isArray(v) ? v.filter(isStoredThread) : [];
+ } catch {
+ return [];
+ }
+}
+
+/** Replace a project's stored thread list. */
+export function writeProjectThreads(projectId: string, threads: StoredThread[]): void {
+ try {
+ localStorage.setItem(threadsKey(projectId), JSON.stringify(threads));
+ } catch {
+ // Storage full/blocked — history just won't persist.
+ }
+}
+
+/** One thread list from many, newest copy of each id winning, newest first. */
+export function mergeThreads(...lists: StoredThread[][]): StoredThread[] {
+ const byId = new Map<string, StoredThread>();
+ for (const t of lists.flat()) {
+ const prev = byId.get(t.id);
+ if (!prev || (t.updatedAt ?? 0) >= (prev.updatedAt ?? 0)) byId.set(t.id, t);
+ }
+ return [...byId.values()].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
+}
+
/** 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();
- }
+ return new Set(readProjectThreads(projectId).map((t) => t.id));
}
/** Drop a project's chat history and active-thread pointer — called when the
diff --git a/site/src/cut/lib/projectCopy.ts b/site/src/cut/lib/projectCopy.ts
index f177949c..8a6c6e20 100644
--- a/site/src/cut/lib/projectCopy.ts
+++ b/site/src/cut/lib/projectCopy.ts
@@ -1,12 +1,39 @@
// Copy a project between backends: read the source doc, create the target
// project, move every media file's bytes across (in doc order — the fresh
// target dedupes only against names this copy already claimed), remap asset
-// fileNames, then save the doc. A failure deletes the half-made copy. Shared
-// by the projects home's "Duplicate to cloud/Mac" and the editor's move.
+// fileNames, save the doc, and carry the chat history. A failure deletes the
+// half-made copy. Shared by the projects home's "Duplicate to cloud/Mac" and
+// the editor's move.
import type { CutBackend } from "./backend/types";
+import { fetchCloudThreads, putCloudThread } from "./chatCloud";
+import { mergeThreads, readProjectThreads, writeProjectThreads } from "./chatThreads";
import { uploadProjectMediaTo } from "./media";
import type { ProjectDoc } from "./types";
+/** Move a project's conversations onto the copy.
+ *
+ * Chat-created media belongs to a thread: it rides the doc like any other
+ * asset, but only its thread shows it, and only deleting that thread deletes
+ * it. A copy that took the media and left the conversations behind would hold
+ * media nobody can see, delete, or account for — while it still counts against
+ * the account's storage. So the threads travel with it. */
+async function copyChatThreads(
+ src: CutBackend,
+ dst: CutBackend,
+ srcProjectId: string,
+ dstProjectId: string
+): Promise<void> {
+ const threads = mergeThreads(
+ await fetchCloudThreads(src, srcProjectId),
+ readProjectThreads(srcProjectId)
+ );
+ if (threads.length === 0) return;
+ writeProjectThreads(dstProjectId, threads);
+ for (const thread of threads) {
+ await putCloudThread(dst, dstProjectId, thread);
+ }
+}
+
export async function copyProjectAcross(
src: CutBackend,
dst: CutBackend,
@@ -59,6 +86,7 @@ export async function copyProjectAcross(
body: JSON.stringify(copied),
});
if (!putRes.ok) throw new Error("Could not save the project.");
+ await copyChatThreads(src, dst, projectId, summary.id);
return summary.id;
} catch (e) {
if (created) {
diff --git a/site/src/cut/server/cloud/copyQueue.ts b/site/src/cut/server/cloud/copyQueue.ts
index c7cf5501..18350c2e 100644
--- a/site/src/cut/server/cloud/copyQueue.ts
+++ b/site/src/cut/server/cloud/copyQueue.ts
@@ -154,8 +154,12 @@ async function shareSource(job: { shareId: string | null; userId: string }): Pro
};
}
-/** An owner duplicate's source: the whole doc verbatim, same folder, media
- * only — the same shape the old synchronous duplicate produced. */
+/** An owner duplicate's source: the whole doc, same folder, all its media, and
+ * its conversations — chat-created media rides the doc and only its own thread
+ * shows it, so a duplicate without the threads would hold media the owner can
+ * neither see nor delete while it counts against their storage. A mid-flight
+ * brief-to-video run is dropped, as on a share copy: a live plan on the
+ * duplicate would resume and bill every shot a second time. */
async function duplicateSource(job: {
projectId: string | null;
userId: string;
@@ -166,12 +170,20 @@ async function duplicateSource(job: {
if (!row) return "The project was deleted.";
const doc = row.doc as unknown as ProjectDoc;
const media = await completeMedia(job.userId, row.id);
+ const chats = await prisma.cutChatThread.findMany({
+ where: { userId: job.userId, projectId: row.id },
+ select: { id: true, data: true },
+ });
+ const gv = doc.genvideo;
return {
- doc,
+ doc: {
+ ...doc,
+ genvideo: gv && (gv.phase === "done" || gv.phase === "failed") ? gv : undefined,
+ },
name: `${doc.name} copy`,
folderId: row.folderId,
media,
- chats: [],
+ chats,
added: mediaBytes(media),
};
}
diff --git a/site/src/cut/server/cloud/sharedView.test.ts b/site/src/cut/server/cloud/sharedView.test.ts
new file mode 100644
index 00000000..575cfc40
--- /dev/null
+++ b/site/src/cut/server/cloud/sharedView.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from "bun:test";
+
+import type { ProjectDoc, ShareFeatures } from "@/cut/lib/types";
+import { filterDocForShare } from "./sharedView";
+
+// The doc a viewer receives is also the copy's manifest: a share copy moves the
+// media of exactly the assets that survive this filter, so what a shared project
+// carries into someone else's account is decided here.
+const features = (on: Partial<ShareFeatures> = {}): ShareFeatures =>
+ ({ chat: false, media: false, genai: false, subtitles: false, details: false, ...on }) as ShareFeatures;
+
+const doc = {
+ version: 1,
+ name: "p",
+ createdAt: 0,
+ updatedAt: 0,
+ assets: [
+ { id: "imported", fileName: "imported.mp4", type: "video", duration: 1 },
+ { id: "placed", fileName: "placed.mp4", type: "video", duration: 1, origin: "chat", chatId: "t1" },
+ { id: "card", fileName: "card.png", type: "image", duration: 0, origin: "chat", chatId: "t1" },
+ { id: "made", fileName: "made.mp4", type: "video", duration: 1, origin: "generated" },
+ ],
+ clips: [{ id: "c1", assetId: "placed", track: 0, start: 0, in: 0, out: 1, muted: false }],
+ audioClips: [],
+ overlays: [],
+} as unknown as ProjectDoc;
+
+const ids = (d: ProjectDoc) => d.assets.map((a) => a.id).sort();
+
+describe("filterDocForShare", () => {
+ test("chat-created media travels only when chat is shared", () => {
+ expect(ids(filterDocForShare(doc, features({ chat: true })))).toEqual(["card", "placed"]);
+ expect(ids(filterDocForShare(doc, features()))).toEqual(["placed"]);
+ });
+
+ test("a clip's own media always travels — playback is the point", () => {
+ // "placed" is chat-created and on the timeline: shared either way.
+ expect(ids(filterDocForShare(doc, features()))).toEqual(["placed"]);
+ });
+
+ test("each panel carries its own assets", () => {
+ expect(ids(filterDocForShare(doc, features({ media: true })))).toEqual(["imported", "placed"]);
+ expect(ids(filterDocForShare(doc, features({ genai: true })))).toEqual(["made", "placed"]);
+ });
+
+ test("chat's renders ride with chat, and nothing else does", () => {
+ const withRenders = { ...doc, renders: [{ id: "r1" }] } as unknown as ProjectDoc;
+ expect(filterDocForShare(withRenders, features({ chat: true })).renders?.length).toBe(1);
+ expect(filterDocForShare(withRenders, features({ media: true })).renders).toBeUndefined();
+ });
+});