Open source CapCut alternative.
TypeScript
fix(cut): prepare imports across project storage modes [rebuild]
David Le672adfc58381
diff --git a/docs/guides/cut/local-compute.md b/docs/guides/cut/local-compute.mdindex 7604660c..3c69e5dc 100644--- a/docs/guides/cut/local-compute.md+++ b/docs/guides/cut/local-compute.md@@ -51,17 +51,13 @@ A client with no compositor at all asks by project id instead. The phone sends t## Converting footage-A camera writes what it likes. A phone's `.mov` is HEVC, a screen recorder's is ProRes, and a camera file often carries raw PCM sound — formats some browsers have no decoder for. Cut reads media through the browser's own decoders, so a file this browser cannot decode is a file it cannot preview, cut, or render, and the fix is to rewrite it as MP4 with H.264 picture and AAC sound.+Imports and the assistant's conversion tool prepare playable H.264/AAC media through the backend that holds the file. Compatible streams copy into the new container. Unsupported streams are encoded, and a playable audio rendition takes precedence over optional spatial audio.-Where it runs is decided by where the bytes already are, since moving a video file costs more than converting one. A Mac project converts on the engine's bundled ffmpeg, on the file in the project folder. A cloud project queues a render-worker job, which runs the identical code against the object in R2 — the tab sends nothing and watches the job row. A browser project converts in the tab, where mediabunny drives WebCodecs. A file whose streams already fit the container takes the cheap path everywhere: its packets are copied into a new wrapper in seconds, with no decoding and nothing lost. That case is most of what people mean by "turn these .mov files into mp4".+The Library uploads originals even when browser probing fails; the worker prepares playback and retains the source for download. A browser-local project or shelf without the required codec borrows preparation, saves the result into its own storage, and removes the temporary cloud copy. The engine shelf uses the same worker when its tools fail. Hosted preparation requires a signed-in account with available storage and worker capacity.-The one case with no machine of its own is a browser project holding footage this browser cannot decode, and that is where the Mac comes back in. With the app running, the page posts the bytes to the engine and takes an MP4 back — the same trade transcription makes, and for the same reason: the work is free, fast, and already installed. The engine keeps nothing; it converts what it is handed. With no app, the conversion fails and says what would fix it — a browser that decodes the format, the Mac app, or moving the project to the cloud.+Retries resume the same uploaded object and job. The Library publishes the prepared asset and its storage accounting together; failed preparation keeps the upload available for retry until its staging claim expires. The pending tile reports uploading, queued, preparing, and failure states.-A process with no page converts for itself. The engine holds the project folder, so it converts there directly and never calls its own HTTP surface; the cloud runner carries decoders of its own and runs the same in-process path a tab runs. That is what keeps conversion available to a chat turn whose tab has gone away.--Conversion happens on two occasions. An import whose bytes this browser cannot decode converts on the way in: the file reaches the project, converts there, and the asset that lands points at the result. And the assistant converts on request, in place — the asset keeps its id and its name, so clips already cut from it keep playing, and the file underneath changes.--In place is what makes the plain version of this work. Someone with a folder of `.mov` files drops them on the chat and asks for mp4: the drop makes each one an attachment on the thread, the conversion rewrites those same attachments, and the converted files come back as cards in the same conversation, ready to download or drag onto the timeline. Nothing is filed anywhere the user has to go find, and an attachment that was already an H.264 MP4 comes back untouched.+Project conversion keeps the asset id, so existing clips continue to reference it. The same tools run in the editor and headless clients.## Rules@@ -77,7 +73,7 @@ In place is what makes the plain version of this work. Someone with a folder of| Transcription, dictation | the Mac when it is there, hosted otherwise | the app ships the speech tool || Export | the Mac for its own projects, the browser for cloud and browser ones, the worker when the tab can't encode the choice | see Export above || Thumbnails, waveforms, media probing | the browser, always | it decodes the media itself |-| Converting media to MP4 | the machine holding the bytes: the Mac, the worker, or the tab — and the Mac for a browser project the tab can't decode | see Converting footage above |+| Converting media to MP4 | the backend holding the bytes, with hosted preparation when the browser lacks a codec | see Converting footage above || Image, video, and voice generation | hosted, always | no local counterpart || Cutout mattes | the quick person matte in the tab, on-device and free; the quality and tracked bakes hosted (credits), driven by the tab | the tab decodes the clip and owns the session; the engine and the worker only consume the stored matte asset || The assistant's Gemini models | hosted, always | credits and the user's session |diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex 04815ff2..f234e3d2 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -6,6 +6,8 @@* toolset and `aiTools.ts` keys its handlers on `LibraryToolName`.*/+import { CLOUD_LIBRARY_IMPORT_DESCRIPTION } from "@/cut/lib/libraryUpload";+import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";import { LIBRARY_SHARE_ACTIONS, LIBRARY_SHARE_KINDS, SHARE_ACCESS } from "@/cut/lib/librarySharing";@@ -26,7 +28,7 @@ export const LIBRARY_TOOLS = [{name: "library_list",description:- "List the shared Library — reusable media saved across projects: folders (nested; a folder's parentId names the folder it sits in), assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). An asset's `origin` says it came from the user's iOS app: \"camera\" is a clip they recorded on their phone (their Camera Roll), \"inspiration\" a reference they saved to the Inspiration folder. Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",+ CLOUD_LIBRARY_IMPORT_DESCRIPTION + " " + "List the shared Library — reusable media saved across projects: folders (nested; a folder's parentId names the folder it sits in), assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). An asset's `origin` says it came from the user's iOS app: \"camera\" is a clip they recorded on their phone (their Camera Roll), \"inspiration\" a reference they saved to the Inspiration folder. Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",inputSchema: obj({}),},{diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex eb9f692b..f4d16e6a 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -1,5 +1,7 @@"use client";+import type { LibraryUploadState } from "@/cut/lib/libraryUpload";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import { useRouter, useSearchParams } from "next/navigation";@@ -486,6 +488,7 @@ export function LibraryView() {const id = crypto.randomUUID();// Filing can fail after storage succeeds. Retrying keeps that stored copy.let asset: LibraryAsset | undefined;+ const uploadState: LibraryUploadState = {};const run = async () => {try {if (isFontArchive(file)) {@@ -505,7 +508,11 @@ export function LibraryView() {const shelf = isLinkedFile(file) && !folderId? await shelfForNewItem(file.size): residency;- asset = await uploadToLibrary(file, shelf);+ asset = await uploadToLibrary(file, shelf, {+ state: uploadState,+ folderId: shelf === "cloud" ? folderId : undefined,+ onStage: (stage) => setStage(id, stage),+ });}if (folderId) {setStage(id, "saving");diff --git a/site/src/cut/components/SidePanel.tools.ts b/site/src/cut/components/SidePanel.tools.tsindex e63fb90e..3264a357 100644--- a/site/src/cut/components/SidePanel.tools.ts+++ b/site/src/cut/components/SidePanel.tools.ts@@ -35,7 +35,7 @@ export const SIDE_PANEL_TOOLS = [{name: "convert_media",description:- "Convert project media to MP4 — H.264 picture, AAC sound — replacing each asset's file in place, so clips already cut from it keep playing. This is the fix for footage that previews black or refuses to play: a phone's HEVC .mov, a screen recorder's ProRes, a camera file with raw PCM sound. It is also the whole answer to \"turn these into mp4\": the user drops the files on this chat, you convert them, and each converted file is on its own card right here for them to download or drag in — nothing to go looking for. A file already in Media stays in Media. Streams that already fit the container are copied packet for packet, so a .mov of H.264 converts in seconds and loses nothing, and a file that is already an MP4 of those streams comes back untouched. `max_height` shrinks the picture at the same time (1080 for a 4K source that only needs to be a timeline clip). It runs wherever the project's bytes already are — this Mac, the render worker, or the tab — so it needs no setup; when nothing available can decode the source the error says what would fix it, and retrying changes nothing.",+ "Convert project media to MP4 — H.264 picture, AAC sound — replacing each asset's file in place, so clips already cut from it keep playing. This is the fix for footage that previews black or refuses to play: a phone's HEVC .mov, a screen recorder's ProRes, a camera file with raw PCM sound. It is also the whole answer to \"turn these into mp4\": the user drops the files on this chat, you convert them, and each converted file is on its own card right here for them to download or drag in — nothing to go looking for. A file already in Media stays in Media. Streams that already fit the container are copied packet for packet, so a .mov of H.264 converts in seconds and loses nothing, and a file that is already an MP4 of those streams comes back untouched. `max_height` shrinks the picture at the same time (1080 for a 4K source that only needs to be a timeline clip). Conversion runs automatically through the project backend. A browser missing a required codec uses hosted preparation and saves the result back into its own project.",inputSchema: obj({asset_ids: {type: "array",diff --git a/site/src/cut/lib/cloudLibraryUpload.test.ts b/site/src/cut/lib/cloudLibraryUpload.test.tsnew file mode 100644index 00000000..8feca6a2--- /dev/null+++ b/site/src/cut/lib/cloudLibraryUpload.test.ts@@ -0,0 +1,85 @@+import { afterEach, describe, expect, spyOn, test } from "bun:test";+import { cloudBackend } from "./backend/cloud";+import * as jobs from "./cloudJob";+import * as media from "./media";+import { uploadCloudLibraryMedia, withCloudPreparedMedia } from "./cloudLibraryUpload";+import type { LibraryAsset } from "./library";+import type { LibraryUploadState } from "./libraryUpload";++const restores: (() => void)[] = [];+afterEach(() => { for (const restore of restores.splice(0)) restore(); });+const asset: LibraryAsset = { id: "import", fileName: "playable.mp4", originalFile: "phone.mov", name: "phone.mov", type: "video", duration: 1, residency: "cloud", addedAt: 0 };+const file = () => new File(["original media"], "phone.mov", { type: "video/quicktime" });+function harness() {+ const upload = spyOn(media, "presignedUpload").mockResolvedValue("cut/user/library/phone.mov");+ const fetch = spyOn(cloudBackend, "fetch").mockImplementation(async () => Response.json({ jobId: "job" }));+ const poll = spyOn(jobs, "pollCloudJob").mockResolvedValue(asset);+ restores.push(() => upload.mockRestore(), () => fetch.mockRestore(), () => poll.mockRestore());+ return { upload, fetch, poll };+}++describe("cloud library preparation", () => {+ test("uploads original bytes and waits for prepared metadata without browser decoding", async () => {+ const h = harness();+ const source = file();+ const state: LibraryUploadState = {};+ expect(await uploadCloudLibraryMedia(source, { state, folderId: "folder" })).toEqual(asset);+ expect(h.upload.mock.calls[0]?.[1]).toBe(source);+ expect(JSON.parse(String(h.fetch.mock.calls[0]?.[1]?.body))).toMatchObject({ key: state.key, folderId: "folder", name: "phone.mov" });+ expect(h.poll.mock.calls.length).toBe(1);+ });++ test("a retry resumes the existing upload after preparation fails", async () => {+ const h = harness();+ let failed = false;+ h.poll.mockImplementation(async () => { if (!failed) { failed = true; throw new Error("Worker interrupted"); } return asset; });+ const state: LibraryUploadState = {};+ const source = file();+ await expect(uploadCloudLibraryMedia(source, { state })).rejects.toThrow("Worker interrupted");+ expect(await uploadCloudLibraryMedia(source, { state })).toEqual(asset);+ expect(h.upload.mock.calls.length).toBe(1);+ expect(h.fetch.mock.calls.length).toBe(2);+ });++ test("a completed upload returns directly on retry", async () => {+ const h = harness();+ h.fetch.mockResolvedValue(Response.json(asset));+ expect(await uploadCloudLibraryMedia(file(), { state: { key: "stored" } })).toEqual(asset);+ expect(h.upload).not.toHaveBeenCalled();+ expect(h.poll).not.toHaveBeenCalled();+ });++ test("browser-local adoption receives the converted bytes and removes staging", async () => {+ const h = harness();+ const responses = [Response.json({ jobId: "job" }), new Response("converted", { headers: { "Content-Type": "video/mp4" } }), Response.json({ ok: true })];+ h.fetch.mockImplementation(async () => responses.shift()!);+ const state: LibraryUploadState = {};+ const adopted = await withCloudPreparedMedia(file(), async (prepared) => {+ expect(prepared.name).toBe("playable.mp4");+ expect(await prepared.text()).toBe("converted");+ return "saved locally";+ }, { state });+ expect(adopted).toBe("saved locally");+ expect(h.fetch.mock.calls.at(-1)).toEqual(["/api/cut/library/import", { method: "DELETE" }]);+ expect(state.key).toBeUndefined();+ });++ test("failed local adoption removes the temporary cloud copy", async () => {+ const h = harness();+ const responses = [Response.json({ jobId: "job" }), new Response("converted"), Response.json({ ok: true })];+ h.fetch.mockImplementation(async () => responses.shift()!);+ await expect(withCloudPreparedMedia(file(), async () => { throw new Error("Local storage full"); })).rejects.toThrow("Local storage full");+ expect(h.fetch.mock.calls.at(-1)?.[1]?.method).toBe("DELETE");+ });++ test("cleanup failure leaves local adoption untouched so retry cannot duplicate it", async () => {+ const h = harness();+ const responses = [Response.json({ jobId: "job" }), new Response("converted"), new Response(null, { status: 500 })];+ h.fetch.mockImplementation(async () => responses.shift()!);+ let adopted = false;+ const state: LibraryUploadState = {};+ await expect(withCloudPreparedMedia(file(), async () => { adopted = true; }, { state })).rejects.toThrow("temporary cloud import");+ expect(adopted).toBe(false);+ expect(state.key).toBe("cut/user/library/phone.mov");+ });+});diff --git a/site/src/cut/lib/cloudLibraryUpload.ts b/site/src/cut/lib/cloudLibraryUpload.tsnew file mode 100644index 00000000..bca80894--- /dev/null+++ b/site/src/cut/lib/cloudLibraryUpload.ts@@ -0,0 +1,68 @@+"use client";++import { apiJson } from "@/cut/lib/backend";+import { cloudBackend } from "@/cut/lib/backend/cloud";+import { pollCloudJob } from "@/cut/lib/cloudJob";+import { presignedUpload } from "@/cut/lib/media";+import type { LibraryAsset, LibrarySource } from "@/cut/lib/library";+import type { LibraryUploadStage, LibraryUploadState } from "@/cut/lib/libraryUpload";++export type CloudUploadOptions = {+ name?: string;+ source?: LibrarySource;+ folderId?: string | null;+ maxHeight?: number;+ state?: LibraryUploadState;+ onStage?: (stage: LibraryUploadStage) => void;+};++/** The original uploads once; retries resume preparation by its storage key. */+export async function uploadCloudLibraryMedia(file: File, options: CloudUploadOptions = {}): Promise<LibraryAsset> {+ const state = options.state ?? {};+ if (!state.key) {+ options.onStage?.("uploading");+ state.key = await presignedUpload("/api/cut/library/presign", file, file.name, cloudBackend);+ }+ options.onStage?.("preparing");+ const res = await cloudBackend.fetch("/api/cut/library/prepare", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ key: state.key, name: options.name ?? file.name,+ ...(options.folderId ? { folderId: options.folderId } : {}),+ ...(options.source ? { source: options.source } : {}),+ ...(options.maxHeight ? { maxHeight: options.maxHeight } : {}),+ }),+ });+ const body = await apiJson<LibraryAsset | { jobId: string }>(res);+ if (!res.ok) throw new Error(body.error ?? "Could not prepare this upload.");+ const asset = "jobId" in body ? await pollCloudJob<LibraryAsset>(body.jobId, cloudBackend,+ "Could not prepare this upload.", {+ timedOut: "This file is still being prepared. Retry to check its progress.",+ onState: (status) => options.onStage?.(status === "queued" ? "queued" : "preparing"),+ }) : body;+ if (!asset.id || !asset.fileName) throw new Error("The import returned no media.");+ return { ...asset, residency: "cloud" };+}++/** A browser without a decoder borrows cloud preparation and takes the result home. */+export async function withCloudPreparedMedia<T>(+ file: File,+ adopt: (file: File) => Promise<T>,+ options: CloudUploadOptions = {},+): Promise<T> {+ const asset = await uploadCloudLibraryMedia(file, options);+ let prepared: File;+ try {+ const response = await cloudBackend.fetch(`/api/cut/library/media/${encodeURIComponent(asset.fileName)}`);+ if (!response.ok) throw new Error("Could not read the prepared media.");+ const blob = await response.blob();+ prepared = new File([blob], asset.fileName, { type: blob.type });+ } finally {+ const removed = await cloudBackend.fetch(`/api/cut/library/${encodeURIComponent(asset.id)}`, { method: "DELETE" });+ if (!removed.ok) throw new Error("Could not remove the temporary cloud import.");+ if (options.state) delete options.state.key;+ }+ // Finish staging cleanup before adoption so a cleanup retry cannot import twice.+ return adopt(prepared);+}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex d08dd574..ec393969 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -1,5 +1,9 @@"use client";+import { uploadCloudLibraryMedia, withCloudPreparedMedia } from "@/cut/lib/cloudLibraryUpload";+import type { LibraryUploadStage, LibraryUploadState } from "@/cut/lib/libraryUpload";+import { assetTypeOf } from "@/cut/lib/media";+import { apiJson, getBackend } from "./backend";import { cloudBackend } from "./backend/cloud";import { readSnapshot, writeSnapshot } from "./cache";@@ -51,6 +55,8 @@ export interface LibrarySource {export interface LibraryAsset {id: string;fileName: string;+ /** Uploaded source retained when playback needs conversion. */+ originalFile?: string;name: string;type: "video" | "audio" | "image" | "font";duration: number;@@ -194,9 +200,10 @@ export const libraryPosterUrl = (* on. The download goes through the route because it signs the attachment* name; a minted edge URL is signed for inline reads only. */export function downloadLibraryAsset(- a: Pick<LibraryAsset, "fileName" | "residency">,+ a: Pick<LibraryAsset, "fileName" | "originalFile" | "residency">,) {- downloadFromUrl(libraryRouteUrl(a.fileName, a.residency), a.fileName);+ const file = a.originalFile ?? a.fileName;+ downloadFromUrl(libraryRouteUrl(file, a.residency), file);}async function fetchLibraryFrom(r: Residency): Promise<LibraryData> {@@ -590,7 +597,7 @@ export async function uploadToLibrary(/** What the shelf should call it and where it came from, when the file is* arriving from somewhere that already knows — a carry from another shelf,* say. Left out, the file names itself and keeps whatever cover it makes. */- keep: { name?: string; source?: LibrarySource; poster?: Blob } = {},+ keep: { name?: string; source?: LibrarySource; poster?: Blob; folderId?: string | null; state?: LibraryUploadState; onStage?: (stage: LibraryUploadStage) => void } = {},): Promise<LibraryAsset> {const backend = backendFor(residency);// A font has no streams to measure; it is checked by installing it instead,@@ -601,19 +608,17 @@ export async function uploadToLibrary(const posterName = `${file.name}${SPECIMEN_FILE_SUFFIX}`;const fontMeta = { type: "font" as const, duration: 0 };if (residency === "cloud") {- // Presign -> direct R2 PUT -> complete, with the media probed here — the- // cloud can't cheaply probe an R2 object the way the engine probes disk.- // A file this browser can't decode would land as a zero-length asset it- // also couldn't preview, so reject it before any bytes go up.- const meta = fontLabel- ? fontMeta- : await probeFileMeta(file).catch(() => null);+ const type = assetTypeOf(file);+ const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);+ if ((!meta || !(meta.duration > 0)) && (type === "video" || type === "audio")) {+ return uploadCloudLibraryMedia(file, keep);+ }if (!meta ||(meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))) {throw new Error(- "This file can't be read in this browser, so it can't go in the cloud library. Import it in the Mac app instead.",+ "This image could not be read.",);}const key = await presignedUpload(@@ -656,27 +661,40 @@ export async function uploadToLibrary(if (keep.source) form.append("source", JSON.stringify(keep.source));if (poster) form.append("poster", poster, posterName);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 = fontLabel- ? fontMeta- : await probeFileMeta(file).catch(() => null);+ // Hosted preparation supplies missing decoders before the page stores media.+ const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);if (!meta ||(meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))) {- throw new Error(- "This file can't be read in this browser, so it can't go in the library.",- );+ const type = assetTypeOf(file);+ if (type === "video" || type === "audio") {+ return withCloudPreparedMedia(file, async (prepared) => {+ await probeFileMeta(prepared);+ return uploadToLibrary(prepared, residency, { ...keep, name: keep.name ?? file.name });+ }, { ...keep, folderId: undefined });+ }+ throw new Error("This image could not be read.");}form.append("meta", JSON.stringify(meta));+ } else {+ const type = assetTypeOf(file);+ if ((type === "video" || type === "audio") && !(await probeFileMeta(file).catch(() => null))) {+ keep.onStage?.("preparing");+ form.append("prepare", "true");+ }}const res = await backend.fetch("/api/cut/library", {method: "POST",body: form,});const body = await apiJson<LibraryAsset>(res);+ if (!res.ok && form.get("prepare") === "true") {+ return withCloudPreparedMedia(file, async (prepared) => {+ await probeFileMeta(prepared);+ return uploadToLibrary(prepared, residency, { ...keep, name: keep.name ?? file.name });+ }, { ...keep, folderId: undefined });+ }if (!res.ok) throw new Error(body.error ?? "Upload failed.");return { ...body, residency };}diff --git a/site/src/cut/lib/libraryUpload.ts b/site/src/cut/lib/libraryUpload.tsnew file mode 100644index 00000000..1282b55f--- /dev/null+++ b/site/src/cut/lib/libraryUpload.ts@@ -0,0 +1,23 @@+import { z } from "zod";++export const CLOUD_LIBRARY_IMPORT_DESCRIPTION =+ "Cloud Library uploads accept original video and audio files. The cloud prepares playable media automatically and retains the original for download.";++export const libraryUploadSchema = z.object({+ key: z.string().min(1),+ name: z.string().min(1).max(512),+ maxHeight: z.number().int().min(2).max(8192).optional(),+ folderId: z.string().min(1).nullable().optional(),+ source: z.object({+ url: z.string().url(),+ title: z.string().optional(),+ uploader: z.string().optional(),+ uploadDate: z.string().optional(),+ }).optional(),+});++export type LibraryUploadInput = z.infer<typeof libraryUploadSchema>;+export type LibraryUploadState = { key?: string };+export type LibraryUploadStage = "uploading" | "queued" | "preparing";++export const libraryUploadId = (objectId: string) => `library-upload-${objectId}`;diff --git a/site/src/cut/lib/libraryUploadResidency.test.ts b/site/src/cut/lib/libraryUploadResidency.test.tsnew file mode 100644index 00000000..ded47c22--- /dev/null+++ b/site/src/cut/lib/libraryUploadResidency.test.ts@@ -0,0 +1,89 @@+import { afterEach, describe, expect, spyOn, test } from "bun:test";+import * as residency from "./residency";+import * as media from "./media";+import * as preparation from "./cloudLibraryUpload";+import { uploadToLibrary, type LibraryAsset } from "./library";+import type { CutBackend } from "./backend";++const restores: (() => void)[] = [];+afterEach(() => { for (const restore of restores.splice(0)) restore(); });+const file = () => new File(["phone video"], "phone.mov", { type: "video/quicktime" });+const asset: LibraryAsset = { id: "asset", fileName: "phone.mp4", name: "phone.mov", type: "video", duration: 1, addedAt: 0, residency: "cloud" };+const meta = { type: "video" as const, duration: 1, width: 64, height: 64 };+function backend(kind: CutBackend["kind"], respond = () => Response.json(asset)) {+ const fetches: { path: string; init?: RequestInit }[] = [];+ const driver = { kind, fetch: async (path: string, init?: RequestInit) => {+ fetches.push({ path, init });+ return respond();+ } } as CutBackend;+ const seam = spyOn(residency, "backendFor").mockReturnValue(driver);+ restores.push(() => seam.mockRestore());+ return fetches;+}++describe("library import residencies", () => {+ test("cloud hands unreadable footage to preparation", async () => {+ backend("cloud");+ const probe = spyOn(media, "probeFileMeta").mockImplementation(async () => { throw new Error("Decoder unavailable"); });+ const prepare = spyOn(preparation, "uploadCloudLibraryMedia").mockResolvedValue(asset);+ restores.push(() => probe.mockRestore(), () => prepare.mockRestore());+ const source = file();+ expect(await uploadToLibrary(source, "cloud")).toEqual(asset);+ expect(prepare.mock.calls[0]?.[0]).toBe(source);+ });++ test("readable cloud media keeps the direct upload path", async () => {+ const fetches = backend("cloud");+ const probe = spyOn(media, "probeFileMeta").mockResolvedValue(meta);+ const upload = spyOn(media, "presignedUpload").mockResolvedValue("stored");+ const prepare = spyOn(preparation, "uploadCloudLibraryMedia");+ restores.push(() => probe.mockRestore(), () => upload.mockRestore(), () => prepare.mockRestore());+ await uploadToLibrary(file(), "cloud");+ expect(fetches[0]?.path).toBe("/api/cut/library/complete");+ expect(prepare).not.toHaveBeenCalled();+ });++ test("browser-local footage uses prepared bytes and lands in browser storage", async () => {+ const fetches = backend("browser");+ const probe = spyOn(media, "probeFileMeta").mockImplementation(async (source) => {+ if (source.name === "phone.mov") throw new Error("Decoder unavailable");+ return meta;+ });+ const prepared = new File(["playable"], "phone.mp4", { type: "video/mp4" });+ const prepare = spyOn(preparation, "withCloudPreparedMedia").mockImplementation(async (_file, adopt) => adopt(prepared));+ restores.push(() => probe.mockRestore(), () => prepare.mockRestore());+ expect((await uploadToLibrary(file(), "browser")).residency).toBe("browser");+ const form = fetches[0]?.init?.body as FormData;+ expect((form.get("file") as File).name).toBe("phone.mp4");+ expect(form.get("name")).toBe("phone.mov");+ expect(prepare.mock.calls.length).toBe(1);+ });++ test("engine storage receives the original and a preparation request", async () => {+ const fetches = backend("local");+ const probe = spyOn(media, "probeFileMeta").mockImplementation(async () => { throw new Error("Decoder unavailable"); });+ restores.push(() => probe.mockRestore());+ expect((await uploadToLibrary(file(), "local")).residency).toBe("local");+ const form = fetches[0]?.init?.body as FormData;+ expect((form.get("file") as File).name).toBe("phone.mov");+ expect(form.get("prepare")).toBe("true");+ });++ test("engine preparation failure borrows the worker and keeps the chosen storage", async () => {+ let calls = 0;+ const fetches = backend("local", () => ++calls === 1+ ? Response.json({ error: "Decoder unavailable" }, { status: 500 }) : Response.json(asset));+ const probe = spyOn(media, "probeFileMeta").mockImplementation(async (source) => {+ if (source.name === "phone.mov") throw new Error("Decoder unavailable");+ return meta;+ });+ const prepared = new File(["playable"], "phone.mp4", { type: "video/mp4" });+ const prepare = spyOn(preparation, "withCloudPreparedMedia").mockImplementation(async (_file, adopt) => adopt(prepared));+ restores.push(() => probe.mockRestore(), () => prepare.mockRestore());+ expect((await uploadToLibrary(file(), "local")).residency).toBe("local");+ expect(prepare.mock.calls.length).toBe(1);+ const form = fetches[1]?.init?.body as FormData;+ expect((form.get("file") as File).name).toBe("phone.mp4");+ expect(form.get("prepare")).toBeNull();+ });+});diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex d9d15432..70c154a5 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -735,6 +735,7 @@ export async function importFileToProject(if (!type) return null;let fileName = await uploadProjectMediaTo(backend, projectId, file, file.name);+ const originalFileName = fileName;let name = file.name;// Probe the bytes in hand: the same file the upload just wrote, with no// second network read — which also lets a headless process import media.@@ -751,7 +752,7 @@ export async function importFileToProject(void dropProjectFile(projectId, fileName, backend).catch(() => {});throw convertError;});- void dropProjectFile(projectId, fileName, backend).catch(() => {});+ if (made.fileName !== fileName) void dropProjectFile(projectId, fileName, backend).catch(() => {});fileName = made.fileName;// The asset answers to what it now is: a card reading .MOV over an MP4// file is the card lying about the media.@@ -760,7 +761,7 @@ export async function importFileToProject(});const url = mediaUrl(projectId, fileName, backend);const id = uid();- keepImportedBytes(id, file);+ if (fileName === originalFileName) keepImportedBytes(id, file);return {id,fileName,diff --git a/site/src/cut/lib/mediaConvert.ts b/site/src/cut/lib/mediaConvert.tsindex 461ba880..f4a4296c 100644--- a/site/src/cut/lib/mediaConvert.ts+++ b/site/src/cut/lib/mediaConvert.ts@@ -1,36 +1,8 @@"use client";-/**- * Converting a project's media to MP4 — H.264 picture, AAC sound — in place.- *- * Footage arrives in whatever the camera wrote. A phone's .mov is HEVC, a- * screen recorder's is ProRes with raw PCM sound, and neither decodes in- * every browser: the clip previews black, or refuses to import at all.- * Converting it is the repair, and it is the same repair someone means when- * they say "turn these .mov files into mp4".- *- * Where a conversion runs is decided by where the bytes already are, because- * moving a video file costs more than converting one:- *- * Mac project the engine's ffmpeg, on the file in the project folder.- * cloud project a render-worker job, on the object in R2. The tab sends- * nothing and waits on the job row it polls.- * browser project this tab, where mediabunny drives WebCodecs — and where- * a file whose streams already fit is copied packet for- * packet, with no decoding at all. Footage this browser- * has no decoder for goes to the Mac when the app is- * running: the page posts the bytes to the engine and gets- * an MP4 back, the trade transcription already makes.- * headless a process with no page converts for itself. The engine- * installs a converter that works the project folder- * directly; the cloud runner carries decoders of its own- * and runs the same in-process path a tab runs.- *- * The asset keeps its id and its name, so every clip cut from it keeps- * playing; only the file underneath changes. The old file is deleted once the- * new one is in the document — a conversion that left both behind would- * double what the project costs against the user's storage.- */+/** Conversion uses the project's backend and keeps each asset's identity.+ * Browser projects borrow preparation when a decoder or encoder is unavailable;+ * the prepared media returns to the project's own storage. */import {BufferTarget,@@ -40,6 +12,7 @@ import {type ConversionAudioOptions,type ConversionVideoOptions,} from "mediabunny";+import { withCloudPreparedMedia } from "@/cut/lib/cloudLibraryUpload";import { apiFetch as engineFetch } from "./api";import { getBackend, hasLocalCompute, type CutBackend } from "./backend";import { resolveRegisteredBlob } from "./backend/browser/registry";@@ -48,12 +21,11 @@ import { enrichAsset, uploadProjectMediaTo } from "./media";import { storedMediaUrl } from "./mediaSync";import {audioTrackOf,- hasUndecodableVideo,openMedia,probeMediaFile,readMediaFileSize,videoTrackOf,- withMedia,+ UnreadableMediaError,} from "./mediaRead";import { useEditor } from "./store";import type { MediaAsset } from "./types";@@ -260,24 +232,38 @@ async function convertOnBackend(return fromServer(body);}-/** No machine stores this project, so the work happens beside the bytes: in- * this process, or on the Mac when this process has no decoder for them. */+/** Convert beside the project, borrowing hosted preparation for missing codecs. */async function convertNearThePage(projectId: string,source: ConvertSource,opts: ConvertOptions): Promise<FileConversion> {- const decodable = await withMedia(- source.url,- async (input) => !(await hasUndecodableVideo(input))- );- if (decodable) return convertInProcess(projectId, source, opts);- if (hasLocalCompute()) return convertOnTheMac(projectId, source, opts);- throw new Error(- `${source.name} is in a format this browser can't decode. Run the Donkey app to convert it on this Mac, open the project in Safari, or move it to the cloud.`+ const decodable = await probeMediaFile(source.url).then(() => true, (error: unknown) => {+ if (error instanceof UnreadableMediaError && error.undecodable) return false;+ throw error;+ });+ if (decodable) {+ try { return await convertInProcess(projectId, source, opts); }+ catch (error) { if (!(error instanceof ConversionUnavailableError)) throw error; }+ }+ if (hasLocalCompute()) {+ try { return await convertOnTheMac(projectId, source, opts); }+ catch { /* The browser still needs a decoder; hosted preparation supplies it. */ }+ }+ const response = resolveRegisteredBlob(source.url) ?? await fetch(source.url).then((res) => {+ if (!res.ok) throw new Error(`Could not read ${source.name}.`);+ return res.blob();+ });+ if (!response) throw new Error(`Could not read ${source.name}.`);+ return withCloudPreparedMedia(+ new File([response], source.fileName, { type: response.type }),+ (prepared) => land(projectId, source, prepared, opts),+ { name: source.name, maxHeight: opts.maxHeight },);}+class ConversionUnavailableError extends Error {}+/*** Convert in this process with mediabunny: WebCodecs in a tab, the headless* runtime's decoders in a worker. Source packets that already fit the@@ -291,7 +277,7 @@ async function convertInProcess(): Promise<FileConversion> {const bytes = resolveRegisteredBlob(source.url);if (bytes && bytes.size > IN_PROCESS_MAX_BYTES) {- throw new Error(`${source.name} is too large to convert here.`);+ throw new ConversionUnavailableError(`${source.name} needs hosted conversion.`);}const input = openMedia(source.url);try {@@ -332,17 +318,14 @@ async function convertInProcess(const conversion = await Conversion.init({input,output,- video: videoOptions,- audio: audioOptions,+ video: (track) => track === video ? videoOptions : { discard: true },+ audio: (track) => track === audio ? audioOptions : { discard: true },});- if (!conversion.isValid) {- const reason = conversion.discardedTracks[0]?.reason;- throw new Error(- reason === "undecodable_source_codec" || reason === "no_encodable_target_codec"- ? `${source.name} is in a format this browser can't convert. Run the Donkey app to convert it on this Mac, open the project in Safari, or move it to the cloud.`- : `Could not convert ${source.name}.`- );- }+ if (conversion.discardedTracks.some(({ track, reason }) =>+ (track === video || track === audio) &&+ (reason === "undecodable_source_codec" || reason === "no_encodable_target_codec")+ )) throw new ConversionUnavailableError("This media needs hosted conversion.");+ if (!conversion.isValid) throw new Error(`Could not convert ${source.name}.`);await conversion.execute();const buffer = output.target.buffer;if (!buffer) throw new Error(`Could not convert ${source.name}.`);diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex d5a65c4b..a591318c 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -542,7 +542,7 @@ Project media (\`media\` in editor_state) is every file in the open project. The- file_asset moves a created asset into Media (to:"media", clears its origin) or copies any asset into the Library (to:"library").- media_organize keeps the Media panel's own folders (\`mediaFolders\` in editor_state, per project): create/rename/delete a folder (a delete removes every file in it, timeline clips and all), move_asset to file media into one — filing a created asset also moves it into Media, like dropping its card on a folder tile.- delete_asset removes an asset from the project plus its timeline clips; the media does not come back with undo, so only on an explicit ask, and say what went with it.-- convert_media rewrites project media as MP4 (H.264/AAC) in place, one call for a whole list of asset ids. Reach for it when footage plays black or shows a format warning — phone HEVC, ProRes, raw PCM sound — and whenever someone asks for mp4 files. That ask is usually files dropped straight on this chat: convert them and each one is on its own card in the thread, converted, ready to download or drag onto the timeline — close by saying they're on their cards. An asset that came from the Media panel stays there. Streams that already fit are copied, so most .mov files convert in seconds, and a file that is already H.264/AAC MP4 comes back untouched (say so instead of claiming a conversion); max_height shrinks an oversized source at the same time. Clips already cut from the asset keep playing. It runs on whichever machine already holds the bytes — this Mac, the render worker, or the tab — and works with no editor tab attached; when nothing available can decode the source the error names the fix (the Mac app, another browser, or moving the project to the cloud), so report it and move on.+- convert_media rewrites project media as MP4 (H.264/AAC) in place, one call for a whole list of asset ids. Reach for it when footage plays black or shows a format warning — phone HEVC, ProRes, raw PCM sound — and whenever someone asks for mp4 files. That ask is usually files dropped straight on this chat: convert them and each one is on its own card in the thread, converted, ready to download or drag onto the timeline — close by saying they're on their cards. An asset that came from the Media panel stays there. Streams that already fit are copied, so most .mov files convert in seconds, and a file that is already H.264/AAC MP4 comes back untouched (say so instead of claiming a conversion); max_height shrinks an oversized source at the same time. Clips already cut from the asset keep playing. Conversion runs through the project backend, including headless tools. A browser missing a required codec uses hosted preparation and saves the result back into its own project.Preview selection is shared with the timeline. Use select with additive:true to toggle multiple items, then move_selection with dx/dy frame fractions to move them together. Caption positions apply to their whole track.The Library is shared across every project: folders, reusable assets, and templates — a template is a saved arrangement (clips, overlays, titles, captions, by reference) that comes back editable.diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.tsindex ec8d0baa..6ba3d1c5 100644--- a/site/src/cut/server/cloud/gc.ts+++ b/site/src/cut/server/cloud/gc.ts@@ -284,9 +284,18 @@ export async function runGc(): Promise<Response> {});}+ const preparing = await prisma.cutRenderJob.findMany({+ where: { kind: "convert", state: { in: ["queued", "running"] }, spec: { path: ["target"], equals: "library" } },+ select: { spec: true },+ });+ const heldUploads = preparing.flatMap((job) => {+ const key = (job.spec as { key?: unknown } | null)?.key;+ return typeof key === "string" ? [key] : [];+ });const pending = await prisma.cutMediaObject.findMany({where: {uploadState: "pending",+ r2Key: { notIn: heldUploads },createdAt: { lt: new Date(Date.now() - PENDING_CLAIM_MAX_AGE_MS) },},select: { id: true, r2Key: true },diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex ce7ea3d4..9adc60ad 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -30,6 +30,7 @@ const PRESIGN_GET_BATCH_MAX = 500;* the source project doc. */interface AssetMeta {name?: string;+ originalFile?: string;/** The short name the titling model read off the clip itself, standing in* for the file's own name wherever the asset is shown. Written once, by* cloud/clipTitle.ts. */@@ -92,6 +93,7 @@ export function assetView(return {id: row.id,fileName: obj.fileName,+ ...(meta.originalFile ? { originalFile: meta.originalFile } : {}),name: meta.name ?? obj.fileName,type: meta.type ?? typeOf(obj.fileName) ?? "video",duration: meta.duration ?? 0,@@ -218,7 +220,11 @@ export async function deleteLibraryAssetCascade(where: { userId, kind: "library", fileName: posterName },}): null;- const objects = [obj, poster].filter((o): o is NonNullable<typeof o> => !!o);+ const originalName = ((asset.meta ?? {}) as AssetMeta).originalFile;+ const original = originalName+ ? await prisma.cutMediaObject.findFirst({ where: { userId, kind: "library", fileName: originalName } })+ : null;+ const objects = [obj, poster, original].filter((o): o is NonNullable<typeof o> => !!o);const freed = objects.filter((o) => o.uploadState === "complete").reduce((n, o) => n + Number(o.bytes), 0);diff --git a/site/src/cut/server/cloud/libraryUpload.test.ts b/site/src/cut/server/cloud/libraryUpload.test.tsnew file mode 100644index 00000000..acd1ab56--- /dev/null+++ b/site/src/cut/server/cloud/libraryUpload.test.ts@@ -0,0 +1,72 @@+import { expect, mock, test } from "bun:test";+import { prisma } from "@/lib/prisma";+import { createLibraryUploadPreparation } from "./libraryUpload";++function harness() {+ const object = { id: "object", userId: "owner", fileName: "phone.mov", bytes: BigInt(10), r2Key: "cut/owner/library/phone.mov", kind: "library", projectId: null, mime: "video/quicktime", uploadState: "pending", quotaExempt: false, createdAt: new Date(), updatedAt: new Date() };+ const source = mock(async (args: unknown) => { void args; return object as typeof object | null; });+ const asset = mock(async () => null);+ const folder = mock(async () => null);+ const existing = mock(async () => null as { id: string; state: string } | null);+ const create = mock(async (args: unknown) => { void args; return { id: "library-upload-object" }; });+ const reset = mock(async (args: unknown) => { void args; return { count: 1 }; });+ const head = mock(async () => ({ bytes: 10, mime: "video/quicktime", etag: "tag" }));+ const gate = mock(async () => null);+ const start = mock(() => {});+ const db = {+ cutMediaObject: { findFirst: source }, cutLibraryAsset: { findFirst: asset },+ cutFolder: { findFirst: folder }, cutRenderJob: { findFirst: existing, upsert: create, updateMany: reset },+ } as unknown as typeof prisma;+ const prepare = createLibraryUploadPreparation({ db, inspect: head, checkLimit: gate, wake: start });+ return { prepare, object, source, asset, folder, existing, create, reset, head, gate, start };+}+const req = (data: unknown = { key: "cut/owner/library/phone.mov", name: "phone.mov" }) => new Request("https://donkeycut.com/api/cut-cloud/library/prepare", { method: "POST", body: JSON.stringify(data) });++test("preparation verifies upload ownership before touching storage", async () => {+ const h = harness();+ h.source.mockResolvedValue(null);+ expect((await h.prepare("stranger", req())).status).toBe(404);+ expect(h.source.mock.calls[0]?.[0]).toMatchObject({ where: { userId: "stranger", kind: "library", projectId: null } });+ expect(h.head).not.toHaveBeenCalled();+ expect(h.create).not.toHaveBeenCalled();+});++test("preparation refuses invalid bodies, foreign folders and incomplete uploads", async () => {+ const h = harness();+ expect((await h.prepare("owner", req({ key: 3 }))).status).toBe(400);+ expect((await h.prepare("owner", req({ key: h.object.r2Key, name: "phone.mov", folderId: "foreign" }))).status).toBe(404);+ h.head.mockResolvedValue({ bytes: 9, mime: "video/quicktime", etag: "tag" });+ expect((await h.prepare("owner", req())).status).toBe(400);+ expect(h.create).not.toHaveBeenCalled();+});++test("preparation queues one deterministic conversion for the stored original", async () => {+ const h = harness();+ expect(await (await h.prepare("owner", req())).json()).toEqual({ jobId: "library-upload-object" });+ expect(h.create.mock.calls[0]?.[0]).toMatchObject({ where: { id: "library-upload-object" }, create: { userId: "owner", kind: "convert", spec: { target: "library", key: h.object.r2Key } } });+ expect(h.start.mock.calls.length).toBe(1);+});++test("preparation cannot take ownership of an existing Library asset's file", async () => {+ const h = harness();+ h.object.uploadState = "complete";+ expect((await h.prepare("owner", req())).status).toBe(409);+ expect(h.create).not.toHaveBeenCalled();+ expect(h.head).not.toHaveBeenCalled();+});++test("retrying active work returns the same job without a new upload or quota charge", async () => {+ const h = harness();+ h.existing.mockResolvedValue({ id: "library-upload-object", state: "running" } as never);+ expect(await (await h.prepare("owner", req())).json()).toEqual({ jobId: "library-upload-object" });+ expect(h.create).not.toHaveBeenCalled();+ expect(h.gate).not.toHaveBeenCalled();+ expect(h.head).not.toHaveBeenCalled();+});++test("worker failure can be retried under the same job id", async () => {+ const h = harness();+ h.existing.mockResolvedValue({ id: "library-upload-object", state: "error" } as never);+ expect((await h.prepare("owner", req())).status).toBe(200);+ expect(h.reset.mock.calls[0]?.[0]).toMatchObject({ where: { id: "library-upload-object", userId: "owner" }, data: { state: "queued", error: null } });+});diff --git a/site/src/cut/server/cloud/libraryUpload.ts b/site/src/cut/server/cloud/libraryUpload.tsnew file mode 100644index 00000000..7920489c--- /dev/null+++ b/site/src/cut/server/cloud/libraryUpload.ts@@ -0,0 +1,67 @@+import { libraryUploadId, libraryUploadSchema } from "@/cut/lib/libraryUpload";+import { typeOf as libraryTypeOf } from "./util";+import { assetView } from "@/cut/server/cloud/library";+import { renderJobCheck } from "@/cut/server/cloud/limits";+import { head } from "@/cut/server/cloud/r2";+import { err } from "@/cut/server/cloud/util";+import { wakeRenderWorker } from "@/cut/server/cloud/wake";+import { prisma } from "@/lib/prisma";++export function createLibraryUploadPreparation({+ db = prisma, inspect = head, checkLimit = renderJobCheck, wake = wakeRenderWorker,+}: {+ db?: Pick<typeof prisma, "cutMediaObject" | "cutLibraryAsset" | "cutFolder" | "cutRenderJob">;+ inspect?: typeof head;+ checkLimit?: typeof renderJobCheck;+ wake?: typeof wakeRenderWorker;+} = {}) {+ /** Queue preparation after the original's direct upload has arrived. */+ return async function prepareLibraryUpload(userId: string, req: Request): Promise<Response> {+ const parsed = libraryUploadSchema.safeParse(await req.json().catch(() => null));+ if (!parsed.success) return err("Invalid library upload.", 400);+ const input = parsed.data;+ const object = await db.cutMediaObject.findFirst({+ where: { userId, r2Key: input.key, kind: "library", projectId: null },+ });+ if (!object) return err("Unknown upload.", 404);+ const type = libraryTypeOf(object.fileName);+ if (type !== "video" && type !== "audio") return err("This upload has no video or audio.", 400);+ if (input.folderId && !(await db.cutFolder.findFirst({+ where: { id: input.folderId, userId, scope: "library" }, select: { id: true },+ }))) return err("Folder not found.", 404);++ const id = libraryUploadId(object.id);+ const asset = await db.cutLibraryAsset.findFirst({ where: { id, userId, deletedAt: null } });+ if (asset) {+ const media = await db.cutMediaObject.findFirst({ where: { id: asset.mediaObjectId, userId } });+ if (media) return Response.json(assetView(asset, media));+ }+ if (object.uploadState !== "pending") return err("This file is already in the Library.", 409);+ const existing = await db.cutRenderJob.findFirst({ where: { id, userId } });+ if (existing && (existing.state === "queued" || existing.state === "running")) {+ wake();+ return Response.json({ jobId: id });+ }+ const info = await inspect(input.key);+ if (!info || info.bytes !== Number(object.bytes)) return err("The upload is incomplete. Select the file again.", 400);+ const capped = await checkLimit(userId);+ if (capped) return capped;+ const spec = { ...input, target: "library", objectId: object.id };+ await db.cutRenderJob.upsert({+ where: { id },+ create: { id, userId, kind: "convert", spec },+ update: {},+ });+ if (existing) {+ await db.cutRenderJob.updateMany({+ where: { id, userId, state: { in: ["error", "canceled", "dismissed", "done"] } },+ data: { state: "queued", progress: 0, error: null, claimedAt: null, spec },+ });+ }+ wake();+ return Response.json({ jobId: id });+ }++}++export const prepareLibraryUpload = createLibraryUploadPreparation();diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 0e23b09b..bd799acd 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -1,3 +1,4 @@+import { prepareLibraryUpload } from "@/cut/server/cloud/libraryUpload";import { librarySharing } from "@/cut/server/cloud/librarySharing";// The hosted Cut API surface in one table, namespaced under /api/cut-cloud/*.// The client's cloud driver rewrites /api/cut/X -> /api/cut-cloud/X, so paths@@ -77,6 +78,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "DELETE", path: "/api/cut-cloud/library/shares/:kind/:id", handler: (r, u, p) => librarySharing.manage(r, u, p.kind, p.id) },{ method: "GET", path: "/api/cut-cloud/library", handler: (r, u) => libraryCloud.list(u, r) },{ method: "POST", path: "/api/cut-cloud/library/presign", handler: (r, u) => libraryCloud.presign(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/prepare", handler: (r, u) => prepareLibraryUpload(u, r) },{ method: "POST", path: "/api/cut-cloud/library/complete", handler: (r, u) => libraryCloud.complete(u, r) },{ method: "POST", path: "/api/cut-cloud/library/presign-get", handler: (r, u) => libraryCloud.presignGetBatch(u, r) },{ method: "POST", path: "/api/cut-cloud/library/use", handler: (r, u) => libraryCloud.use(u, r) },diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex 20c177aa..8346ef9e 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -187,6 +187,7 @@ export const libraryApi = {typeof name === "string" ? name : undefined,source,poster instanceof File ? poster : undefined,+ form.get("prepare") === "true",),);} catch (e) {diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex f42f72c5..c171131c 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -1,3 +1,4 @@+import { convertToMp4, mp4NameFor, streamCodecs } from "@/cut/server/convert";import { spawn } from "node:child_process";import { copyFile, constants, mkdir, readFile, rm, writeFile } from "node:fs/promises";import path from "node:path";@@ -26,6 +27,8 @@ export interface LibrarySource {export interface LibraryAsset {id: string;fileName: string;+ /** Uploaded source retained when playback needs conversion. */+ originalFile?: string;name: string;type: "video" | "audio" | "image" | "font";duration: number;@@ -270,6 +273,7 @@ export async function register(name: string,source?: LibrarySource,posterFile?: string,+ originalFile?: string,): Promise<LibraryAsset> {const type = typeOf(fileName);if (!type) throw new Error("Unsupported file type.");@@ -278,6 +282,7 @@ export async function register(const asset: LibraryAsset = {id: crypto.randomUUID().slice(0, 8),fileName,+ ...(originalFile ? { originalFile } : {}),name,type,duration: meta.duration,@@ -299,6 +304,7 @@ export async function addUpload(name?: string,source?: LibrarySource,poster?: File,+ prepare = false,): Promise<LibraryAsset> {if (!typeOf(file.name)) throw new Error("Unsupported file type.");await mkdir(libMedia(), { recursive: true });@@ -318,7 +324,22 @@ export async function addUpload(Buffer.from(await poster.arrayBuffer()),);}- return register(fileName, name?.trim() || file.name, source, posterFile);+ let playback = fileName;+ try {+ if (prepare) {+ const codecs = await streamCodecs(libMediaPath(fileName));+ const convertedName = mp4NameFor(fileName);+ playback = await freeName(codecs.video ? convertedName : convertedName.replace(/\.mp4$/, ".m4a"));+ const handle = { tmpDir: "", outPath: libMediaPath(playback), progress: 0, log: [] as string[] };+ const outcome = await convertToMp4(handle, libMediaPath(fileName), libMediaPath(playback));+ if (outcome.unchanged) playback = fileName;+ }+ return await register(playback, name?.trim() || file.name, source, posterFile,+ playback === fileName ? undefined : fileName);+ } catch (error) {+ await removeFiles([...new Set([fileName, playback, ...(posterFile ? [posterFile] : [])])]);+ throw error;+ }}/** Copy a project's media file into the library for reuse. */@@ -387,6 +408,7 @@ function takeAssets(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {if (!ids.has(a.id)) return true;files.push(a.fileName);if (a.posterFile) files.push(a.posterFile);+ if (a.originalFile) files.push(a.originalFile);return false;});return files;diff --git a/site/src/cut/worker/convertJob.ts b/site/src/cut/worker/convertJob.tsindex 6a3e11b9..9d10c58a 100644--- a/site/src/cut/worker/convertJob.ts+++ b/site/src/cut/worker/convertJob.ts@@ -1,3 +1,5 @@+import { runLibraryUploadJob } from "@/cut/worker/libraryUploadJob";+import type { LibraryAsset } from "@/cut/server/library";import { mkdtemp, rm } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -32,7 +34,10 @@ export async function runConvertJob(job: ClaimedJob,handle: RenderHandle,isCanceled: () => boolean-): Promise<ConvertResult> {+): Promise<ConvertResult | LibraryAsset> {+ if ((job.spec as { target?: string } | null)?.target === "library") {+ return runLibraryUploadJob(job, handle, isCanceled);+ }const { file, maxHeight } = (job.spec ?? {}) as { file?: string; maxHeight?: number };if (!file) throw new Error("Convert job has no file.");const projectId = job.projectId;diff --git a/site/src/cut/worker/db.ts b/site/src/cut/worker/db.tsindex bd8cb2a7..0c05f277 100644--- a/site/src/cut/worker/db.ts+++ b/site/src/cut/worker/db.ts@@ -9,7 +9,7 @@ import { resolveSettings } from "@/lib/config/resolve";export { prisma };/** A conflict rolls back every write; retry with a fresh transaction snapshot. */-async function storageTransaction<T>(run: (tx: Prisma.TransactionClient) => Promise<T>): Promise<T> {+export async function storageTransaction<T>(run: (tx: Prisma.TransactionClient) => Promise<T>): Promise<T> {const override = await prisma.settingOverride.findUnique({where: { key: "cutStorageTransactions" }, select: { value: true },});@@ -88,7 +88,7 @@ export async function claimNextJob(): Promise<ClaimedJob | null> {* preview re-render, a retried job) charge only the size delta instead of* double-counting.*/-export async function registerObject(opts: {+type ObjectRegistration = {userId: string;/** Null for objects no project owns — the account's shared library. */projectId: string | null;@@ -97,36 +97,41 @@ export async function registerObject(opts: {mime: string;bytes: number;kind: string;-}): Promise<string> {- return storageTransaction(async (tx) => {- const prior = await tx.cutMediaObject.findUnique({- where: { r2Key: opts.r2Key },- select: { bytes: true, uploadState: true, quotaExempt: true },- });- const quotaExempt = artifactLifecycle(opts.kind) !== "retained";- const priorBytes = prior ? artifactUsageBytes(prior.bytes, prior.uploadState === "complete", prior.quotaExempt) : BigInt(0);- const delta = artifactUsageBytes(BigInt(opts.bytes), true, quotaExempt) - priorBytes;- // The wall every stored artifact meets, wherever it came from: a job that- // grew past what its account can hold is failed here, at the moment the- // bytes would be charged, instead of landing a row nothing can undo.- if (delta > BigInt(0)) {- const ceiling = storageCeiling(await cutLimitsFor(opts.userId), quotaMarginFor(opts.kind));- if (ceiling !== null) {- const usage = await tx.cutStorageUsage.findUnique({- where: { userId: opts.userId },- select: { bytes: true },- });- if ((usage?.bytes ?? BigInt(0)) + delta > BigInt(ceiling)) throw new Error(STORAGE_FULL);- }+};++export async function registerObject(opts: ObjectRegistration): Promise<string> {+ return storageTransaction((tx) => registerObjectIn(tx, opts));+}++/** Register related files inside the transaction that publishes their asset. */+export async function registerObjectIn(tx: Prisma.TransactionClient, opts: ObjectRegistration): Promise<string> {+ const prior = await tx.cutMediaObject.findUnique({+ where: { r2Key: opts.r2Key },+ select: { bytes: true, uploadState: true, quotaExempt: true },+ });+ const quotaExempt = artifactLifecycle(opts.kind) !== "retained";+ const priorBytes = prior ? artifactUsageBytes(prior.bytes, prior.uploadState === "complete", prior.quotaExempt) : BigInt(0);+ const delta = artifactUsageBytes(BigInt(opts.bytes), true, quotaExempt) - priorBytes;+ // The wall every stored artifact meets, wherever it came from: a job that+ // grew past what its account can hold is failed here, at the moment the+ // bytes would be charged, instead of landing a row nothing can undo.+ if (delta > BigInt(0)) {+ const ceiling = storageCeiling(await cutLimitsFor(opts.userId), quotaMarginFor(opts.kind));+ if (ceiling !== null) {+ const usage = await tx.cutStorageUsage.findUnique({+ where: { userId: opts.userId },+ select: { bytes: true },+ });+ if ((usage?.bytes ?? BigInt(0)) + delta > BigInt(ceiling)) throw new Error(STORAGE_FULL);}- const row = await tx.cutMediaObject.upsert({- where: { r2Key: opts.r2Key },- create: { ...opts, bytes: BigInt(opts.bytes), quotaExempt, uploadState: "complete" },- update: { bytes: BigInt(opts.bytes), uploadState: "complete", quotaExempt },- });- if (delta !== BigInt(0)) await adjustStorageBytes(tx, opts.userId, delta);- return row.id;+ }+ const row = await tx.cutMediaObject.upsert({+ where: { r2Key: opts.r2Key },+ create: { ...opts, bytes: BigInt(opts.bytes), quotaExempt, uploadState: "complete" },+ update: { bytes: BigInt(opts.bytes), uploadState: "complete", quotaExempt },});+ if (delta !== BigInt(0)) await adjustStorageBytes(tx, opts.userId, delta);+ return row.id;}/**diff --git a/site/src/cut/worker/libraryUploadJob.test.ts b/site/src/cut/worker/libraryUploadJob.test.tsnew file mode 100644index 00000000..16de38ef--- /dev/null+++ b/site/src/cut/worker/libraryUploadJob.test.ts@@ -0,0 +1,89 @@+import { describe, expect, mock, test } from "bun:test";+import { writeFile } from "node:fs/promises";+import type { Prisma } from "@/generated/prisma/client";+import { prisma } from "@/lib/prisma";+import { runLibraryUploadJob } from "./libraryUploadJob";+import type { LibraryAsset } from "@/cut/server/library";++function harness() {+ const source = { id: "original", fileName: "phone.mov", userId: "owner", r2Key: "cut/owner/library/phone.mov", bytes: BigInt(8), mime: "video/quicktime" };+ const sourceRead = mock(async (args: unknown) => { void args; return source; });+ const prior = mock(async () => null as null | { id: string; userId: string; mediaObjectId: string; deletedAt: Date | null; folderId: null; meta: unknown; createdAt: Date });+ const create = mock(async ({ data }: { data: Record<string, unknown> }) => ({ ...data, createdAt: new Date() }));+ const db = { cutMediaObject: { findFirst: sourceRead }, cutLibraryAsset: { findFirst: prior } } as unknown as typeof prisma;+ const tx = {+ cutRenderJob: { findFirst: mock(async () => ({ state: "running" })) },+ cutFolder: { findFirst: mock(async () => ({ id: "folder" })) },+ cutLibraryAsset: { create },+ };+ const register = mock(async (_tx: Prisma.TransactionClient, object: { fileName: string }) => object.fileName);+ const io = {+ db,+ download: mock(async (_key: string, file: string) => { await writeFile(file, "original"); }),+ upload: mock(async (_key: string, _file: string, _mime: string) => { void _file; void _mime; return 5; }),+ remove: mock(async (_keys: string[]) => { void _keys; }),+ convert: mock(async () => ({ transcodedVideo: true, transcodedAudio: false, width: 64, height: 64, unchanged: false })),+ codecs: mock(async () => ({ video: "hevc", audio: "aac", videoIndex: 0, audioIndex: 1, remux: false, videoNeedsEncoding: true })),+ duration: mock(async () => 2),+ transact: async <T>(run: (tx: Prisma.TransactionClient) => Promise<T>) => run(tx as unknown as Prisma.TransactionClient),+ register,+ };+ const job = { id: "library-upload-original", userId: "owner", projectId: null, kind: "convert", outName: null, spec: { target: "library", key: source.r2Key, name: "phone.mov", folderId: "folder" } };+ const handle = { tmpDir: "", outPath: "", progress: 0, log: [] as string[] };+ const run = (canceled = () => false) => runLibraryUploadJob(job, handle, canceled, io);+ return { run, job, source, sourceRead, prior, create, register, io, tx };+}++describe("library upload worker", () => {+ test("publishes prepared media and its retained original together in the chosen folder", async () => {+ const h = harness();+ const result = await h.run();+ expect(result).toMatchObject({ id: h.job.id, fileName: "original.mp4", originalFile: "phone.mov", type: "video", duration: 2, folderId: "folder" });+ expect(h.register.mock.calls.map((call) => call[1].fileName)).toEqual(["phone.mov", "original.mp4"]);+ expect(h.create.mock.calls[0]?.[0].data).toMatchObject({ mediaObjectId: "original.mp4", folderId: "folder" });+ expect(h.io.remove).not.toHaveBeenCalled();+ });++ test("a worker replay returns its published asset without converting or charging again", async () => {+ const h = harness();+ h.prior.mockResolvedValue({ id: h.job.id, userId: "owner", mediaObjectId: "original", deletedAt: null, folderId: null, meta: { type: "video", duration: 2 }, createdAt: new Date() });+ const result: LibraryAsset = await h.run();+ expect(result.id).toBe(h.job.id);+ expect(h.io.download).not.toHaveBeenCalled();+ expect(h.register).not.toHaveBeenCalled();+ });++ test("unchanged media registers just its source", async () => {+ const h = harness();+ h.io.convert.mockResolvedValue({ unchanged: true, transcodedVideo: false, transcodedAudio: false, width: 64, height: 64 });+ expect(await h.run()).toMatchObject({ fileName: "phone.mov" });+ expect(h.register.mock.calls.length).toBe(1);+ expect(h.io.upload).not.toHaveBeenCalled();+ });++ test("conversion failure retains the original upload and publishes nothing", async () => {+ const h = harness();+ h.io.convert.mockImplementation(async () => { throw new Error("Codec unavailable"); });+ await expect(h.run()).rejects.toThrow("Codec unavailable");+ expect(h.create).not.toHaveBeenCalled();+ expect(h.register).not.toHaveBeenCalled();+ expect(h.io.remove).not.toHaveBeenCalled();+ });++ test("quota refusal removes only the staged playback object", async () => {+ const h = harness();+ h.register.mockImplementation(async () => { throw new Error("storage_quota_exceeded"); });+ await expect(h.run()).rejects.toThrow("storage_quota_exceeded");+ expect(h.create).not.toHaveBeenCalled();+ expect(h.io.remove.mock.calls).toEqual([[["cut/owner/library/original.mp4"]]]);+ });++ test("cancellation after output upload prevents publication and removes that output", async () => {+ const h = harness();+ let canceled = false;+ h.io.upload.mockImplementation(async () => { canceled = true; return 5; });+ await expect(h.run(() => canceled)).rejects.toThrow("Import canceled");+ expect(h.create).not.toHaveBeenCalled();+ expect(h.io.remove.mock.calls.length).toBe(1);+ });+});diff --git a/site/src/cut/worker/libraryUploadJob.ts b/site/src/cut/worker/libraryUploadJob.tsnew file mode 100644index 00000000..c8d7cbbc--- /dev/null+++ b/site/src/cut/worker/libraryUploadJob.ts@@ -0,0 +1,106 @@+import { mkdtemp, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { libraryUploadId, libraryUploadSchema } from "@/cut/lib/libraryUpload";+import { convertToMp4, streamCodecs } from "@/cut/server/convert";+import type { RenderHandle } from "@/cut/server/exportPipeline";+import { probeDuration } from "@/cut/server/frames";+import { assetView } from "@/cut/server/cloud/library";+import type { LibraryAsset } from "@/cut/server/library";+import { prisma, registerObjectIn, storageTransaction, type ClaimedJob } from "@/cut/worker/db";+import { deleteObjects, downloadToFile, libraryKey, uploadFile } from "@/cut/worker/r2";++const dependencies = {+ db: prisma, download: downloadToFile, upload: uploadFile, remove: deleteObjects,+ convert: convertToMp4, codecs: streamCodecs, duration: probeDuration,+ transact: storageTransaction, register: registerObjectIn,+};++/** Prepare uploaded media on disk and publish one asset with its original. */+export async function runLibraryUploadJob(+ job: ClaimedJob,+ handle: RenderHandle,+ isCanceled: () => boolean,+ io = dependencies,+): Promise<LibraryAsset> {+ const input = libraryUploadSchema.parse(job.spec);+ const source = await io.db.cutMediaObject.findFirst({+ where: { userId: job.userId, r2Key: input.key, kind: "library", projectId: null },+ });+ if (!source || libraryUploadId(source.id) !== job.id) throw new Error("Upload not found.");+ const already = await io.db.cutLibraryAsset.findFirst({ where: { id: job.id, userId: job.userId } });+ if (already) {+ if (already.deletedAt) throw new Error("This imported file was deleted.");+ const media = await io.db.cutMediaObject.findFirst({ where: { id: already.mediaObjectId, userId: job.userId } });+ if (!media) throw new Error("Imported media is missing.");+ return assetView(already, media);+ }+ const checkCanceled = () => { if (isCanceled()) throw new Error("Import canceled."); };+ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-library-upload-"));+ handle.tmpDir = tmp;+ let stagedKey: string | undefined;+ let published = false;+ try {+ checkCanceled();+ const src = path.join(tmp, path.basename(source.fileName));+ await io.download(source.r2Key, src);+ checkCanceled();+ const bytes = (await stat(src)).size;+ if (bytes !== Number(source.bytes)) throw new Error("The uploaded file is incomplete.");+ const codecs = await io.codecs(src);+ const type = codecs.video ? "video" : "audio";+ const duration = await io.duration(src);+ if (!(duration > 0)) throw new Error("This file has no readable media duration.");+ const outputName = `${source.id}.${type === "video" ? "mp4" : "m4a"}`;+ const out = path.join(tmp, outputName);+ handle.outPath = out;+ const converted = await io.convert(handle, src, out, {+ maxHeight: input.maxHeight,+ onProgress: (seconds) => { handle.progress = Math.min(0.95, seconds / duration); },+ });+ checkCanceled();+ const fileName = converted.unchanged ? source.fileName : outputName;+ const mime = type === "video" ? "video/mp4" : "audio/mp4";+ let outputBytes = 0;+ if (!converted.unchanged) {+ stagedKey = libraryKey(job.userId, fileName);+ outputBytes = await io.upload(stagedKey, out, mime);+ }+ checkCanceled();+ const row = await io.transact(async (tx) => {+ checkCanceled();+ const active = await tx.cutRenderJob.findFirst({ where: { id: job.id, userId: job.userId, state: "running" } });+ if (!active) throw new Error("Import canceled.");+ if (input.folderId && !(await tx.cutFolder.findFirst({+ where: { id: input.folderId, userId: job.userId, scope: "library" },+ }))) throw new Error("The destination folder was deleted.");+ const sourceId = await io.register(tx, {+ userId: job.userId, projectId: null, r2Key: source.r2Key, fileName: source.fileName,+ mime: source.mime, bytes, kind: "library",+ });+ const mediaObjectId = stagedKey ? await io.register(tx, {+ userId: job.userId, projectId: null, r2Key: stagedKey, fileName,+ mime, bytes: outputBytes, kind: "library",+ }) : sourceId;+ return tx.cutLibraryAsset.create({+ data: {+ id: job.id, userId: job.userId, mediaObjectId, folderId: input.folderId ?? null,+ meta: {+ name: input.name, type, duration,+ ...(converted.width ? { width: converted.width, height: converted.height } : {}),+ ...(stagedKey ? { originalFile: source.fileName } : {}),+ ...(input.source ? { source: input.source } : {}),+ },+ },+ });+ });+ published = true;+ return assetView(row, { fileName });+ } finally {+ try {+ if (stagedKey && !published) await io.remove([stagedKey]);+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }+}