Skip to content

Open source CapCut alternative.

TypeScript

feat(site): store cloud project chats on the server

David Le7d76900d9527
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index 036d4fa8..7aa0d686 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -80,7 +80,7 @@ Because a scene renders many paid shots, the tool plans and then stops. `generat
## Context across turns
-Threads persist per project in the browser's local storage — the newest 30, titled by their first message. What a returning thread remembers depends on the provider:
+Threads persist per project in the browser's local storage — the newest 30, titled by their first message. A cloud project also mirrors each thread to the hosted chat routes (Postgres, keyed to the account), merging the server copy back into local storage on open, so its history follows the account across devices. What a returning thread remembers depends on the provider:
- **Claude and Codex hold their own history.** Each turn sends only the newest message plus the fresh snapshot; prior turns live in the provider's native session, whose id is saved on the thread and resumed. The engine never replays conversation history itself.
- **Gemini is stateless.** The page replays the whole thread every turn — text only. Old turns are stripped to their words; tool traffic, old snapshots, and old attachment payloads stay out, and the fresh snapshot rides only the newest message.
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prisma
index 566be7ac..6bdbcf40 100644
--- a/site/prisma/Cut.prisma
+++ b/site/prisma/Cut.prisma
@@ -48,6 +48,21 @@ model CutMediaObject {
@@index([projectId, kind])
}
+// One AI chat thread of a cloud project, stored as the same slimmed payload
+// the client keeps in localStorage. The thread id is client-generated, so the
+// key is (projectId, id); ownership is checked against CutProject on write.
+model CutChatThread {
+ id String
+ userId String
+ projectId String
+ data Json
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@id([projectId, id])
+ @@index([userId, projectId, updatedAt])
+}
+
model CutLibraryAsset {
id String @id @default(cuid())
userId String
diff --git a/site/prisma/migrations/20260724130834/migration.sql b/site/prisma/migrations/20260724130834/migration.sql
new file mode 100644
index 00000000..8cb26502
--- /dev/null
+++ b/site/prisma/migrations/20260724130834/migration.sql
@@ -0,0 +1,14 @@
+-- CreateTable
+CREATE TABLE "CutChatThread" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "projectId" TEXT NOT NULL,
+ "data" JSONB NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "CutChatThread_pkey" PRIMARY KEY ("projectId","id")
+);
+
+-- CreateIndex
+CREATE INDEX "CutChatThread_userId_projectId_updatedAt_idx" ON "CutChatThread"("userId", "projectId", "updatedAt");
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index 0d184378..b93fe0a0 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -47,6 +47,12 @@ 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 {
+ deleteCloudThread,
+ ensureCloudThreads,
+ flushCloudThreadSaves,
+ queueCloudThreadSave,
+} from "@/cut/lib/chatCloud";
import {
beginChatTurn,
deleteChatAssets,
@@ -166,10 +172,13 @@ function writeThreads(projectId: string, list: ChatThread[]) {
.filter((t) => threadOwnsAssets(t.id) || threadHasLiveRun(t.id)),
];
// A pruned thread is gone the way a deleted one is — anything it still
- // owned (by construction nothing live) dies with it.
+ // owned (by construction nothing live) dies with it, cloud copy included.
const keptIds = new Set(kept.map((t) => t.id));
for (const t of list) {
- if (!keptIds.has(t.id)) useGenScene.getState().killThread(t.id);
+ if (!keptIds.has(t.id)) {
+ useGenScene.getState().killThread(t.id);
+ deleteCloudThread(projectId, t.id);
+ }
}
try {
localStorage.setItem(
@@ -241,6 +250,18 @@ export function AiPanel({
}, [activeChat, projectId]);
const [historyOpen, setHistoryOpen] = useState(false);
const [threads, setThreads] = useState<ChatThread[]>([]);
+ // A cloud project's server threads merge into localStorage before the
+ // session reads it, so a project opened on another device resumes its chats.
+ const [chatsReady, setChatsReady] = useState(false);
+ useEffect(() => {
+ let alive = true;
+ void ensureCloudThreads(projectId).then(() => {
+ if (alive) setChatsReady(true);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [projectId]);
useEffect(() => {
// The models probe asks the engine which CLIs are installed; without the
@@ -281,6 +302,7 @@ export function AiPanel({
// The thread's chat-only assets go with it; anything placed or filed
// into Media/Library stays.
deleteChatAssets(id);
+ deleteCloudThread(projectId, id);
// Its work dies with it too: a scene run the thread owned aborts and its
// plan clears — nothing keeps running behind a conversation the user killed.
useGenScene.getState().killThread(id);
@@ -405,14 +427,16 @@ export function AiPanel({
</>
)}
- <ChatSession
- key={activeChat}
- projectId={projectId}
- threadId={activeChat}
- info={mergedInfo}
- model={model}
- onModelChange={selectModel}
- />
+ {chatsReady && (
+ <ChatSession
+ key={activeChat}
+ projectId={projectId}
+ threadId={activeChat}
+ info={mergedInfo}
+ model={model}
+ onModelChange={selectModel}
+ />
+ )}
</aside>
);
}
@@ -644,19 +668,25 @@ function ChatSession({
.join("")
.trim()
.slice(0, 80) || "New chat";
+ const thread: ChatThread = {
+ id: threadId,
+ title,
+ updatedAt: Date.now(),
+ messages,
+ sessions: { ...providerSessions.current },
+ };
const rest = readThreads(projectId).filter((t) => t.id !== threadId);
- writeThreads(projectId, [
- {
- id: threadId,
- title,
- updatedAt: Date.now(),
- messages,
- sessions: { ...providerSessions.current },
- },
- ...rest,
- ]);
+ writeThreads(projectId, [thread, ...rest]);
+ // Cloud projects mirror the thread server-side (debounced while it streams).
+ queueCloudThreadSave(projectId, slimForStorage([thread])[0]);
}, [messages, threadId, projectId]);
+ // Land the final transcript on the server as soon as the turn settles
+ // instead of waiting out the save debounce.
+ useEffect(() => {
+ if (!busy) flushCloudThreadSaves();
+ }, [busy]);
+
// Stay glued to the newest message while the user sits at the bottom;
// scrolling up releases the glue until they return. The ResizeObserver
// catches growth the messages effect misses — streamed text reflowing and
diff --git a/site/src/cut/lib/chatCloud.ts b/site/src/cut/lib/chatCloud.ts
new file mode 100644
index 00000000..5715e65b
--- /dev/null
+++ b/site/src/cut/lib/chatCloud.ts
@@ -0,0 +1,127 @@
+// Cloud mirror of a project's chat threads. Local projects keep chat purely in
+// localStorage; a cloud project's threads also sync to the hosted
+// /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";
+
+type ThreadRecord = { id: string; updatedAt?: number };
+
+const isThread = (v: unknown): v is ThreadRecord =>
+ !!v && typeof v === "object" && typeof (v as ThreadRecord).id === "string";
+
+const seeded = new Map<string, Promise<void>>();
+
+/** Merge the server's copy of a cloud project's threads into localStorage —
+ * per thread, the newer updatedAt wins. Resolves immediately for local
+ * projects; memoized per project, but a network failure clears the memo so
+ * the next panel mount retries. */
+export function ensureCloudThreads(projectId: string): Promise<void> {
+ if (cutMode() !== "cloud") return Promise.resolve();
+ let p = seeded.get(projectId);
+ if (!p) {
+ p = seedThreads(projectId).catch(() => {
+ seeded.delete(projectId);
+ });
+ seeded.set(projectId, p);
+ }
+ return p;
+}
+
+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.
+ }
+}
+
+// Saves debounce per thread: while a turn streams, the panel re-saves on every
+// token, and each save only needs to land eventually. flush() pushes whatever
+// is queued right away — on turn end and on pagehide.
+const SAVE_DELAY_MS = 1500;
+
+interface PendingSave {
+ projectId: string;
+ threadId: string;
+ data: unknown;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+const pending = new Map<string, PendingSave>();
+let pageHideHooked = false;
+
+const saveKey = (projectId: string, threadId: string) => `${projectId}/${threadId}`;
+
+export function queueCloudThreadSave(projectId: string, thread: ThreadRecord): void {
+ if (cutMode() !== "cloud") return;
+ const key = saveKey(projectId, thread.id);
+ const prev = pending.get(key);
+ if (prev) clearTimeout(prev.timer);
+ pending.set(key, {
+ projectId,
+ threadId: thread.id,
+ data: thread,
+ timer: setTimeout(() => void flushOne(key), SAVE_DELAY_MS),
+ });
+ if (!pageHideHooked && typeof window !== "undefined") {
+ pageHideHooked = true;
+ window.addEventListener("pagehide", () => flushCloudThreadSaves(true));
+ }
+}
+
+async function flushOne(key: string, keepalive = false): Promise<void> {
+ const entry = pending.get(key);
+ if (!entry) return;
+ pending.delete(key);
+ clearTimeout(entry.timer);
+ try {
+ await apiFetch(`/api/cut/projects/${entry.projectId}/chats/${entry.threadId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(entry.data),
+ keepalive,
+ });
+ } catch {
+ // The thread is still in localStorage; its next change re-queues it.
+ }
+}
+
+/** Push every queued save now instead of waiting out the debounce. */
+export function flushCloudThreadSaves(keepalive = false): void {
+ for (const key of [...pending.keys()]) void flushOne(key, keepalive);
+}
+
+/** Delete the server copy of a thread (deleted or pruned locally). */
+export function deleteCloudThread(projectId: string, threadId: string): void {
+ if (cutMode() !== "cloud") return;
+ const entry = pending.get(saveKey(projectId, threadId));
+ if (entry) {
+ clearTimeout(entry.timer);
+ pending.delete(saveKey(projectId, threadId));
+ }
+ void apiFetch(`/api/cut/projects/${projectId}/chats/${threadId}`, {
+ method: "DELETE",
+ }).catch(() => {
+ // Offline delete — the copy resurfaces on the next merge; the user can
+ // delete it again.
+ });
+}
diff --git a/site/src/cut/server/cloud/chats.ts b/site/src/cut/server/cloud/chats.ts
new file mode 100644
index 00000000..e25b04b1
--- /dev/null
+++ b/site/src/cut/server/cloud/chats.ts
@@ -0,0 +1,53 @@
+// AI chat threads for cloud projects. The client owns the thread shape (the
+// same slimmed payload it keeps in localStorage) and syncs it here so a cloud
+// project's chats follow the account across devices; the server stores each
+// thread as an opaque JSON blob keyed by (projectId, thread id).
+import { prisma } from "@/lib/prisma";
+import type { Prisma } from "@/generated/prisma/client";
+import { getProject } from "./projects";
+import { caught, err } from "./util";
+
+// Well above a slimmed thread (data-URL frames are stripped client-side), well
+// below anything that could hurt the database.
+const MAX_THREAD_BYTES = 4_000_000;
+
+export const chatsCloud = {
+ async list(userId: string, projectId: string) {
+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ const rows = await prisma.cutChatThread.findMany({
+ where: { userId, projectId },
+ orderBy: { updatedAt: "desc" },
+ select: { data: true },
+ });
+ return Response.json(rows.map((r) => r.data));
+ },
+
+ async put(userId: string, projectId: string, chatId: string, req: Request) {
+ try {
+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ const text = await req.text();
+ if (text.length > MAX_THREAD_BYTES) return err("Chat thread too large.", 413);
+ const body = JSON.parse(text) as Record<string, unknown>;
+ const data = { ...body, id: chatId } as Prisma.InputJsonValue;
+ await prisma.cutChatThread.upsert({
+ where: { projectId_id: { projectId, id: chatId } },
+ create: { projectId, id: chatId, userId, data },
+ update: { data },
+ });
+ return Response.json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not save chat thread.");
+ }
+ },
+
+ async remove(userId: string, projectId: string, chatId: string) {
+ try {
+ await prisma.cutChatThread.deleteMany({
+ where: { userId, projectId, id: chatId },
+ });
+ return Response.json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not delete chat thread.");
+ }
+ },
+};
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index a8e87c58..c5c9d0dc 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -218,6 +218,7 @@ export const projectsCloud = {
});
await prisma.$transaction(async (tx) => {
await tx.cutMediaObject.deleteMany({ where: { userId, projectId: id } });
+ await tx.cutChatThread.deleteMany({ where: { userId, projectId: id } });
await tx.cutProject.delete({ where: { id } });
await addUsage(tx, userId, -freed);
});
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index aacf3f0c..125c190d 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -7,6 +7,7 @@
import { type DonkeyAuthenticatedRequest, isDonkeySuperUser } from "@/lib/donkey-api-auth";
import { matchRouteTable, type RouteEntry } from "../http/match";
import { captionsCloud } from "./captions";
+import { chatsCloud } from "./chats";
import { runGc } from "./gc";
import { jobsCloud } from "./jobs";
import { libraryCloud } from "./library";
@@ -43,6 +44,9 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "GET", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.serveMedia(u, p.id, p.file) },
{ method: "DELETE", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.removeMedia(u, p.id, p.file) },
{ method: "GET", path: "/api/cut-cloud/projects/:id/preview", handler: (_r, u, p) => projectsCloud.servePreview(u, p.id) },
+ { method: "GET", path: "/api/cut-cloud/projects/:id/chats", handler: (_r, u, p) => chatsCloud.list(u, p.id) },
+ { method: "PUT", path: "/api/cut-cloud/projects/:id/chats/:chatId", handler: (r, u, p) => chatsCloud.put(u, p.id, p.chatId, r) },
+ { method: "DELETE", path: "/api/cut-cloud/projects/:id/chats/:chatId", handler: (_r, u, p) => chatsCloud.remove(u, p.id, p.chatId) },
{ method: "POST", path: "/api/cut-cloud/projects/:id/image", handler: (r, u, p) => mediaCloud.importImage(u, p.id, r) },
{ method: "POST", path: "/api/cut-cloud/projects/:id/media/presign", handler: (r, u, p) => mediaCloud.presign(u, p.id, r) },
{ method: "POST", path: "/api/cut-cloud/projects/:id/media/complete", handler: (r, u) => mediaCloud.complete(u, r) },