Skip to content

Open source CapCut alternative.

TypeScript

feat(site): browser OPFS backend with blob-URL registry [rebuild]

David Lee607216b06c9
diff --git a/site/src/cut/lib/backend/browser.ts b/site/src/cut/lib/backend/browser.ts
new file mode 100644
index 00000000..63795883
--- /dev/null
+++ b/site/src/cut/lib/backend/browser.ts
@@ -0,0 +1,37 @@
+// The browser backend: projects whose truth is this page's own origin-private
+// storage. Storage routes are answered in-page by the browser router; AI and
+// compute ride the hosted twin, metered like cloud projects. This module is
+// compiled into the engine binary with the rest of backend/, so the router and
+// store load through a function-scoped dynamic import and nothing here touches
+// the DOM at module scope.
+import { registeredUrl } from "./browser/registry";
+import type { CutBackend } from "./types";
+
+const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-cloud/");
+
+async function browserFetch(path: string, init?: RequestInit): Promise<Response> {
+ const { dispatchBrowserRoute } = await import("./browser/router");
+ const owned = await dispatchBrowserRoute(path, init);
+ return owned ?? fetch(cloudPath(path), init);
+}
+
+export const browserBackend: CutBackend = {
+ kind: "browser",
+ caps: {
+ importUrl: false, // needs a machine that can run the fetch
+ liveMic: true, // hosted LLM STT (lib/cloudTranscribe.ts)
+ transcribe: true, // hosted LLM STT (lib/cloudTranscribe.ts)
+ captionAi: true, // hosted Gemini twin (server/cloud/captions.ts)
+ revealInFinder: false,
+ watch: true, // browser seek + canvas contact sheets (lib/media.ts)
+ },
+ fetch: (path, init) => browserFetch(path, init),
+ url: (path) => {
+ // The registry is keyed by the bare API path; the blob URL it minted
+ // carries the whole file, so query flags (?download) have nothing to
+ // modify. Unregistered paths fall through to the hosted twin — AI routes
+ // and the window before hydration re-registers the store.
+ const q = path.indexOf("?");
+ return registeredUrl(q === -1 ? path : path.slice(0, q)) ?? cloudPath(path);
+ },
+};
diff --git a/site/src/cut/lib/backend/browser/exportJobs.ts b/site/src/cut/lib/backend/browser/exportJobs.ts
new file mode 100644
index 00000000..f68664ef
--- /dev/null
+++ b/site/src/cut/lib/backend/browser/exportJobs.ts
@@ -0,0 +1,56 @@
+// Export jobs for browser-resident projects. The render happens in this tab
+// (exportClient's in-tab pipeline), so the registry is tab-local memory: rows
+// exist for the dock's feed poll, and a reload drops them while the finished
+// files stay listed on the project's exports shelf. Shapes match the engine's
+// job feed so the dock renders every residency the same way.
+
+export interface BrowserExportJob {
+ id: string;
+ projectId: string;
+ projectName?: string;
+ status: "queued" | "running" | "done" | "error";
+ progress: number;
+ outName?: string;
+ error?: string;
+ startedAt?: number;
+ createdAt?: number;
+}
+
+const jobs: BrowserExportJob[] = [];
+
+/** Claim a feed row for a render this tab is about to run. */
+export function reserveBrowserExportJob(projectId: string, projectName?: string): BrowserExportJob {
+ const now = Date.now();
+ const job: BrowserExportJob = {
+ id: crypto.randomUUID().slice(0, 8),
+ projectId,
+ projectName,
+ status: "running",
+ progress: 0,
+ startedAt: now,
+ createdAt: now,
+ };
+ jobs.push(job);
+ return job;
+}
+
+export function updateBrowserExportJob(
+ id: string,
+ patch: Partial<Omit<BrowserExportJob, "id" | "projectId">>
+): void {
+ const job = jobs.find((j) => j.id === id);
+ if (job) Object.assign(job, patch);
+}
+
+export function getBrowserExportJob(id: string): BrowserExportJob | undefined {
+ return jobs.find((j) => j.id === id);
+}
+
+export function listBrowserExportJobs(): BrowserExportJob[] {
+ return jobs;
+}
+
+export function removeBrowserExportJob(id: string): void {
+ const at = jobs.findIndex((j) => j.id === id);
+ if (at !== -1) jobs.splice(at, 1);
+}
diff --git a/site/src/cut/lib/backend/browser/opfs.ts b/site/src/cut/lib/backend/browser/opfs.ts
new file mode 100644
index 00000000..d8ab36fc
--- /dev/null
+++ b/site/src/cut/lib/backend/browser/opfs.ts
@@ -0,0 +1,294 @@
+// The browser store: Cut projects on the page's own origin-private disk.
+//
+// The tree mirrors the engine's data dir, scoped per signed-in account
+// because OPFS is per-origin and one machine serves many accounts:
+//
+// cut-store/users/<accountId>/
+// index.json folders + media sync ledger
+// projects/<projectId>/
+// project.json the doc (createWritable commits on close,
+// so a torn write never replaces a good doc)
+// media/<fileName>
+// exports/<fileName>
+//
+// Project directories are named by id — no Finder here, so nothing follows
+// display names. Everything is functions over handles; no module-level DOM or
+// storage access, because this file rides along in the engine bundle.
+import type { ProjectDoc, ProjectFolder, ProjectSummary } from "../../types";
+import { currentEngineUser } from "../../api";
+
+const ROOT_DIR = "cut-store";
+
+/** Whether this browser can hold a store: OPFS with committed writes. The
+ * same capability line the in-tab render draws. */
+export function supportsBrowserStore(): boolean {
+ return (
+ typeof navigator !== "undefined" &&
+ typeof navigator.storage?.getDirectory === "function" &&
+ typeof FileSystemFileHandle !== "undefined" &&
+ "createWritable" in FileSystemFileHandle.prototype
+ );
+}
+
+const accountId = () => currentEngineUser() ?? "-";
+
+async function dirAt(parts: string[], create: boolean): Promise<FileSystemDirectoryHandle | null> {
+ try {
+ let dir = await navigator.storage.getDirectory();
+ for (const part of parts) dir = await dir.getDirectoryHandle(part, { create });
+ return dir;
+ } catch {
+ return null;
+ }
+}
+
+const userParts = () => [ROOT_DIR, "users", accountId()];
+const projectParts = (id: string) => [...userParts(), "projects", id];
+
+export const projectsDir = (create = false) => dirAt([...userParts(), "projects"], create);
+export const projectDir = (id: string, create = false) => dirAt(projectParts(id), create);
+export const mediaDir = (id: string, create = false) => dirAt([...projectParts(id), "media"], create);
+export const exportsDir = (id: string, create = false) =>
+ dirAt([...projectParts(id), "exports"], create);
+
+/** One storage-persistence ask per session, on the first write that makes
+ * this browser hold something worth keeping. */
+let persistAsked = false;
+export function askPersist(): void {
+ if (persistAsked) return;
+ persistAsked = true;
+ try {
+ void navigator.storage.persist?.().catch(() => {});
+ } catch {
+ // Denied or unsupported: the store still works, eviction just stays
+ // possible; the UI reads navigator.storage.persisted() where it matters.
+ }
+}
+
+/** Serialize writers of shared files (index.json) across tabs. Falls through
+ * to running bare where Web Locks are unavailable. */
+export async function withStoreLock<T>(name: string, fn: () => Promise<T>): Promise<T> {
+ const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;
+ if (!locks) return fn();
+ return locks.request(`cut-store:${accountId()}:${name}`, fn) as Promise<T>;
+}
+
+// --- file primitives ---
+
+export async function readFileAt(
+ dir: FileSystemDirectoryHandle | null,
+ name: string
+): Promise<File | null> {
+ if (!dir) return null;
+ try {
+ return await (await dir.getFileHandle(name)).getFile();
+ } catch {
+ return null;
+ }
+}
+
+export async function writeFileAt(
+ dir: FileSystemDirectoryHandle,
+ name: string,
+ data: Blob | ArrayBuffer | string
+): Promise<void> {
+ const handle = await dir.getFileHandle(name, { create: true });
+ const w = await handle.createWritable();
+ try {
+ await w.write(data);
+ } catch (err) {
+ await w.abort().catch(() => {});
+ throw err;
+ }
+ await w.close();
+}
+
+async function readJsonAt<T>(dir: FileSystemDirectoryHandle | null, name: string): Promise<T | null> {
+ const file = await readFileAt(dir, name);
+ if (!file) return null;
+ try {
+ return JSON.parse(await file.text()) as T;
+ } catch {
+ return null;
+ }
+}
+
+// --- index: folders + the media sync ledger ---
+
+/** A cloud project's media file the cloud doesn't hold yet. The entry is the
+ * pin: media listed here exists only in this browser and is never evicted;
+ * the sync queue drains it and clears the entry. */
+export type PendingUpload = {
+ projectId: string;
+ fileName: string;
+ /** Bytes, for queue ordering and the storage pill. */
+ size: number;
+ addedAt: number;
+};
+
+type StoreIndex = {
+ version: 1;
+ folders: ProjectFolder[];
+ pendingUploads: PendingUpload[];
+};
+
+const EMPTY_INDEX: StoreIndex = { version: 1, folders: [], pendingUploads: [] };
+
+export async function readIndex(): Promise<StoreIndex> {
+ const idx = await readJsonAt<StoreIndex>(await dirAt(userParts(), false), "index.json");
+ return idx && Array.isArray(idx.folders)
+ ? { ...EMPTY_INDEX, ...idx, pendingUploads: idx.pendingUploads ?? [] }
+ : EMPTY_INDEX;
+}
+
+export async function updateIndex(mutate: (idx: StoreIndex) => StoreIndex | void): Promise<StoreIndex> {
+ return withStoreLock("index", async () => {
+ const dir = await dirAt(userParts(), true);
+ if (!dir) throw new Error("Browser storage is unavailable.");
+ const idx = await readIndex();
+ const next = mutate(idx) ?? idx;
+ await writeFileAt(dir, "index.json", JSON.stringify(next));
+ return next;
+ });
+}
+
+// --- docs ---
+
+export async function readDoc(id: string): Promise<ProjectDoc | null> {
+ return readJsonAt<ProjectDoc>(await projectDir(id), "project.json");
+}
+
+export async function writeDoc(id: string, doc: ProjectDoc): Promise<void> {
+ const dir = await projectDir(id, true);
+ if (!dir) throw new Error("Browser storage is unavailable.");
+ doc.id = id;
+ doc.updatedAt = Date.now();
+ await writeFileAt(dir, "project.json", JSON.stringify(doc));
+}
+
+/** Every project id in the store (directories holding a readable doc). */
+export async function listProjectIds(): Promise<string[]> {
+ const dir = await projectsDir();
+ if (!dir) return [];
+ const ids: string[] = [];
+ try {
+ for await (const [name, handle] of dir) {
+ if (handle.kind === "directory") ids.push(name);
+ }
+ } catch {
+ return ids;
+ }
+ return ids;
+}
+
+async function dirBytes(dir: FileSystemDirectoryHandle | null): Promise<number> {
+ if (!dir) return 0;
+ let total = 0;
+ try {
+ for await (const [, handle] of dir) {
+ if (handle.kind === "file") {
+ total += (await (handle as FileSystemFileHandle).getFile()).size;
+ } else {
+ total += await dirBytes(handle as FileSystemDirectoryHandle);
+ }
+ }
+ } catch {
+ // Partial totals are fine; this feeds a size hint, never a decision.
+ }
+ return total;
+}
+
+/** The engine's summary shape for a doc in the store. */
+export async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSummary> {
+ const track0 = doc.clips.filter((c) => (c.track ?? 0) === 0);
+ const firstClip = track0[0];
+ const firstClipAsset = firstClip ? doc.assets.find((a) => a.id === firstClip.assetId) : undefined;
+ const previewAsset =
+ firstClipAsset ?? doc.assets.find((a) => a.type === "video" || a.type === "image");
+ return {
+ id,
+ name: doc.name,
+ createdAt: doc.createdAt,
+ updatedAt: doc.updatedAt,
+ duration: track0.reduce((sum, c) => sum + Math.max(0, c.out - c.in), 0),
+ clipCount: track0.length,
+ assetCount: doc.assets.length,
+ previewFile: previewAsset?.fileName,
+ previewIsImage: previewAsset?.type === "image",
+ previewStart: firstClipAsset && firstClip ? firstClip.in : 0,
+ hasPreview: false,
+ folderId: doc.folderId ?? null,
+ sizeBytes: await dirBytes(await projectDir(id)),
+ };
+}
+
+// --- 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)
+ .split("/")
+ .pop()!
+ .replace(/[^\w.\-() ]+/g, "_")
+ .slice(-80);
+ const dot = base.lastIndexOf(".");
+ const ext = dot > 0 ? base.slice(dot) : "";
+ 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}`;
+ await writeFileAt(dir, name, file);
+ askPersist();
+ return name;
+}
+
+export async function deleteMedia(id: string, fileName: string): Promise<void> {
+ const dir = await mediaDir(id);
+ await dir?.removeEntry(fileName).catch(() => {});
+}
+
+export async function deleteProject(id: string): Promise<void> {
+ const dir = await projectsDir();
+ await dir?.removeEntry(id, { recursive: true }).catch(() => {});
+}
+
+// --- exports ---
+
+export type ExportListing = { file: string; size: number; mtime: number };
+
+export async function listExports(id: string): Promise<ExportListing[]> {
+ const dir = await exportsDir(id);
+ if (!dir) return [];
+ const items: ExportListing[] = [];
+ try {
+ for await (const [name, handle] of dir) {
+ if (handle.kind !== "file" || !name.endsWith(".mp4")) continue;
+ const file = await (handle as FileSystemFileHandle).getFile();
+ if (file.size > 0) items.push({ file: name, size: file.size, mtime: file.lastModified });
+ }
+ } catch {
+ // A half-listed exports shelf still renders.
+ }
+ return items.sort((a, b) => b.mtime - a.mtime);
+}
+
+/** Land a finished render in exports/, deduping like media names do. */
+export async function saveExport(id: string, file: File, wantName: string): Promise<string> {
+ const dir = await exportsDir(id, true);
+ if (!dir) throw new Error("Browser storage is unavailable.");
+ const dot = wantName.lastIndexOf(".");
+ const ext = dot > 0 ? wantName.slice(dot) : ".mp4";
+ const stem = dot > 0 ? wantName.slice(0, dot) : wantName;
+ let name = wantName;
+ for (let n = 1; await readFileAt(dir, name); n++) name = `${stem}-${n}${ext}`;
+ await writeFileAt(dir, name, file);
+ askPersist();
+ return name;
+}
+
+export async function deleteExport(id: string, fileName: string): Promise<void> {
+ const dir = await exportsDir(id);
+ await dir?.removeEntry(fileName).catch(() => {});
+}
diff --git a/site/src/cut/lib/backend/browser/registry.test.ts b/site/src/cut/lib/backend/browser/registry.test.ts
new file mode 100644
index 00000000..cae9c252
--- /dev/null
+++ b/site/src/cut/lib/backend/browser/registry.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test } from "bun:test";
+import {
+ cancelRevoke,
+ holdRegistered,
+ registerBlobFile,
+ registeredUrl,
+ releaseRegistered,
+ resolveRegisteredBlob,
+ revokeRegistered,
+} from "./registry";
+
+const file = (name: string) => new File(["bytes"], name, { type: "video/mp4" });
+
+describe("blob-URL registry", () => {
+ test("a registered path answers with its URL and backing file", () => {
+ const path = "/api/cut/projects/p1/media/a.mp4";
+ const f = file("a.mp4");
+ const url = registerBlobFile(path, f);
+ expect(registeredUrl(path)).toBe(url);
+ expect(resolveRegisteredBlob(url)).toBe(f);
+ revokeRegistered(path);
+ });
+
+ test("re-registering a path retires the old URL", () => {
+ const path = "/api/cut/projects/p2/media/a.mp4";
+ const first = registerBlobFile(path, file("a.mp4"));
+ const second = registerBlobFile(path, file("a.mp4"));
+ expect(second).not.toBe(first);
+ expect(registeredUrl(path)).toBe(second);
+ expect(resolveRegisteredBlob(first)).toBe(null);
+ revokeRegistered(path);
+ });
+
+ test("a prefix revoke sweeps a project's subtree and nothing else", () => {
+ const mine = "/api/cut/projects/p3/media/a.mp4";
+ const other = "/api/cut/projects/p30/media/b.mp4";
+ const mineUrl = registerBlobFile(mine, file("a.mp4"));
+ const otherUrl = registerBlobFile(other, file("b.mp4"));
+ revokeRegistered("/api/cut/projects/p3/");
+ expect(registeredUrl(mine)).toBe(null);
+ expect(resolveRegisteredBlob(mineUrl)).toBe(null);
+ expect(registeredUrl(other)).toBe(otherUrl);
+ revokeRegistered(other);
+ });
+
+ test("a hold defers a revoke until its release", () => {
+ const path = "/api/cut/projects/p4/media/a.mp4";
+ const url = registerBlobFile(path, file("a.mp4"));
+ holdRegistered("/api/cut/projects/p4/");
+ revokeRegistered("/api/cut/projects/p4/");
+ expect(registeredUrl(path)).toBe(url);
+ releaseRegistered("/api/cut/projects/p4/");
+ expect(registeredUrl(path)).toBe(null);
+ });
+
+ test("re-opening cancels a deferred revoke", () => {
+ const path = "/api/cut/projects/p5/media/a.mp4";
+ const url = registerBlobFile(path, file("a.mp4"));
+ holdRegistered("/api/cut/projects/p5/");
+ revokeRegistered("/api/cut/projects/p5/");
+ cancelRevoke("/api/cut/projects/p5/");
+ releaseRegistered("/api/cut/projects/p5/");
+ expect(registeredUrl(path)).toBe(url);
+ revokeRegistered("/api/cut/projects/p5/");
+ expect(registeredUrl(path)).toBe(null);
+ });
+
+ test("unregistered lookups answer null", () => {
+ expect(registeredUrl("/api/cut/projects/none/media/x.mp4")).toBe(null);
+ expect(resolveRegisteredBlob("blob:nothing")).toBe(null);
+ });
+});
diff --git a/site/src/cut/lib/backend/browser/registry.ts b/site/src/cut/lib/backend/browser/registry.ts
new file mode 100644
index 00000000..ccd34755
--- /dev/null
+++ b/site/src/cut/lib/backend/browser/registry.ts
@@ -0,0 +1,99 @@
+// The blob-URL registry: the synchronous face of the browser store.
+//
+// `backend.url()` must answer without awaiting, and OPFS reads can't. The
+// store closes that gap by registering every file it serves under its API
+// path — the same `/api/cut/projects/:id/media/:file` string every call site
+// already builds — and minting one blob URL per file. `url()` becomes a map
+// lookup, media elements consume the blob URL natively, and decoders skip the
+// URL entirely: `openMedia` resolves the backing File here and reads it as a
+// Blob, because ranged fetches of blob URLs are unreliable across browsers.
+//
+// Blob URLs are session-scoped by nature, so nothing here persists: a reload
+// re-registers from OPFS during hydration. Registration is idempotent per
+// path — re-registering the same path revokes the old URL first, and dropping
+// a project revokes everything under its path prefix.
+
+type Entry = { url: string; file: File };
+
+const byPath = new Map<string, Entry>();
+const byUrl = new Map<string, File>();
+
+/** Mint (or re-mint) the blob URL for a store file at its API path. */
+export function registerBlobFile(path: string, file: File): string {
+ const prior = byPath.get(path);
+ if (prior) {
+ byUrl.delete(prior.url);
+ URL.revokeObjectURL(prior.url);
+ }
+ const url = URL.createObjectURL(file);
+ byPath.set(path, { url, file });
+ byUrl.set(url, file);
+ return url;
+}
+
+/** The minted URL for an API path, when its file has been registered. */
+export function registeredUrl(path: string): string | null {
+ return byPath.get(path)?.url ?? null;
+}
+
+/** The backing File of a minted blob URL — decoders read this directly
+ * instead of fetching the URL. Null for URLs the store didn't mint. */
+export function resolveRegisteredBlob(url: string): File | null {
+ return byUrl.get(url) ?? null;
+}
+
+// An in-tab render reads its project's files through these URLs for as long
+// as it runs, and it survives the user opening another project — which is
+// exactly when the store revokes the subtree. A hold keeps the URLs alive for
+// the render; the revoke waits and lands when the last hold releases.
+const holds = new Map<string, number>();
+const deferred = new Set<string>();
+
+function held(prefix: string): boolean {
+ for (const h of holds.keys()) {
+ if (h.startsWith(prefix) || prefix.startsWith(h)) return true;
+ }
+ return false;
+}
+
+/** Keep every registration under `prefix` alive until the matching release. */
+export function holdRegistered(prefix: string): void {
+ holds.set(prefix, (holds.get(prefix) ?? 0) + 1);
+}
+
+/** Release a hold and land any revokes that waited on it. */
+export function releaseRegistered(prefix: string): void {
+ const n = (holds.get(prefix) ?? 0) - 1;
+ if (n > 0) holds.set(prefix, n);
+ else holds.delete(prefix);
+ for (const d of deferred) {
+ if (held(d)) continue;
+ deferred.delete(d);
+ sweep(d);
+ }
+}
+
+function sweep(prefix: string): void {
+ for (const [path, entry] of byPath) {
+ if (!path.startsWith(prefix)) continue;
+ byPath.delete(path);
+ byUrl.delete(entry.url);
+ URL.revokeObjectURL(entry.url);
+ }
+}
+
+/** A subtree coming back into use (its project re-opened while a hold kept it
+ * alive): a revoke still waiting on it no longer applies. */
+export function cancelRevoke(prefix: string): void {
+ deferred.delete(prefix);
+}
+
+/** Revoke every registration whose API path starts with `prefix` (a closed or
+ * deleted project's subtree). A held subtree revokes when its hold releases. */
+export function revokeRegistered(prefix: string): void {
+ if (held(prefix)) {
+ deferred.add(prefix);
+ return;
+ }
+ sweep(prefix);
+}
diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.ts
new file mode 100644
index 00000000..0184df68
--- /dev/null
+++ b/site/src/cut/lib/backend/browser/router.ts
@@ -0,0 +1,437 @@
+// The browser backend's route table: the engine's storage routes, served from
+// the OPFS store in this page. The driver lazy-imports this module, so the
+// engine bundle never pulls it in. Handlers mirror the engine's JSON shapes
+// (`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.
+import { normalizeAspect, type ProjectDoc, type ProjectFolder } from "../../types";
+import {
+ getBrowserExportJob,
+ listBrowserExportJobs,
+ removeBrowserExportJob,
+} from "./exportJobs";
+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);
+
+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 = (
+ await Promise.all(
+ ids.map(async (id) => {
+ const doc = await store.readDoc(id);
+ return doc ? store.summarize(id, doc) : null;
+ })
+ )
+ ).filter((s): s is NonNullable<typeof s> => s !== null);
+ return json(summaries.sort((a, b) => b.updatedAt - a.updatedAt));
+}
+
+async function createProject(req: Request): Promise<Response> {
+ try {
+ const { name, folderId } = (await req.json()) as { name?: string; folderId?: string | null };
+ const id = crypto.randomUUID().slice(0, 10);
+ const displayName = (name ?? "Untitled").trim() || "Untitled";
+ const folders = (await store.readIndex()).folders;
+ const folder = folderId && folders.some((f) => f.id === folderId) ? folderId : null;
+ const now = Date.now();
+ const doc: ProjectDoc = {
+ version: 1,
+ id,
+ name: displayName,
+ createdAt: now,
+ updatedAt: now,
+ assets: [],
+ clips: [],
+ audioClips: [],
+ overlays: [],
+ ...(folder ? { folderId: folder } : {}),
+ };
+ await store.writeDoc(id, doc);
+ store.askPersist();
+ return json(await store.summarize(id, doc));
+ } catch (e) {
+ return caught(e, "Could not create project.");
+ }
+}
+
+/** The engine's PUT merge, field for field: arrays replace when sent, scalars
+ * validate, `ui`/`publish`/`notes` shallow-merge, and a `clips` save with no
+ * `overlayClips` clears the legacy array. */
+async function putProject(req: Request, id: string): Promise<Response> {
+ try {
+ const existing = await store.readDoc(id);
+ if (!existing) return err("Project not found.", 404);
+ const body = (await req.json()) as Partial<ProjectDoc>;
+ const doc: ProjectDoc = {
+ ...existing,
+ name: typeof body.name === "string" && body.name.trim() ? body.name.trim() : existing.name,
+ assets: Array.isArray(body.assets) ? body.assets : existing.assets,
+ clips: Array.isArray(body.clips) ? body.clips : existing.clips,
+ transitions: Array.isArray(body.transitions) ? body.transitions : existing.transitions,
+ audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,
+ overlayClips: Array.isArray(body.overlayClips)
+ ? body.overlayClips
+ : Array.isArray(body.clips)
+ ? []
+ : existing.overlayClips,
+ overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
+ templates: Array.isArray(body.templates) ? body.templates : existing.templates,
+ aspect: normalizeAspect(body.aspect) ?? existing.aspect,
+ fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,
+ fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,
+ subtitles:
+ body.subtitles && typeof body.subtitles === "object" ? body.subtitles : existing.subtitles,
+ ui: body.ui && typeof body.ui === "object" ? { ...existing.ui, ...body.ui } : existing.ui,
+ publish:
+ body.publish && typeof body.publish === "object"
+ ? { ...existing.publish, ...body.publish }
+ : existing.publish,
+ notes:
+ body.notes && typeof body.notes === "object"
+ ? { ...existing.notes, ...body.notes }
+ : existing.notes,
+ genvideo: body.genvideo !== undefined ? body.genvideo ?? undefined : existing.genvideo,
+ renders: Array.isArray(body.renders) ? body.renders : existing.renders,
+ };
+ await store.writeDoc(id, doc);
+ return json({ ok: true, updatedAt: doc.updatedAt });
+ } catch (e) {
+ return caught(e, "Could not save project.");
+ }
+}
+
+async function duplicateProject(id: string): Promise<Response> {
+ try {
+ const doc = await store.readDoc(id);
+ if (!doc) return err("Project not found.", 404);
+ const newId = crypto.randomUUID().slice(0, 10);
+ const now = Date.now();
+ const copy: ProjectDoc = { ...doc, id: newId, name: `${doc.name} copy`, createdAt: now, updatedAt: now };
+ await store.writeDoc(newId, copy);
+ const srcMedia = await store.mediaDir(id);
+ if (srcMedia) {
+ for await (const [name, handle] of srcMedia) {
+ if (handle.kind !== "file") continue;
+ const file = await (handle as FileSystemFileHandle).getFile();
+ await store.saveMedia(newId, file, name);
+ }
+ }
+ return json(await store.summarize(newId, copy));
+ } catch (e) {
+ return caught(e, "Could not duplicate project.");
+ }
+}
+
+async function moveProject(req: Request, id: string): Promise<Response> {
+ try {
+ const { folderId } = (await req.json()) as { folderId: string | null };
+ const doc = await store.readDoc(id);
+ if (!doc) return err("Project not found.", 404);
+ if (folderId && !(await store.readIndex()).folders.some((f) => f.id === folderId)) {
+ return err("Folder not found.", 404);
+ }
+ doc.folderId = folderId ?? null;
+ await store.writeDoc(id, doc);
+ return json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not move project.");
+ }
+}
+
+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: ProjectFolder = {
+ id: crypto.randomUUID().slice(0, 8),
+ name: trimmed.slice(0, 80),
+ createdAt: Date.now(),
+ };
+ await store.updateIndex((idx) => ({ ...idx, folders: [...idx.folders, folder] }));
+ return json(folder);
+ } catch (e) {
+ return caught(e, "Could not create folder.");
+ }
+}
+
+async function renameFolder(req: Request, fid: string): Promise<Response> {
+ try {
+ const { name } = (await req.json()) as { name?: string };
+ const trimmed = (name ?? "").trim();
+ if (!trimmed) return err("Folder name required.", 500);
+ let renamed: ProjectFolder | null = null;
+ await store.updateIndex((idx) => ({
+ ...idx,
+ folders: idx.folders.map((f) =>
+ f.id === fid ? (renamed = { ...f, name: trimmed.slice(0, 80) }) : f
+ ),
+ }));
+ return renamed ? json(renamed) : err("Folder not found.", 500);
+ } catch (e) {
+ return caught(e, "Could not rename folder.");
+ }
+}
+
+async function deleteFolder(fid: string): Promise<Response> {
+ try {
+ await store.updateIndex((idx) => ({
+ ...idx,
+ folders: idx.folders.filter((f) => f.id !== fid),
+ }));
+ // Projects in the folder fall back to ungrouped rather than disappearing.
+ for (const id of await store.listProjectIds()) {
+ const doc = await store.readDoc(id);
+ if (doc?.folderId === fid) {
+ doc.folderId = null;
+ await store.writeDoc(id, doc);
+ }
+ }
+ return json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not delete folder.");
+ }
+}
+
+async function uploadMedia(req: Request, id: string): Promise<Response> {
+ try {
+ if (!(await store.readDoc(id))) return err("Project not found.", 404);
+ 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);
+ registerBlobFile(mediaApiPath(id, fileName), file);
+ return json({ fileName });
+ } catch (e) {
+ return caught(e, "Upload failed.");
+ }
+}
+
+async function importImage(req: Request, id: string): Promise<Response> {
+ try {
+ if (!(await store.readDoc(id))) return err("Project not found.", 404);
+ const form = await req.formData();
+ const file = form.get("file");
+ if (!(file instanceof File)) return err("No image in upload.", 400);
+ const nameField = form.get("name");
+ 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);
+ registerBlobFile(mediaApiPath(id, fileName), file);
+ let width = 0;
+ let height = 0;
+ try {
+ const bmp = await createImageBitmap(file);
+ width = bmp.width;
+ height = bmp.height;
+ bmp.close();
+ } catch {
+ // Undecodable here; the asset still lands, dims stay unknown like the
+ // engine's probe failing.
+ }
+ return json({
+ id: crypto.randomUUID().slice(0, 8),
+ type: "image",
+ name,
+ fileName,
+ duration: 0,
+ width,
+ height,
+ ...(origin ? { origin } : {}),
+ });
+ } catch (e) {
+ return caught(e, "Could not import the image.");
+ }
+}
+
+/** Signed-URL mint, answered locally: every hit is a blob URL for the store's
+ * own bytes. No `expiresIn` in the reply — blob URLs live as long as the page,
+ * so the client's link-rotation clock stays off. */
+async function presignGet(req: Request): Promise<Response> {
+ try {
+ const body = (await req.json()) as { items?: { projectId: string; fileName: string }[] };
+ const urls: { fileName: string; url: string }[] = [];
+ for (const item of body.items ?? []) {
+ if (!item?.projectId || !item?.fileName) continue;
+ const path = mediaApiPath(item.projectId, item.fileName);
+ let url = registeredUrl(path);
+ if (!url) {
+ const file = await store.readFileAt(await store.mediaDir(item.projectId), item.fileName);
+ if (!file) continue;
+ url = registerBlobFile(path, file);
+ }
+ urls.push({ fileName: item.fileName, url });
+ }
+ return json({ urls });
+ } catch (e) {
+ return caught(e, "Could not resolve media.");
+ }
+}
+
+async function listProjectExports(id: string): Promise<Response> {
+ const items = await store.listExports(id);
+ // Register while listing so the shelf's players and download links resolve
+ // synchronously through backend.url().
+ for (const item of items) {
+ const path = exportApiPath(id, item.file);
+ if (!registeredUrl(path)) {
+ const file = await store.readFileAt(await store.exportsDir(id), item.file);
+ if (file) registerBlobFile(path, file);
+ }
+ }
+ return json(items);
+}
+
+async function exportJobStatus(jobId: string): Promise<Response> {
+ const job = getBrowserExportJob(jobId);
+ if (!job) return err("Unknown export.", 404);
+ return json({ status: job.status, progress: job.progress, error: job.error, outName: job.outName });
+}
+
+async function exportJobFile(jobId: string, download: boolean): Promise<Response> {
+ const job = getBrowserExportJob(jobId);
+ if (!job || job.status !== "done" || !job.outName) {
+ return new Response("Export not ready.", { status: 404 });
+ }
+ const file = await store.readFileAt(await store.exportsDir(job.projectId), job.outName);
+ if (!file) return new Response("Export not ready.", { status: 404 });
+ return serveFile(file, job.outName, download);
+}
+
+/**
+ * Serve one browser-backend request. Returns null for paths this router does
+ * not own — the driver proxies those to the hosted twin.
+ */
+export async function dispatchBrowserRoute(
+ path: string,
+ init?: RequestInit
+): Promise<Response | null> {
+ const url = new URL(path, "http://cut.browser");
+ const seg = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
+ if (seg[0] !== "api" || seg[1] !== "cut") return null;
+ const rest = seg.slice(2);
+ const method = (init?.method ?? "GET").toUpperCase();
+ const req = () => new Request(url, init);
+ const download = url.searchParams.has("download");
+
+ if (rest[0] === "projects") {
+ // /projects
+ if (rest.length === 1) {
+ if (method === "GET") return listSummaries();
+ if (method === "POST") return createProject(req());
+ return err("Method not allowed.", 405);
+ }
+ // /projects/folders[/:fid]
+ if (rest[1] === "folders") {
+ if (rest.length === 2) {
+ if (method === "GET") {
+ const { folders } = await store.readIndex();
+ return json([...folders].sort((a, b) => a.createdAt - b.createdAt));
+ }
+ if (method === "POST") return createFolder(req());
+ return err("Method not allowed.", 405);
+ }
+ if (rest.length === 3) {
+ if (method === "PUT") return renameFolder(req(), rest[2]);
+ if (method === "DELETE") return deleteFolder(rest[2]);
+ return err("Method not allowed.", 405);
+ }
+ return err("Not found.", 404);
+ }
+ const id = rest[1];
+ // /projects/:id
+ if (rest.length === 2) {
+ if (method === "HEAD" || method === "GET") {
+ const doc = await store.readDoc(id);
+ if (!doc) return err("Project not found.", 404);
+ return method === "HEAD" ? new Response(null, { status: 200 }) : json(doc);
+ }
+ if (method === "PUT") return putProject(req(), id);
+ if (method === "DELETE") {
+ await store.deleteProject(id);
+ revokeRegistered(`/api/cut/projects/${id}/`);
+ return json({ ok: true });
+ }
+ return err("Method not allowed.", 405);
+ }
+ // /projects/:id/<action>
+ if (rest.length === 3) {
+ if (rest[2] === "duplicate" && method === "POST") return duplicateProject(id);
+ if (rest[2] === "move" && method === "POST") return moveProject(req(), id);
+ if (rest[2] === "media" && method === "POST") return uploadMedia(req(), id);
+ if (rest[2] === "image" && method === "POST") return importImage(req(), id);
+ if (rest[2] === "exports" && method === "GET") return listProjectExports(id);
+ }
+ // /projects/:id/media/:file | /projects/:id/exports/:file
+ if (rest.length === 4 && (rest[2] === "media" || rest[2] === "exports")) {
+ const dir = rest[2] === "media" ? await store.mediaDir(id) : await store.exportsDir(id);
+ const fileName = rest[3];
+ if (method === "GET") {
+ const file = await store.readFileAt(dir, fileName);
+ if (!file) return err(`${rest[2] === "media" ? "Media file" : "Export"} not found.`, 404);
+ const apiPath =
+ rest[2] === "media" ? mediaApiPath(id, fileName) : exportApiPath(id, fileName);
+ if (!registeredUrl(apiPath)) registerBlobFile(apiPath, file);
+ return serveFile(file, fileName, download);
+ }
+ if (method === "DELETE") {
+ if (rest[2] === "media") await store.deleteMedia(id, fileName);
+ else await store.deleteExport(id, fileName);
+ revokeRegistered(
+ rest[2] === "media" ? mediaApiPath(id, fileName) : exportApiPath(id, fileName)
+ );
+ return json({ ok: true });
+ }
+ return err("Method not allowed.", 405);
+ }
+ // Engine-only compute under /projects (freeze, silence, transcribe, …):
+ // no browser implementation, answered like the cloud twin answers them.
+ return err("Not available for browser projects.", 404);
+ }
+
+ if (rest[0] === "media" && rest[1] === "presign-get" && method === "POST") {
+ return presignGet(req());
+ }
+
+ if (rest[0] === "export-jobs" && method === "GET") {
+ return json(listBrowserExportJobs());
+ }
+
+ if (rest[0] === "export" && rest.length >= 2) {
+ const jobId = rest[1];
+ if (rest.length === 2 && method === "GET") return exportJobStatus(jobId);
+ if (rest.length === 2 && method === "DELETE") {
+ removeBrowserExportJob(jobId);
+ return json({ ok: true });
+ }
+ if (rest.length === 3 && rest[2] === "file" && method === "GET") {
+ return exportJobFile(jobId, download);
+ }
+ return err("Not found.", 404);
+ }
+
+ return null;
+}
diff --git a/site/src/cut/lib/backend/index.test.ts b/site/src/cut/lib/backend/index.test.ts
index 084a01d1..346f74ba 100644
--- a/site/src/cut/lib/backend/index.test.ts
+++ b/site/src/cut/lib/backend/index.test.ts
@@ -34,6 +34,16 @@ describe("cut mode", () => {
expect(cutMode()).toBe("cloud");
});
+ test("browser is a mode of its own, ambient and pinned", () => {
+ setCutMode("browser");
+ expect(cutMode()).toBe("browser");
+ expect(getBackend().kind).toBe("browser");
+ bindCutMode("browser");
+ setCutMode("local"); // the gate finds an engine after the editor bound
+ expect(cutMode()).toBe("browser");
+ expect(getBackend().kind).toBe("browser");
+ });
+
test("subscribers hear effective changes only", () => {
let calls = 0;
const stop = subscribeCutMode(() => calls++);
diff --git a/site/src/cut/lib/backend/index.ts b/site/src/cut/lib/backend/index.ts
index 4ec92b2c..6d5f0d2d 100644
--- a/site/src/cut/lib/backend/index.ts
+++ b/site/src/cut/lib/backend/index.ts
@@ -6,6 +6,7 @@
// This module stays React-free: the engine binary compiles lib/types.ts, which
// imports apiUrl from here. React hooks live in ./hooks.
import { engineOrigin, servedFromEngine } from "../api";
+import { browserBackend } from "./browser";
import { cloudBackend } from "./cloud";
import { localBackend } from "./local";
import { sharedBackend } from "./shared";
@@ -68,7 +69,13 @@ export function subscribeCutMode(onChange: () => void) {
export function getBackend(): CutBackend {
const mode = cutMode();
- return mode === "cloud" ? cloudBackend : mode === "shared" ? sharedBackend : localBackend;
+ return mode === "cloud"
+ ? cloudBackend
+ : mode === "browser"
+ ? browserBackend
+ : mode === "shared"
+ ? sharedBackend
+ : localBackend;
}
/**
diff --git a/site/src/cut/lib/backend/types.ts b/site/src/cut/lib/backend/types.ts
index 437a0e21..65a41c15 100644
--- a/site/src/cut/lib/backend/types.ts
+++ b/site/src/cut/lib/backend/types.ts
@@ -1,11 +1,12 @@
// A Cut backend is where a project lives and executes: "local" is the engine
// on this Mac (127.0.0.1, disk storage, native tools), "cloud" is the hosted
-// deployment (session auth, Postgres + R2), and "shared" is a read-only view
-// of another account's cloud project through a share link. All speak the same
-// JSON route shapes, so ordinary API calls dispatch through one transport;
-// operations whose contracts genuinely differ (uploads, export,
+// deployment (session auth, Postgres + R2), "browser" is this page's own
+// origin-private storage with AI riding the hosted twin, and "shared" is a
+// read-only view of another account's cloud project through a share link. All
+// speak the same JSON route shapes, so ordinary API calls dispatch through one
+// transport; operations whose contracts genuinely differ (uploads, export,
// transcription) branch on the backend kind where they are implemented.
-export type CutMode = "local" | "cloud" | "shared";
+export type CutMode = "local" | "cloud" | "browser" | "shared";
// What the active backend can do. Components consult these to hide
// affordances instead of feature-detecting or failing at call time.
diff --git a/site/src/cut/lib/mediaSync.ts b/site/src/cut/lib/mediaSync.ts
new file mode 100644
index 00000000..25fc2f58
--- /dev/null
+++ b/site/src/cut/lib/mediaSync.ts
@@ -0,0 +1,204 @@
+// A cloud project's working copy in the browser store.
+//
+// Imports land here first: the dropped bytes are written into OPFS under the
+// name the cloud claimed, the asset plays from a blob URL over those bytes,
+// and the upload to R2 drains in the background (importQueue). The ledger in
+// the store's index — `pendingUploads` — is what makes that durable: an entry
+// means this browser holds the only copy, so the file is pinned and the next
+// open re-marks the asset and resumes the upload. Once the cloud confirms the
+// object, the entry clears and the local file becomes a read cache.
+//
+// The cache side runs the other way: media that hydrated over a signed URL is
+// streamed into the store in the background, so the next open of the same
+// project on this machine plays from disk.
+//
+// Every function is a no-op wherever the browser can't hold a store, so call
+// sites stay unconditional.
+import {
+ askPersist,
+ deleteMedia,
+ deleteProject,
+ mediaDir,
+ readFileAt,
+ readIndex,
+ saveMedia,
+ supportsBrowserStore,
+ updateIndex,
+ writeFileAt,
+ type PendingUpload,
+} from "./backend/browser/opfs";
+import { registerBlobFile, registeredUrl, revokeRegistered } from "./backend/browser/registry";
+
+const mediaPath = (projectId: string, fileName: string) =>
+ `/api/cut/projects/${projectId}/media/${encodeURIComponent(fileName)}`;
+
+/** Write an import's bytes into the store under the name the cloud claimed
+ * and pin them in the ledger. Returns the blob URL the asset plays from, or
+ * null when the store can't hold it — the import then stays tab-scoped and
+ * uploads the way it always has. */
+export async function stashCloudMedia(
+ projectId: string,
+ file: File,
+ fileName: string
+): Promise<string | null> {
+ if (!supportsBrowserStore()) return null;
+ try {
+ const dir = await mediaDir(projectId, true);
+ if (!dir) return null;
+ await writeFileAt(dir, fileName, file);
+ askPersist();
+ await updateIndex((idx) => {
+ idx.pendingUploads = [
+ ...idx.pendingUploads.filter((p) => p.projectId !== projectId || p.fileName !== fileName),
+ { projectId, fileName, size: file.size, addedAt: Date.now() },
+ ];
+ });
+ return registerBlobFile(mediaPath(projectId, fileName), file);
+ } catch {
+ return null;
+ }
+}
+
+/** Stash an import the cloud refused to claim (a full account's 413): the
+ * bytes land under a locally deduped name and stay pinned until the drain
+ * claims a cloud name for them. The claim is the cloud's to resolve, so the
+ * name can shift when it lands — `renameLocalMedia` follows it. */
+export async function stashUnclaimedMedia(
+ projectId: string,
+ file: File
+): Promise<{ fileName: string; url: string } | null> {
+ if (!supportsBrowserStore()) return null;
+ try {
+ const fileName = await saveMedia(projectId, file, file.name);
+ await updateIndex((idx) => {
+ idx.pendingUploads = [
+ ...idx.pendingUploads,
+ { projectId, fileName, size: file.size, addedAt: Date.now() },
+ ];
+ });
+ return { fileName, url: registerBlobFile(mediaPath(projectId, fileName), file) };
+ } catch {
+ return null;
+ }
+}
+
+/** Follow a cloud claim that resolved to a different name: move the stored
+ * bytes, their pin, and their blob URL onto it. */
+export async function renameLocalMedia(
+ projectId: string,
+ from: string,
+ to: string
+): Promise<void> {
+ if (!supportsBrowserStore() || from === to) return;
+ try {
+ const file = await readFileAt(await mediaDir(projectId), from);
+ if (!file) return;
+ const dir = await mediaDir(projectId, true);
+ if (!dir) return;
+ await writeFileAt(dir, to, file);
+ registerBlobFile(mediaPath(projectId, to), file);
+ // Decoders repoint when the asset's URL swaps to the new name; let the
+ // frame they are painting finish before the old URL dies under them.
+ setTimeout(() => revokeRegistered(mediaPath(projectId, from)), 10_000);
+ await dir.removeEntry(from).catch(() => {});
+ await updateIndex((idx) => {
+ idx.pendingUploads = idx.pendingUploads.map((p) =>
+ p.projectId === projectId && p.fileName === from ? { ...p, fileName: to } : p
+ );
+ });
+ } catch {
+ // The old copy stands; the next resume walks the same path.
+ }
+}
+
+/** The upload landed (or its object turned out to already exist): unpin. The
+ * local file stays on as a read cache. */
+export async function clearPendingUpload(projectId: string, fileName: string): Promise<void> {
+ if (!supportsBrowserStore()) return;
+ try {
+ await updateIndex((idx) => {
+ idx.pendingUploads = idx.pendingUploads.filter(
+ (p) => p.projectId !== projectId || p.fileName !== fileName
+ );
+ });
+ } catch {
+ // A stale pin costs a redundant resume, which the server answers "done".
+ }
+}
+
+/** The ledger entries pinning this project's unsynced media. */
+export async function pendingUploadsFor(projectId: string): Promise<PendingUpload[]> {
+ if (!supportsBrowserStore()) return [];
+ try {
+ return (await readIndex()).pendingUploads.filter((p) => p.projectId === projectId);
+ } catch {
+ return [];
+ }
+}
+
+/** The store's copy of a cloud project's media file, when it holds one. */
+export async function localMediaFile(projectId: string, fileName: string): Promise<File | null> {
+ if (!supportsBrowserStore()) return null;
+ return readFileAt(await mediaDir(projectId), fileName);
+}
+
+/** The blob URL for a locally held media file, minting it on first ask.
+ * Null when the store has no copy — the caller falls back to a signed URL. */
+export async function localMediaUrl(projectId: string, fileName: string): Promise<string | null> {
+ if (!supportsBrowserStore()) return null;
+ const path = mediaPath(projectId, fileName);
+ const prior = registeredUrl(path);
+ if (prior) return prior;
+ const file = await localMediaFile(projectId, fileName);
+ return file ? registerBlobFile(path, file) : null;
+}
+
+/** A media delete's local half: the file, its blob URL, and its pin. */
+export async function dropLocalMedia(projectId: string, fileName: string): Promise<void> {
+ if (!supportsBrowserStore()) return;
+ revokeRegistered(mediaPath(projectId, fileName));
+ await deleteMedia(projectId, fileName).catch(() => {});
+ await clearPendingUpload(projectId, fileName);
+}
+
+/** A project delete's local half: its whole subtree, URLs, and pins. */
+export async function dropLocalProjectCopy(projectId: string): Promise<void> {
+ if (!supportsBrowserStore()) return;
+ revokeRegistered(`/api/cut/projects/${projectId}/`);
+ await deleteProject(projectId).catch(() => {});
+ try {
+ await updateIndex((idx) => {
+ idx.pendingUploads = idx.pendingUploads.filter((p) => p.projectId !== projectId);
+ });
+ } catch {
+ // Orphaned pins for a gone project are swept on the next open attempt.
+ }
+}
+
+const caching = new Set<string>();
+
+/** Cache-on-read: stream a signed URL's bytes into the store in the
+ * background, so the next open of this project plays the file from disk.
+ * Fire-and-forget; a failed or refused write costs nothing but the cache. */
+export function cacheCloudMedia(projectId: string, fileName: string, url: string): void {
+ if (!supportsBrowserStore()) return;
+ const path = mediaPath(projectId, fileName);
+ if (registeredUrl(path) || caching.has(path)) return;
+ caching.add(path);
+ void (async () => {
+ try {
+ if (await localMediaFile(projectId, fileName)) return;
+ const res = await fetch(url);
+ if (!res.ok) return;
+ const blob = await res.blob();
+ const dir = await mediaDir(projectId, true);
+ if (!dir) return;
+ await writeFileAt(dir, fileName, blob);
+ } catch {
+ // Out of space or offline mid-stream: the abort discards the partial
+ // write, and signed URLs keep the project playing.
+ } finally {
+ caching.delete(path);
+ }
+ })();
+}