Open source CapCut alternative.
TypeScript
feat(site): send inference media through object storage
David Le001f0b563d2e
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex 929f2a25..47b255d2 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -83,6 +83,20 @@ hand back job IDs, generation IDs, polling URLs, and output references, but itnever persists prompts, generation records, provider output references, orgenerated assets in Postgres.+**Media never rides the request body.** The routes run as serverless functions+behind a request-body limit the platform enforces at the edge, and an oversized+body is refused before a handler runs — the caller sees a dropped connection, not+an error anyone can act on. So a client with pictures or sound to send uploads+the bytes straight to object storage and puts a placeholder in the body naming+the object and the field the bytes belong in. The route swaps the bytes back in+before the provider call, where the request is server-to-server and only the+model's own limit applies.++Two rules follow. A placeholder is scoped to the account that uploaded it, so a+route reads an object only under the caller's own prefix. And storage is how a+large request succeeds, never why a small one fails: a client that can't reach+storage sends the bytes inline, as it always could.+### Computer useComputer use is a built-in tool of Gemini's main flash model, so one modeldiff --git a/docs/guides/cut/brief-to-video.md b/docs/guides/cut/brief-to-video.mdindex 89bb5eb5..58a7be7c 100644--- a/docs/guides/cut/brief-to-video.md+++ b/docs/guides/cut/brief-to-video.md@@ -75,6 +75,12 @@ instead — the same fixed words every shot:reference-conditioned video from the sheets → text-only, where the cast'sfull written descriptions ride the prompt and identity drifts the most.+Sheets are what make a run expensive to send: every keyframe and every take+carries several of them, so the pictures travel through object storage rather+than the request body (see the inference gateway's media rule). A sheet is+addressed by its content, so it uploads once for the whole run no matter how+many shots ride it.+The project's frame is the user's setting. A run reads it when the plan isapproved and never changes it — a reference in another shape or a platform thebrief names is something to mention, not a reason to reframe someone's project.diff --git a/site/src/app/api/inference/assets/route.ts b/site/src/app/api/inference/assets/route.tsindex f8a2515a..c2726c62 100644--- a/site/src/app/api/inference/assets/route.ts+++ b/site/src/app/api/inference/assets/route.ts@@ -21,7 +21,9 @@ import {} from "@/lib/inference/responses";import { assetGenerationRequestSchema } from "@/lib/inference/schemas";import { withDonkeyAuth } from "@/lib/donkey-api-auth";-import { InferenceProviderError } from "@/lib/inference/providers";+import { resolveInferenceBlobs } from "@/lib/inference/blobs";+import { InferenceProviderError, type JsonObject } from "@/lib/inference/providers";+import { toJsonObject, toJsonValue } from "@/lib/inference/json";export const dynamic = "force-dynamic";@@ -75,9 +77,19 @@ export const POST = withDonkeyAuth(async (request) => {id: generationId,kind: parsed.data.kind,};+ // Reference pictures and seed frames ride storage, not the request body —+ // they become inline data here, on the server-to-server leg.+ const inputs: JsonObject | undefined = parsed.data.inputs+ ? toJsonObject(+ await resolveInferenceBlobs(+ toJsonValue(parsed.data.inputs),+ request.donkey.userId,+ ),+ )+ : undefined;const result = await provider.generateAsset?.({generationId,- request: parsed.data,+ request: inputs ? { ...parsed.data, inputs } : parsed.data,});if (!result) {diff --git a/site/src/app/api/inference/chat/completions/route.ts b/site/src/app/api/inference/chat/completions/route.tsindex 3bbd968a..263f2c0b 100644--- a/site/src/app/api/inference/chat/completions/route.ts+++ b/site/src/app/api/inference/chat/completions/route.ts@@ -9,6 +9,8 @@ import {requireInferenceCredits,} from "@/lib/credits/inference";import { createProviderRegistry } from "@/lib/inference/router";+import { resolveInferenceBlobs } from "@/lib/inference/blobs";+import { toJsonValue } from "@/lib/inference/json";import {inferenceErrorCode,inferenceProviderErrorResponse,@@ -65,12 +67,21 @@ export const POST = withDonkeyAuth(async (request) => {let failedUsageProvider = "default";try {+ // Attached pictures and sound ride storage, not the request body — they+ // become inline message parts here, on the server-to-server leg.+ const data = {+ ...parsed.data,+ messages: (await resolveInferenceBlobs(+ toJsonValue(parsed.data.messages),+ request.donkey.userId,+ )) as typeof parsed.data.messages,+ };const registry = createProviderRegistry();- const provider = registry.textProvider(parsed.data.stream);+ const provider = registry.textProvider(data.stream);failedUsageProvider = provider.id;- if (parsed.data.stream) {- const result = await provider.streamCompletion?.(parsed.data);+ if (data.stream) {+ const result = await provider.streamCompletion?.(data);if (!result) {if (!bypassCredits) {await recordFailedInferenceUsage({@@ -124,7 +135,7 @@ export const POST = withDonkeyAuth(async (request) => {});}- const result = await provider.completeText?.(parsed.data);+ const result = await provider.completeText?.(data);if (!result) {if (!bypassCredits) {await recordFailedInferenceUsage({diff --git a/site/src/app/api/inference/responses/route.ts b/site/src/app/api/inference/responses/route.tsindex 25fe8a38..a22222e8 100644--- a/site/src/app/api/inference/responses/route.ts+++ b/site/src/app/api/inference/responses/route.ts@@ -9,7 +9,8 @@ import {requireInferenceCredits,} from "@/lib/credits/inference";import { createProviderRegistry } from "@/lib/inference/router";-import { isJsonObject, toJsonValue } from "@/lib/inference/json";+import { resolveInferenceBlobs } from "@/lib/inference/blobs";+import { isJsonObject, toJsonObject, toJsonValue } from "@/lib/inference/json";import {inferenceErrorCode,inferenceProviderErrorResponse,@@ -70,12 +71,20 @@ export const POST = withDonkeyAuth(async (request) => {let failedUsageProvider = parsed.data.donkeyProvider ?? "default";try {+ // Attached pictures and sound ride storage, not the request body — they+ // become inline content parts here, on the server-to-server leg.+ const data = {+ ...parsed.data,+ body: toJsonObject(+ await resolveInferenceBlobs(parsed.data.body, request.donkey.userId),+ ),+ };const registry = createProviderRegistry();- const provider = registry.responsesProvider(parsed.data);+ const provider = registry.responsesProvider(data);failedUsageProvider = provider.id;- if (parsed.data.stream) {- const streamed = await provider.createResponseStream?.(parsed.data);+ if (data.stream) {+ const streamed = await provider.createResponseStream?.(data);if (!streamed) {if (!bypassCredits) {await recordFailedInferenceUsage({@@ -174,7 +183,7 @@ export const POST = withDonkeyAuth(async (request) => {}const providerStartedAt = performance.now();- const result = await provider.createResponse?.(parsed.data);+ const result = await provider.createResponse?.(data);if (!result) {if (!bypassCredits) {await recordFailedInferenceUsage({diff --git a/site/src/app/api/inference/uploads/route.ts b/site/src/app/api/inference/uploads/route.tsnew file mode 100644index 00000000..c33d1fd7--- /dev/null+++ b/site/src/app/api/inference/uploads/route.ts@@ -0,0 +1,85 @@+import { NextResponse } from "next/server";++import {+ head,+ inferenceBlobKey,+ presignPut,+ R2NotConfiguredError,+} from "@/cut/server/cloud/r2";+import {+ requireInferenceClientId,+ validationErrorResponse,+} from "@/lib/inference/responses";+import { inferenceUploadRequestSchema } from "@/lib/inference/schemas";+import { withDonkeyAuth } from "@/lib/donkey-api-auth";++export const dynamic = "force-dynamic";++// Media a hosted inference call carries rides object storage rather than the+// request body (see lib/inference/blobs.ts). This mints the upload URLs: one+// content-addressed key per picture or sound, and a direct PUT the browser sends+// the bytes to. Nothing is billed here — the render that follows is.+//+// A key already in storage comes back without a URL, so the reference sheet a+// scene run rides into every shot uploads once for the whole run.+const MAX_BLOB_BYTES = 32 * 1024 * 1024;++const EXTENSIONS: Record<string, string> = {+ "image/png": "png",+ "image/jpeg": "jpg",+ "image/webp": "webp",+ "image/gif": "gif",+ "audio/mpeg": "mp3",+ "audio/mp4": "m4a",+ "audio/aac": "aac",+ "audio/wav": "wav",+ "audio/x-wav": "wav",+ "audio/webm": "weba",+ "audio/ogg": "ogg",+ "video/mp4": "mp4",+ "video/quicktime": "mov",+ "video/webm": "webm",+};++export const POST = withDonkeyAuth(async (request) => {+ const client = requireInferenceClientId(request.donkey.clientId);+ if (!client.ok) {+ return client.response;+ }++ const parsed = inferenceUploadRequestSchema.safeParse(await request.json());+ if (!parsed.success) {+ return validationErrorResponse(parsed.error);+ }++ try {+ // Per-item outcomes, in request order: one blob this route can't take never+ // costs the caller the rest of the batch. A skipped blob rides the request+ // body as before, which is what it would have done anyway.+ const blobs = await Promise.all(+ parsed.data.blobs.map(async (blob) => {+ const ext = EXTENSIONS[blob.mimeType];+ if (!ext) return { skipped: "unsupported" };+ if (blob.bytes > MAX_BLOB_BYTES) return { skipped: "too_large" };+ const key = inferenceBlobKey(request.donkey.userId, blob.sha256, ext);+ const stored = await head(key);+ if (stored && stored.bytes === blob.bytes) {+ return { blobRef: key };+ }+ return { blobRef: key, putUrl: await presignPut(key, blob.mimeType) };+ }),+ );+ return NextResponse.json({ blobs });+ } catch (error) {+ if (error instanceof R2NotConfiguredError) {+ return NextResponse.json(+ {+ error: "storage_unavailable",+ message: "Media storage is not configured.",+ },+ { status: 503 },+ );+ }+ throw error;+ }+});diff --git a/site/src/cut/lib/hosted.ts b/site/src/cut/lib/hosted.tsindex 5d3c308c..1fdc47d0 100644--- a/site/src/cut/lib/hosted.ts+++ b/site/src/cut/lib/hosted.ts@@ -3,6 +3,8 @@import { useEffect } from "react";import { create } from "zustand";+import { offloadHostedMedia } from "./hostedBlobs";+// Donkey's hosted inference routes, called from the page with the user's// session and credits (the one hosted carve-out on the otherwise local-only// Cut page). Shared by media generation, prompt composition, and AI chat.@@ -86,13 +88,19 @@ export function useCreditsRecheck(): void {// The hosted routes run as serverless functions behind a 4.5MB request-body// limit the platform enforces at the edge: an oversized body is refused before// the route runs, the upload resets mid-flight, and fetch rejects with a bare-// "Failed to fetch" that reads like the network died. Attachments are fitted to-// fit (refMedia.ts); this says so plainly if one ever isn't.+// "Failed to fetch" that reads like the network died. Media never rides the body+// far enough to reach that: past the soft limit every picture and sound moves to+// storage and travels as a reference (hostedBlobs.ts). The hard limit stands+// behind that as a plain error, for a body that is large without being media.+const OFFLOAD_ABOVE_BYTES = 1024 * 1024;const MAX_BODY_BYTES = 4 * 1024 * 1024;/** POST one of Donkey's hosted inference routes with the user's session. */export const hostedPost = async (path: string, body: unknown, signal?: AbortSignal) => {- const payload = JSON.stringify(body);+ let payload = JSON.stringify(body);+ if (payload.length > OFFLOAD_ABOVE_BYTES) {+ payload = JSON.stringify(await offloadHostedMedia(body, CLIENT_ID));+ }if (new Blob([payload]).size > MAX_BODY_BYTES) {throw new Error("That request carries too much attached media to send. Use fewer references.");}diff --git a/site/src/cut/lib/hostedBlobs.test.ts b/site/src/cut/lib/hostedBlobs.test.tsnew file mode 100644index 00000000..f4ed2fd5--- /dev/null+++ b/site/src/cut/lib/hostedBlobs.test.ts@@ -0,0 +1,107 @@+import { beforeEach, describe, expect, test } from "bun:test";++import { offloadHostedMedia } from "./hostedBlobs";++// One picture, large enough to be worth storing.+const bigImage = btoa("x".repeat(200_000));+const otherImage = btoa("y".repeat(200_000));+const tinyImage = btoa("z".repeat(1_000));++type Call = { url: string; body?: unknown; clientId?: string | null };+let calls: Call[] = [];+let claim: (n: number) => unknown;++function stubFetch() {+ calls = [];+ globalThis.fetch = (async (url: string | URL, init?: RequestInit) => {+ const href = String(url);+ if (href === "/api/inference/uploads") {+ const body = JSON.parse(String(init?.body)) as { blobs: unknown[] };+ calls.push({+ url: href,+ body,+ clientId: new Headers(init?.headers).get("x-donkey-client-id"),+ });+ return new Response(JSON.stringify({ blobs: body.blobs.map((_, i) => claim(i)) }), {+ status: 200,+ });+ }+ calls.push({ url: href });+ return new Response(null, { status: 200 });+ }) as unknown as typeof fetch;+}++describe("offloadHostedMedia", () => {+ beforeEach(() => {+ claim = (n) => ({ blobRef: `cut/inference/u1/hash${n}.png`, putUrl: `https://r2/put/${n}` });+ stubFetch();+ });++ test("a picture leaves the body and travels as a reference", async () => {+ const out = (await offloadHostedMedia({+ kind: "image",+ prompt: "hi",+ inputs: { images: [{ data: bigImage, mimeType: "image/png" }] },+ }, "donkey-cut")) as { inputs: { images: Record<string, unknown>[] } };++ const part = out.inputs.images[0];+ expect(part.data).toBeUndefined();+ expect(part.blobRef).toBe("cut/inference/u1/hash0.png");+ // The field the bytes came out of, so the server puts them back in it.+ expect(part.blobField).toBe("data");+ expect(part.mimeType).toBe("image/png");+ expect(calls.map((c) => c.url)).toEqual(["/api/inference/uploads", "https://r2/put/0"]);+ // The claim is an inference call like any other, and the routes require it.+ expect(calls[0].clientId).toBe("donkey-cut");+ });++ test("content parts keep their own payload field", async () => {+ const out = (await offloadHostedMedia({+ input: [{ type: "input_image", dataBase64: bigImage, mimeType: "image/jpeg" }],+ }, "donkey-cut")) as { input: Record<string, unknown>[] };++ expect(out.input[0].dataBase64).toBeUndefined();+ expect(out.input[0].blobField).toBe("dataBase64");+ });++ test("the same picture in many requests uploads once", async () => {+ const body = { inputs: { images: [{ data: otherImage, mimeType: "image/png" }] } };+ await offloadHostedMedia(body, "donkey-cut");+ const before = calls.length;+ const out = (await offloadHostedMedia(body, "donkey-cut")) as {+ inputs: { images: Record<string, unknown>[] };+ };+ // Second pass: no claim, no PUT, and still a reference.+ expect(calls.length).toBe(before);+ expect(out.inputs.images[0].blobRef).toBe("cut/inference/u1/hash0.png");+ });++ test("a payload storage refuses stays in the body", async () => {+ claim = () => ({ skipped: "unsupported" });+ const out = (await offloadHostedMedia({+ inputs: { images: [{ data: btoa("q".repeat(200_000)), mimeType: "image/avif" }] },+ }, "donkey-cut")) as { inputs: { images: Record<string, unknown>[] } };++ expect(out.inputs.images[0].blobRef).toBeUndefined();+ expect(typeof out.inputs.images[0].data).toBe("string");+ });++ test("storage being down never fails the request", async () => {+ globalThis.fetch = (async () => new Response(null, { status: 503 })) as unknown as typeof fetch;+ const out = (await offloadHostedMedia({+ inputs: { images: [{ data: btoa("w".repeat(200_000)), mimeType: "image/png" }] },+ }, "donkey-cut")) as { inputs: { images: Record<string, unknown>[] } };++ expect(typeof out.inputs.images[0].data).toBe("string");+ });++ test("small payloads and plain fields are left alone", async () => {+ const body = {+ prompt: "a long prompt that is not media at all",+ inputs: { images: [{ data: tinyImage, mimeType: "image/png" }] },+ parameters: { data: "not base64, just a string" },+ };+ expect(await offloadHostedMedia(body, "donkey-cut")).toBe(body);+ expect(calls.length).toBe(0);+ });+});diff --git a/site/src/cut/lib/hostedBlobs.ts b/site/src/cut/lib/hostedBlobs.tsnew file mode 100644index 00000000..4445a99b--- /dev/null+++ b/site/src/cut/lib/hostedBlobs.ts@@ -0,0 +1,201 @@+"use client";++// Media leaves a hosted inference request through object storage.+//+// The hosted routes run as serverless functions behind a request-body limit+// enforced at the edge: an oversized body is refused before the route runs, so+// the upload resets mid-flight and fetch rejects with a bare "Failed to fetch".+// A video editor's requests are made of media — reference sheets, keyframes,+// contact sheets, chat attachments — and no amount of downscaling makes a+// request with several pictures reliably fit.+//+// So the bytes never ride the body. Every base64 payload above a trivial size is+// PUT straight to storage and replaced with `{ blobRef, blobField, mimeType }`;+// the route resolves those back into inline data server-side, where the request+// is server-to-server (lib/inference/blobs.ts). This runs inside hostedPost, so+// it covers every caller — generation, the scene pipeline's reviewers, chat —+// and no producer needs to know its picture travels separately.+//+// Anything that goes wrong here leaves the payload inline and the request goes+// out as it would have: storage is how a large request succeeds, never the+// reason a small one fails.+import { bytesFromBase64 } from "./bytes";++/** Keys a hosted payload carries base64 media under, and the media type to+ * assume when the part does not name one. */+const PAYLOAD_KEYS: Record<string, string> = {+ data: "",+ dataBase64: "",+ data_base64: "",+ image_base64: "image/png",+ audio_base64: "audio/mpeg",+ video_base64: "video/mp4",+};++// Below this a round trip to storage costs more than the body it saves.+const MIN_OFFLOAD_BYTES = 32 * 1024;++// A stored object is addressed by its content hash, so a hash seen before needs+// no second upload. The sweep clears scratch objects after a day; reusing a+// mapping for a few hours stays well inside that.+const REUSE_MS = 6 * 60 * 60 * 1000;+const hosted = new Map<string, { key: string; at: number }>();++type Json = { [key: string]: unknown };++const isObject = (v: unknown): v is Json =>+ typeof v === "object" && v !== null && !Array.isArray(v);++const BASE64_HEAD = /^[A-Za-z0-9+/]{64}/;++/** The base64 payload this part carries, if any. */+function payloadOf(part: Json): { field: string; base64: string; mimeType: string } | null {+ for (const [field, fallback] of Object.entries(PAYLOAD_KEYS)) {+ const base64 = part[field];+ // A field named `data` is not always media, so the value has to read as+ // base64 and the part has to say what it is before anything is decoded.+ if (typeof base64 !== "string" || !BASE64_HEAD.test(base64)) continue;+ const declared =+ typeof part.mimeType === "string"+ ? part.mimeType+ : typeof part.mime_type === "string"+ ? part.mime_type+ : "";+ const mimeType = declared || fallback;+ // A payload whose media type nobody stated can't be stored with a type the+ // model will accept, so it stays inline.+ if (!mimeType) continue;+ return { field, base64, mimeType };+ }+ return null;+}++function decode(base64: string): Uint8Array | null {+ try {+ return bytesFromBase64(base64);+ } catch {+ return null;+ }+}++async function sha256Hex(bytes: Uint8Array): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", bytes as unknown as ArrayBuffer);+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++type Claim = { blobRef?: string; putUrl?: string; skipped?: string };++// One claim request covers this many blobs; the rest follow in more requests, so+// a contact sheet with dozens of frames is not a request nobody can send.+const CLAIM_BATCH = 16;++type Claimable = { sha256: string; mimeType: string; bytes: number };++/** Claim a storage key per blob, and the URL to PUT the ones not already there. */+async function claimKeys(blobs: Claimable[], clientId: string): Promise<Claim[]> {+ const batches: Claimable[][] = [];+ for (let i = 0; i < blobs.length; i += CLAIM_BATCH) {+ batches.push(blobs.slice(i, i + CLAIM_BATCH));+ }+ const claimed = await Promise.all(+ batches.map(async (batch) => {+ const unavailable = batch.map(() => ({ skipped: "unavailable" }));+ const res = await fetch("/api/inference/uploads", {+ method: "POST",+ headers: { "Content-Type": "application/json", "x-donkey-client-id": clientId },+ body: JSON.stringify({ blobs: batch }),+ }).catch(() => null);+ if (!res?.ok) return unavailable;+ const body = (await res.json().catch(() => ({}))) as { blobs?: Claim[] };+ return body.blobs?.length === batch.length ? body.blobs : unavailable;+ })+ );+ return claimed.flat();+}++async function put(url: string, bytes: Uint8Array, mimeType: string): Promise<boolean> {+ try {+ const res = await fetch(url, {+ method: "PUT",+ headers: { "Content-Type": mimeType },+ body: new Blob([bytes as unknown as BlobPart], { type: mimeType }),+ });+ return res.ok;+ } catch {+ return false;+ }+}++/**+ * A copy of `body` with its media payloads moved to storage and replaced by+ * references. Returns `body` itself when there is nothing worth moving.+ */+export async function offloadHostedMedia(body: unknown, clientId: string): Promise<unknown> {+ const parts: {+ part: Json;+ field: string;+ mimeType: string;+ bytes: Uint8Array;+ }[] = [];++ const rewrite = (value: unknown): unknown => {+ if (Array.isArray(value)) return value.map(rewrite);+ if (!isObject(value)) return value;+ const found = payloadOf(value);+ if (found) {+ const bytes = decode(found.base64);+ if (bytes && bytes.byteLength >= MIN_OFFLOAD_BYTES) {+ const part: Json = { ...value };+ parts.push({ part, field: found.field, mimeType: found.mimeType, bytes });+ return part;+ }+ return { ...value };+ }+ const out: Json = {};+ for (const [k, v] of Object.entries(value)) out[k] = rewrite(v);+ return out;+ };++ const next = rewrite(body);+ if (parts.length === 0) return body;++ const hashes = await Promise.all(parts.map((p) => sha256Hex(p.bytes)));+ const fresh = Date.now() - REUSE_MS;+ const keys: (string | null)[] = hashes.map((hash) => {+ const known = hosted.get(hash);+ return known && known.at >= fresh ? known.key : null;+ });++ const claiming = parts+ .map((p, i) => ({ i, p, hash: hashes[i] }))+ .filter(({ i }) => keys[i] === null);+ if (claiming.length > 0) {+ const claims = await claimKeys(+ claiming.map(({ p, hash }) => ({+ sha256: hash,+ mimeType: p.mimeType,+ bytes: p.bytes.byteLength,+ })),+ clientId+ );+ await Promise.all(+ claiming.map(async ({ i, p, hash }, n) => {+ const claim = claims[n];+ if (!claim?.blobRef) return;+ if (claim.putUrl && !(await put(claim.putUrl, p.bytes, p.mimeType))) return;+ keys[i] = claim.blobRef;+ hosted.set(hash, { key: claim.blobRef, at: Date.now() });+ })+ );+ }++ for (const [i, key] of keys.entries()) {+ if (!key) continue; // stayed inline+ const { part, field, mimeType } = parts[i];+ delete part[field];+ part.blobRef = key;+ part.blobField = field;+ part.mimeType = mimeType;+ }+ return next;+}diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.tsindex 0f31111d..50bc19d5 100644--- a/site/src/cut/lib/refMedia.ts+++ b/site/src/cut/lib/refMedia.ts@@ -21,22 +21,14 @@ export interface InlineImage {const MAX_W = 1280;const JPEG_Q = 0.85;-// Every picture riding to a hosted model is fitted to this budget first.-//-// A generated reference sheet comes back at the image model's full output size-// — a 2752x1536 PNG is around 4MB — and base64 inflates it by a third. The-// hosted routes run as serverless functions behind a 4.5MB request-body limit-// enforced at the edge, so one such sheet as a reference blows the whole-// request up before the route sees it: the upload resets mid-flight and the-// browser reports a bare "Failed to fetch". A scene run rides its anchor sheet-// into every later call, so that one oversized picture failed every location-// design, every keyframe, and every video take in the run.-//-// Fitting here — the one place bytes become an inline part — keeps any number-// of references comfortably inside one request. The models resample inputs to-// roughly this size anyway, so nothing the model sees is lost.-const MAX_INLINE_EDGE = 1536;-const MAX_INLINE_BYTES = 900 * 1024;+// Every picture riding to a hosted model is fitted to this budget first — a+// generated reference sheet comes back at the image model's full output size, and+// a handful of those is more than one model call should carry. Getting the bytes+// to the model is storage's job (hostedBlobs.ts), so this budget is about what+// the model reads: it resamples inputs to roughly this size anyway, so nothing+// it sees is lost.+const MAX_INLINE_EDGE = 2048;+const MAX_INLINE_BYTES = 4 * 1024 * 1024;// Vertex image models accept only real image mime types. Read the format from the// bytes rather than the transport Content-Type: a media file served as@@ -141,8 +133,7 @@ export async function blobToInlineAudio(blob: Blob): Promise<InlineImage | null>/** Video models take input images only as JPEG or PNG — the render rejects anything* else by format, killing the render after it was billed. Re-encode any other- * picture (webp saved off the web is the common case) through the inline- * budget, so the conversion lands as a JPEG the request can carry; jpeg and png+ * picture (webp saved off the web is the common case) to JPEG; jpeg and png* pass through untouched. */export async function videoSafeInline(img: InlineImage): Promise<InlineImage> {if (img.mimeType === "image/jpeg" || img.mimeType === "image/png") return img;diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.tsindex 89539215..21615690 100644--- a/site/src/cut/server/cloud/gc.ts+++ b/site/src/cut/server/cloud/gc.ts@@ -8,10 +8,13 @@ import { graceDeadline } from "./grace";import { cutLimitsFor, FREE_STORAGE_BYTES } from "./limits";import { deleteLibraryAssetCascade } from "./library";import { deleteProjectCascade } from "./projects";-import { del } from "./r2";+import { del, INFERENCE_PREFIX, listOlderThan } from "./r2";import { addUsage } from "./usage";const PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;+// Scratch media a hosted inference call carried. No row tracks these — they are+// found by prefix and live only as long as the calls that might reuse them.+const SCRATCH_MAX_AGE_MS = 24 * 60 * 60 * 1000;const ORPHAN_MAX_AGE_MS = 24 * 60 * 60 * 1000;const JOB_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;const TERMINAL_STATES = ["done", "error", "canceled"];@@ -240,11 +243,20 @@ export async function runGc(): Promise<Response> {? await prisma.cutRenderJob.deleteMany({ where: { id: { in: oldJobs.map((j) => j.id) } } }): { count: 0 };+ // Scratch inference media, swept by prefix: it never counted toward usage and+ // no row points at it, so age is the only thing that makes it garbage.+ const scratch = await listOlderThan(+ INFERENCE_PREFIX,+ new Date(Date.now() - SCRATCH_MAX_AGE_MS)+ ).catch(() => [] as string[]);+ await del(scratch);+const reclaimed = await reclaimOverQuota();return Response.json({pendingObjects: pending.length,orphanedMedia: orphans.length,+ inferenceScratch: scratch.length,renderJobs: jobs.count,reclaimedUsers: reclaimed.users,reclaimedProjects: reclaimed.projects,diff --git a/site/src/cut/server/cloud/r2.ts b/site/src/cut/server/cloud/r2.tsindex cdde7e62..1438c794 100644--- a/site/src/cut/server/cloud/r2.ts+++ b/site/src/cut/server/cloud/r2.ts@@ -6,6 +6,7 @@ import {DeleteObjectsCommand,GetObjectCommand,HeadObjectCommand,+ ListObjectsV2Command,PutObjectCommand,S3Client,} from "@aws-sdk/client-s3";@@ -59,6 +60,16 @@ export const libraryKey = (userId: string, fileName: string) =>export const overlayKey = (userId: string, batchId: string, name: string) =>`cut/${userId}/overlays/${batchId}/${name}`;+/** Scratch media a hosted inference call carries — reference sheets, keyframes,+ * chat attachments. Keyed by the SHA-256 of the bytes, so a sheet that rides+ * into thirty calls uploads once and every caller addresses it by content.+ * These live outside the per-user media prefix: they are not the user's media,+ * they never count against a storage quota, and the sweep finds them by prefix+ * rather than by row. */+export const INFERENCE_PREFIX = "cut/inference/";+export const inferenceBlobKey = (userId: string, sha256: string, ext: string) =>+ `${INFERENCE_PREFIX}${userId}/${sha256}.${ext}`;+export function presignPut(key: string, mime: string): Promise<string> {return getSignedUrl(r2(),@@ -115,6 +126,49 @@ export async function head(key: string): Promise<{ bytes: number; mime: string }}}+/** An object's bytes, or null when it does not exist. */+export async function getObject(key: string): Promise<{ bytes: Buffer; mime: string } | null> {+ try {+ const res = await r2().send(new GetObjectCommand({ Bucket: R2_BUCKET, Key: key }));+ const body = res.Body;+ if (!body) return null;+ return {+ bytes: Buffer.from(await body.transformToByteArray()),+ mime: res.ContentType ?? "application/octet-stream",+ };+ } catch (e) {+ if (e instanceof R2NotConfiguredError) throw e;+ return null;+ }+}++/** Keys under `prefix` last written before `before`, paged to `limit` objects.+ * For prefix sweeps of objects no database row tracks. */+export async function listOlderThan(+ prefix: string,+ before: Date,+ limit = 5000+): Promise<string[]> {+ const out: string[] = [];+ let token: string | undefined;+ do {+ const res = await r2().send(+ new ListObjectsV2Command({+ Bucket: R2_BUCKET,+ Prefix: prefix,+ ContinuationToken: token,+ MaxKeys: 1000,+ })+ );+ for (const o of res.Contents ?? []) {+ if (o.Key && o.LastModified && o.LastModified < before) out.push(o.Key);+ if (out.length >= limit) return out;+ }+ token = res.IsTruncated ? res.NextContinuationToken : undefined;+ } while (token);+ return out;+}+export async function copy(srcKey: string, dstKey: string): Promise<void> {await r2().send(new CopyObjectCommand({diff --git a/site/src/lib/inference/blobs.test.ts b/site/src/lib/inference/blobs.test.tsnew file mode 100644index 00000000..f05447d5--- /dev/null+++ b/site/src/lib/inference/blobs.test.ts@@ -0,0 +1,76 @@+import { describe, expect, test } from "bun:test";++import { resolveInferenceBlobs, type BlobReader } from "./blobs";++const stored = new Map<string, { bytes: Buffer; mime: string }>([+ ["cut/inference/u1/abc.png", { bytes: Buffer.from("picture bytes"), mime: "image/png" }],+]);+const read: BlobReader = async (key) => stored.get(key) ?? null;++const b64 = Buffer.from("picture bytes").toString("base64");++async function failure(promise: Promise<unknown>): Promise<string> {+ try {+ await promise;+ return "";+ } catch (e) {+ return e instanceof Error ? e.message : String(e);+ }+}++describe("resolveInferenceBlobs", () => {+ test("a reference becomes bytes in the field it names", async () => {+ const out = (await resolveInferenceBlobs(+ {+ prompt: "hi",+ inputs: { images: [{ blobRef: "cut/inference/u1/abc.png", blobField: "data" }] },+ },+ "u1",+ read+ )) as { inputs: { images: Record<string, unknown>[] } };++ const part = out.inputs.images[0];+ expect(part.data).toBe(b64);+ expect(part.mimeType).toBe("image/png");+ expect(part.blobRef).toBeUndefined();+ expect(part.blobField).toBeUndefined();+ });++ test("a content part's payload field is honored", async () => {+ const out = (await resolveInferenceBlobs(+ [{ type: "input_image", blobRef: "cut/inference/u1/abc.png", blobField: "dataBase64" }],+ "u1",+ read+ )) as Record<string, unknown>[];++ expect(out[0].dataBase64).toBe(b64);+ expect(out[0].type).toBe("input_image");+ });++ test("another account's object is refused", async () => {+ const message = await failure(+ resolveInferenceBlobs(+ { inputs: { images: [{ blobRef: "cut/inference/u2/abc.png", blobField: "data" }] } },+ "u1",+ read+ )+ );+ expect(message.includes("does not belong")).toBe(true);+ });++ test("a swept object reads as a plain retry, not a broken request", async () => {+ const message = await failure(+ resolveInferenceBlobs(+ { inputs: { images: [{ blobRef: "cut/inference/u1/gone.png", blobField: "data" }] } },+ "u1",+ read+ )+ );+ expect(message.includes("no longer in storage")).toBe(true);+ });++ test("a body carrying no references is returned as it came", async () => {+ const body = { prompt: "hi", inputs: { images: [{ data: "inline", mimeType: "image/png" }] } };+ expect(await resolveInferenceBlobs(body, "u1", read)).toEqual(body);+ });+});diff --git a/site/src/lib/inference/blobs.ts b/site/src/lib/inference/blobs.tsnew file mode 100644index 00000000..3119411a--- /dev/null+++ b/site/src/lib/inference/blobs.ts@@ -0,0 +1,105 @@+// Media a hosted inference request carries by reference instead of by value.+//+// A video editor's requests carry pictures and sound: reference sheets, shot+// keyframes, contact sheets, chat attachments. Base64 in the request body is a+// dead end — the routes run as serverless functions behind a request-body limit+// enforced at the edge, so an oversized body is refused before the route runs+// and the browser only sees a dropped connection. So bytes travel out of band:+// the client PUTs them straight to object storage (/api/inference/uploads mints+// the URL) and sends a placeholder in their place. This resolves those+// placeholders back into inline data on the way to the model, where the request+// is server-to-server and the only ceiling is the model's own.+//+// A placeholder is `{ blobRef, blobField, mimeType }`: `blobRef` is the object+// key, `blobField` names the field the base64 belongs in. Naming the field is+// what keeps this one function enough for every payload shape — asset inputs+// read `data`, content parts read `dataBase64` — with no consumer aware that+// media ever left the body.+import { getObject } from "@/cut/server/cloud/r2";+import { isJsonObject } from "@/lib/inference/json";+import { InferenceProviderError, type JsonValue } from "@/lib/inference/providers";++// What one request may inline once resolved. Sized to sit under the model's own+// per-request ceiling: past it the upstream call fails on bytes we already+// counted, so the caller hears about it here instead.+const MAX_RESOLVED_BYTES = 20 * 1024 * 1024;++/** True for a value shaped like a stored-blob placeholder. */+function blobRefOf(value: JsonValue): { key: string; field: string } | null {+ if (!isJsonObject(value)) return null;+ const key = value.blobRef;+ const field = value.blobField;+ if (typeof key !== "string" || !key) return null;+ return { key, field: typeof field === "string" && field ? field : "data" };+}++export type BlobReader = (key: string) => Promise<{ bytes: Buffer; mime: string } | null>;++/** The object's bytes, retried once — a single storage blip must not cost a+ * render that was about to be billed. */+const readBlob: BlobReader = async (key) => {+ const first = await getObject(key).catch(() => null);+ if (first) return first;+ return getObject(key).catch(() => null);+};++/**+ * Replace every stored-blob placeholder in `body` with the bytes it points at.+ * Keys are scoped to the caller: a placeholder naming another user's object is+ * rejected rather than read. Returns the body unchanged when it carries none.+ */+export async function resolveInferenceBlobs(+ body: JsonValue,+ userId: string,+ read: BlobReader = readBlob+): Promise<JsonValue> {+ const scope = `cut/inference/${userId}/`;+ let resolved = 0;++ const walk = async (value: JsonValue): Promise<JsonValue> => {+ if (Array.isArray(value)) {+ return Promise.all(value.map(walk));+ }+ if (!isJsonObject(value)) {+ return value;+ }+ const ref = blobRefOf(value);+ if (!ref) {+ const out: { [key: string]: JsonValue } = {};+ for (const [k, v] of Object.entries(value)) {+ out[k] = await walk(v);+ }+ return out;+ }+ if (!ref.key.startsWith(scope)) {+ throw new InferenceProviderError("That attachment does not belong to this account.", {+ statusCode: 403,+ code: "blob_not_owned",+ });+ }+ const object = await read(ref.key);+ if (!object) {+ throw new InferenceProviderError(+ "An attached file is no longer in storage. Send the request again.",+ { statusCode: 400, code: "blob_missing" }+ );+ }+ resolved += object.bytes.byteLength;+ if (resolved > MAX_RESOLVED_BYTES) {+ throw new InferenceProviderError(+ "This request carries more media than the model can take at once. Use fewer or shorter attachments.",+ { statusCode: 413, code: "attachments_too_large" }+ );+ }+ const rest = { ...value };+ delete rest.blobRef;+ delete rest.blobField;+ return {+ ...rest,+ mimeType: typeof value.mimeType === "string" ? value.mimeType : object.mime,+ [ref.field]: object.bytes.toString("base64"),+ };+ };++ return walk(body);+}diff --git a/site/src/lib/inference/schemas.ts b/site/src/lib/inference/schemas.tsindex 81d239dd..9168a456 100644--- a/site/src/lib/inference/schemas.ts+++ b/site/src/lib/inference/schemas.ts@@ -80,6 +80,22 @@ export const assetGenerationRequestSchema = z.object({metadata: metadataSchema.optional(),});+// Media a request will carry by reference: the client hashes the bytes, claims a+// key for each, and uploads straight to storage. Hashes are content addresses,+// so the same picture claimed twice resolves to the same object.+export const inferenceUploadRequestSchema = z.object({+ blobs: z+ .array(+ z.object({+ sha256: z.string().regex(/^[0-9a-f]{64}$/),+ mimeType: z.string().min(1).max(128),+ bytes: z.number().int().positive(),+ })+ )+ .min(1)+ .max(24),+});+const nullableProviderStringSchema = z.string().min(1)