Open source CapCut alternative.
TypeScript
feat(site): a deleted library asset leaves a tombstone
David Le3678d7f8e8f6
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 5330fe77..f1549c02 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -86,7 +86,7 @@ Every client call goes through a backend seam (`site/src/cut/lib/backend/`): theThe library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up. Filing an item into a folder on another shelf crosses the same way — the bytes come down and go back up, a file with its cover and a template with its own media, and the copy left behind comes off.-The phone feeds the cloud shelf. Clips recorded in the iOS app upload themselves to it, marked as camera footage; that marker gives the desktop its Camera Roll — a tab of phone clips kept out of the main Library grid, and a locked Camera Roll folder in the editor's library panel so the footage drops into any project. Inspiration saved on the phone lands in an Inspiration folder on the same shelf, links riding the same worker import every shelf uses. Notes are the one thing that flows both ways: the phone and the desktop's Notes tab edit the same set, the newer edit winning, deletes carrying across. Notes file into folders of their own, on the shelf's folder table: the desktop files them by dragging onto the same folder tiles the Library uses, the phone by a folder list it opens like any other, and a folder made on either side is on the other by the next pass. Every request from the app carries a client marker, the server remembers accounts it has seen it from, and only those accounts get the phone tabs — a desktop-only account's sidebar never changes. The app's own guide covers the phone side: [The iOS App](../ios-app.md).+The phone feeds the cloud shelf. Clips recorded in the iOS app upload themselves to it, marked as camera footage; that marker gives the desktop its Camera Roll — a tab of phone clips kept out of the main Library grid, and a locked Camera Roll folder in the editor's library panel so the footage drops into any project. Inspiration saved on the phone lands in an Inspiration folder on the same shelf, links riding the same worker import every shelf uses. What the phone put on the shelf it also mirrors: deleting a clip from the Camera Roll or the Library tombstones it, and the phone deletes its own copy on the next pass, so the roll on the phone and the roll at the desk stay one set. Notes are edited on both sides: the phone and the desktop's Notes tab work the same set, the newer edit winning, deletes carrying across. Notes file into folders of their own, on the shelf's folder table: the desktop files them by dragging onto the same folder tiles the Library uses, the phone by a folder list it opens like any other, and a folder made on either side is on the other by the next pass. Every request from the app carries a client marker, the server remembers accounts it has seen it from, and only those accounts get the phone tabs — a desktop-only account's sidebar never changes. The app's own guide covers the phone side: [The iOS App](../ios-app.md).Some of what the Library holds is lent. Most items are copied when they are used — a clip's bytes become the project's own — but a font is pointed at: every title set in it names it, and the file stays on the shelf where every project can reach it. Lent items follow three rules. They are identified by their bytes, so the same file on two shelves is one entry in the menu and one id in a document. A new one lands on the shelf every surface can read, whenever it is small and the account has room. And a project moving to the cloud takes what it points at with it, so a title keeps its typeface when it starts rendering there — since the id is the bytes, not a word of the document changes. Fonts are the first of these; a .ttf, .otf, .woff or .woff2 dropped on the Library is filed in folders, deleted, and counted against storage like anything else, and every project offers it for titles and captions. A font download arrives as a zip, so the zip is droppable: the faces come out of it and the licence text stays behind, and a family of eighteen weights becomes a single entry. The file is checked by installing it through the renderer's font seam before any bytes move, so what lands is what a preview and an export can draw with, and the family name comes off the font's own metadata. That same moment draws the specimen the shelf keeps as the file's cover, so a font card shows the alphabet in its own face whether or not the page looking at it has that face installed. A new account starts with an empty Fonts folder to say the shelf takes them; it is an ordinary folder and can be deleted. A render job reaches the cloud shelf alone, which is what those rules are for. A font filed into a folder belongs to that folder's shelf like anything else, and a full account keeps its font on the shelf it was working from: it draws in the tab, is marked in the font menu as living on this device, and falls back to the base face in a render job. A title set in a font that is later deleted falls back too, so nothing in a document has to be rewritten.diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismaindex b1970b1a..0213f09a 100644--- a/site/prisma/Cut.prisma+++ b/site/prisma/Cut.prisma@@ -105,13 +105,17 @@ model CutChatThread {}model CutLibraryAsset {- id String @id @default(cuid())+ id String @id @default(cuid())userId StringmediaObjectId StringfolderId String?meta Json?- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ // Set when someone deleted this asset. The bytes leave at once; the row+ // stays as a tombstone so the iOS app takes the same clip off the phone,+ // and the nightly sweep drops it once every device has had time to see it.+ deletedAt DateTime?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt@@index([userId, createdAt])}diff --git a/site/src/cut/components/CameraRollView.tsx b/site/src/cut/components/CameraRollView.tsxindex 3794dd6f..0563d05b 100644--- a/site/src/cut/components/CameraRollView.tsx+++ b/site/src/cut/components/CameraRollView.tsx@@ -98,8 +98,8 @@ export function CameraRollView() {<AlertDialogHeader><AlertDialogTitle>Delete “{deleting?.name}”?</AlertDialogTitle><AlertDialogDescription>- The clip leaves your cloud Camera Roll. Projects that already use it keep their own- copy, and a copy still on your phone stays there.+ The clip leaves your cloud Camera Roll and the phone it was shot on. Projects that+ already use it keep their own copy.</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex 0c67cfd0..f579199f 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -54,7 +54,7 @@ export const LIBRARY_TOOLS = [{name: "library_organize",description:- "Organize the shared Library: create_folder / rename_folder / delete_folder (a deleted folder's items drop to the root), move_asset files an asset or template into a folder (omit folder_id for the root), delete_asset / delete_template remove an item. Deletes are permanent — projects keep their own copies, but delete only what the user explicitly asked to remove.",+ "Organize the shared Library: create_folder / rename_folder / delete_folder (a deleted folder's items drop to the root), move_asset files an asset or template into a folder (omit folder_id for the root), delete_asset / delete_template remove an item. Deletes are permanent — projects keep their own copies, but delete only what the user explicitly asked to remove. Deleting an asset with origin \"camera\" or \"inspiration\" takes it off the user's phone as well.",inputSchema: obj({action: {type: "string",diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.tsindex ae38e4c1..55c7bb4f 100644--- a/site/src/cut/server/cloud/gc.ts+++ b/site/src/cut/server/cloud/gc.ts@@ -18,6 +18,10 @@ const PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;const SCRATCH_MAX_AGE_MS = 24 * 60 * 60 * 1000;const ORPHAN_MAX_AGE_MS = 24 * 60 * 60 * 1000;const JOB_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;+// A deleted library asset leaves a row behind so the iOS app can take the same+// clip off the phone. A phone that has not synced in a season has a bigger+// problem than a missed delete, so the row goes after that.+const LIBRARY_TOMBSTONE_MAX_AGE_MS = 90 * 24 * 60 * 60 * 1000;const TERMINAL_STATES = ["done", "error", "canceled"];// Reclamation converges over daily runs rather than risking one long one.const RECLAIM_SCAN_LIMIT = 500;@@ -117,7 +121,7 @@ async function reclaimPlan(userId: string, target: number): Promise<ReclaimPlan>}const assets = await prisma.cutLibraryAsset.findMany({- where: { userId },+ where: { userId, deletedAt: null },orderBy: { createdAt: "asc" },select: { id: true, mediaObjectId: true },});@@ -332,6 +336,12 @@ export async function runGc(): Promise<Response> {return { projects: 0, versions: 0, objects: 0, failed: 1 };});+ // Library tombstones past the window every client has had to see them in.+ // Their bytes went with the delete; this is the empty row.+ const tombstones = await prisma.cutLibraryAsset.deleteMany({+ where: { deletedAt: { lt: new Date(Date.now() - LIBRARY_TOMBSTONE_MAX_AGE_MS) } },+ });+const reclaimed = await reclaimOverQuota();return Response.json({@@ -339,6 +349,7 @@ export async function runGc(): Promise<Response> {orphanedMedia: orphans.length,inferenceScratch: scratch.length,renderJobs: jobs.count,+ libraryTombstones: tombstones.count,staleLadderProjects: ladders.projects,staleLadderVersions: ladders.versions,staleLadderObjects: ladders.objects,diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex 100f90fc..33b0f9c4 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -178,13 +178,20 @@ async function copyIntoLibrary(/** Delete a library asset with its media object, bytes, and R2 key. Returns* bytes freed, or null when the asset is not this user's. Shared by the delete- * route and the storage-reclamation sweep (gc.ts). */+ * route and the storage-reclamation sweep (gc.ts).+ *+ * `tombstone` keeps the asset row behind with `deletedAt` set. That row is how+ * a delete made here reaches the iOS app, which mirrors the Camera Roll on the+ * phone: the listing names it, and the phone takes the same clip off. The+ * reclamation sweep passes nothing, so an asset it collects simply stops being+ * listed and the phone keeps the copy it shot. */export async function deleteLibraryAssetCascade(userId: string,id: string,+ opts?: { tombstone?: boolean },): Promise<number | null> {const asset = await prisma.cutLibraryAsset.findFirst({- where: { id, userId },+ where: { id, userId, deletedAt: null },});if (!asset) return null;const obj = await prisma.cutMediaObject.findFirst({@@ -203,7 +210,14 @@ export async function deleteLibraryAssetCascade(.filter((o) => o.uploadState === "complete").reduce((n, o) => n + Number(o.bytes), 0);await prisma.$transaction(async (tx) => {- await tx.cutLibraryAsset.delete({ where: { id } });+ if (opts?.tombstone) {+ await tx.cutLibraryAsset.update({+ where: { id },+ data: { deletedAt: new Date() },+ });+ } else {+ await tx.cutLibraryAsset.delete({ where: { id } });+ }for (const o of objects)await tx.cutMediaObject.delete({ where: { id: o.id } });if (freed > 0) await addUsage(tx, userId, -freed);@@ -257,12 +271,24 @@ async function deleteLibraryObject(userId: string, fileName: string) {}export const libraryCloud = {- async list(userId: string) {- const [assetRows, folderRows, templateRows] = await Promise.all([+ /** The shelf. `?deleted=1` adds the tombstoned ids — the phone asks for+ * them to mirror a delete made here onto its Camera Roll, and it is the+ * only client that does. Every other listing skips the query and the rows+ * it would carry: an account that has pruned its shelf for a season has+ * thousands of them, and the editor reads none. */+ async list(userId: string, req?: Request) {+ const wantsDeleted = !!req && new URL(req.url).searchParams.get("deleted") === "1";+ const [assetRows, deletedRows, folderRows, templateRows] = await Promise.all([prisma.cutLibraryAsset.findMany({- where: { userId },+ where: { userId, deletedAt: null },orderBy: { createdAt: "desc" },}),+ wantsDeleted+ ? prisma.cutLibraryAsset.findMany({+ where: { userId, deletedAt: { not: null } },+ select: { id: true },+ })+ : Promise.resolve([]),prisma.cutFolder.findMany({where: { userId, scope: "library" },orderBy: { createdAt: "asc" },@@ -289,7 +315,14 @@ export const libraryCloud = {createdAt: f.createdAt.getTime(),}));const templates = templateRows.map(templateView);- return Response.json({ assets, folders, templates });+ // Assets someone deleted, for a client that holds its own copy of them:+ // the iOS app deletes the matching clip on the phone.+ return Response.json({+ assets,+ folders,+ templates,+ ...(wantsDeleted ? { deletedAssetIds: deletedRows.map((r) => r.id) } : {}),+ });},/** Mint a presigned PUT for a direct-to-library upload. */@@ -380,7 +413,7 @@ export const libraryCloud = {// A retried complete (the iOS app reconciling after an interrupted// sync) lands on the asset it already made instead of minting a twin.const already = await prisma.cutLibraryAsset.findFirst({- where: { userId, mediaObjectId: obj.id },+ where: { userId, mediaObjectId: obj.id, deletedAt: null },});if (already) return Response.json(assetView(already, obj));const info = obj.uploadState === "complete" ? null : await head(key);@@ -461,7 +494,7 @@ export const libraryCloud = {projectId: string;};const asset = await prisma.cutLibraryAsset.findFirst({- where: { id: assetId, userId },+ where: { id: assetId, userId, deletedAt: null },});if (!asset) throw new Error("Library asset not found.");const obj = await prisma.cutMediaObject.findUnique({@@ -537,7 +570,7 @@ export const libraryCloud = {if (!folder) throw new Error("Folder not found.");}const asset = await prisma.cutLibraryAsset.findFirst({- where: { id, userId },+ where: { id, userId, deletedAt: null },});if (asset) {await prisma.cutLibraryAsset.update({@@ -563,7 +596,7 @@ export const libraryCloud = {try {// Idempotent: a delete replayed from the iOS app's journal after the// asset already left reports done, so the tombstone clears.- await deleteLibraryAssetCascade(userId, id);+ await deleteLibraryAssetCascade(userId, id, { tombstone: true });return Response.json({ ok: true });} catch (e) {return caught(e, "Could not delete.");diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex b4ef9f0a..97a3fa5a 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -64,7 +64,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "POST", path: "/api/cut-cloud/projects/:id/convert", handler: (r, u, p) => jobsCloud.convert(u, p.id, r) },{ method: "POST", path: "/api/cut-cloud/media/presign-get", handler: (r, u) => mediaCloud.presignGetBatch(u, r) },- { method: "GET", path: "/api/cut-cloud/library", handler: (_r, u) => libraryCloud.list(u) },+ { method: "GET", path: "/api/cut-cloud/library", handler: (r, u) => libraryCloud.list(u, r) },{ method: "POST", path: "/api/cut-cloud/library/presign", handler: (r, u) => libraryCloud.presign(u, r) },{ method: "POST", path: "/api/cut-cloud/library/complete", handler: (r, u) => libraryCloud.complete(u, r) },{ method: "POST", path: "/api/cut-cloud/library/presign-get", handler: (r, u) => libraryCloud.presignGetBatch(u, r) },