Open source CapCut alternative.
TypeScript
feat(site): undo checkpoints and a write lease for cloud projects [rebuild]
David Leca18d2a06f02
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismaindex 80c19a95..8b1b8973 100644--- a/site/prisma/Cut.prisma+++ b/site/prisma/Cut.prisma@@ -18,6 +18,24 @@ model CutProject {@@index([userId, updatedAt])}+// One saved state of a cloud project, kept so an edit made from outside the+// editor (the ChatGPT app) can be undone and redone from another request.+// Rows form a linear history per project ordered by seq; `version` is the+// CutProject.version whose doc this row holds, re-aliased when a restore+// writes the same doc under a new version.+model CutProjectCheckpoint {+ id String @id @default(cuid())+ projectId String+ userId String+ seq Int+ version Int+ doc Json+ label String+ createdAt DateTime @default(now())++ @@index([projectId, seq])+}+// A read-only share of one cloud project. The row id doubles as the link// token: deleting the row kills the link, and re-sharing mints a fresh URL// without moving the project. For a public share the token is the only gate,diff --git a/site/prisma/migrations/20260916150000/migration.sql b/site/prisma/migrations/20260916150000/migration.sqlnew file mode 100644index 00000000..942363c4--- /dev/null+++ b/site/prisma/migrations/20260916150000/migration.sql@@ -0,0 +1,16 @@+-- CreateTable+CREATE TABLE "CutProjectCheckpoint" (+ "id" TEXT NOT NULL,+ "projectId" TEXT NOT NULL,+ "userId" TEXT NOT NULL,+ "seq" INTEGER NOT NULL,+ "version" INTEGER NOT NULL,+ "doc" JSONB NOT NULL,+ "label" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "CutProjectCheckpoint_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "CutProjectCheckpoint_projectId_seq_idx" ON "CutProjectCheckpoint"("projectId", "seq");diff --git a/site/src/cut/server/cloud/history.test.ts b/site/src/cut/server/cloud/history.test.tsnew file mode 100644index 00000000..443bd013--- /dev/null+++ b/site/src/cut/server/cloud/history.test.ts@@ -0,0 +1,107 @@+import { expect, test } from "bun:test";+import type { ProjectDoc } from "@/cut/lib/types";+import {+ CHECKPOINT_KEEP,+ historyState,+ recordCheckpoint,+ restoreCheckpoint,+ type HistoryDb,+} from "./history";++type Row = { id: string; projectId: string; userId: string; seq: number; version: number; doc: unknown; label: string };++/** An in-memory stand-in for the two tables the history touches. */+function fakeDb(project: { id: string; userId: string; version: number; doc: ProjectDoc }) {+ const rows: Row[] = [];+ let nextId = 1;+ const matches = (row: Row, where: Record<string, unknown>) =>+ Object.entries(where).every(([k, v]) => {+ if (k === "id" && v && typeof v === "object" && "in" in v) return (v.in as string[]).includes(row.id);+ return (row as Record<string, unknown>)[k] === v;+ });+ const db = {+ cutProjectCheckpoint: {+ findMany: async ({ where }: { where: Record<string, unknown> }) =>+ rows.filter((r) => matches(r, where)).sort((a, b) => a.seq - b.seq).map((r) => ({ ...r })),+ findUnique: async ({ where }: { where: { id: string } }) => rows.find((r) => r.id === where.id) ?? null,+ create: async ({ data }: { data: Omit<Row, "id"> }) => {+ const row = { ...data, id: `cp${nextId++}` };+ rows.push(row);+ return row;+ },+ deleteMany: async ({ where }: { where: Record<string, unknown> }) => {+ const keep = rows.filter((r) => !matches(r, where));+ const count = rows.length - keep.length;+ rows.splice(0, rows.length, ...keep);+ return { count };+ },+ update: async ({ where, data }: { where: { id: string }; data: Partial<Row> }) => {+ const row = rows.find((r) => r.id === where.id)!;+ Object.assign(row, data);+ return row;+ },+ },+ cutProject: {+ findFirst: async ({ where }: { where: { id: string; userId: string } }) =>+ where.id === project.id && where.userId === project.userId ? { version: project.version } : null,+ updateMany: async ({ where, data }: { where: { version: number }; data: { doc: ProjectDoc; version: number } }) => {+ if (where.version !== project.version) return { count: 0 };+ project.version = data.version;+ project.doc = data.doc;+ return { count: 1 };+ },+ },+ };+ return { db: db as unknown as HistoryDb, rows, project };+}++const docWith = (background: string): ProjectDoc =>+ ({ version: 1, name: "Cut", createdAt: 0, updatedAt: 0, assets: [], clips: [], audioClips: [], overlays: [], background }) as ProjectDoc;++test("edits record a line, undo and redo walk it, and a new edit after undo drops the redo branch", async () => {+ const { db, project } = fakeDb({ id: "p", userId: "u", version: 3, doc: docWith("#000") });+ // Version 3 → 4: the first step also writes the baseline.+ await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#000"), version: 3 }, after: { doc: docWith("#111"), version: 4 }, label: "Black to grey" });+ project.version = 4;+ await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#111"), version: 4 }, after: { doc: docWith("#222"), version: 5 }, label: "Grey to lighter" });+ project.version = 5;+ expect(await historyState(db, "u", "p", 5)).toEqual({ undo: "Grey to lighter", redo: null });++ const undone = await restoreCheckpoint(db, "u", "p", "undo");+ expect(undone).toEqual({ label: "Grey to lighter", version: 6 });+ expect(project.doc.background).toBe("#111");+ expect(await historyState(db, "u", "p", 6)).toEqual({ undo: "Black to grey", redo: "Grey to lighter" });++ const twice = await restoreCheckpoint(db, "u", "p", "undo");+ expect(twice.label).toBe("Black to grey");+ expect(project.doc.background).toBe("#000");+ await expect(restoreCheckpoint(db, "u", "p", "undo")).rejects.toThrow("Nothing to undo.");++ const redone = await restoreCheckpoint(db, "u", "p", "redo");+ expect(redone.label).toBe("Black to grey");+ expect(project.doc.background).toBe("#111");++ // A fresh edit from here forgets the redo branch.+ await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#111"), version: project.version }, after: { doc: docWith("#333"), version: project.version + 1 }, label: "New direction" });+ project.version += 1;+ expect(await historyState(db, "u", "p", project.version)).toEqual({ undo: "New direction", redo: null });+});++test("a save from the editor breaks the line, and the next edit starts a new one", async () => {+ const { db, project, rows } = fakeDb({ id: "p", userId: "u", version: 1, doc: docWith("#000") });+ await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#000"), version: 1 }, after: { doc: docWith("#111"), version: 2 }, label: "First" });+ project.version = 9; // the editor saved+ await expect(restoreCheckpoint(db, "u", "p", "undo")).rejects.toThrow("last saved from the editor");+ await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#999"), version: 9 }, after: { doc: docWith("#aaa"), version: 10 }, label: "Second" });+ expect(rows.map((r) => [r.seq, r.version, r.label])).toEqual([[0, 9, "Before edits"], [1, 10, "Second"]]);+});++test("the line is capped", async () => {+ const { db, project, rows } = fakeDb({ id: "p", userId: "u", version: 0, doc: docWith("#000") });+ for (let i = 0; i < CHECKPOINT_KEEP + 5; i++) {+ await recordCheckpoint(db, { userId: "u", projectId: "p", before: { doc: docWith("#000"), version: i }, after: { doc: docWith("#111"), version: i + 1 }, label: `Step ${i}` });+ project.version = i + 1;+ }+ expect(rows.length).toBe(CHECKPOINT_KEEP);+ expect(rows[rows.length - 1].label).toBe(`Step ${CHECKPOINT_KEEP + 4}`);+});diff --git a/site/src/cut/server/cloud/history.ts b/site/src/cut/server/cloud/history.tsnew file mode 100644index 00000000..989e9d8e--- /dev/null+++ b/site/src/cut/server/cloud/history.ts@@ -0,0 +1,117 @@+// A cloud project's undo history for edits made from outside the editor.+//+// The editor keeps its history in the tab. An edit that arrives as a job — a+// ChatGPT tool call, a headless command — has no tab, so its history lives+// here: one checkpoint per applied step, holding the whole document. The+// rows form one linear line per project, ordered by seq. Each row names the+// project version whose document it holds; a restore writes that document+// back under a fresh version and re-labels the row with it, so the line stays+// walkable in both directions.+//+// The line is anchored to the project's live version. A save from the editor+// moves the version off the line, and the next recorded step starts a new+// line from that state — an outside edit is never silently undone.+import type { Prisma } from "@/generated/prisma/client";+import { prisma } from "@/lib/prisma";+import type { ProjectDoc } from "@/cut/lib/types";++/** Checkpoints kept per project; the oldest fall off. */+export const CHECKPOINT_KEEP = 30;++export type HistoryDb = Pick<typeof prisma, "cutProjectCheckpoint" | "cutProject">;++type Snapshot = { doc: ProjectDoc; version: number };++const asJson = (doc: ProjectDoc) => doc as unknown as Prisma.InputJsonValue;++async function line(db: HistoryDb, userId: string, projectId: string) {+ return db.cutProjectCheckpoint.findMany({+ where: { projectId, userId },+ orderBy: { seq: "asc" },+ select: { id: true, seq: true, version: true, label: true },+ });+}++/** Record one applied step: the document before it and after it. */+export async function recordCheckpoint(+ db: HistoryDb,+ input: { userId: string; projectId: string; before: Snapshot; after: Snapshot; label: string }+): Promise<void> {+ const { userId, projectId } = input;+ const rows = await line(db, userId, projectId);+ const at = rows.findIndex((r) => r.version === input.before.version);+ let seq: number;+ if (at >= 0) {+ // Continuing the line: whatever was undone past this point is gone.+ const dropped = rows.slice(at + 1).map((r) => r.id);+ if (dropped.length) await db.cutProjectCheckpoint.deleteMany({ where: { id: { in: dropped } } });+ seq = rows[at].seq + 1;+ } else {+ // A new line from the current state.+ if (rows.length) await db.cutProjectCheckpoint.deleteMany({ where: { projectId, userId } });+ await db.cutProjectCheckpoint.create({+ data: { projectId, userId, seq: 0, version: input.before.version, doc: asJson(input.before.doc), label: "Before edits" },+ });+ seq = 1;+ }+ await db.cutProjectCheckpoint.create({+ data: { projectId, userId, seq, version: input.after.version, doc: asJson(input.after.doc), label: input.label },+ });+ const kept = await line(db, userId, projectId);+ const excess = kept.slice(0, Math.max(0, kept.length - CHECKPOINT_KEEP)).map((r) => r.id);+ if (excess.length) await db.cutProjectCheckpoint.deleteMany({ where: { id: { in: excess } } });+}++export class HistoryError extends Error {}++/** What undo and redo would each restore from the given version, by label. */+export async function historyState(+ db: HistoryDb,+ userId: string,+ projectId: string,+ version: number+): Promise<{ undo: string | null; redo: string | null }> {+ const rows = await line(db, userId, projectId);+ const at = rows.findIndex((r) => r.version === version);+ if (at < 0) return { undo: null, redo: null };+ return {+ undo: at > 0 ? rows[at].label : null,+ redo: at + 1 < rows.length ? rows[at + 1].label : null,+ };+}++/** Walk one step along the line and write that document back as a new+ * version. Returns the label of the step undone or redone. */+export async function restoreCheckpoint(+ db: HistoryDb,+ userId: string,+ projectId: string,+ direction: "undo" | "redo"+): Promise<{ label: string; version: number }> {+ const project = await db.cutProject.findFirst({+ where: { id: projectId, userId },+ select: { version: true },+ });+ if (!project) throw new HistoryError("Project not found.");+ const rows = await line(db, userId, projectId);+ const at = rows.findIndex((r) => r.version === project.version);+ if (at < 0)+ throw new HistoryError(+ direction === "undo"+ ? "Nothing to undo: the project was last saved from the editor."+ : "Nothing to redo: the project was last saved from the editor."+ );+ const target = direction === "undo" ? rows[at - 1] : rows[at + 1];+ if (!target) throw new HistoryError(direction === "undo" ? "Nothing to undo." : "Nothing to redo.");+ const row = await db.cutProjectCheckpoint.findUnique({ where: { id: target.id }, select: { doc: true } });+ if (!row) throw new HistoryError("The checkpoint is gone.");+ const doc = { ...(row.doc as unknown as ProjectDoc), updatedAt: Date.now() };+ const version = project.version + 1;+ const updated = await db.cutProject.updateMany({+ where: { id: projectId, userId, version: project.version },+ data: { doc: asJson(doc), name: doc.name, version },+ });+ if (updated.count === 0) throw new HistoryError("The project changed while restoring. Try again.");+ await db.cutProjectCheckpoint.update({ where: { id: target.id }, data: { version } });+ return { label: direction === "undo" ? rows[at].label : target.label, version };+}diff --git a/site/src/cut/server/cloud/lease.ts b/site/src/cut/server/cloud/lease.tsnew file mode 100644index 00000000..1257e852--- /dev/null+++ b/site/src/cut/server/cloud/lease.ts@@ -0,0 +1,61 @@+// A project's agent write lease: one job that edits the document at a time.+// The queued or running row is the lease itself, so a chat turn and a command+// batch on the same project never race through the versioned PUT.+import type { Prisma } from "@/generated/prisma/client";+import { prisma } from "@/lib/prisma";+import { err } from "./util";+import { wakeRenderWorker } from "./wake";++/** The job kinds that hold the lease. An import that adopts its files into+ * the document (spec.adopt) writes the document too, so it holds the lease+ * against turns and batches; adopting imports run alongside each other and+ * merge through a retry in the worker. */+export const LEASE_KINDS = ["agent_turn", "commands"];++/** A live import that will write the document, if any. */+export async function liveAdoptingImport(userId: string, projectId: string): Promise<{ id: string } | null> {+ const rows = await prisma.cutRenderJob.findMany({+ where: { userId, projectId, kind: "import_url", state: { in: ["queued", "running"] } },+ select: { id: true, spec: true },+ });+ return rows.find((r) => Boolean((r.spec as { adopt?: unknown } | null)?.adopt)) ?? null;+}++/** The live lease holders on a project, oldest first. A read-only command+ * batch never saves, so it holds nothing. */+async function liveLeaseRows(userId: string, projectId: string): Promise<{ id: string }[]> {+ const rows = await prisma.cutRenderJob.findMany({+ where: { userId, projectId, kind: { in: LEASE_KINDS }, state: { in: ["queued", "running"] } },+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],+ select: { id: true, spec: true },+ });+ return rows.filter((r) => !(r.spec as { readOnly?: boolean } | null)?.readOnly).map((r) => ({ id: r.id }));+}++/** A live turn or batch holding the lease, if any. */+export async function liveLeaseHolder(userId: string, projectId: string): Promise<{ id: string } | null> {+ return (await liveLeaseRows(userId, projectId))[0] ?? null;+}++/** Create the row, then keep it only if it is the oldest live lease holder for+ * the project. Two concurrent queues both create, both re-check, and exactly+ * one — the older row — survives. Returns the 409 for the loser. */+export async function queueLeasedJob(+ userId: string,+ projectId: string,+ kind: (typeof LEASE_KINDS)[number],+ spec: Prisma.InputJsonValue+): Promise<{ id: string } | Response> {+ const row = await prisma.cutRenderJob.create({ data: { userId, projectId, kind, spec } });+ const oldest = await liveLeaseHolder(userId, projectId);+ if (oldest && oldest.id !== row.id) {+ await prisma.cutRenderJob.delete({ where: { id: row.id } }).catch(() => {});+ return err("Another edit is already running for this project. Wait for it to finish.", 409);+ }+ if (await liveAdoptingImport(userId, projectId)) {+ await prisma.cutRenderJob.delete({ where: { id: row.id } }).catch(() => {});+ return err("An import is still landing in this project. Wait for it to finish, then edit.", 409);+ }+ wakeRenderWorker();+ return { id: row.id };+}diff --git a/site/src/cut/server/cloud/limits.ts b/site/src/cut/server/cloud/limits.tsindex be1b0d3e..b6652da7 100644--- a/site/src/cut/server/cloud/limits.ts+++ b/site/src/cut/server/cloud/limits.ts@@ -75,7 +75,7 @@ export async function liveJobCheck(userId: string): Promise<Response | null> {const live = await prisma.cutRenderJob.count({where: {userId,- kind: { in: [...COUNTED_JOB_KINDS, "agent_turn"] },+ kind: { in: [...COUNTED_JOB_KINDS, "agent_turn", "commands"] },state: { in: ["queued", "running"] },},});diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.tsindex 88b1b2cb..55b05269 100644--- a/site/src/cut/server/cloud/projects.ts+++ b/site/src/cut/server/cloud/projects.ts@@ -120,6 +120,7 @@ export async function deleteProjectCascade(userId: string, id: string): Promise<await prisma.$transaction(async (tx) => {await tx.cutMediaObject.deleteMany({ where: { userId, projectId: id } });await tx.cutChatThread.deleteMany({ where: { userId, projectId: id } });+ await tx.cutProjectCheckpoint.deleteMany({ where: { userId, projectId: id } });await tx.cutProjectShare.deleteMany({ where: { projectId: id } });// deleteMany, so ownership is enforced here rather than trusted from the// caller: a mismatched (userId, id) pair deletes nothing.diff --git a/site/src/cut/server/cloud/turns.ts b/site/src/cut/server/cloud/turns.tsindex a8be17e4..690592f1 100644--- a/site/src/cut/server/cloud/turns.ts+++ b/site/src/cut/server/cloud/turns.ts@@ -1,14 +1,14 @@// One chat turn as a durable job. The page (or an API caller) posts the// thread's messages; the worker container claims the row, runs the headless// turn against the project doc, and settles the row with the reply. The-// queued/running row doubles as the project's agent write lease — one turn at-// a time per project — and the generic /jobs/:jobId route serves the poll.+// queued/running row holds the project's agent write lease (lease.ts), and+// the generic /jobs/:jobId route serves the poll.import type { Prisma } from "@/generated/prisma/client";import { prisma } from "@/lib/prisma";import { cutLimitsFor, liveJobCheck } from "./limits";+import { queueLeasedJob } from "./lease";import { getProject } from "./projects";import { caught, err } from "./util";-import { wakeRenderWorker } from "./wake";// Well above a slimmed thread, well below anything that could hurt the row.const MAX_TURN_BYTES = 1_000_000;@@ -58,27 +58,8 @@ export const turnsCloud = {messages: body.messages,...(typeof body.model === "string" && body.model ? { model: body.model } : {}),};- // The write lease, race-safely: create first, then keep the row only if- // it is the oldest live turn for the project. Two concurrent queues both- // create, both re-check, and exactly one — the older row — survives.- const row = await prisma.cutRenderJob.create({- data: {- userId,- projectId,- kind: "agent_turn",- spec: spec as unknown as Prisma.InputJsonValue,- },- });- const oldest = await prisma.cutRenderJob.findFirst({- where: { userId, projectId, kind: "agent_turn", state: { in: ["queued", "running"] } },- orderBy: [{ createdAt: "asc" }, { id: "asc" }],- select: { id: true },- });- if (oldest && oldest.id !== row.id) {- await prisma.cutRenderJob.delete({ where: { id: row.id } }).catch(() => {});- return err("A turn is already running for this project.", 409);- }- wakeRenderWorker();+ const row = await queueLeasedJob(userId, projectId, "agent_turn", spec as unknown as Prisma.InputJsonValue);+ if (row instanceof Response) return row;return Response.json({ jobId: row.id });} catch (e) {return caught(e, "Could not start the turn.");