Open source CapCut alternative.
TypeScript
feat(site): Mac projects export in the tab [rebuild]
David Lec6eaea169c6c
diff --git a/docs/guides/cut/local-compute.md b/docs/guides/cut/local-compute.mdindex 26f2e14a..7604660c 100644--- a/docs/guides/cut/local-compute.md+++ b/docs/guides/cut/local-compute.md@@ -39,13 +39,13 @@ The assistant's background sweep over a source takes the same fork under one ext## Export-A cloud project exports in the browser, and so does a browser project — the tab is that project's whole machine. The rule above still holds: the finished file lands in the project's own storage and is registered there, R2 for a cloud project and the origin-private `exports/` folder for a browser one. What moved is who does the work, and the answer turned out to be the machine already in front of the user.+Every project exports in the browser: a cloud project, a browser project, and a project resident on this Mac. The rule above still holds: the finished file lands in the project's own storage and is registered there, R2 for a cloud project, the origin-private `exports/` folder for a browser one, and the project folder's `exports/` on the Mac, where the engine holds the job row while the tab draws and takes the file in when it is done. What moved is who does the work, and the answer turned out to be the machine already in front of the user: the export is the preview, drawn by the compositor and mixed by the graph the user was watching and listening to.That works because the editor composites the cut live to draw the preview. Rendering is the same drawing done on a clock the tab steps, so a browser and a container produce the same picture from the same document, and the browser needs nothing pulled out of storage that it is not already playing.-Two facts decide whether a tab can carry a render, both probed per export: origin-private scratch storage to stream the file to, and WebCodecs encoders for the codecs the user chose at the requested dimensions — the video one, and AAC when the cut has sound. The probe asks for exactly those codecs; nothing stands in for a missing one, because a file with a substitute codec inside is a file the user's player refuses. ProRes has no browser encoder, so a master always renders on the worker. A cut of any length renders in the tab, since the pipeline streams to disk and duration costs only time. A project that fails either probe, or fails mid-render, goes to the worker silently. For a cloud project the worker already holds the media. A browser project's media lives only in that tab, so it goes up with the job beside the overlay stills, the worker renders from those uploads, and the finished file comes back down into the project's own exports folder; the cloud keeps nothing afterwards. Whatever the user picked, something renders it — the only thing that stops a browser project's export is an account that cannot use the cloud, and the export says so.+Two facts decide whether a tab can carry a render, both probed per export: origin-private scratch storage to stream the file to, and WebCodecs encoders for the codecs the user chose at the requested dimensions — the video one, and AAC when the cut has sound. The probe asks for exactly those codecs; nothing stands in for a missing one, because a file with a substitute codec inside is a file the user's player refuses. ProRes has no browser encoder, so a master always renders on the worker. A cut of any length renders in the tab, since the pipeline streams to disk and duration costs only time. A project that fails either probe, or fails mid-render, goes silently to the machine behind it: the engine on this Mac renders a Mac project with its own ffmpeg, and the worker renders the rest. For a cloud project the worker already holds the media. A browser project's media lives only in that tab, so it goes up with the job beside the overlay stills, the worker renders from those uploads, and the finished file comes back down into the project's own exports folder; the cloud keeps nothing afterwards. Whatever the user picked, something renders it — the only thing that stops a browser project's export is an account that cannot use the cloud, and the export says so.-The worker also takes the renders the editor fires on its own — hover proxies, share cards, streaming ladders. Moving export to the Mac would be a third path and there is no longer much to win from it.+The worker and the engine also take the renders the editor fires on its own — hover proxies, share cards, streaming ladders — and the ProRes masters no browser can encode. Those are the renders nobody watched first, and ffmpeg's picture and sound are held to the browser's by measurement: the same numbers for framing, grades and fades, the browser's own makeup gain on a compressed clip, a mono source at full level.A client with no compositor at all asks by project id instead. The phone sends the project and a size; the worker opens the stored document into the editor store, runs the same payload builder the export dialog runs, paints the overlay stills straight into the render's own scratch dir, and encodes. This is the headless runtime doing what it was built for — canvas, decoders, fonts standing in for the page — so the phone's export is the editor's export, not an approximation of it.diff --git a/site/scripts/eval-cut-export.ts b/site/scripts/eval-cut-export.tsindex 05744e8b..4b0e93ec 100644--- a/site/scripts/eval-cut-export.ts+++ b/site/scripts/eval-cut-export.ts@@ -47,6 +47,10 @@ const arg = (name: string) => {const has = (name: string) => args.includes(name);const BASE = arg("--base") ?? "http://localhost:3000";const HERMETIC = has("--hermetic");+/** Export a Mac-resident project: the fixtures go into a project on the dev+ * server's engine mount, the page starts the export through the store the+ * way the dialog does, and the engine lands the file in the project folder. */+const ENGINE = has("--engine") && !HERMETIC;/** The dev-only account the API bypass authenticates as. */const DEV_USER = "donkey-dev-auth-bypass";/** The project id a hermetic run opens; its doc is answered in-context. */@@ -61,7 +65,8 @@ function run(cmd: string, cmdArgs: string[]): Promise<string> {const p = spawn(cmd, cmdArgs);let out = "";let err = "";- p.stdout.on("data", (d) => (out += d.toString()));+ // Bytes land as latin1 so a raw-video or PCM stream reads back intact.+ p.stdout.on("data", (d: Buffer) => (out += d.toString("latin1")));p.stderr.on("data", (d) => (err += d.toString()));p.on("error", reject);p.on("close", (code) => {@@ -258,10 +263,85 @@ async function probeInPage(page: Page): Promise<Record<string, unknown>> {});}+/** The fixture cut: every feature the renderer carries, over media named by+ * `url`. */+function fixtureDoc(url: (file: string) => string, clipS = CLIP_S) {+ const asset = (id: string, file: string, type: string, duration: number) => ({+ id,+ fileName: file,+ name: id,+ type,+ url: url(file),+ duration,+ ...(type === "video" ? { width: 1280, height: 720 } : {}),+ });+ const doc = {+ aspect: "16:9",+ background: "#102030",+ fadeIn: 0.3,+ fadeOut: 0.3,+ assets: [+ asset("v0", "clip-0.mp4", "video", clipS),+ asset("v1", "clip-1.mp4", "video", clipS),+ asset("m0", "music.m4a", "audio", 8),+ ],+ clips: [+ {+ id: "c0", assetId: "v0", track: 0, start: 0, in: 0, out: clipS,+ muted: false, volume: 0.8,+ fit: "fill", zoom: 1.4, panX: 0.3, panY: -0.2,+ speed: 1.25,+ transition: 0.5, transitionStyle: "crossfade",+ },+ {+ id: "c1", assetId: "v1", track: 0, start: clipS / 1.25, in: 0, out: clipS,+ muted: false,+ fit: "fit",+ grade: { brightness: 5, contrast: 8, saturation: -10, temperature: 12, hue: 10 },+ kf: [+ { t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 0, opacity: 1 },+ { t: 2, x: 0.6, y: 0.4, scale: 0.85, rotation: 12, opacity: 1 },+ ],+ },+ {+ id: "c2", assetId: "v0", track: 1, start: 1, in: 0, out: 1.5,+ muted: true,+ frame: { x: 0.55, y: 0.05, w: 0.4, h: 0.4 },+ fit: "fill", rotation: 5, opacity: 0.9,+ },+ ],+ audioClips: [+ {+ id: "a0", assetId: "m0", start: 0, in: 0, out: 5,+ volume: 0.5, fadeIn: 0.3, fadeOut: 0.5, lane: 0,+ },+ ],+ overlays: [+ {+ id: "t0", kind: "text", text: "Everything test",+ start: 0.5, end: 3, x: 0.5, y: 0.2, lane: 0,+ size: 64, font: "sf", weight: 700, color: "#FFFFFF",+ shadow: true, plate: true,+ },+ ],+ subtitles: {+ cues: [+ { id: "s0", start: 0.3, end: 1.2, text: "every feature" },+ { id: "s1", start: 1.4, end: 2.2, text: "in one render" },+ ],+ showOnVideo: true,+ showOnTimeline: false,+ },+ };+ return doc;+}++const SETTINGS = { width: 1280, height: 720, fps: 24, crf: 24, preset: "veryfast", codec: "h264", container: "mp4", audioCodec: "aac" } as const;+/** Render the fixture doc in the tab and hand the MP4 bytes back. */-async function renderInPage(page: Page): Promise<{ b64: string; duration: number }> {+async function renderInPage(page: Page, doc: unknown): Promise<{ b64: string; duration: number }> {return page.evaluate(- async ({ clipS }) => {+ async ({ doc, settings }) => {const dev = (window as unknown as {__cutDev: {renderProjectToMp4: (@@ -276,74 +356,6 @@ async function renderInPage(page: Page): Promise<{ b64: string; duration: number};}).__cutDev;- const asset = (id: string, file: string, type: string, duration: number) => ({- id,- fileName: file,- name: id,- type,- url: `/__cutexport/${file}`,- duration,- ...(type === "video" ? { width: 1280, height: 720 } : {}),- });- const doc = {- aspect: "16:9",- background: "#102030",- fadeIn: 0.3,- fadeOut: 0.3,- assets: [- asset("v0", "clip-0.mp4", "video", clipS),- asset("v1", "clip-1.mp4", "video", clipS),- asset("m0", "music.m4a", "audio", 8),- ],- clips: [- {- id: "c0", assetId: "v0", track: 0, start: 0, in: 0, out: clipS,- muted: false, volume: 0.8,- fit: "fill", zoom: 1.4, panX: 0.3, panY: -0.2,- speed: 1.25,- transition: 0.5, transitionStyle: "crossfade",- },- {- id: "c1", assetId: "v1", track: 0, start: clipS / 1.25, in: 0, out: clipS,- muted: false,- fit: "fit",- grade: { brightness: 5, contrast: 8, saturation: -10, temperature: 12, hue: 10 },- kf: [- { t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 0, opacity: 1 },- { t: 2, x: 0.6, y: 0.4, scale: 0.85, rotation: 12, opacity: 1 },- ],- },- {- id: "c2", assetId: "v0", track: 1, start: 1, in: 0, out: 1.5,- muted: true,- frame: { x: 0.55, y: 0.05, w: 0.4, h: 0.4 },- fit: "fill", rotation: 5, opacity: 0.9,- },- ],- audioClips: [- {- id: "a0", assetId: "m0", start: 0, in: 0, out: 5,- volume: 0.5, fadeIn: 0.3, fadeOut: 0.5, lane: 0,- },- ],- overlays: [- {- id: "t0", kind: "text", text: "Everything test",- start: 0.5, end: 3, x: 0.5, y: 0.2, lane: 0,- size: 64, font: "sf", weight: 700, color: "#FFFFFF",- shadow: true, plate: true,- },- ],- subtitles: {- cues: [- { id: "s0", start: 0.3, end: 1.2, text: "every feature" },- { id: "s1", start: 1.4, end: 2.2, text: "in one render" },- ],- showOnVideo: true,- showOnTimeline: false,- },- };- const settings = { width: 1280, height: 720, fps: 24, crf: 24, preset: "veryfast", codec: "h264", container: "mp4", audioCodec: "aac" } as const;const duration = dev.projectDuration(doc);let stage = "start";@@ -365,7 +377,48 @@ async function renderInPage(page: Page): Promise<{ b64: string; duration: number}return { b64: btoa(bin), duration };},- { clipS: CLIP_S }+ { doc, settings: SETTINGS }+ );+}++/** Start the export through the store, the way the dialog does, and watch the+ * dock's rows until the engine's row reads done. */+async function exportThroughStore(page: Page, doc: unknown): Promise<{ duration: number; rows: string[] }> {+ return page.evaluate(+ async ({ doc, settings }) => {+ const dev = (window as unknown as {+ __cutDev: {+ projectDuration: (doc: unknown) => number;+ useEditor: { getState(): { projectId: string; projectName: string } };+ useExports: {+ getState(): {+ start(projectId: string, doc: unknown, settings: unknown, name: string): Promise<void>;+ local: { status: string; progress?: number; error?: string }[];+ jobs: { id: string; status: string; outName?: string; error?: string }[];+ rendering: string[];+ };+ };+ };+ }).__cutDev;+ const editor = dev.useEditor.getState();+ void dev.useExports.getState().start(editor.projectId, doc, settings, editor.projectName);+ const rows: string[] = [];+ const t0 = Date.now();+ while (Date.now() - t0 < 180_000) {+ await new Promise((r) => setTimeout(r, 250));+ const st = dev.useExports.getState();+ const line = [+ ...st.local.map((r) => `tab:${r.status}${r.progress != null ? ` ${(r.progress * 100).toFixed(0)}%` : ""}${r.error ? ` ${r.error}` : ""}`),+ ...st.jobs.map((j) => `engine:${j.status}${st.rendering.includes(j.id) ? " (hidden)" : ""} ${j.outName ?? ""}${j.error ? ` ${j.error}` : ""}`),+ ].join(" | ");+ if (rows[rows.length - 1] !== line) rows.push(line);+ if (st.local.some((r) => r.status === "error")) throw new Error(`export failed: ${rows.join("\n")}`);+ if (st.local.length === 0 && st.jobs.some((j) => j.status === "done")) break;+ }+ if (!dev.useExports.getState().jobs.some((j) => j.status === "done")) throw new Error(`export never finished: ${rows.join("\n")}`);+ return { duration: dev.projectDuration(doc), rows };+ },+ { doc, settings: SETTINGS });}@@ -376,8 +429,9 @@ async function main(): Promise<void> {const { browser, page } = await launch();const probe = () => probeInPage(page).then((r) => console.log(`[probe] ${JSON.stringify(r)}`));let projectId = HERMETIC_PROJECT;+ const engine = (p: string, init?: RequestInit) => fetch(`${BASE}${p}${p.includes("?") ? "&" : "?"}u=${DEV_USER}`, init);if (!HERMETIC) {- const res = await fetch(`${BASE}/api/cut/projects?u=${DEV_USER}`, {+ const res = await engine("/api/cut/projects", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: "cut-export eval" }),@@ -385,17 +439,60 @@ async function main(): Promise<void> {if (!res.ok) throw new Error(`create project failed: ${res.status} (is next dev running?)`);projectId = ((await res.json()) as { id: string }).id;}- console.log(`[ready] ${BASE}/app/p/${projectId}${HERMETIC ? " (hermetic)" : ""}`);+ console.log(`[ready] ${BASE}/app/p/${projectId}${HERMETIC ? " (hermetic)" : ENGINE ? " (engine)" : ""}`);- await open(page, projectId);- await probe();+ const outPath = path.join(OUT, "export.mp4");+ let duration = 0;const t0 = Date.now();- const { b64, duration } = await renderInPage(page);- await browser.close();+ try {+ if (ENGINE) {+ // The media lives in the project on the engine, and the doc names it+ // by the engine's own media URLs, the way an imported file is stored.+ const upload = async (file: string) => {+ const form = new FormData();+ const type = file.endsWith(".m4a") ? "audio/mp4" : "video/mp4";+ form.set("file", new File([await readFile(path.join(OUT, file))], file, { type }));+ const res = await engine(`/api/cut/projects/${projectId}/media`, { method: "POST", body: form });+ if (!res.ok) throw new Error(`upload ${file} failed: ${res.status}`);+ return ((await res.json()) as { fileName: string }).fileName;+ };+ const stored = new Map<string, string>();+ for (const file of ["clip-0.mp4", "clip-1.mp4", "music.m4a"]) stored.set(file, await upload(file));+ const doc = fixtureDoc((file) => `/api/cut/projects/${projectId}/media/${encodeURIComponent(stored.get(file)!)}`);+ const put = await engine(`/api/cut/projects/${projectId}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(doc),+ });+ if (!put.ok) throw new Error(`save project failed: ${put.status}`);- const outPath = path.join(OUT, "export.mp4");- await writeFile(outPath, Buffer.from(b64, "base64"));- console.log(`[render] ${((Date.now() - t0) / 1000).toFixed(1)}s → ${outPath}`);+ await open(page, projectId);+ await probe();+ const result = await exportThroughStore(page, doc);+ duration = result.duration;+ for (const row of result.rows) console.log(` ${row}`);+ await browser.close();++ const feed = (await (await engine(`/api/cut/projects/${projectId}/exports`)).json()) as { file: string }[];+ const landed = feed.find((f) => f.file.endsWith(".mp4"));+ if (!landed) throw new Error(`no export in the project folder: ${JSON.stringify(feed)}`);+ const file = await engine(`/api/cut/projects/${projectId}/exports/${encodeURIComponent(landed.file)}`);+ if (!file.ok) throw new Error(`read ${landed.file} failed: ${file.status}`);+ await writeFile(outPath, Buffer.from(await file.arrayBuffer()));+ console.log(`[render] ${((Date.now() - t0) / 1000).toFixed(1)}s → ${landed.file} in the project folder → ${outPath}`);+ } else {+ await open(page, projectId);+ await probe();+ const rendered = await renderInPage(page, fixtureDoc((file) => `/__cutexport/${file}`));+ duration = rendered.duration;+ await browser.close();+ await writeFile(outPath, Buffer.from(rendered.b64, "base64"));+ console.log(`[render] ${((Date.now() - t0) / 1000).toFixed(1)}s → ${outPath}`);+ }+ } finally {+ // The project was this run's; nothing of it stays on the machine.+ if (!HERMETIC) await engine(`/api/cut/projects/${projectId}`, { method: "DELETE" }).catch(() => {});+ }const probed = JSON.parse(await run("ffprobe", [@@ -428,6 +525,37 @@ async function main(): Promise<void> {failures.push("no audio stream");}+ // The picture at every cut: a frame of bare background between two+ // clips is the black flash a fixed-rate render lands in a gap the timeline+ // never showed. The project fade darkens the first and last frames by+ // design, so the scan stays clear of them.+ const raw = await run("ffmpeg", ["-loglevel", "error", "-i", outPath, "-vf", "scale=1:1:flags=area", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]);+ const bytes = Buffer.from(raw, "binary");+ const frames: number[][] = [];+ for (let i = 0; i + 2 < bytes.length; i += 3) frames.push([bytes[i], bytes[i + 1], bytes[i + 2]]);+ const dark = (c: number[]) => c[0] + c[1] + c[2] < 96;+ const flashes = frames+ .map((c, i) => ({ c, i }))+ .filter(({ c, i }) => i / 24 > 0.5 && i / 24 < duration - 0.5 && dark(c) && !dark(frames[i - 1]) && !dark(frames[i + 1]))+ .map(({ i }) => (i / 24).toFixed(2));+ if (flashes.length) failures.push(`bare frames at ${flashes.join(", ")}s`);++ // The level: the second clip at full volume over the music bed at half,+ // measured where nothing fades, against the sources through the same+ // decode. Half a decibel either way is the preview's own gain math.+ const rmsOf = async (file: string, from: number, to: number) => {+ const pcm = await run("ffmpeg", ["-loglevel", "error", "-ss", String(from), "-t", String(to - from), "-i", file, "-vn", "-af", "pan=mono|c0=c0", "-f", "f32le", "-ar", "48000", "-"]);+ const x = new Float32Array(Buffer.from(pcm, "binary").buffer);+ let sum = 0;+ for (const v of x) sum += v * v;+ return Math.sqrt(sum / Math.max(1, x.length));+ };+ const expected = Math.hypot(await rmsOf(path.join(OUT, "clip-1.mp4"), 0.5, 1.5), 0.5 * (await rmsOf(path.join(OUT, "music.m4a"), 0.5, 1.5)));+ const level = await rmsOf(outPath, 3.5, 4.5);+ const dB = 20 * Math.log10(level / expected);+ if (!(Math.abs(dB) <= 0.5)) failures.push(`level at 3.5–4.5s is ${dB.toFixed(2)} dB off the sources`);+ console.log(`[level] ${dB >= 0 ? "+" : ""}${dB.toFixed(2)} dB against the sources; ${frames.length} frames, ${flashes.length} bare`);+if (failures.length) {console.error(`[FAIL] ${failures.join("; ")}`);process.exit(1);diff --git a/site/src/cut/lib/devHooks.ts b/site/src/cut/lib/devHooks.tsindex d19c75bc..4983ba12 100644--- a/site/src/cut/lib/devHooks.ts+++ b/site/src/cut/lib/devHooks.ts@@ -8,6 +8,7 @@*/import { renderProjectToMp4 } from "./exportRender";+import { useExports } from "./exportStore";import { useGenerate } from "./generate";import { useGenScene } from "./genScene";import { edgeFramesPending, enrichAsset, importFileToProject } from "./media";@@ -44,6 +45,9 @@ export function installDevHooks(): void {// the bytes back out.renderProjectToMp4,projectDuration,+ // The export eval starts a real export through the store, the way the+ // dialog does, and watches the dock's feed for the file.+ useExports,};// The perf eval arms and reads the frame trace through here. Off until// `start()` is called, so an ordinary dev session records nothing.diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 3c8a234c..c8954e34 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -1421,8 +1421,10 @@ export async function createExportJob(* nothing waits behind another account's render — and the file matches the* preview, because the same compositor drew both.*- * Cloud projects only: a local project's engine has ffmpeg, a whole machine,- * and the media already on disk.+ * Every residency: a cloud project's file goes up to storage, a browser+ * project's into the tab's own store, and a Mac project's to the engine on+ * this machine, which holds the job row and lands the file in the project's+ * folder.*/export async function runBrowserExport(projectId: string,@@ -1440,7 +1442,7 @@ export async function runBrowserExport(): Promise<string> {const backend = getBackend(); // pinned: the render outlives navigationif (backend.kind === "browser") return runStoreExport(projectId, doc, settings, opts);- if (backend.kind !== "cloud") throw new Error("This project renders on its own machine.");+ if (backend.kind === "local") return runEngineExport(projectId, doc, settings, opts, backend);// The name and the destination are claimed before a frame is drawn, so a// render that is going to be refused for space or for the render cap is@@ -1506,6 +1508,101 @@ export async function runBrowserExport(}}+/**+ * A Mac-resident project's export: the same in-tab render, with the finished+ * file streamed into the project's exports folder on this Mac. The engine+ * holds the job row — the file's name, the dock's slot, the progress every+ * other tab's dock shows — and encodes nothing: what the user watched on the+ * stage is what goes into the file, drawn by the same compositor and mixed+ * by the same graph.+ */+/** How often a tab render tells the engine it is still drawing. Well inside+ * the engine's silence window even for a hidden tab's throttled timers. */+const CLIENT_HEARTBEAT_MS = 5000;++async function runEngineExport(+ projectId: string,+ doc: ExportDoc,+ settings: ExportSettings,+ opts: NonNullable<Parameters<typeof runBrowserExport>[3]>,+ backend: CutBackend+): Promise<string> {+ const claim = await backend.fetch("/api/cut/export/client", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ projectId, container: settings.container }),+ });+ const claimed = await apiJson<{ id?: string; outName?: string }>(claim);+ if (!claim.ok || !claimed.id) throw new Error(claimed.error ?? "Export failed to start.");+ const jobId = claimed.id;+ opts.onClaimed?.(jobId);+ // The engine's feed carries the progress to every other tab's dock; a+ // report every couple of percent is plenty for a bar.+ let reported = 0;+ const post = (ratio: number) =>+ void backend+ .fetch(`/api/cut/export/client/${jobId}/progress`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ratio }),+ })+ .catch(() => {});+ const report = (ratio: number) => {+ if (ratio - reported < 0.02 && ratio < 1) return;+ reported = ratio;+ post(ratio);+ };+ // Each report is also the engine's sign that this tab is still drawing; a+ // long stretch with no new percent still says so on a timer, so a tab that+ // closed mid-render is told apart from one encoding a slow stretch.+ const heartbeat = setInterval(() => post(reported), CLIENT_HEARTBEAT_MS);+ try {+ const rendered = await renderProjectToMp4(doc, settings, {+ resolve: (asset) =>+ useEditor.getState().assets.find((a) => a.id === asset.id)?.url ?? asset.url,+ signal: opts.signal,+ // The render is nearly all of the work; the hand-in to the engine on+ // this machine is the tail of the bar.+ onProgress: ({ ratio }) => {+ opts.onProgress?.(ratio * 0.95);+ report(ratio * 0.95);+ },+ });+ let done: Response;+ try {+ done = await backend.fetch(`/api/cut/export/client/${jobId}/file`, {+ method: "PUT",+ headers: { "Content-Type": deliveryContainer(settings.container).mime },+ body: rendered.file,+ signal: opts.signal,+ });+ } finally {+ // The file streamed from scratch disk into the engine's folder; its+ // space comes back as soon as the hand-in is done with it.+ void rendered.discard();+ }+ // The engine refuses a file for a job it no longer holds: the user+ // canceled this render from another dock. That is their stop, and it+ // ends here the way a cancel in this tab does.+ if (done.status === 409) throw new DOMException("Export canceled.", "AbortError");+ const body = await apiJson<{ id?: string }>(done);+ if (!done.ok || !body.id) throw new Error(body.error ?? "Could not save the export.");+ opts.onProgress?.(1);+ return body.id;+ } catch (err) {+ // A render that stopped — cancelled, failed — gives back the name it was+ // holding, so no row stays in the feed for a file that will never exist.+ // The release lands before the store hears of the stop, so the feed the+ // dock reads next is already clear of the row.+ await backend+ .fetch(`/api/cut/export/client/${jobId}/release`, { method: "POST" })+ .catch(() => {});+ throw err;+ } finally {+ clearInterval(heartbeat);+ }+}+/** A browser-resident project's export: the same in-tab render, with the* finished file written into the project's exports shelf in the browser store.* The job is a row in the tab-local feed, so the dock tracks, cancels, anddiff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.tsindex 31ce8ff4..69c36633 100644--- a/site/src/cut/lib/exportStore.ts+++ b/site/src/cut/lib/exportStore.ts@@ -109,18 +109,16 @@ export const useExports = create<ExportsState>((set, get) => ({start: async (projectId, doc, settings, projectName) => {const localId = `local-${crypto.randomUUID().slice(0, 8)}`;const backend = getBackend();- // A cloud project renders in the tab: no upload of the cut to a container,- // no queue behind other accounts, and the file matches the preview because- // the same compositor drew both. A browser that can't carry the render —- // no encoder for the codec, no scratch storage — sends it to the worker,- // which has a whole machine. A browser-resident project renders in the tab- // too, and borrows the same worker when the tab can't: its media goes up- // with the job and the file comes back into its own storage. Whatever the- // user chose, something renders it.- const inBrowser =- (backend.kind === "cloud" || backend.kind === "browser") &&- (await canRenderInBrowser(doc, settings));- const tabOwned = backend.kind !== "local";+ // Every project renders in the tab: the file matches the preview because+ // the compositor that drew the stage and the graph that played the sound+ // draw and mix the file. A browser that can't carry the render — no+ // encoder for the codec, no scratch storage — hands it to the machine+ // behind the project: the engine on this Mac for a Mac project, the+ // worker for a cloud one, and the worker again for a browser project,+ // whose media goes up with the job and whose file comes back into its own+ // storage. Whatever the user chose, something renders it.+ const inBrowser = await canRenderInBrowser(doc, settings);+ const tabOwned = backend.kind !== "local" || inBrowser;const abort = tabOwned ? new AbortController() : undefined;set((s) => ({local: [@@ -171,8 +169,9 @@ export const useExports = create<ExportsState>((set, get) => ({local: s.local.map((r) => (r.id === localId ? { ...r, progress } : r)),})),};- // The worker renders what the tab could not: a cloud project's own media- // is already there, a browser project's goes up with the job.+ // The machine behind the project renders what the tab could not: the+ // engine has a Mac project's media, the worker a cloud project's, and a+ // browser project's goes up with the job.const renderOnWorker = async () => {release();if (backend.kind === "browser") {@@ -193,10 +192,10 @@ export const useExports = create<ExportsState>((set, get) => ({} catch (err) {// The probe said yes and the browser then failed anyway — an encoder// that refuses mid-stream, scratch storage that gives out. The- // export goes to the worker and the user sees it carry on, never an- // error for a render they could not have done anything about. A- // stopped render is theirs, and a gate's refusal is final: the- // worker sits behind the same gate.+ // export goes to the machine behind the project and the user sees+ // it carry on, never an error for a render they could not have done+ // anything about. A stopped render is theirs, and a gate's refusal+ // is final: the worker sits behind the same gate.if (err instanceof DOMException && err.name === "AbortError") throw err;if (err instanceof ExportRefusedError) throw err;await renderOnWorker();diff --git a/site/src/cut/server/http/export.ts b/site/src/cut/server/http/export.tsindex 80e62e78..7414fd17 100644--- a/site/src/cut/server/http/export.ts+++ b/site/src/cut/server/http/export.ts@@ -1,4 +1,14 @@-import { cancelJob, createJob, getJob, listAllJobs } from "../jobs";+import {+ cancelJob,+ completeClientJob,+ createClientJob,+ createJob,+ getJob,+ listAllJobs,+ progressClientJob,+ releaseClientJob,+ type ExportSpec,+} from "../jobs";import { serveFileRange } from "../serveFile";/** Export rendering: start a job, poll it, cancel it, download the result. */@@ -25,6 +35,42 @@ export const exportApi = {}},+ /** A render the browser tab carries itself: open the job row and claim the+ * file's name; the tab draws the frames and hands the file in below. */+ async createClient(req: Request) {+ try {+ const body = (await req.json()) as { projectId?: string; container?: ExportSpec["container"] };+ if (!body.projectId) return Response.json({ error: "Missing project." }, { status: 400 });+ const job = await createClientJob(body.projectId, body.container);+ if (job.status === "error") return Response.json({ error: job.error }, { status: 400 });+ return Response.json({ id: job.id, outName: job.outName });+ } catch (e) {+ return Response.json(+ { error: e instanceof Error ? e.message : "Export failed to start." },+ { status: 500 }+ );+ }+ },++ async clientProgress(req: Request, { jobId }: { jobId: string }) {+ const body = (await req.json().catch(() => ({}))) as { ratio?: number };+ progressClientJob(jobId, Number(body.ratio));+ return Response.json({ ok: true });+ },++ /** The finished file, streamed straight into the project's exports folder. */+ async clientComplete(req: Request, { jobId }: { jobId: string }) {+ const job = await completeClientJob(jobId, req.body);+ if (!job) return Response.json({ error: "This export is no longer running." }, { status: 409 });+ if (job.status === "error") return Response.json({ error: job.error }, { status: 500 });+ return Response.json({ id: job.id, outName: job.outName });+ },++ async clientRelease(_req: Request, { jobId }: { jobId: string }) {+ releaseClientJob(jobId);+ return Response.json({ ok: true });+ },+async status(_req: Request, { jobId }: { jobId: string }) {const job = getJob(jobId);if (!job) return Response.json({ error: "Unknown export." }, { status: 404 });diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 516c486f..69458977 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -73,6 +73,10 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "GET", path: "/api/cut/export-jobs", handler: () => exportApi.activeAll() },{ method: "POST", path: "/api/cut/export", handler: (req) => exportApi.create(req) },+ { method: "POST", path: "/api/cut/export/client", handler: (req) => exportApi.createClient(req) },+ { method: "POST", path: "/api/cut/export/client/:jobId/progress", handler: (req, p) => exportApi.clientProgress(req, { jobId: p.jobId }) },+ { method: "PUT", path: "/api/cut/export/client/:jobId/file", handler: (req, p) => exportApi.clientComplete(req, { jobId: p.jobId }) },+ { method: "POST", path: "/api/cut/export/client/:jobId/release", handler: (req, p) => exportApi.clientRelease(req, { jobId: p.jobId }) },{ method: "GET", path: "/api/cut/export/:jobId", handler: (req, p) => exportApi.status(req, { jobId: p.jobId }) },{ method: "DELETE", path: "/api/cut/export/:jobId", handler: (req, p) => exportApi.cancel(req, { jobId: p.jobId }) },{ method: "GET", path: "/api/cut/export/:jobId/file", handler: (req, p) => exportApi.file(req, { jobId: p.jobId }) },diff --git a/site/src/cut/server/jobs.test.ts b/site/src/cut/server/jobs.test.tsnew file mode 100644index 00000000..f45ed2de--- /dev/null+++ b/site/src/cut/server/jobs.test.ts@@ -0,0 +1,109 @@+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { mkdtemp, readFile, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++// The engine's data root is read per call, so a temp root set before the+// modules load keeps the test off the user's own Movies folder.+const root = await mkdtemp(path.join(os.tmpdir(), "cut-jobs-test-"));+process.env.DONKEY_CUT_DATA_DIR = root;+const jobs = await import("./jobs");+const projects = await import("./projects");++const exists = (file: string) =>+ stat(file).then(+ () => true,+ () => false+ );++const bytes = (text: string) =>+ new ReadableStream<Uint8Array>({+ start(c) {+ c.enqueue(new TextEncoder().encode(text));+ c.close();+ },+ });++describe("a render the tab carries itself", () => {+ let projectId = "";+ beforeAll(async () => {+ projectId = (await projects.createProject("Tab Render")).id;+ });+ afterAll(async () => {+ await rm(root, { recursive: true, force: true });+ });++ test("holds a name and a running row, then lands the file under that name", async () => {+ const job = await jobs.createClientJob(projectId, "mp4");+ expect(job.status).toBe("running");+ expect(job.outName).toBe("Tab Render.mp4");+ expect(jobs.listAllJobs().find((j) => j.id === job.id)?.status).toBe("running");++ jobs.progressClientJob(job.id, 0.5);+ expect(jobs.getJob(job.id)?.progress).toBe(0.5);++ const done = await jobs.completeClientJob(job.id, bytes("mp4 bytes"));+ expect(done?.status).toBe("done");+ expect(done?.progress).toBe(1);+ const file = path.join(projects.exportsDir(projectId), "Tab Render.mp4");+ expect(await readFile(file, "utf8")).toBe("mp4 bytes");+ expect(await exists(`${file}.part`)).toBe(false);+ });++ test("a second render takes the next name while the first holds its own", async () => {+ const job = await jobs.createClientJob(projectId, "mp4");+ expect(job.outName).toBe("Tab Render 2.mp4");+ jobs.releaseClientJob(job.id);+ expect(jobs.getJob(job.id)).toBeUndefined();+ const again = await jobs.createClientJob(projectId, "mov");+ expect(again.outName).toBe("Tab Render.mov");+ jobs.releaseClientJob(again.id);+ });++ test("a cancel from another dock settles the row and refuses the file", async () => {+ const job = await jobs.createClientJob(projectId, "mp4");+ jobs.cancelJob(job.id);+ expect(jobs.getJob(job.id)?.status).toBe("error");+ expect(await jobs.completeClientJob(job.id, bytes("late"))).toBeNull();+ expect(await exists(path.join(projects.exportsDir(projectId), "Tab Render 2.mp4"))).toBe(false);+ });++ test("a tab that fell silent gives its row and name up", async () => {+ const job = await jobs.createClientJob(projectId, "mp4");+ jobs.progressClientJob(job.id, 0.4);+ jobs.sweepClientJobsForTest(Date.now() + 60_000);+ expect(jobs.getJob(job.id)?.status).toBe("running");+ jobs.sweepClientJobsForTest(Date.now() + 10 * 60_000);+ expect(jobs.getJob(job.id)?.status).toBe("error");+ expect(jobs.listAllJobs().find((j) => j.id === job.id)?.status).toBe("error");+ // "Tab Render.mp4" is on disk from the first render; the silent job's+ // name is free again.+ const next = await jobs.createClientJob(projectId, "mp4");+ expect(next.outName).toBe("Tab Render 2.mp4");+ jobs.releaseClientJob(next.id);+ jobs.releaseClientJob(job.id);+ });++ test("a hand-in that broke off leaves no row once the tab releases it", async () => {+ const job = await jobs.createClientJob(projectId, "mp4");+ // A request body whose connection dropped mid-stream.+ const broken = new ReadableStream<Uint8Array>({+ start(c) {+ c.enqueue(new TextEncoder().encode("half"));+ },+ pull(c) {+ c.error(new Error("aborted"));+ },+ });+ const settled = await jobs.completeClientJob(job.id, broken);+ expect(settled?.status).toBe("error");+ expect(await exists(path.join(projects.exportsDir(projectId), "Tab Render.mp4.part"))).toBe(false);+ jobs.releaseClientJob(job.id);+ expect(jobs.getJob(job.id)).toBeUndefined();+ });++ test("an unknown project is refused up front", async () => {+ const job = await jobs.createClientJob("nope", "mp4");+ expect(job.status).toBe("error");+ });+});diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 6d3114d1..09ebde32 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -1,5 +1,5 @@import { type ChildProcess } from "node:child_process";-import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, open, readdir, rename, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import { assertLocalRuntime } from "./local-only";@@ -29,16 +29,31 @@ export interface Job {outPath: string;outName: string;proc?: ChildProcess;+ /** A render the browser tab carries itself: the row holds the file's name+ * and the dock's slot while the tab draws the frames, and the finished file+ * streams in when it is done. The engine encodes nothing for it. */+ client?: boolean;+ /** A tab render's last sign of life: its claim, a progress report, or the+ * start of its hand-in. */+ seenAt?: number;log: string[];}const MAX_RUNNING = 2; // concurrent ffmpeg exports; extra exports queue behind them// Survives dev-server module reloads; caps the terminal backlog. Queued jobs// are active work, not backlog, so they are exempt from eviction.-const { jobs, runningCount, retire } = createJobRegistry<Job>("__veditorJobs", {+const { jobs, retire } = createJobRegistry<Job>("__veditorJobs", {isTerminal: (j) => j.status === "done" || j.status === "error",});+/** Renders holding an ffmpeg slot. A tab's own render is in the feed with+ * status "running" and takes none: the encoding happens in the browser. */+const runningCount = () => {+ let n = 0;+ for (const j of jobs.values()) if (j.status === "running" && !j.client) n++;+ return n;+};+// Export jobs waiting for a running slot, oldest first. Held on globalThis so a// dev-server module reload doesn't strand a queued render. Preview proxies never// queue — they run when a slot is free and are rejected otherwise.@@ -49,13 +64,34 @@ interface Pending {const g = globalThis as unknown as { __veditorPending?: Pending[] };const pending: Pending[] = (g.__veditorPending ??= []);+/** How long a tab render may go quiet before its row is given up. The tab+ * reports every few seconds while it draws; a tab that closed, crashed, or+ * lost the page mid-render stops, and its row would otherwise hold the file+ * name and the project's busy flag forever. Long enough to ride out a hidden+ * tab's throttled timers. */+const CLIENT_RENDER_WINDOW_MS = 3 * 60 * 1000;++/** Settle every tab render that fell silent: the row errors and retires, so+ * the name frees, the folder may follow its project's name again, and the+ * docks stop polling for a render nothing is drawing. */+function sweepClientJobs(now = Date.now()): void {+ for (const job of jobs.values()) {+ if (!job.client || job.status !== "running") continue;+ if (now - (job.seenAt ?? job.startedAt ?? job.createdAt) < CLIENT_RENDER_WINDOW_MS) continue;+ job.status = "error";+ job.error = "The tab rendering this export went away.";+ retire(job);+ }+}+// A project folder never moves while a render holds paths inside it: the// rename-follows-name machinery asks here before touching the folder.-setActiveJobGuard((projectId) =>- [...jobs.values()].some(+setActiveJobGuard((projectId) => {+ sweepClientJobs();+ return [...jobs.values()].some((j) => j.projectId === projectId && (j.status === "queued" || j.status === "running")- )-);+ );+});/** Promote queued exports into free running slots, oldest first. Called after* every enqueue and every settle, so the queue always drains to capacity. */@@ -111,6 +147,7 @@ function jobView(j: Job) {/** Every export job across all projects — the source of truth the app-wide* exports dock reflects, so it shows the same set in every tab. */export function listAllJobs() {+ sweepClientJobs();return [...jobs.values()].filter((j) => j.target !== "preview").sort((a, b) => a.createdAt - b.createdAt)@@ -125,6 +162,12 @@ export function cancelJob(id: string) {job.status = "error";job.error = "Export canceled.";retire(job);+ } else if (job.status === "running" && job.client) {+ // The tab drawing it learns of the cancel when it comes to hand the file+ // in and is refused; the row settles now so every dock clears.+ job.status = "error";+ job.error = "Export canceled.";+ retire(job);} else if (job.status === "queued") {// Never started: drop it from the queue and settle it so the dock clears.job.status = "error";@@ -147,8 +190,10 @@ async function exportName(projectId: string, projectName: string, ext: string) {const taken = new Set(await readdir(exportsDir(projectId)).catch(() => [] as string[]));+ // A failed job wrote nothing under its name; only live and finished ones+ // hold theirs.for (const j of jobs.values()) {- if (j.projectId === projectId && j.outName) taken.add(j.outName);+ if (j.projectId === projectId && j.outName && j.status !== "error") taken.add(j.outName);}for (let n = 1; ; n++) {const candidate = n === 1 ? `${base}${ext}` : `${base} ${n}${ext}`;@@ -253,3 +298,109 @@ export async function createJob(form: FormData): Promise<Job> {}return job;}++/**+ * Open a job for a render the tab carries itself. The name is claimed and the+ * row enters the feed as running, so every dock shows it and no other export+ * can take its file name; the frames are the browser's to draw.+ */+export async function createClientJob(+ projectId: string,+ container: ExportSpec["container"]+): Promise<Job> {+ assertLocalRuntime();+ sweepClientJobs();+ const job: Job = {+ id: crypto.randomUUID().slice(0, 12),+ projectId,+ projectName: "",+ target: "export",+ status: "running",+ progress: 0,+ createdAt: Date.now(),+ startedAt: Date.now(),+ seenAt: Date.now(),+ tmpDir: "",+ outPath: "",+ outName: "",+ client: true,+ log: [],+ };+ jobs.set(job.id, job);+ try {+ const doc = await readProject(projectId);+ if (!doc) throw new Error("Project not found.");+ job.projectName = doc.name;+ await claimExportName(job, doc.name, containerExtension({ container }));+ job.outPath = path.join(exportsDir(projectId), job.outName);+ await mkdir(path.dirname(job.outPath), { recursive: true });+ } catch (err) {+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ retire(job);+ }+ return job;+}++/** How far the tab has drawn, for the docks in every other tab. A report is+ * also the tab's heartbeat, whatever the ratio. */+export function progressClientJob(id: string, ratio: number): void {+ const job = jobs.get(id);+ if (!job?.client || job.status !== "running") return;+ job.seenAt = Date.now();+ if (Number.isFinite(ratio)) job.progress = Math.max(job.progress, Math.min(1, Math.max(0, ratio)));+}++/**+ * The finished file, streamed into exports/ under the claimed name. Null when+ * the job is no longer a running tab render — canceled from another dock, or+ * never one at all — so the tab knows its file has nowhere to go.+ */+export async function completeClientJob(+ id: string,+ body: ReadableStream<Uint8Array> | null+): Promise<Job | null> {+ const job = jobs.get(id);+ if (!job?.client || job.status !== "running") return null;+ job.seenAt = Date.now();+ const partial = `${job.outPath}.part`;+ try {+ if (!body) throw new Error("The export arrived without a file.");+ // Read chunk by chunk into a file handle. A body whose connection drops+ // rejects the loop, so the catch below runs; under Bun the Node stream+ // adapter hangs on the same body and leaks the rejection.+ const file = await open(partial, "w");+ try {+ for await (const chunk of body) await file.write(chunk);+ } finally {+ await file.close();+ }+ await rename(partial, job.outPath);+ job.status = "done";+ job.progress = 1;+ } catch (err) {+ await rm(partial, { force: true });+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ } finally {+ retire(job);+ }+ return job;+}++/** A tab render that stopped before its file landed gives the name and the+ * row back; nothing of it stays in the feed. That covers a render the tab+ * abandoned while still running and one whose hand-in broke off — a cancel+ * that lands mid-stream errors the row first, and the tab's release then+ * takes it out so no dock shows a failure card for the user's own stop. A+ * finished file keeps its row. */+export function releaseClientJob(id: string): void {+ const job = jobs.get(id);+ if (!job?.client || job.status === "done") return;+ jobs.delete(id);+}++/** Test seam: settle tab renders that have been silent longer than the window. */+export function sweepClientJobsForTest(now: number): void {+ sweepClientJobs(now);+}diff --git a/site/src/types/bun-test.d.ts b/site/src/types/bun-test.d.tsindex 73c63246..4f673919 100644--- a/site/src/types/bun-test.d.ts+++ b/site/src/types/bun-test.d.ts@@ -10,6 +10,8 @@ declare module "bun:test" {skipIf(condition: boolean): TestFn;}export const test: TestFn;+ export function beforeAll(fn: () => void | Promise<void>): void;+ export function afterAll(fn: () => void | Promise<void>): void;export function beforeEach(fn: () => void | Promise<void>): void;export function afterEach(fn: () => void | Promise<void>): void;export interface Matchers {