Skip to content

Open source CapCut alternative.

TypeScript

feat(site): the library gets a shelf in the browser store [rebuild]

David Le35aa786137e4
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index 4ecbcdf6..f9d84d8a 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -50,7 +50,7 @@ Cloud projects follow the account: the same project opens in any browser on any
Every client call goes through a backend seam (`site/src/cut/lib/backend/`): the local driver is the engine transport unchanged, the cloud driver rewrites the same paths to `/api/cut-cloud/*` with the session cookie, and the browser driver answers storage routes in the page from origin-private storage, falling through to the cloud twin for AI. Residency is per project and fixed when the project is created, so creating one is where the user chooses. One picker makes that choice, standing beside New project in the sidebar: it names a shelf — Local or Cloud — and everything the browser creates lands there, new projects and anything added to the library alike. Local is this Mac's engine when the app has connected and this browser's own storage otherwise, so a machine without the app still has a real local shelf. The choice sticks on that browser until they change it, and every other New project button follows it. Inside a folder the folder decides, since a project files only into a folder beside it. The home lists every shelf as one listing — the Mac's from its stored listing when the app is closed — each project badged with where it lives, and opening one binds the editor to that project's backend. Capability flags on the driver hide what a backend can't do, so components never feature-detect.
-The library is the exception, because it is the user's one shelf across places: it lists the Mac's half and the cloud's at once as one listing, newest first, with a badge saying which shelf each item is on. The browser's own store holds projects only, so those are the library's two shelves. So a cloud project can pull a clip off this Mac, and a local project can pull one out of the cloud. Each half 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.
+The 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. 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.
Cloud projects store their doc in Postgres (versioned; a stale autosave 409s and the editor reloads the newer copy) and media in R2: uploads go direct from the browser on presigned URLs (the hosted functions never see the bytes), playback streams on signed range URLs, and a flat per-user quota is enforced at presign time. That quota is visible rather than implicit: a free account editing a cloud project sees what it has used in the editor's top bar, and a presign rejected for space opens an upgrade offer wherever it happened instead of a bare error. The same slot carries the countdown when a subscription is set to cancel, and clicking it opens the billing portal.
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index a3e46deb..84db1600 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -70,7 +70,6 @@ import { useListedResidencies, useLocalCompute } from "@/cut/lib/backend/hooks";
import { setNeedsApp } from "@/cut/lib/needsApp";
import {
availableResidencies,
- libraryResidencies,
RESIDENCY_LABEL,
type Residency,
} from "@/cut/lib/residency";
@@ -125,7 +124,9 @@ export function LibraryView() {
const library = useLibrary();
const listed = useListedResidencies();
const engineUp = useLocalCompute();
- const live = useCallback((r: Residency) => r === "cloud" || engineUp, [engineUp]);
+ // Every shelf but the Mac's is always answering: the cloud is a request away
+ // and the browser shelf is this page's own storage.
+ const live = useCallback((r: Residency) => r !== "local" || engineUp, [engineUp]);
// Drop the flag when this view goes away: the banner belongs to the surface
// that raised it.
useEffect(() => () => setNeedsApp(false), []);
@@ -623,7 +624,7 @@ export function LibraryCard({
const videoRef = useRef<HTMLVideoElement>(null);
const { flash, attachReveal } = useRevealFlash("library", a.id);
// With one shelf listed, every card is on it — the badge would say nothing.
- const bothShelves = libraryResidencies(availableResidencies()).length > 1 || offline;
+ const bothShelves = availableResidencies().length > 1 || offline;
// Each card is a real media element, so the source waits until the tile has
// been scrolled near: a large library would otherwise pull every file's
// metadata across the network the moment the page opened.
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 90160623..9d46378b 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -25,7 +25,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { apiFetch, apiUrl } from "@/cut/lib/backend";
-import { useCutCaps, useCutMode } from "@/cut/lib/backend/hooks";
+import { useCutCaps } from "@/cut/lib/backend/hooks";
import {
clearAssetDrag,
draggingLibrary,
@@ -68,7 +68,6 @@ import {
import {
activeResidency,
availableResidencies,
- libraryResidencies,
type Residency,
} from "@/cut/lib/residency";
import { isStylePresetTemplate } from "@/cut/lib/stylePresets";
@@ -629,10 +628,6 @@ function ProjectFilesPanel({
importing: boolean;
}) {
const caps = useCutCaps();
- // The library passes over browser storage (`libraryResidencies`), and its
- // server-side copy can't reach bytes that live in this browser's store, so
- // a browser-resident project's templates stay on the project shelf.
- const cutMode = useCutMode();
// Only user-imported media lives here; anything Cut created (recordings, AI
// generations, voiceovers, freeze frames, stock adds) is tagged with an
// `origin` and stays where it was made.
@@ -764,11 +759,9 @@ function ProjectFilesPanel({
if (r.scope === "project") useEditor.getState().addAssetToTemplate(t.id, r.id);
}}
extraMenu={
- cutMode === "browser" ? undefined : (
- <DropdownMenuItem onClick={() => void saveTemplate(projectId, t)}>
- <FolderPlus /> Add to Library
- </DropdownMenuItem>
- )
+ <DropdownMenuItem onClick={() => void saveTemplate(projectId, t)}>
+ <FolderPlus /> Add to Library
+ </DropdownMenuItem>
}
/>
))}
@@ -1295,7 +1288,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
};
const all = assets ?? [];
- const bothShelves = libraryResidencies(availableResidencies()).length > 1;
+ const bothShelves = availableResidencies().length > 1;
const shown = all.filter((a) => (a.folderId ?? null) === openFolder);
const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);
const openFolderName = folders.find((f) => f.id === openFolder)?.name;
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 2077a8b7..12dafc1b 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -2159,7 +2159,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
},
library_organize: async (_s, input) => {
- // The library spans both shelves, so every id is resolved against the
+ // The library spans every shelf, so each id is resolved against the
// current listing to find the backend that owns it.
const lib = await fetchLibrary();
const folderShelf = (id: string) => lib.folders.find((f) => f.id === id)?.residency;
@@ -2196,7 +2196,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const r = itemShelf(id);
if (!r) throw new ToolError(`No library item with id ${id}.`);
if (folderId && folderShelf(folderId) !== r) {
- throw new ToolError("That folder is on the other library shelf.");
+ throw new ToolError("That folder is on a different library shelf.");
}
await moveLibraryItem(r, id, folderId);
return { moved: true, folderId };
diff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.ts
new file mode 100644
index 00000000..ae4f5baa
--- /dev/null
+++ b/site/src/cut/lib/backend/browser/library.ts
@@ -0,0 +1,514 @@
+// The browser shelf's library: reusable media outside any project, held in
+// this page's own storage. Handlers answer the engine's `/api/cut/library`
+// routes (`server/http/library.ts`) with the same JSON, so a call site can't
+// tell which shelf it reached.
+//
+// The whole shelf is one index file next to a media folder. Templates keep
+// private copies of their media here, the way the engine's do, so a template
+// stays whole after the project it came from is gone.
+//
+// Not owned here: `import-url`, `presign` and `complete`. A page can't fetch a
+// 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 type {
+ AssetType,
+ LibraryTemplate,
+ TemplateAudio,
+ TemplateLayer,
+ TemplateMedia,
+} from "../../types";
+import * as store from "./opfs";
+import { registerBlobFile, registeredUrl, revokeRegistered } from "./registry";
+import { caught, err, json, serveFile } from "./respond";
+
+const INDEX_FILE = "library.json";
+
+export const libraryMediaApiPath = (fileName: string) =>
+ `/api/cut/library/media/${encodeURIComponent(fileName)}`;
+
+const projectMediaApiPath = (id: string, fileName: string) =>
+ `/api/cut/projects/${id}/media/${encodeURIComponent(fileName)}`;
+
+/** Where a URL-imported asset came from, kept as notes on the asset. */
+type LibrarySource = { url: string; title?: string; uploader?: string; uploadDate?: string };
+
+type StoredAsset = {
+ id: string;
+ fileName: string;
+ name: string;
+ type: AssetType;
+ duration: number;
+ width?: number;
+ height?: number;
+ addedAt: number;
+ folderId?: string | null;
+ source?: LibrarySource;
+};
+
+type StoredFolder = { id: string; name: string; createdAt: number };
+
+type LibraryIndex = {
+ version: 1;
+ assets: StoredAsset[];
+ folders: StoredFolder[];
+ templates: LibraryTemplate[];
+};
+
+const EMPTY: LibraryIndex = { version: 1, assets: [], folders: [], templates: [] };
+
+async function readIndex(): Promise<LibraryIndex> {
+ const idx = await store.readJson<LibraryIndex>(await store.libraryDir(), INDEX_FILE);
+ if (!idx) return EMPTY;
+ return {
+ version: 1,
+ assets: Array.isArray(idx.assets) ? idx.assets : [],
+ folders: Array.isArray(idx.folders) ? idx.folders : [],
+ templates: Array.isArray(idx.templates) ? idx.templates : [],
+ };
+}
+
+/** Read-modify-write the shelf under the store lock, so two tabs filing items
+ * at once can't clobber each other's index. */
+async function mutateIndex<T>(fn: (idx: LibraryIndex) => T): Promise<T> {
+ return store.withStoreLock("library", async () => {
+ const dir = await store.libraryDir(true);
+ if (!dir) throw new Error("Browser storage is unavailable.");
+ const idx = await readIndex();
+ const result = fn(idx);
+ await store.writeFileAt(dir, INDEX_FILE, JSON.stringify(idx));
+ return result;
+ });
+}
+
+const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;
+const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;
+const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;
+
+function typeOf(fileName: string): AssetType | null {
+ if (VIDEO_RE.test(fileName)) return "video";
+ if (AUDIO_RE.test(fileName)) return "audio";
+ if (IMAGE_RE.test(fileName)) return "image";
+ return null;
+}
+
+function parseField<T>(value: FormDataEntryValue | null): T | null {
+ if (typeof value !== "string" || !value) return null;
+ try {
+ return JSON.parse(value) as T;
+ } catch {
+ return null;
+ }
+}
+
+/** Mint the blob URL for a library file so `backend.url()` answers for it
+ * without awaiting. */
+async function register(fileName: string, file?: File | null): Promise<void> {
+ const path = libraryMediaApiPath(fileName);
+ if (registeredUrl(path)) return;
+ const bytes = file ?? (await store.readFileAt(await store.libraryMediaDir(), fileName));
+ if (bytes) registerBlobFile(path, bytes);
+}
+
+/** The whole shelf, with every file it holds registered so cards, players and
+ * download links resolve synchronously. */
+async function list(): Promise<Response> {
+ const idx = await readIndex();
+ for (const name of new Set([
+ ...idx.assets.map((a) => a.fileName),
+ ...idx.templates.flatMap((t) => t.media.map((m) => m.fileName)),
+ ])) {
+ await register(name);
+ }
+ return json({
+ assets: [...idx.assets].sort((a, b) => b.addedAt - a.addedAt),
+ folders: [...idx.folders].sort((a, b) => a.createdAt - b.createdAt),
+ templates: [...idx.templates].sort((a, b) => b.addedAt - a.addedAt),
+ });
+}
+
+/** Write the row for a file already stored in the library. */
+async function addAsset(
+ fileName: string,
+ name: string,
+ meta: { type?: AssetType; duration?: number; width?: number; height?: number } | null,
+ source?: LibrarySource | null
+): Promise<StoredAsset> {
+ const type = meta?.type ?? typeOf(fileName);
+ if (!type) throw new Error("Unsupported file type.");
+ const asset: StoredAsset = {
+ id: crypto.randomUUID().slice(0, 8),
+ fileName,
+ name,
+ type,
+ duration: meta?.duration ?? 0,
+ ...(meta?.width && meta?.height ? { width: meta.width, height: meta.height } : {}),
+ addedAt: Date.now(),
+ folderId: null,
+ ...(source ? { source } : {}),
+ };
+ await mutateIndex((idx) => {
+ idx.assets.push(asset);
+ });
+ return asset;
+}
+
+/**
+ * Upload straight onto the shelf. The page probes the file before sending it
+ * (`meta`), because nothing here can read a duration out of stored bytes the
+ * way the engine's ffprobe can.
+ */
+async function upload(req: Request): Promise<Response> {
+ try {
+ const form = await req.formData();
+ const file = form.get("file");
+ if (!(file instanceof File)) return err("No file in upload.", 400);
+ const nameField = form.get("name");
+ const name = typeof nameField === "string" && nameField.trim() ? nameField.trim() : file.name;
+ const meta = parseField<{
+ type?: AssetType;
+ duration?: number;
+ width?: number;
+ height?: number;
+ }>(form.get("meta"));
+ const source = parseField<LibrarySource>(form.get("source"));
+ if (!(meta?.type ?? typeOf(file.name))) return err("Unsupported file type.", 400);
+ const fileName = await store.saveLibraryMedia(file, file.name);
+ await register(fileName, file);
+ return json(await addAsset(fileName, name, meta, source));
+ } catch (e) {
+ return caught(e, "Upload failed.");
+ }
+}
+
+async function serveMedia(fileName: string, download: boolean): Promise<Response> {
+ const file = await store.readFileAt(await store.libraryMediaDir(), fileName);
+ if (!file) return err("Media file not found.", 404);
+ await register(fileName, file);
+ return serveFile(file, fileName, download);
+}
+
+async function removeAsset(id: string): Promise<Response> {
+ try {
+ const fileName = 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 asset.fileName;
+ });
+ await store.deleteLibraryMedia(fileName);
+ revokeRegistered(libraryMediaApiPath(fileName));
+ return json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not delete.");
+ }
+}
+
+async function move(req: Request): Promise<Response> {
+ try {
+ const { id, folderId } = (await req.json()) as { id: string; folderId: string | null };
+ await mutateIndex((idx) => {
+ const item = idx.assets.find((a) => a.id === id) ?? idx.templates.find((t) => t.id === id);
+ if (!item) throw new Error("Library item not found.");
+ if (folderId && !idx.folders.some((f) => f.id === folderId)) {
+ throw new Error("Folder not found.");
+ }
+ item.folderId = folderId ?? null;
+ });
+ return json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not move item.");
+ }
+}
+
+async function createFolder(req: Request): Promise<Response> {
+ try {
+ const { name } = (await req.json()) as { name?: string };
+ const trimmed = (name ?? "").trim();
+ if (!trimmed) return err("Folder name required.", 500);
+ const folder: StoredFolder = {
+ id: crypto.randomUUID().slice(0, 8),
+ name: trimmed.slice(0, 80),
+ createdAt: Date.now(),
+ };
+ await mutateIndex((idx) => {
+ idx.folders.push(folder);
+ });
+ return json(folder);
+ } catch (e) {
+ return caught(e, "Could not create folder.");
+ }
+}
+
+async function renameFolder(req: Request, id: string): Promise<Response> {
+ try {
+ const { name } = (await req.json()) as { name?: string };
+ const trimmed = (name ?? "").trim();
+ if (!trimmed) return err("Folder name required.", 500);
+ return json(
+ await mutateIndex((idx) => {
+ const folder = idx.folders.find((f) => f.id === id);
+ if (!folder) throw new Error("Folder not found.");
+ folder.name = trimmed.slice(0, 80);
+ return folder;
+ })
+ );
+ } catch (e) {
+ return caught(e, "Could not rename folder.");
+ }
+}
+
+async function deleteFolder(id: string): Promise<Response> {
+ try {
+ await mutateIndex((idx) => {
+ idx.folders = idx.folders.filter((f) => f.id !== id);
+ // Items in the folder fall back to ungrouped rather than vanishing.
+ for (const a of idx.assets) if (a.folderId === id) a.folderId = null;
+ for (const t of idx.templates) if (t.folderId === id) t.folderId = null;
+ });
+ return json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not delete folder.");
+ }
+}
+
+/** Copy a library file into a project's media folder. */
+async function copyIntoProject(projectId: string, fileName: string): Promise<string> {
+ const file = await store.readFileAt(await store.libraryMediaDir(), fileName);
+ if (!file) throw new Error("Library file not found.");
+ const stored = await store.saveMedia(projectId, file, fileName);
+ registerBlobFile(projectMediaApiPath(projectId, stored), file);
+ return stored;
+}
+
+/** Copy a project's media file onto the shelf. */
+async function copyFromProject(projectId: string, fileName: string): Promise<string> {
+ const file = await store.readFileAt(await store.mediaDir(projectId), fileName);
+ if (!file) throw new Error("Media file not found in project.");
+ const stored = await store.saveLibraryMedia(file, fileName);
+ await register(stored, file);
+ return stored;
+}
+
+async function addToProject(req: Request): Promise<Response> {
+ try {
+ const { assetId, projectId } = (await req.json()) as { assetId: string; projectId: string };
+ const asset = (await readIndex()).assets.find((a) => a.id === assetId);
+ if (!asset) return err("Library asset not found.", 404);
+ if (!(await store.readDoc(projectId))) return err("Project not found.", 404);
+ return json({ fileName: await copyIntoProject(projectId, asset.fileName) });
+ } catch (e) {
+ return caught(e, "Could not add from library.");
+ }
+}
+
+/**
+ * Save a project's media file onto the shelf. The doc is right here, so the
+ * asset's own row supplies the dimensions and duration the page would
+ * otherwise have to re-probe.
+ */
+async function saveFromProject(req: Request): Promise<Response> {
+ try {
+ const { projectId, fileName, name } = (await req.json()) as {
+ projectId: string;
+ fileName: string;
+ name?: string;
+ };
+ const doc = await store.readDoc(projectId);
+ if (!doc) return err("Project not found.", 404);
+ const known = doc.assets.find((a) => a.fileName === fileName);
+ const stored = await copyFromProject(projectId, fileName);
+ return json(
+ await addAsset(stored, name || fileName, {
+ type: known?.type as AssetType | undefined,
+ duration: known?.duration,
+ width: known?.width,
+ height: known?.height,
+ })
+ );
+ } catch (e) {
+ return caught(e, "Could not save to library.");
+ }
+}
+
+// --- templates: selections saved by reference, media copied in privately ---
+
+type TemplateInput = {
+ name: string;
+ duration: number;
+ media: TemplateMedia[];
+ layers: TemplateLayer[];
+ audio: TemplateAudio[];
+ texts: LibraryTemplate["texts"];
+ cues: LibraryTemplate["cues"];
+};
+
+async function saveTemplate(req: Request): Promise<Response> {
+ try {
+ const { projectId, ...input } = (await req.json()) as { projectId: string } & TemplateInput;
+ if (!(await store.readDoc(projectId))) return err("Project not found.", 404);
+ if (!input.media?.length && !input.texts?.length && !input.cues?.length) {
+ return err("Nothing to save.", 500);
+ }
+ const media: TemplateMedia[] = [];
+ for (const m of input.media ?? []) {
+ media.push({ ...m, fileName: await copyFromProject(projectId, m.fileName) });
+ }
+ const template: LibraryTemplate = {
+ id: crypto.randomUUID().slice(0, 8),
+ name: (input.name || "Template").trim().slice(0, 80),
+ addedAt: Date.now(),
+ duration: input.duration,
+ media,
+ layers: input.layers ?? [],
+ audio: input.audio ?? [],
+ texts: input.texts ?? [],
+ cues: input.cues ?? [],
+ };
+ await mutateIndex((idx) => {
+ idx.templates.push(template);
+ });
+ return json(template);
+ } catch (e) {
+ return caught(e, "Could not save the template.");
+ }
+}
+
+async function materializeTemplate(req: Request, id: string): Promise<Response> {
+ try {
+ const { projectId } = (await req.json()) as { projectId: string };
+ if (!(await store.readDoc(projectId))) return err("Project not found.", 404);
+ const template = (await readIndex()).templates.find((t) => t.id === id);
+ if (!template) return err("Template not found.", 404);
+ const media: TemplateMedia[] = [];
+ for (const m of template.media) {
+ media.push({ ...m, fileName: await copyIntoProject(projectId, m.fileName) });
+ }
+ return json({ template, media });
+ } catch (e) {
+ return caught(e, "Could not add the template.");
+ }
+}
+
+async function addToTemplate(req: Request, id: string): Promise<Response> {
+ try {
+ const { projectId, media, layer, audio, extend } = (await req.json()) as {
+ projectId: string;
+ media: TemplateMedia;
+ layer?: Omit<TemplateLayer, "media" | "start">;
+ audio?: Omit<TemplateAudio, "media" | "start">;
+ extend: number;
+ };
+ const stored = await copyFromProject(projectId, media.fileName);
+ try {
+ return json(
+ await mutateIndex((idx) => {
+ const t = idx.templates.find((x) => x.id === id);
+ if (!t) throw new Error("Template not found.");
+ const mi = t.media.length;
+ t.media = [...t.media, { ...media, fileName: stored }];
+ if (audio) t.audio = [...t.audio, { ...audio, media: mi, start: t.duration }];
+ else if (layer) t.layers = [...t.layers, { ...layer, media: mi, start: t.duration }];
+ t.duration += extend;
+ return t;
+ })
+ );
+ } catch (e) {
+ await store.deleteLibraryMedia(stored);
+ throw e;
+ }
+ } catch (e) {
+ return caught(e, "Could not add to the template.");
+ }
+}
+
+async function renameTemplate(req: Request, id: string): Promise<Response> {
+ try {
+ const { name } = (await req.json()) as { name?: string };
+ const trimmed = (name ?? "").trim();
+ if (!trimmed) return err("Template name required.", 500);
+ return json(
+ await mutateIndex((idx) => {
+ const template = idx.templates.find((t) => t.id === id);
+ if (!template) throw new Error("Template not found.");
+ template.name = trimmed.slice(0, 80);
+ return template;
+ })
+ );
+ } catch (e) {
+ return caught(e, "Could not rename the template.");
+ }
+}
+
+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));
+ }
+ return json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not delete the template.");
+ }
+}
+
+/**
+ * Serve one `/api/cut/library/...` request against this browser's shelf.
+ * `rest` is the path past `library`. Returns null for the paths the shelf
+ * doesn't own, which the driver proxies to the hosted twin.
+ */
+export async function dispatchLibraryRoute(
+ rest: string[],
+ method: string,
+ req: () => Request,
+ download: boolean
+): Promise<Response | null> {
+ // /library
+ if (rest.length === 0) {
+ if (method === "GET") return list();
+ if (method === "POST") return upload(req());
+ return err("Method not allowed.", 405);
+ }
+
+ // /library/media/:file
+ if (rest[0] === "media" && rest.length === 2) {
+ if (method === "GET") return serveMedia(rest[1], download);
+ return err("Method not allowed.", 405);
+ }
+
+ if (rest[0] === "folders") {
+ if (rest.length === 1 && method === "POST") return createFolder(req());
+ if (rest.length === 2 && method === "PUT") return renameFolder(req(), rest[1]);
+ if (rest.length === 2 && method === "DELETE") return deleteFolder(rest[1]);
+ return err("Not found.", 404);
+ }
+
+ if (rest[0] === "templates") {
+ if (rest.length === 1 && method === "POST") return saveTemplate(req());
+ if (rest.length === 2 && method === "PUT") return renameTemplate(req(), rest[1]);
+ if (rest.length === 2 && method === "DELETE") return deleteTemplate(rest[1]);
+ if (rest.length === 3 && method === "POST") {
+ if (rest[2] === "use") return materializeTemplate(req(), rest[1]);
+ if (rest[2] === "add") return addToTemplate(req(), rest[1]);
+ }
+ return err("Not found.", 404);
+ }
+
+ if (rest.length === 1 && method === "POST") {
+ if (rest[0] === "move") return move(req());
+ if (rest[0] === "use") return addToProject(req());
+ if (rest[0] === "save") return saveFromProject(req());
+ // import-url, presign, complete: the cloud's, not this shelf's.
+ return null;
+ }
+
+ // /library/:id
+ if (rest.length === 1 && method === "DELETE") return removeAsset(rest[0]);
+ return null;
+}
diff --git a/site/src/cut/lib/backend/browser/opfs.ts b/site/src/cut/lib/backend/browser/opfs.ts
index ed3750c3..29ef080a 100644
--- a/site/src/cut/lib/backend/browser/opfs.ts
+++ b/site/src/cut/lib/backend/browser/opfs.ts
@@ -5,6 +5,9 @@
//
// cut-store/users/<accountId>/
// index.json folders + media sync ledger
+// library/
+// library.json the shelf's assets, folders, templates
+// media/<fileName>
// projects/<projectId>/
// project.json the doc (createWritable commits on close,
// so a torn write never replaces a good doc)
@@ -103,7 +106,10 @@ export async function writeFileAt(
await w.close();
}
-async function readJsonAt<T>(dir: FileSystemDirectoryHandle | null, name: string): Promise<T | null> {
+export async function readJson<T>(
+ dir: FileSystemDirectoryHandle | null,
+ name: string
+): Promise<T | null> {
const file = await readFileAt(dir, name);
if (!file) return null;
try {
@@ -138,7 +144,7 @@ type StoreIndex = {
const EMPTY_INDEX: StoreIndex = { version: 1, folders: [], pendingUploads: [], opens: {} };
export async function readIndex(): Promise<StoreIndex> {
- const idx = await readJsonAt<StoreIndex>(await dirAt(userParts(), false), "index.json");
+ const idx = await readJson<StoreIndex>(await dirAt(userParts(), false), "index.json");
return idx && Array.isArray(idx.folders)
? { ...EMPTY_INDEX, ...idx, pendingUploads: idx.pendingUploads ?? [], opens: idx.opens ?? {} }
: EMPTY_INDEX;
@@ -158,7 +164,7 @@ export async function updateIndex(mutate: (idx: StoreIndex) => StoreIndex | void
// --- docs ---
export async function readDoc(id: string): Promise<ProjectDoc | null> {
- return readJsonAt<ProjectDoc>(await projectDir(id), "project.json");
+ return readJson<ProjectDoc>(await projectDir(id), "project.json");
}
export async function writeDoc(id: string, doc: ProjectDoc): Promise<void> {
@@ -228,12 +234,13 @@ export async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSum
// --- media ---
-/** Store media bytes under a deduped name — the engine's sanitize + suffix
- * rules, so a project copied across residencies keeps consistent names. */
-export async function saveMedia(id: string, file: File, wantName?: string): Promise<string> {
- const dir = await mediaDir(id, true);
- if (!dir) throw new Error("Browser storage is unavailable.");
- const base = (wantName ?? file.name)
+/** A name nothing in `dir` holds yet — the engine's sanitize + suffix rules,
+ * so a project copied across residencies keeps consistent names. */
+export async function freeName(
+ dir: FileSystemDirectoryHandle,
+ wantName: string
+): Promise<string> {
+ const base = wantName
.split("/")
.pop()!
.replace(/[^\w.\-() ]+/g, "_")
@@ -243,6 +250,14 @@ export async function saveMedia(id: string, file: File, wantName?: string): Prom
const stem = (dot > 0 ? base.slice(0, dot) : base) || "media";
let name = base || `media${ext}`;
for (let n = 1; await readFileAt(dir, name); n++) name = `${stem}-${n}${ext}`;
+ return name;
+}
+
+/** Store media bytes in a project under a deduped name. */
+export async function saveMedia(id: string, file: Blob, wantName: string): Promise<string> {
+ const dir = await mediaDir(id, true);
+ if (!dir) throw new Error("Browser storage is unavailable.");
+ const name = await freeName(dir, wantName);
await writeFileAt(dir, name, file);
askPersist();
return name;
@@ -258,6 +273,29 @@ export async function deleteProject(id: string): Promise<void> {
await dir?.removeEntry(id, { recursive: true }).catch(() => {});
}
+// --- library ---
+
+// The shelf beside the projects: reusable media, its folders, and templates,
+// all in this browser's own storage. The route handlers live in ./library.ts.
+const libraryParts = () => [...userParts(), "library"];
+
+export const libraryDir = (create = false) => dirAt(libraryParts(), create);
+export const libraryMediaDir = (create = false) => dirAt([...libraryParts(), "media"], create);
+
+export async function saveLibraryMedia(file: Blob, wantName: string): Promise<string> {
+ const dir = await libraryMediaDir(true);
+ if (!dir) throw new Error("Browser storage is unavailable.");
+ const name = await freeName(dir, wantName);
+ await writeFileAt(dir, name, file);
+ askPersist();
+ return name;
+}
+
+export async function deleteLibraryMedia(fileName: string): Promise<void> {
+ const dir = await libraryMediaDir();
+ await dir?.removeEntry(fileName).catch(() => {});
+}
+
// --- exports ---
export type ExportListing = { file: string; size: number; mtime: number };
diff --git a/site/src/cut/lib/backend/browser/respond.ts b/site/src/cut/lib/backend/browser/respond.ts
new file mode 100644
index 00000000..61b4d1b2
--- /dev/null
+++ b/site/src/cut/lib/backend/browser/respond.ts
@@ -0,0 +1,19 @@
+// The replies the browser backend's handlers build. Shapes match the engine's
+// (`server/http/*`), so a call site can't tell which backend answered.
+
+export const json = (body: unknown, status = 200) => Response.json(body, { status });
+
+export const err = (message: string, status: number) => json({ error: message }, status);
+
+export const caught = (e: unknown, fallback: string) =>
+ err(e instanceof Error ? e.message : fallback, 500);
+
+/** Serve a store file the way serveFileRange presents it: typed bytes, an
+ * attachment disposition when the URL asks to download. Blob-backed Responses
+ * satisfy media-element range requests without explicit 206 handling. */
+export function serveFile(file: File, name: string, download: boolean): Response {
+ const headers: Record<string, string> = {};
+ if (file.type) headers["Content-Type"] = file.type;
+ if (download) headers["Content-Disposition"] = `attachment; filename="${name.replace(/"/g, "")}"`;
+ return new Response(file, { headers });
+}
diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.ts
index 943178e1..622c5b9d 100644
--- a/site/src/cut/lib/backend/browser/router.ts
+++ b/site/src/cut/lib/backend/browser/router.ts
@@ -4,37 +4,24 @@
// (`server/http/projects.ts`) — call sites can't tell which backend answered.
//
// Owned here: projects CRUD + folders, media bytes, image import, presign-get
-// (answered with blob URLs), exports, and the export-jobs feed. Everything
-// else is the driver's cloud proxy.
+// (answered with blob URLs), exports, the export-jobs feed, and the library
+// shelf (./library.ts). Everything else is the driver's cloud proxy.
import { normalizeAspect, type ProjectDoc, type ProjectFolder } from "../../types";
import {
getBrowserExportJob,
listBrowserExportJobs,
removeBrowserExportJob,
} from "./exportJobs";
+import { dispatchLibraryRoute } from "./library";
import * as store from "./opfs";
import { registerBlobFile, registeredUrl, revokeRegistered } from "./registry";
-
-const json = (body: unknown, status = 200) => Response.json(body, { status });
-const err = (message: string, status: number) => json({ error: message }, status);
-const caught = (e: unknown, fallback: string) =>
- err(e instanceof Error ? e.message : fallback, 500);
+import { caught, err, json, serveFile } from "./respond";
const mediaApiPath = (id: string, fileName: string) =>
`/api/cut/projects/${id}/media/${encodeURIComponent(fileName)}`;
const exportApiPath = (id: string, fileName: string) =>
`/api/cut/projects/${id}/exports/${encodeURIComponent(fileName)}`;
-/** Serve a store file the way serveFileRange presents it: typed bytes, an
- * attachment disposition when the URL asks to download. Blob-backed Responses
- * satisfy media-element range requests without explicit 206 handling. */
-function serveFile(file: File, name: string, download: boolean): Response {
- const headers: Record<string, string> = {};
- if (file.type) headers["Content-Type"] = file.type;
- if (download) headers["Content-Disposition"] = `attachment; filename="${name.replace(/"/g, "")}"`;
- return new Response(file, { headers });
-}
-
async function listSummaries(): Promise<Response> {
const ids = await store.listProjectIds();
const summaries = (
@@ -221,7 +208,7 @@ async function uploadMedia(req: Request, id: string): Promise<Response> {
const form = await req.formData();
const file = form.get("file");
if (!(file instanceof File)) return err("No file in upload.", 400);
- const fileName = await store.saveMedia(id, file);
+ const fileName = await store.saveMedia(id, file, file.name);
registerBlobFile(mediaApiPath(id, fileName), file);
return json({ fileName });
} catch (e) {
@@ -239,7 +226,7 @@ async function importImage(req: Request, id: string): Promise<Response> {
const name = typeof nameField === "string" && nameField.trim() ? nameField.trim() : file.name;
const raw = form.get("origin");
const origin = raw === "generated" || raw === "sticker" ? raw : undefined;
- const fileName = await store.saveMedia(id, file);
+ const fileName = await store.saveMedia(id, file, file.name);
registerBlobFile(mediaApiPath(id, fileName), file);
let width = 0;
let height = 0;
@@ -412,6 +399,10 @@ export async function dispatchBrowserRoute(
return err("Not available for browser projects.", 404);
}
+ if (rest[0] === "library") {
+ return dispatchLibraryRoute(rest.slice(1), method, req, download);
+ }
+
if (rest[0] === "media" && rest[1] === "presign-get" && method === "POST") {
return presignGet(req());
}
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index c3f722f2..c8a5331b 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -1,6 +1,8 @@
"use client";
import { apiJson, getBackend } from "./backend";
+import { browserBackend } from "./backend/browser";
+import { cloudBackend } from "./backend/cloud";
import { readSnapshot, writeSnapshot } from "./cache";
import { pollCloudJob } from "./cloudJob";
import { downloadFromUrl } from "./download";
@@ -15,7 +17,6 @@ import {
activeResidency,
availableResidencies,
backendFor,
- libraryResidencies,
libraryShelfKey,
listedResidencies,
type Residency,
@@ -108,8 +109,8 @@ async function rememberedLibraryFrom(r: Residency): Promise<LibraryData | null>
* item it can't copy into the project has no business in a picker.
*/
export async function fetchLibrary(opts?: { remembered?: boolean }): Promise<LibraryData> {
- const live = libraryResidencies(availableResidencies());
- const rs = libraryResidencies(opts?.remembered ? listedResidencies() : live);
+ const live = availableResidencies();
+ const rs = opts?.remembered ? listedResidencies() : live;
const parts = await Promise.all(
rs.map((r) =>
live.includes(r) ? fetchLibraryFrom(r).catch(() => null) : rememberedLibraryFrom(r)
@@ -130,6 +131,7 @@ export async function importUrlToLibrary(
url: string,
residency: Residency = activeResidency()
): Promise<LibraryAsset[]> {
+ if (residency === "browser") return importUrlToBrowserShelf(url);
const backend = backendFor(residency);
const res = await backend.fetch("/api/cut/library/import-url", {
method: "POST",
@@ -156,6 +158,71 @@ export async function importUrlToLibrary(
return (Array.isArray(body) ? body : []).map((a) => ({ ...a, residency }));
}
+/**
+ * A link imported onto the browser shelf.
+ *
+ * Nothing in a page can fetch a video off a YouTube or TikTok link, so the
+ * cloud worker does it — into the account's cloud shelf, where this browser
+ * can read it — and the bytes come straight back down into this browser's own
+ * storage. The staged cloud copy is dropped once they land, however this ends,
+ * so an import leaves nothing behind on a shelf the user wasn't importing to.
+ */
+async function importUrlToBrowserShelf(url: string): Promise<LibraryAsset[]> {
+ const res = await cloudBackend.fetch("/api/cut/library/import-url", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ url }),
+ });
+ const started = await apiJson<{ jobId?: string }>(res);
+ if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not import that URL.");
+ const done = await pollCloudJob<{ assets?: LibraryAsset[] }>(
+ started.jobId,
+ cloudBackend,
+ "Could not import that URL."
+ );
+ // The library holds media, so a source that turned out to be only words
+ // fails here — the same line the engine's library import draws.
+ if (!done.assets?.length) throw new Error("That link has no media to import.");
+ const landed: LibraryAsset[] = [];
+ try {
+ for (const staged of done.assets) {
+ const bytes = await cloudBackend.fetch(
+ `/api/cut/library/media/${encodeURIComponent(staged.fileName)}`
+ );
+ if (!bytes.ok) throw new Error("Could not import that URL.");
+ const form = new FormData();
+ form.append("file", await bytes.blob(), staged.fileName);
+ form.append("name", staged.name);
+ form.append(
+ "meta",
+ JSON.stringify({
+ type: staged.type,
+ duration: staged.duration,
+ width: staged.width,
+ height: staged.height,
+ })
+ );
+ if (staged.source) form.append("source", JSON.stringify(staged.source));
+ const saved = await browserBackend.fetch("/api/cut/library", { method: "POST", body: form });
+ const body = await apiJson<LibraryAsset>(saved);
+ if (!saved.ok) throw new Error(body.error ?? "Could not import that URL.");
+ landed.push({ ...body, residency: "browser" });
+ }
+ } catch (e) {
+ // A part-written import is worse than none: the user reads an error and is
+ // left holding half a link.
+ for (const a of landed) await deleteFromLibrary("browser", a.id).catch(() => {});
+ throw e;
+ } finally {
+ for (const staged of done.assets) {
+ await cloudBackend
+ .fetch(`/api/cut/library/${staged.id}`, { method: "DELETE" })
+ .catch(() => {});
+ }
+ }
+ return landed;
+}
+
export async function createLibraryFolder(
name: string,
residency: Residency = activeResidency()
@@ -234,6 +301,16 @@ export async function uploadToLibrary(
}
const form = new FormData();
form.append("file", file, file.name);
+ if (residency === "browser") {
+ // The shelf is this page's storage, with no ffprobe behind it: the file is
+ // measured here, and one this browser can't read is refused rather than
+ // shelved as an asset nothing can play.
+ const meta = await probeFileMeta(file).catch(() => null);
+ if (!meta || (meta.type !== "image" && !(meta.duration > 0))) {
+ throw new Error("This file can't be read in this browser, so it can't go in the library.");
+ }
+ form.append("meta", JSON.stringify(meta));
+ }
const res = await backend.fetch("/api/cut/library", { method: "POST", body: form });
const body = await apiJson<LibraryAsset>(res);
if (!res.ok) throw new Error(body.error ?? "Upload failed.");
diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.ts
index 4eca5424..bce2f35a 100644
--- a/site/src/cut/lib/queries.ts
+++ b/site/src/cut/lib/queries.ts
@@ -27,7 +27,6 @@ import { fetchLibrary, type LibraryData } from "./library";
import {
availableResidencies,
backendFor,
- libraryResidencies,
listedResidencies,
projectsSnapshotKey,
type Residency,
@@ -47,7 +46,7 @@ export const projectsKey = (r: Residency) => ["cut", "projects", r] as const;
* the memory. */
export const libraryScope = () => {
const live = availableResidencies();
- return libraryResidencies(listedResidencies())
+ return listedResidencies()
.map((r) => (live.includes(r) ? r : `${r}!`))
.join("+");
};
diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.ts
index ebedcf61..c526cfa3 100644
--- a/site/src/cut/lib/residency.ts
+++ b/site/src/cut/lib/residency.ts
@@ -8,9 +8,9 @@
// app has to come back for.
//
// A project opens into one residency. The library is the other way around: it
-// is the user's shelf, and both halves of it are theirs, so every surface that
+// is the user's shelf, and every part of it is theirs, so every surface that
// shows the library shows every residency this browser can reach — a cloud
-// project can still pull a clip off this Mac's disk, and a local project can
+// project can still pull a clip off this Mac's disk, and a browser project can
// still pull one out of the cloud.
import { engineOrigin, servedFromEngine } from "./api";
import { cutMode } from "./backend";
@@ -57,12 +57,6 @@ export function availableResidencies(): Residency[] {
return out;
}
-/** The shelves the library spans. Library items keep a Mac and a cloud home;
- * browser-resident storage holds projects only, so library reads and writes
- * pass over it. */
-export const libraryResidencies = (rs: Residency[]): Residency[] =>
- rs.filter((r) => r !== "browser");
-
/** Set the first time an engine answers in this browser (by the ConnectGate).
* It separates a browser that never had the Donkey app from one whose app
* isn't running — the second has projects on this Mac and the first doesn't. */
@@ -114,11 +108,11 @@ async function lastLocalProjects(): Promise<Set<string>> {
}
/** The library residency the app is bound to: where a new library upload
- * lands. Browser mode uploads to the cloud shelf — the library passes over
- * browser storage. A shared view reads the local shelf. */
+ * lands. Every residency keeps its own shelf, so this follows the open
+ * project. A shared view reads the local shelf. */
export function activeResidency(): Residency {
const mode = cutMode();
- return mode === "cloud" || mode === "browser" ? "cloud" : "local";
+ return mode === "cloud" || mode === "browser" ? mode : "local";
}
const owners = new Map<string, Promise<CutBackend>>();