Skip to content

Open source CapCut alternative.

TypeScript

feat(site): delete folders recursively on every residency [rebuild]

David Le492f8df68c82
diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.ts
index 7a4ace18..04815ff2 100644
--- a/site/src/cut/components/LibraryView.tools.ts
+++ b/site/src/cut/components/LibraryView.tools.ts
@@ -71,7 +71,7 @@ export const LIBRARY_TOOLS = [
{
name: "library_organize",
description:
- "Organize the shared Library. Folders nest: create_folder makes one at the root or inside parent_id, rename_folder renames, move_folder files a folder under another (omit parent_id for the root; never into itself or a folder inside it), delete_folder removes one (what it held — items and folders — moves up one level). 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.",
+ "Organize the shared Library. Folders nest: create_folder makes one at the root or inside parent_id, rename_folder renames, move_folder files a folder under another (omit parent_id for the root; never into itself or a folder inside it), delete_folder deletes one with everything in it — its folders and every item they hold — permanently; a camera clip filed there stays in Camera Roll, and an inspiration item in it leaves the phone too. 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/components/SidePanel.tools.ts b/site/src/cut/components/SidePanel.tools.ts
index ecbd4587..e63fb90e 100644
--- a/site/src/cut/components/SidePanel.tools.ts
+++ b/site/src/cut/components/SidePanel.tools.ts
@@ -48,7 +48,7 @@ export const SIDE_PANEL_TOOLS = [
{
name: "media_organize",
description:
- "Organize the Media panel's Project Files with folders (this project only; the shared Library has library_organize): create_folder / rename_folder / delete_folder (a deleted folder's files drop back to the top level), move_asset files user-imported media into a folder (omit folder_id for the top level). Folders and each asset's folderId are in `media` / `mediaFolders` from get_state. create_folder can take asset_ids to file into the new folder in the same call.",
+ "Organize the Media panel's Project Files with folders (this project only; the shared Library has library_organize): create_folder / rename_folder / delete_folder (permanent: every file in the folder is removed from the project, and the timeline clips made from them go too), move_asset files user-imported media into a folder (omit folder_id for the top level). Folders and each asset's folderId are in `media` / `mediaFolders` from get_state. create_folder can take asset_ids to file into the new folder in the same call.",
inputSchema: obj({
action: {
type: "string",
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index e9dc3718..7acbe3cd 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -104,11 +104,13 @@ import {
deleteLibraryFolder,
deleteTemplate,
fetchLibrary,
+ folderDeleteTakes,
importLibraryAsset,
moveLibraryItem,
updateLibraryFolder,
saveAssetToLibrary,
} from "./library";
+import { forgetLinkedCopies } from "./linkedLibrary";
import { fetchNotes } from "./notes";
import {
captureFreezeFrame,
@@ -3896,8 +3898,16 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const id = String(input.folder_id ?? "");
const r = folderShelf(id);
if (!r) throw new ToolError(`No library folder with id ${id}.`);
+ const takes = folderDeleteTakes(lib, [{ id }]);
+ forgetLinkedCopies(takes.assets);
await deleteLibraryFolder(r, id);
- return { deleted: true, note: "What it held moved up one level." };
+ const phone = takes.assets.filter((a) => !!a.origin).length;
+ return {
+ deleted: true,
+ items: takes.assets.length + takes.templates.length,
+ ...(phone > 0 ? { removedFromPhone: phone } : {}),
+ note: "Everything in it — folders and items — was deleted too. A camera clip filed there stays in Camera Roll.",
+ };
}
case "move_asset": {
const folderId =
@@ -3973,8 +3983,13 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
}
case "delete_folder": {
const f = folderOf(String(input.folder_id ?? ""));
+ const files = s.assets.filter((a) => a.folderId === f.id).length;
s.removeMediaFolder(f.id);
- return { deleted: true, note: "Its files moved to the Media panel's top level." };
+ return {
+ deleted: true,
+ files,
+ note: "Its files were removed from the project, with the timeline clips made from them.",
+ };
}
case "move_asset": {
const folderId =
diff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.ts
index d9e1251f..5fedbc9f 100644
--- a/site/src/cut/lib/backend/browser/library.ts
+++ b/site/src/cut/lib/backend/browser/library.ts
@@ -11,7 +11,7 @@
// video off a link, so that import runs on the cloud worker and the bytes are
// adopted afterwards (`lib/library.ts`); those paths fall through to the
// hosted twin.
-import { resolveParent, settleParents } from "../../folderTree";
+import { resolveParent, settleParents, subtreeOf } from "../../folderTree";
import type {
AssetType,
LibraryTemplate,
@@ -244,20 +244,47 @@ async function serveMedia(
return serveFile(file, fileName, download);
}
+/** Take the assets in `ids` out of the index, handing back the files they
+ * own — the source and its poster — for the caller to drop once the index
+ * is written. */
+function takeAssets(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {
+ const files: string[] = [];
+ idx.assets = idx.assets.filter((a) => {
+ if (!ids.has(a.id)) return true;
+ files.push(a.fileName);
+ if (a.posterFile) files.push(a.posterFile);
+ return false;
+ });
+ return files;
+}
+
+/** Take the templates in `ids` out of the index, handing back their media
+ * copies, which are private to them. */
+function takeTemplates(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {
+ const files: string[] = [];
+ idx.templates = idx.templates.filter((t) => {
+ if (!ids.has(t.id)) return true;
+ for (const m of t.media ?? []) files.push(m.fileName);
+ return false;
+ });
+ return files;
+}
+
+/** Drop files the index no longer names, with the blob URLs minted for them. */
+async function dropFiles(files: string[]): Promise<void> {
+ for (const f of files) {
+ await store.deleteLibraryMedia(f);
+ revokeRegistered(libraryMediaApiPath(f));
+ }
+}
+
async function removeAsset(id: string): Promise<Response> {
try {
- const { fileName, posterFile } = await mutateIndex((idx) => {
- const asset = idx.assets.find((a) => a.id === id);
- if (!asset) throw new Error("Library asset not found.");
- idx.assets = idx.assets.filter((a) => a.id !== id);
- return { fileName: asset.fileName, posterFile: asset.posterFile };
+ const files = await mutateIndex((idx) => {
+ if (!idx.assets.some((a) => a.id === id)) throw new Error("Library asset not found.");
+ return takeAssets(idx, new Set([id]));
});
- await store.deleteLibraryMedia(fileName);
- revokeRegistered(libraryMediaApiPath(fileName));
- if (posterFile) {
- await store.deleteLibraryMedia(posterFile).catch(() => {});
- revokeRegistered(libraryMediaApiPath(posterFile));
- }
+ await dropFiles(files);
return json({ ok: true });
} catch (e) {
return caught(e, "Could not delete.");
@@ -338,19 +365,20 @@ async function updateFolder(req: Request, id: string): Promise<Response> {
}
}
-/** Delete a folder. What it held — its items and the folders inside it —
- * comes up one level, filed where the folder was. */
+/** Delete a folder and everything in it: the folders filed under it, however
+ * deep, and every asset and template they hold, in one write of the index. */
async function deleteFolder(id: string): Promise<Response> {
try {
- await mutateIndex((idx) => {
- const gone = idx.folders.find((f) => f.id === id);
- if (!gone) return;
- const up = gone.parentId ?? null;
- idx.folders = idx.folders.filter((f) => f.id !== id);
- for (const f of idx.folders) if ((f.parentId ?? null) === id) f.parentId = up;
- for (const a of idx.assets) if (a.folderId === id) a.folderId = up;
- for (const t of idx.templates) if (t.folderId === id) t.folderId = up;
+ const files = await mutateIndex((idx) => {
+ if (!idx.folders.some((f) => f.id === id)) return [];
+ const tree = new Set(subtreeOf(idx.folders, id));
+ const filed = (x: { folderId?: string | null }) => !!x.folderId && tree.has(x.folderId);
+ const assets = new Set(idx.assets.filter(filed).map((a) => a.id));
+ const templates = new Set(idx.templates.filter(filed).map((t) => t.id));
+ idx.folders = idx.folders.filter((f) => !tree.has(f.id));
+ return [...takeAssets(idx, assets), ...takeTemplates(idx, templates)];
});
+ await dropFiles(files);
return json({ ok: true });
} catch (e) {
return caught(e, "Could not delete folder.");
@@ -609,16 +637,8 @@ async function renameTemplate(req: Request, id: string): Promise<Response> {
async function deleteTemplate(id: string): Promise<Response> {
try {
- const template = await mutateIndex((idx) => {
- const t = idx.templates.find((x) => x.id === id);
- idx.templates = idx.templates.filter((x) => x.id !== id);
- return t;
- });
- // A template's media copies are private to it, so they go with it.
- for (const m of template?.media ?? []) {
- await store.deleteLibraryMedia(m.fileName);
- revokeRegistered(libraryMediaApiPath(m.fileName));
- }
+ const files = await mutateIndex((idx) => takeTemplates(idx, new Set([id])));
+ await dropFiles(files);
return json({ ok: true });
} catch (e) {
return caught(e, "Could not delete the template.");
diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.ts
index f6b2ca2d..e6497165 100644
--- a/site/src/cut/lib/backend/browser/router.ts
+++ b/site/src/cut/lib/backend/browser/router.ts
@@ -6,7 +6,7 @@
// Owned here: projects CRUD + folders, media bytes, image import, presign-get
// (answered with blob URLs), exports, the export-jobs feed, and the library
// shelf (./library.ts). Everything else is the driver's cloud proxy.
-import { resolveParent, settleParents } from "../../folderTree";
+import { resolveParent, settleParents, subtreeOf } from "../../folderTree";
import { sanitizeGuideLines, sanitizeGuides } from "../../guides";
import { normalizeAspect, type ProjectDoc, type ProjectFolder } from "../../types";
import {
@@ -207,33 +207,35 @@ async function updateFolder(req: Request, fid: string): Promise<Response> {
}
}
-/** Delete a folder. What it held — its projects and the folders inside it —
- * comes up one level, filed where the folder was. */
+/** Delete a folder and everything in it: the folders filed under it, however
+ * deep, and every project they hold, each the way its own delete goes. The
+ * projects go first and the folders last, so a run that stops partway leaves
+ * the rest where a retry finds it. */
async function deleteFolder(fid: string): Promise<Response> {
try {
- let up: string | null = null;
- await store.updateIndex((idx) => {
- up = idx.folders.find((f) => f.id === fid)?.parentId ?? null;
- return {
- ...idx,
- folders: idx.folders
- .filter((f) => f.id !== fid)
- .map((f) => ((f.parentId ?? null) === fid ? { ...f, parentId: up } : f)),
- };
- });
+ const { folders } = await store.readIndex();
+ if (!folders.some((f) => f.id === fid)) return json({ ok: true });
+ const tree = new Set(subtreeOf(folders, fid));
for (const id of await store.listProjectIds()) {
const doc = await store.readDoc(id);
- if (doc?.folderId === fid) {
- doc.folderId = up;
- await store.writeDoc(id, doc);
- }
+ if (doc?.folderId && tree.has(doc.folderId)) await dropProject(id);
}
+ await store.updateIndex((idx) => ({
+ ...idx,
+ folders: idx.folders.filter((f) => !tree.has(f.id)),
+ }));
return json({ ok: true });
} catch (e) {
return caught(e, "Could not delete folder.");
}
}
+/** Delete a project: its directory, and the blob URLs minted for its files. */
+async function dropProject(id: string): Promise<void> {
+ await store.deleteProject(id);
+ revokeRegistered(`/api/cut/projects/${id}/`);
+}
+
async function uploadMedia(req: Request, id: string): Promise<Response> {
try {
if (!(await store.readDoc(id))) return err("Project not found.", 404);
@@ -392,8 +394,7 @@ export async function dispatchBrowserRoute(
}
if (method === "PUT") return putProject(req(), id);
if (method === "DELETE") {
- await store.deleteProject(id);
- revokeRegistered(`/api/cut/projects/${id}/`);
+ await dropProject(id);
return json({ ok: true });
}
return err("Method not allowed.", 405);
diff --git a/site/src/cut/lib/folderTree.test.ts b/site/src/cut/lib/folderTree.test.ts
new file mode 100644
index 00000000..0c777e4a
--- /dev/null
+++ b/site/src/cut/lib/folderTree.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "bun:test";
+import { childrenOf, folderWithin, resolveParent, subtreeOf } from "./folderTree";
+
+// A shelf three deep, with a branch beside the one being deleted.
+const folders = [
+ { id: "a", parentId: null },
+ { id: "b", parentId: "a" },
+ { id: "c", parentId: "b" },
+ { id: "d", parentId: "a" },
+ { id: "e", parentId: null },
+];
+
+describe("what a folder delete takes", () => {
+ test("the folder and everything filed under it, however deep", () => {
+ expect(subtreeOf(folders, "a").sort()).toEqual(["a", "b", "c", "d"]);
+ expect(subtreeOf(folders, "b")).toEqual(["b", "c"]);
+ });
+
+ test("a folder beside it is left standing", () => {
+ expect(subtreeOf(folders, "a")).not.toContain("e");
+ expect(subtreeOf(folders, "e")).toEqual(["e"]);
+ });
+
+ test("a loop two offline devices made is walked once", () => {
+ const looped = [
+ { id: "x", parentId: "y" },
+ { id: "y", parentId: "x" },
+ ];
+ expect(subtreeOf(looped, "x").sort()).toEqual(["x", "y"]);
+ });
+});
+
+describe("where a folder may file", () => {
+ test("never under itself or anything inside it", () => {
+ expect(folderWithin(folders, "c", "a")).toBe(true);
+ expect(resolveParent(folders, "a", "c")).toBeNull();
+ expect(resolveParent(folders, "d", "b")).toBe("b");
+ });
+
+ test("the top level lists only the folders filed there", () => {
+ expect(childrenOf(folders, null).map((f) => f.id)).toEqual(["a", "e"]);
+ });
+});
diff --git a/site/src/cut/lib/folderTree.ts b/site/src/cut/lib/folderTree.ts
index 4376a0d6..378f4d55 100644
--- a/site/src/cut/lib/folderTree.ts
+++ b/site/src/cut/lib/folderTree.ts
@@ -2,8 +2,10 @@
* Folders that file into folders. Every folder table — project folders,
* library folders, note folders, on every shelf — carries `parentId`, null
* for the top level, and these are the rules they all share: a folder never
- * files under itself, what a deleted folder held comes up one level, and a
- * parent nothing answers for reads as the top level.
+ * files under itself, a deleted folder takes everything under it with it, and
+ * a parent nothing answers for reads as the top level. Note folders are the
+ * exception on deletes: what they held comes up one level, the way the phone
+ * files it.
*/
export interface TreeFolder {
@@ -62,6 +64,25 @@ export function resolveParent(
return parentId;
}
+/** `id` and every folder filed under it, however deep: what a delete of `id`
+ * takes. A loop in the listing is walked once. */
+export function subtreeOf(folders: readonly TreeFolder[], id: string): string[] {
+ const under = new Map<string | null, string[]>();
+ for (const f of folders) {
+ const p = parentOf(f);
+ under.set(p, [...(under.get(p) ?? []), f.id]);
+ }
+ const tree = [id];
+ const seen = new Set(tree);
+ for (let i = 0; i < tree.length; i++)
+ for (const child of under.get(tree[i]) ?? [])
+ if (!seen.has(child)) {
+ seen.add(child);
+ tree.push(child);
+ }
+ return tree;
+}
+
/** The folders filed right under `parentId` (null for the top level). */
export function childrenOf<F extends TreeFolder>(
folders: readonly F[],
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 4ec98ac5..d08dd574 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -5,6 +5,7 @@ import { cloudBackend } from "./backend/cloud";
import { readSnapshot, writeSnapshot } from "./cache";
import { pollCloudJob } from "./cloudJob";
import { downloadFromUrl } from "./download";
+import { subtreeOf } from "./folderTree";
import { normalizeLink } from "./link";
import { installFontFace } from "./fontAssets";
import { fontLabelFor } from "./fontName";
@@ -464,7 +465,24 @@ export async function updateLibraryFolder(
return { ...((await res.json()) as Omit<LibraryFolder, "residency">), residency };
}
-/** Delete a folder. What it held comes up one level. */
+/** What a delete of `folders` takes off the shelf: those folders and the ones
+ * filed under them, however deep, and the assets and templates filed in any
+ * of them. A camera clip lives in Camera Roll whatever folder it is filed
+ * under, so it stays; the shelf unfiles it. */
+export function folderDeleteTakes(
+ data: LibraryData,
+ folders: readonly { id: string }[],
+): { tree: Set<string>; assets: LibraryAsset[]; templates: LibraryTemplateItem[] } {
+ const tree = new Set(folders.flatMap((f) => subtreeOf(data.folders, f.id)));
+ const filed = (x: { folderId?: string | null }) => !!x.folderId && tree.has(x.folderId);
+ return {
+ tree,
+ assets: data.assets.filter((a) => filed(a) && a.origin !== "camera"),
+ templates: data.templates.filter(filed),
+ };
+}
+
+/** Delete a folder and everything in it, folders and items alike. */
export async function deleteLibraryFolder(
residency: Residency,
id: string,
diff --git a/site/src/cut/lib/linkedLibrary/registry.ts b/site/src/cut/lib/linkedLibrary/registry.ts
index 21e185ec..94a22067 100644
--- a/site/src/cut/lib/linkedLibrary/registry.ts
+++ b/site/src/cut/lib/linkedLibrary/registry.ts
@@ -292,6 +292,13 @@ export async function syncLinkedLibrary(): Promise<void> {
publish([...found.values()]);
}
+/** Drop the shelf copies of the linked assets among `assets` — what a
+ * delete of them takes, whether the grid, a folder delete, or the assistant
+ * runs it. */
+export function forgetLinkedCopies(assets: readonly Pick<LibraryAsset, "id" | "type">[]): void {
+ for (const a of assets) if (isLinkedType(a.type)) forgetLinkedCopy(a.id);
+}
+
/** Drop one shelf copy the moment it is deleted, so the shelf and the menus
* never disagree while the round trip settles. */
export function forgetLinkedCopy(assetId: string): void {
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index fcf9c0ae..db71eeca 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -869,7 +869,7 @@ export interface EditorState {
/** Create a Media folder, filing `assetIds` into it; returns the new id. */
addMediaFolder: (name: string, assetIds?: string[]) => string;
renameMediaFolder: (id: string, name: string) => void;
- /** Delete a Media folder; its assets drop back to the panel's top level. */
+ /** Delete a Media folder and every asset in it, timeline clips and all. */
removeMediaFolder: (id: string) => void;
/** File assets into a Media folder (null = back to the top level). */
moveAssetsToMediaFolder: (ids: string[], folderId: string | null) => void;
@@ -3708,13 +3708,13 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
mediaFolders: s.mediaFolders.map((f) => (f.id === id ? { ...f, name } : f)),
})),
- removeMediaFolder: (id) =>
- set((s) => ({
- mediaFolders: s.mediaFolders.filter((f) => f.id !== id),
- assets: s.assets.map((a) =>
- a.folderId === id ? { ...a, folderId: undefined } : a
- ),
- })),
+ removeMediaFolder: (id) => {
+ // Every file in the folder goes the way its own delete goes, timeline
+ // clips and all; then the folder.
+ const s = get();
+ for (const a of s.assets) if (a.folderId === id) s.removeAsset(a.id);
+ set((s) => ({ mediaFolders: s.mediaFolders.filter((f) => f.id !== id) }));
+ },
moveAssetsToMediaFolder: (ids, folderId) => {
const move = new Set(ids);
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index ca330837..d5a65c4b 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -540,7 +540,7 @@ How to decide the details the user left open. Make the call, apply it, and state
Project media (\`media\` in editor_state) is every file in the open project. The Media panel shows the user's own imports — assets with no origin tag; created media (origin generated, voiceover, stock, chat, freeze, recording, block) lives where it was made until filed away.
- add_clip / add_overlay_video place a project asset on the timeline, and add_clip's \`blocks\` lays a cut out ahead of its footage — one block per shot on track 0, the length that shot runs, labelled with what the person supplies; replace_item fills one of those blocks, or swaps any clip's, soundtrack clip's or sticker's source, in place; listen_audio plays an asset's sound to you — an audio asset, or a video/clip's own track; watch_video is the visual sibling.
- file_asset moves a created asset into Media (to:"media", clears its origin) or copies any asset into the Library (to:"library").
-- media_organize keeps the Media panel's own folders (\`mediaFolders\` in editor_state, per project): create/rename/delete a folder, move_asset to file media into one — filing a created asset also moves it into Media, like dropping its card on a folder tile.
+- media_organize keeps the Media panel's own folders (\`mediaFolders\` in editor_state, per project): create/rename/delete a folder (a delete removes every file in it, timeline clips and all), move_asset to file media into one — filing a created asset also moves it into Media, like dropping its card on a folder tile.
- delete_asset removes an asset from the project plus its timeline clips; the media does not come back with undo, so only on an explicit ask, and say what went with it.
- convert_media rewrites project media as MP4 (H.264/AAC) in place, one call for a whole list of asset ids. Reach for it when footage plays black or shows a format warning — phone HEVC, ProRes, raw PCM sound — and whenever someone asks for mp4 files. That ask is usually files dropped straight on this chat: convert them and each one is on its own card in the thread, converted, ready to download or drag onto the timeline — close by saying they're on their cards. An asset that came from the Media panel stays there. Streams that already fit are copied, so most .mov files convert in seconds, and a file that is already H.264/AAC MP4 comes back untouched (say so instead of claiming a conversion); max_height shrinks an oversized source at the same time. Clips already cut from the asset keep playing. It runs on whichever machine already holds the bytes — this Mac, the render worker, or the tab — and works with no editor tab attached; when nothing available can decode the source the error names the fix (the Mac app, another browser, or moving the project to the cloud), so report it and move on.
Preview selection is shared with the timeline. Use select with additive:true to toggle multiple items, then move_selection with dx/dy frame fractions to move them together. Caption positions apply to their whole track.
@@ -550,7 +550,7 @@ The Library is shared across every project: folders, reusable assets, and templa
- Assets from the user's iOS app carry an origin: "camera" is a clip they recorded on their phone (their Camera Roll — "the video I shot on my phone" lives here), "inspiration" a reference saved into the Library's Inspiration folder. library_add imports either like any other asset. A camera clip's name is the clock it was shot on; its title, when it has one, was read off the clip itself and is what the user sees on the card — match a request like "the one about the launch" against the title.
- notes_list reads the user's synced notes (written on their phone or the Notes tab) with the folders they are filed in and the labels they carry — the place to look when they point at "my note", or name a folder or label, for a script, caption, or voiceover text.
- library_share creates and manages public or email-restricted links to Library folders and assets. A folder link includes its subfolders and current contents. Local items are copied to Cloud before sharing; manage the returned cloud target id afterward. Viewers can preview and download.
-- library_organize handles folders (create/rename/move/delete — folders nest, and a folder's parentId in library_list says where it sits), filing (move_asset), and deletes (permanent — explicit ask only).
+- library_organize handles folders (create/rename/move/delete — folders nest, and a folder's parentId in library_list says where it sits; deleting a folder deletes everything in it), filing (move_asset), and deletes (permanent — explicit ask only).
- import_url reads any URL (TikTok, YouTube, Instagram, an X post or Article, a web page, direct links): a page comes back as its article text and its pictures, a post as its video or photos, and a source that is only words as sourceText alone. When the user asks for the sound alone — a song, a soundtrack — pass audio_only and the audio track lands as an audio asset. Media lands as a card in the chat with that text quoted beside it; the user drags a card to the timeline, Media, or the Library. Place it with add_clip only when they asked for it in the cut.
Attachments: media files dropped on the chat import into project media by themselves; library attachments wait for library_add.`,
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index 217cee3f..ce7ea3d4 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -12,7 +12,7 @@ import type {
TemplateMedia,
} from "../library";
import { templateExtras } from "../templateExtras";
-import { resolveParent } from "@/cut/lib/folderTree";
+import { resolveParent, subtreeOf } from "@/cut/lib/folderTree";
import type { StoredAsset } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
@@ -783,36 +783,39 @@ export const libraryCloud = {
}
},
- /** Delete a folder. What it held — its items and the folders inside it —
- * comes up one level, filed where the folder was. */
+ /** Delete a folder and everything in it: the folders filed under it,
+ * however deep, and every asset and template they hold, each through the
+ * cascade its own delete runs — an asset leaves a tombstone for the phone
+ * like any other delete. A camera clip lives in Camera Roll whatever folder
+ * it is filed under, so it stays, unfiled. The items go first and the
+ * folders last, so a run that stops partway leaves the rest where a retry
+ * finds it. */
async deleteFolder(userId: string, id: string) {
try {
- await prisma.$transaction(async (tx) => {
- const gone = await tx.cutFolder.findFirst({
- where: { id, userId, scope: "library" },
- select: { parentId: true },
- });
- if (!gone) return;
- const up = gone.parentId;
- await tx.cutFolder.delete({ where: { id } });
- await tx.cutFolder.updateMany({
- where: { userId, scope: "library", parentId: id },
- data: { parentId: up },
- });
- await tx.cutLibraryAsset.updateMany({
- where: { userId, folderId: id },
- data: { folderId: up },
- });
- const templates = await tx.cutTemplate.findMany({ where: { userId } });
- for (const t of templates) {
- const doc = t.doc as unknown as TemplateDoc;
- if (doc.folderId === id) {
- await tx.cutTemplate.update({
- where: { id: t.id },
- data: { doc: asJson({ ...doc, folderId: up }) },
- });
- }
- }
+ const folders = await prisma.cutFolder.findMany({
+ where: { userId, scope: "library" },
+ select: { id: true, parentId: true },
+ });
+ if (!folders.some((f) => f.id === id)) return Response.json({ ok: true });
+ const tree = subtreeOf(folders, id);
+ const assets = await prisma.cutLibraryAsset.findMany({
+ where: { userId, folderId: { in: tree }, deletedAt: null },
+ select: { id: true, meta: true },
+ });
+ const isCamera = (a: { meta: unknown }) => ((a.meta ?? {}) as AssetMeta).origin === "camera";
+ for (const a of assets)
+ if (!isCamera(a)) await deleteLibraryAssetCascade(userId, a.id, { tombstone: true });
+ await prisma.cutLibraryAsset.updateMany({
+ where: { userId, id: { in: assets.filter(isCamera).map((a) => a.id) } },
+ data: { folderId: null },
+ });
+ const templates = await prisma.cutTemplate.findMany({ where: { userId } });
+ for (const t of templates) {
+ const folderId = (t.doc as unknown as TemplateDoc).folderId;
+ if (folderId && tree.includes(folderId)) await deleteTemplateCascade(userId, t);
+ }
+ await prisma.cutFolder.deleteMany({
+ where: { userId, scope: "library", id: { in: tree } },
});
return Response.json({ ok: true });
} catch (e) {
@@ -1060,13 +1063,7 @@ export const libraryCloud = {
async removeTemplate(userId: string, id: string) {
try {
const row = await findTemplate(userId, id);
- if (row) {
- await prisma.cutTemplate.delete({ where: { id } });
- // The media copies are private to this template, so removing them is safe.
- const doc = row.doc as unknown as TemplateDoc;
- for (const m of doc.media ?? [])
- await deleteLibraryObject(userId, m.fileName);
- }
+ if (row) await deleteTemplateCascade(userId, row);
return Response.json({ ok: true });
} catch (e) {
return caught(e, "Could not delete the template.");
@@ -1074,6 +1071,16 @@ export const libraryCloud = {
},
};
+/** Delete a template row with its media copies, which are private to it. */
+async function deleteTemplateCascade(
+ userId: string,
+ row: NonNullable<Awaited<ReturnType<typeof findTemplate>>>,
+) {
+ await prisma.cutTemplate.delete({ where: { id: row.id } });
+ const doc = row.doc as unknown as TemplateDoc;
+ for (const m of doc.media ?? []) await deleteLibraryObject(userId, m.fileName);
+}
+
/** The folder a new account starts with, so the Library shows that it takes
* font files before anyone has dropped one in. Derived from the user id, so a
* retried signup lands on the same row; an ordinary folder otherwise, free to
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index fab891fd..c33cc5c7 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -1,7 +1,7 @@
// Cloud twin of the engine's project CRUD (server/projects.ts + http/projects.ts):
// docs and metadata in Postgres, media bytes in R2. Every query scopes by userId.
import { sanitizeGuideLines, sanitizeGuides } from "@/cut/lib/guides";
-import { resolveParent } from "@/cut/lib/folderTree";
+import { resolveParent, subtreeOf } from "@/cut/lib/folderTree";
import { normalizeAspect, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
@@ -353,25 +353,25 @@ export const projectsCloud = {
}
},
- /** Delete a folder. What it held — its projects and the folders inside it —
- * comes up one level, filed where the folder was. */
+ /** Delete a folder and everything in it: the folders filed under it,
+ * however deep, and every project they hold, each through the cascade its
+ * own delete runs. The projects go first and the folders last, so a run
+ * that stops partway leaves the rest where a retry finds it. */
async deleteFolder(userId: string, id: string) {
try {
- await prisma.$transaction(async (tx) => {
- const gone = await tx.cutFolder.findFirst({
- where: { id, userId, scope: "project" },
- select: { parentId: true },
- });
- if (!gone) return;
- await tx.cutFolder.delete({ where: { id } });
- await tx.cutProject.updateMany({
- where: { userId, folderId: id },
- data: { folderId: gone.parentId },
- });
- await tx.cutFolder.updateMany({
- where: { userId, scope: "project", parentId: id },
- data: { parentId: gone.parentId },
- });
+ const folders = await prisma.cutFolder.findMany({
+ where: { userId, scope: "project" },
+ select: { id: true, parentId: true },
+ });
+ if (!folders.some((f) => f.id === id)) return Response.json({ ok: true });
+ const tree = subtreeOf(folders, id);
+ const projects = await prisma.cutProject.findMany({
+ where: { userId, folderId: { in: tree } },
+ select: { id: true },
+ });
+ for (const p of projects) await deleteProjectCascade(userId, p.id);
+ await prisma.cutFolder.deleteMany({
+ where: { userId, scope: "project", id: { in: tree } },
});
return Response.json({ ok: true });
} catch (e) {
diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.ts
index 55409738..f42f72c5 100644
--- a/site/src/cut/server/library.ts
+++ b/site/src/cut/server/library.ts
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
import { copyFile, constants, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import type { ClipSound } from "@donkeycut/effects-kit";
-import { resolveParent, settleParents } from "@/cut/lib/folderTree";
+import { resolveParent, settleParents, subtreeOf } from "@/cut/lib/folderTree";
import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
import { mediaPath as projectMediaPath, readProject } from "./projects";
@@ -378,15 +378,42 @@ export async function copyLibraryAssetToProject(
return dest;
}
+/** Take the assets in `ids` out of the index, handing back the files they
+ * own — the source and its poster — for the caller to remove once the index
+ * is written. */
+function takeAssets(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {
+ const files: string[] = [];
+ idx.assets = idx.assets.filter((a) => {
+ if (!ids.has(a.id)) return true;
+ files.push(a.fileName);
+ if (a.posterFile) files.push(a.posterFile);
+ return false;
+ });
+ return files;
+}
+
+/** Take the templates in `ids` out of the index, handing back their media
+ * copies, which are private to them. */
+function takeTemplates(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {
+ const files: string[] = [];
+ idx.templates = (idx.templates ?? []).filter((t) => {
+ if (!ids.has(t.id)) return true;
+ for (const m of t.media ?? []) files.push(m.fileName);
+ return false;
+ });
+ return files;
+}
+
+async function removeFiles(files: string[]) {
+ for (const f of files) await rm(libMediaPath(f), { force: true });
+}
+
export async function removeAsset(id: string) {
- const { fileName, posterFile } = await mutateIndex((idx) => {
- const asset = idx.assets.find((a) => a.id === id);
- if (!asset) throw new Error("Library asset not found.");
- idx.assets = idx.assets.filter((a) => a.id !== id);
- return { fileName: asset.fileName, posterFile: asset.posterFile };
+ const files = await mutateIndex((idx) => {
+ if (!idx.assets.some((a) => a.id === id)) throw new Error("Library asset not found.");
+ return takeAssets(idx, new Set([id]));
});
- await rm(libMediaPath(fileName), { force: true });
- if (posterFile) await rm(libMediaPath(posterFile), { force: true });
+ await removeFiles(files);
}
export function getAsset(id: string) {
@@ -439,19 +466,27 @@ export async function updateFolder(
});
}
-/** Delete a folder. What it held — its items and the folders inside it —
- * comes up one level, filed where the folder was. */
+/** Delete a folder and everything in it: the folders filed under it, however
+ * deep, and every asset and template they hold, in one write of the index.
+ * A camera clip lives in Camera Roll whatever folder it is filed under, so
+ * it stays, unfiled. */
export async function deleteFolder(id: string) {
- await mutateIndex((idx) => {
- const gone = (idx.folders ?? []).find((f) => f.id === id);
- if (!gone) return;
- const up = gone.parentId ?? null;
- idx.folders = (idx.folders ?? []).filter((f) => f.id !== id);
- for (const f of idx.folders) if ((f.parentId ?? null) === id) f.parentId = up;
- for (const a of idx.assets) if (a.folderId === id) a.folderId = up;
- for (const t of idx.templates ?? [])
- if (t.folderId === id) t.folderId = up;
+ const files = await mutateIndex((idx) => {
+ const folders = idx.folders ?? [];
+ if (!folders.some((f) => f.id === id)) return [];
+ const tree = new Set(subtreeOf(folders, id));
+ const filed = (x: { folderId?: string | null }) => !!x.folderId && tree.has(x.folderId);
+ const assets = new Set<string>();
+ for (const a of idx.assets) {
+ if (!filed(a)) continue;
+ if (a.origin === "camera") a.folderId = null;
+ else assets.add(a.id);
+ }
+ const templates = new Set((idx.templates ?? []).filter(filed).map((t) => t.id));
+ idx.folders = folders.filter((f) => !tree.has(f.id));
+ return [...takeAssets(idx, assets), ...takeTemplates(idx, templates)];
});
+ await removeFiles(files);
}
/** File a library item — an asset or a template — into a folder (`null` ungroups). */
@@ -666,12 +701,6 @@ export async function renameTemplate(
}
export async function deleteTemplate(id: string) {
- const template = await mutateIndex((idx) => {
- const t = (idx.templates ?? []).find((x) => x.id === id);
- idx.templates = (idx.templates ?? []).filter((x) => x.id !== id);
- return t;
- });
- // The media copies are private to this template, so removing them is safe.
- for (const m of template?.media ?? [])
- await rm(libMediaPath(m.fileName), { force: true });
+ const files = await mutateIndex((idx) => takeTemplates(idx, new Set([id])));
+ await removeFiles(files);
}
diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.ts
index da0f97f0..e21ef264 100644
--- a/site/src/cut/server/projects.ts
+++ b/site/src/cut/server/projects.ts
@@ -2,7 +2,7 @@ import fsSync from "node:fs";
import { isDeliveryName } from "../lib/exportDelivery";
import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
-import { resolveParent, settleParents } from "@/cut/lib/folderTree";
+import { resolveParent, settleParents, subtreeOf } from "@/cut/lib/folderTree";
import type { Aspect, ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";
import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
@@ -470,6 +470,24 @@ async function writeFolders(folders: ProjectFolder[]) {
await writeJsonAtomic(foldersIndex(), { folders });
}
+// Serialize read-modify-write cycles on the folder list, so two folder changes
+// in flight at once can't write each other's out. Each mutation reads the
+// freshly-written list, applies its change, and writes.
+let foldersLock: Promise<unknown> = Promise.resolve();
+async function mutateFolders<T>(fn: (idx: { folders: ProjectFolder[] }) => T): Promise<T> {
+ const run = foldersLock.then(async () => {
+ const idx = { folders: await readFolders() };
+ const result = fn(idx);
+ await writeFolders(idx.folders);
+ return result;
+ });
+ foldersLock = run.then(
+ () => undefined,
+ () => undefined
+ );
+ return run;
+}
+
export async function listProjectFolders(): Promise<ProjectFolder[]> {
return settleParents(await readFolders()).sort((a, b) => a.createdAt - b.createdAt);
}
@@ -480,16 +498,17 @@ export async function createProjectFolder(
): Promise<ProjectFolder> {
const trimmed = name.trim();
if (!trimmed) throw new Error("Folder name required.");
- const folders = await readFolders();
const id = crypto.randomUUID().slice(0, 8);
- const folder: ProjectFolder = {
- id,
- name: trimmed.slice(0, 80),
- parentId: resolveParent(folders, id, parentId),
- createdAt: Date.now(),
- };
- await writeFolders([...folders, folder]);
- return folder;
+ return mutateFolders(({ folders }) => {
+ const folder: ProjectFolder = {
+ id,
+ name: trimmed.slice(0, 80),
+ parentId: resolveParent(folders, id, parentId),
+ createdAt: Date.now(),
+ };
+ folders.push(folder);
+ return folder;
+ });
}
/** Rename a folder, file it under another (null for the top level), or
@@ -500,35 +519,28 @@ export async function updateProjectFolder(
): Promise<ProjectFolder> {
const trimmed = patch.name?.trim();
if (patch.name !== undefined && !trimmed) throw new Error("Folder name required.");
- const folders = await readFolders();
- const folder = folders.find((f) => f.id === id);
- if (!folder) throw new Error("Folder not found.");
- if (trimmed) folder.name = trimmed.slice(0, 80);
- if (patch.parentId !== undefined) folder.parentId = resolveParent(folders, id, patch.parentId);
- await writeFolders(folders);
- return folder;
-}
-
-/** Delete a folder. What it held — its projects and the folders inside it —
- * comes up one level, filed where the folder was. */
+ return mutateFolders(({ folders }) => {
+ const folder = folders.find((f) => f.id === id);
+ if (!folder) throw new Error("Folder not found.");
+ if (trimmed) folder.name = trimmed.slice(0, 80);
+ if (patch.parentId !== undefined) folder.parentId = resolveParent(folders, id, patch.parentId);
+ return folder;
+ });
+}
+
+/** Delete a folder and everything in it: the folders filed under it, however
+ * deep, and every project they hold, each the way its own delete goes. The
+ * projects go first and the folders last, so a run that stops partway leaves
+ * the rest where a retry finds it. */
export async function deleteProjectFolder(id: string) {
const folders = await readFolders();
- const gone = folders.find((f) => f.id === id);
- if (!gone) return;
- const up = gone.parentId ?? null;
- await writeFolders(
- folders
- .filter((f) => f.id !== id)
- .map((f) => ((f.parentId ?? null) === id ? { ...f, parentId: up } : f))
- );
- await Promise.all(
- (await readProjectEntries()).map(async ({ id: projectId, doc }) => {
- if (doc.folderId === id) {
- doc.folderId = up;
- await writeProject(projectId, doc);
- }
- })
- );
+ if (!folders.some((f) => f.id === id)) return;
+ const tree = new Set(subtreeOf(folders, id));
+ for (const { id: projectId, doc } of await readProjectEntries())
+ if (doc.folderId && tree.has(doc.folderId)) await deleteProject(projectId);
+ await mutateFolders((idx) => {
+ idx.folders = idx.folders.filter((f) => !tree.has(f.id));
+ });
}
export async function moveProjectToFolder(id: string, folderId: string | null) {